├── requirements.txt ├── tests ├── unit │ ├── advanced │ │ ├── cloud │ │ │ ├── __init__.py │ │ │ └── creds.zip │ │ ├── __init__.py │ │ ├── test_execution_profile.py │ │ └── test_auth.py │ ├── __init__.py │ ├── io │ │ ├── __init__.py │ │ ├── eventlet_utils.py │ │ ├── gevent_utils.py │ │ ├── test_geventreactor.py │ │ ├── test_asyncioreactor.py │ │ └── test_eventletreactor.py │ ├── cqlengine │ │ ├── __init__.py │ │ ├── test_udt.py │ │ ├── test_columns.py │ │ └── test_connection.py │ ├── cython │ │ ├── __init__.py │ │ ├── test_utils.py │ │ ├── utils_testhelper.pyx │ │ ├── test_types.py │ │ ├── test_bytesio.py │ │ ├── utils.py │ │ └── bytesio_testhelper.pyx │ ├── test_auth.py │ ├── util.py │ ├── utils.py │ ├── test_exception.py │ ├── test_endpoints.py │ └── test_query.py ├── integration │ ├── long │ │ ├── ssl │ │ │ ├── 127.0.0.1.keystore │ │ │ ├── cassandra.truststore │ │ │ ├── rootCa.crt │ │ │ ├── client.crt_signed │ │ │ ├── client.key │ │ │ ├── client_bad.key │ │ │ └── client_encrypted.key │ │ ├── __init__.py │ │ └── test_topology_change.py │ ├── conftest.py │ ├── simulacron │ │ ├── conftest.py │ │ ├── advanced │ │ │ └── __init__.py │ │ └── __init__.py │ ├── cloud │ │ └── conftest.py │ ├── cqlengine │ │ ├── conftest.py │ │ ├── columns │ │ │ └── __init__.py │ │ ├── connections │ │ │ └── __init__.py │ │ ├── model │ │ │ ├── __init__.py │ │ │ └── test_equality_operations.py │ │ ├── query │ │ │ └── __init__.py │ │ ├── statements │ │ │ ├── __init__.py │ │ │ ├── test_base_clause.py │ │ │ ├── test_where_clause.py │ │ │ └── test_insert_statement.py │ │ ├── advanced │ │ │ └── __init__.py │ │ ├── management │ │ │ └── __init__.py │ │ ├── operators │ │ │ └── __init__.py │ │ └── base.py │ ├── standard │ │ ├── conftest.py │ │ ├── __init__.py │ │ ├── utils.py │ │ ├── test_authentication_misconfiguration.py │ │ └── test_custom_cluster.py │ ├── advanced │ │ ├── test_spark.py │ │ └── test_unixsocketendpoint.py │ └── util.py ├── stress_tests │ └── test_load.py └── util.py ├── cassandra ├── numpyFlags.h ├── cython_utils.pxd ├── cython_deps.py ├── datastax │ ├── __init__.py │ ├── insights │ │ ├── __init__.py │ │ └── util.py │ └── graph │ │ ├── fluent │ │ ├── query.py │ │ ├── predicates.py │ │ └── serializers.py │ │ └── __init__.py ├── io │ └── __init__.py ├── graph │ ├── __init__.py │ ├── query.py │ ├── types.py │ └── graphson.py ├── column_encryption │ └── policies.py ├── bytesio.pxd ├── cqlengine │ └── __init__.py ├── type_codes.pxd ├── parsing.pxd ├── tuple.pxd ├── parsing.pyx ├── ioutils.pyx ├── deserializers.pxd ├── bytesio.pyx ├── type_codes.py ├── buffer.pxd ├── cython_utils.pyx ├── row_parser.pyx └── cython_marshal.pyx ├── docs ├── CHANGELOG.rst ├── api │ ├── cassandra │ │ ├── util.rst │ │ ├── metrics.rst │ │ ├── io │ │ │ ├── libevreactor.rst │ │ │ ├── asyncorereactor.rst │ │ │ ├── asyncioreactor.rst │ │ │ ├── geventreactor.rst │ │ │ ├── eventletreactor.rst │ │ │ └── twistedreactor.rst │ │ ├── datastax │ │ │ └── graph │ │ │ │ ├── fluent │ │ │ │ ├── query.rst │ │ │ │ ├── predicates.rst │ │ │ │ └── index.rst │ │ │ │ └── index.rst │ │ ├── concurrent.rst │ │ ├── cqlengine │ │ │ ├── usertype.rst │ │ │ ├── connection.rst │ │ │ ├── management.rst │ │ │ ├── query.rst │ │ │ └── columns.rst │ │ ├── pool.rst │ │ ├── timestamps.rst │ │ ├── auth.rst │ │ ├── connection.rst │ │ ├── decoder.rst │ │ ├── encoder.rst │ │ ├── query.rst │ │ ├── metadata.rst │ │ ├── policies.rst │ │ └── protocol.rst │ ├── index.rst │ └── cassandra.rst ├── themes │ └── custom │ │ ├── theme.conf │ │ └── static │ │ └── custom.css_t ├── .nav ├── geo_types.rst ├── cqlengine │ ├── third_party.rst │ └── faq.rst └── performance.rst ├── test-datastax-requirements.txt ├── test-requirements.txt ├── MANIFEST.in ├── examples ├── README.rst └── concurrent_executions │ ├── execute_async_with_queue.py │ └── execute_with_threads.py ├── .gitignore ├── appveyor.yml ├── tox.ini ├── benchmarks ├── sync.py ├── future_full_throttle.py ├── future_full_pipeline.py ├── future_batches.py └── callback_full_pipeline.py ├── .asf.yaml ├── appveyor └── run_test.ps1 ├── CONTRIBUTING.rst └── example_core.py /requirements.txt: -------------------------------------------------------------------------------- 1 | geomet>=1.1 2 | -------------------------------------------------------------------------------- /tests/unit/advanced/cloud/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /cassandra/numpyFlags.h: -------------------------------------------------------------------------------- 1 | #define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION 2 | -------------------------------------------------------------------------------- /docs/CHANGELOG.rst: -------------------------------------------------------------------------------- 1 | ********* 2 | CHANGELOG 3 | ********* 4 | 5 | .. include:: ../CHANGELOG.rst 6 | -------------------------------------------------------------------------------- /cassandra/cython_utils.pxd: -------------------------------------------------------------------------------- 1 | from libc.stdint cimport int64_t 2 | cdef datetime_from_timestamp(double timestamp) 3 | -------------------------------------------------------------------------------- /test-datastax-requirements.txt: -------------------------------------------------------------------------------- 1 | -r test-requirements.txt 2 | kerberos 3 | gremlinpython==3.4.6 4 | cryptography >= 42.0 5 | -------------------------------------------------------------------------------- /tests/unit/advanced/cloud/creds.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/apache/cassandra-python-driver/HEAD/tests/unit/advanced/cloud/creds.zip -------------------------------------------------------------------------------- /tests/integration/long/ssl/127.0.0.1.keystore: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/apache/cassandra-python-driver/HEAD/tests/integration/long/ssl/127.0.0.1.keystore -------------------------------------------------------------------------------- /docs/api/cassandra/util.rst: -------------------------------------------------------------------------------- 1 | ``cassandra.util`` - Utilities 2 | =================================== 3 | 4 | .. automodule:: cassandra.util 5 | :members: 6 | -------------------------------------------------------------------------------- /tests/integration/long/ssl/cassandra.truststore: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/apache/cassandra-python-driver/HEAD/tests/integration/long/ssl/cassandra.truststore -------------------------------------------------------------------------------- /test-requirements.txt: -------------------------------------------------------------------------------- 1 | -r requirements.txt 2 | scales 3 | pytest 4 | ccm>=3.1.5 5 | pytz 6 | pure-sasl 7 | twisted[tls] 8 | gevent 9 | eventlet 10 | cython>=3.0 11 | packaging 12 | futurist 13 | asynctest 14 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include setup.py README.rst MANIFEST.in LICENSE ez_setup.py 2 | include cassandra/cmurmur3.c 3 | include cassandra/io/libevwrapper.c 4 | include cassandra/*.pyx 5 | include cassandra/*.pxd 6 | include cassandra/*.h 7 | -------------------------------------------------------------------------------- /docs/api/cassandra/metrics.rst: -------------------------------------------------------------------------------- 1 | ``cassandra.metrics`` - Performance Metrics 2 | =========================================== 3 | 4 | .. module:: cassandra.metrics 5 | 6 | .. autoclass:: cassandra.metrics.Metrics () 7 | :members: 8 | -------------------------------------------------------------------------------- /docs/api/cassandra/io/libevreactor.rst: -------------------------------------------------------------------------------- 1 | ``cassandra.io.libevreactor`` - ``libev`` Event Loop 2 | ==================================================== 3 | 4 | .. module:: cassandra.io.libevreactor 5 | 6 | .. autoclass:: LibevConnection 7 | -------------------------------------------------------------------------------- /docs/api/cassandra/datastax/graph/fluent/query.rst: -------------------------------------------------------------------------------- 1 | :mod:`cassandra.datastax.graph.fluent.query` 2 | ============================================ 3 | 4 | .. module:: cassandra.datastax.graph.fluent.query 5 | 6 | 7 | .. autoclass:: TraversalBatch 8 | :members: 9 | -------------------------------------------------------------------------------- /docs/api/cassandra/io/asyncorereactor.rst: -------------------------------------------------------------------------------- 1 | ``cassandra.io.asyncorereactor`` - ``asyncore`` Event Loop 2 | ========================================================== 3 | 4 | .. module:: cassandra.io.asyncorereactor 5 | 6 | .. autoclass:: AsyncoreConnection 7 | :members: 8 | -------------------------------------------------------------------------------- /tests/integration/conftest.py: -------------------------------------------------------------------------------- 1 | import pytest 2 | 3 | from tests.integration import teardown_package 4 | 5 | 6 | @pytest.fixture(scope='session', autouse=True) 7 | def setup_and_teardown_packages(): 8 | print('setup') 9 | yield 10 | teardown_package() 11 | -------------------------------------------------------------------------------- /docs/api/cassandra/io/asyncioreactor.rst: -------------------------------------------------------------------------------- 1 | ``cassandra.io.asyncioreactor`` - ``asyncio`` Event Loop 2 | ===================================================================== 3 | 4 | .. module:: cassandra.io.asyncioreactor 5 | 6 | .. autoclass:: AsyncioConnection 7 | :members: 8 | -------------------------------------------------------------------------------- /tests/integration/simulacron/conftest.py: -------------------------------------------------------------------------------- 1 | import pytest 2 | 3 | from tests.integration.simulacron import teardown_package 4 | 5 | @pytest.fixture(scope='session', autouse=True) 6 | def setup_and_teardown_packages(): 7 | print('setup') 8 | yield 9 | teardown_package() -------------------------------------------------------------------------------- /docs/api/cassandra/io/geventreactor.rst: -------------------------------------------------------------------------------- 1 | ``cassandra.io.geventreactor`` - ``gevent``-compatible Event Loop 2 | ================================================================= 3 | 4 | .. module:: cassandra.io.geventreactor 5 | 6 | .. autoclass:: GeventConnection 7 | :members: 8 | -------------------------------------------------------------------------------- /cassandra/cython_deps.py: -------------------------------------------------------------------------------- 1 | try: 2 | from cassandra.row_parser import make_recv_results_rows 3 | HAVE_CYTHON = True 4 | except ImportError: 5 | HAVE_CYTHON = False 6 | 7 | try: 8 | import numpy 9 | HAVE_NUMPY = True 10 | except ImportError: 11 | HAVE_NUMPY = False 12 | -------------------------------------------------------------------------------- /docs/api/cassandra/io/eventletreactor.rst: -------------------------------------------------------------------------------- 1 | ``cassandra.io.eventletreactor`` - ``eventlet``-compatible Connection 2 | ===================================================================== 3 | 4 | .. module:: cassandra.io.eventletreactor 5 | 6 | .. autoclass:: EventletConnection 7 | :members: 8 | -------------------------------------------------------------------------------- /docs/themes/custom/theme.conf: -------------------------------------------------------------------------------- 1 | [theme] 2 | inherit = alabaster 3 | stylesheet = custom.css 4 | pygments_style = friendly 5 | 6 | [options] 7 | description = Python driver for Cassandra 8 | github_user = datastax 9 | github_repo = python-driver 10 | github_button = true 11 | github_type = star -------------------------------------------------------------------------------- /tests/integration/cloud/conftest.py: -------------------------------------------------------------------------------- 1 | import pytest 2 | 3 | from tests.integration.cloud import setup_package, teardown_package 4 | 5 | 6 | @pytest.fixture(scope='session', autouse=True) 7 | def setup_and_teardown_packages(): 8 | setup_package() 9 | yield 10 | teardown_package() 11 | -------------------------------------------------------------------------------- /docs/api/cassandra/concurrent.rst: -------------------------------------------------------------------------------- 1 | ``cassandra.concurrent`` - Utilities for Concurrent Statement Execution 2 | ======================================================================= 3 | 4 | .. module:: cassandra.concurrent 5 | 6 | .. autofunction:: execute_concurrent 7 | 8 | .. autofunction:: execute_concurrent_with_args 9 | -------------------------------------------------------------------------------- /docs/.nav: -------------------------------------------------------------------------------- 1 | installation 2 | getting_started 3 | execution_profiles 4 | lwt 5 | object_mapper 6 | performance 7 | query_paging 8 | security 9 | upgrading 10 | user_defined_types 11 | dates_and_times 12 | cloud 13 | column_encryption 14 | geo_types 15 | graph 16 | classic_graph 17 | graph_fluent 18 | CHANGELOG 19 | faq 20 | api 21 | 22 | -------------------------------------------------------------------------------- /docs/api/cassandra/cqlengine/usertype.rst: -------------------------------------------------------------------------------- 1 | ``cassandra.cqlengine.usertype`` - Model classes for User Defined Types 2 | ======================================================================= 3 | 4 | .. module:: cassandra.cqlengine.usertype 5 | 6 | UserType 7 | -------- 8 | .. autoclass:: UserType 9 | 10 | .. autoattribute:: __type_name__ 11 | -------------------------------------------------------------------------------- /docs/api/cassandra/io/twistedreactor.rst: -------------------------------------------------------------------------------- 1 | ``cassandra.io.twistedreactor`` - Twisted Event Loop 2 | ==================================================== 3 | 4 | .. module:: cassandra.io.twistedreactor 5 | 6 | .. class:: TwistedConnection 7 | 8 | An implementation of :class:`~cassandra.io.connection.Connection` that uses 9 | Twisted's reactor as its event loop. 10 | -------------------------------------------------------------------------------- /docs/api/cassandra/pool.rst: -------------------------------------------------------------------------------- 1 | ``cassandra.pool`` - Hosts and Connection Pools 2 | =============================================== 3 | 4 | .. automodule:: cassandra.pool 5 | 6 | .. autoclass:: Host () 7 | :members: 8 | :exclude-members: set_location_info, get_and_set_reconnection_handler 9 | 10 | .. autoexception:: NoConnectionsAvailable 11 | :members: 12 | -------------------------------------------------------------------------------- /docs/api/cassandra/datastax/graph/fluent/predicates.rst: -------------------------------------------------------------------------------- 1 | :mod:`cassandra.datastax.graph.fluent.predicates` 2 | ================================================= 3 | 4 | .. module:: cassandra.datastax.graph.fluent.predicates 5 | 6 | 7 | .. autoclass:: Search 8 | :members: 9 | 10 | .. autoclass:: CqlCollection 11 | :members: 12 | 13 | .. autoclass:: Geo 14 | :members: 15 | -------------------------------------------------------------------------------- /tests/integration/cqlengine/conftest.py: -------------------------------------------------------------------------------- 1 | import pytest 2 | 3 | from tests.integration import teardown_package as parent_teardown_package 4 | from tests.integration.cqlengine import setup_package, teardown_package 5 | 6 | 7 | @pytest.fixture(scope='session', autouse=True) 8 | def setup_and_teardown_packages(): 9 | setup_package() 10 | yield 11 | teardown_package() 12 | parent_teardown_package() -------------------------------------------------------------------------------- /docs/themes/custom/static/custom.css_t: -------------------------------------------------------------------------------- 1 | @import url("alabaster.css"); 2 | 3 | div.document { 4 | width: 1200px; 5 | } 6 | 7 | div.sphinxsidebar h1.logo a { 8 | font-size: 24px; 9 | } 10 | 11 | code.descname { 12 | color: #4885ed; 13 | } 14 | 15 | th.field-name { 16 | min-width: 100px; 17 | color: #3cba54; 18 | } 19 | 20 | div.versionmodified { 21 | font-weight: bold 22 | } 23 | 24 | div.versionadded { 25 | font-weight: bold 26 | } 27 | -------------------------------------------------------------------------------- /docs/api/cassandra/timestamps.rst: -------------------------------------------------------------------------------- 1 | ``cassandra.timestamps`` - Timestamp Generation 2 | ============================================= 3 | 4 | .. module:: cassandra.timestamps 5 | 6 | .. autoclass:: MonotonicTimestampGenerator (warn_on_drift=True, warning_threshold=0, warning_interval=0) 7 | 8 | .. autoattribute:: warn_on_drift 9 | 10 | .. autoattribute:: warning_threshold 11 | 12 | .. autoattribute:: warning_interval 13 | 14 | .. automethod:: _next_timestamp 15 | -------------------------------------------------------------------------------- /docs/api/cassandra/cqlengine/connection.rst: -------------------------------------------------------------------------------- 1 | ``cassandra.cqlengine.connection`` - Connection management for cqlengine 2 | ======================================================================== 3 | 4 | .. module:: cassandra.cqlengine.connection 5 | 6 | .. autofunction:: default 7 | 8 | .. autofunction:: set_session 9 | 10 | .. autofunction:: setup 11 | 12 | .. autofunction:: register_connection 13 | 14 | .. autofunction:: unregister_connection 15 | 16 | .. autofunction:: set_default_connection 17 | -------------------------------------------------------------------------------- /docs/api/cassandra/auth.rst: -------------------------------------------------------------------------------- 1 | ``cassandra.auth`` - Authentication 2 | =================================== 3 | 4 | .. module:: cassandra.auth 5 | 6 | .. autoclass:: AuthProvider 7 | :members: 8 | 9 | .. autoclass:: Authenticator 10 | :members: 11 | 12 | .. autoclass:: PlainTextAuthProvider 13 | :members: 14 | 15 | .. autoclass:: PlainTextAuthenticator 16 | :members: 17 | 18 | .. autoclass:: SaslAuthProvider 19 | :members: 20 | 21 | .. autoclass:: SaslAuthenticator 22 | :members: 23 | -------------------------------------------------------------------------------- /examples/README.rst: -------------------------------------------------------------------------------- 1 | Driver Examples 2 | =============== 3 | This directory will contain a set of scripts demonstrating driver APIs or integration techniques. It will not be exhaustive, but will contain examples where they are too involved, or 4 | open-ended to include inline in the docstrings. In that case, they should be referenced from the docstrings 5 | 6 | Features 7 | -------- 8 | * `request_init_listener.py `_ A script demonstrating how to register a session request listener and use it to track alternative metrics about requests (size, for example). 9 | -------------------------------------------------------------------------------- /docs/api/cassandra/cqlengine/management.rst: -------------------------------------------------------------------------------- 1 | ``cassandra.cqlengine.management`` - Schema management for cqlengine 2 | ======================================================================== 3 | 4 | .. module:: cassandra.cqlengine.management 5 | 6 | A collection of functions for managing keyspace and table schema. 7 | 8 | .. autofunction:: create_keyspace_simple 9 | 10 | .. autofunction:: create_keyspace_network_topology 11 | 12 | .. autofunction:: drop_keyspace 13 | 14 | .. autofunction:: sync_table 15 | 16 | .. autofunction:: sync_type 17 | 18 | .. autofunction:: drop_table 19 | 20 | -------------------------------------------------------------------------------- /docs/api/cassandra/connection.rst: -------------------------------------------------------------------------------- 1 | ``cassandra.connection`` - Low Level Connection Info 2 | ==================================================== 3 | 4 | .. module:: cassandra.connection 5 | 6 | .. autoexception:: ConnectionException () 7 | .. autoexception:: ConnectionShutdown () 8 | .. autoexception:: ConnectionBusy () 9 | .. autoexception:: ProtocolError () 10 | 11 | .. autoclass:: EndPoint 12 | :members: 13 | 14 | .. autoclass:: EndPointFactory 15 | :members: 16 | 17 | .. autoclass:: SniEndPoint 18 | 19 | .. autoclass:: SniEndPointFactory 20 | 21 | .. autoclass:: UnixSocketEndPoint 22 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.py[co] 2 | *.swp 3 | *.swo 4 | *.so 5 | *.egg 6 | *.egg-info 7 | *.attr 8 | .tox 9 | .python-version 10 | build 11 | MANIFEST 12 | dist 13 | .coverage 14 | cover/ 15 | docs/_build/ 16 | tests/integration/ccm 17 | setuptools*.tar.gz 18 | setuptools*.egg 19 | 20 | cassandra/*.c 21 | !cassandra/cmurmur3.c 22 | cassandra/*.html 23 | tests/unit/cython/bytesio_testhelper.c 24 | 25 | # OSX 26 | .DS_Store 27 | 28 | # IDE 29 | .project 30 | .pydevproject 31 | .settings/ 32 | .idea/ 33 | *.iml 34 | 35 | .DS_Store 36 | 37 | # Unit test / coverage reports 38 | .coverage 39 | .tox 40 | 41 | #iPython 42 | *.ipynb 43 | 44 | venv 45 | docs/venv 46 | .eggs -------------------------------------------------------------------------------- /docs/api/cassandra/decoder.rst: -------------------------------------------------------------------------------- 1 | ``cassandra.decoder`` - Data Return Formats 2 | =========================================== 3 | 4 | .. module:: cassandra.decoder 5 | 6 | .. function:: tuple_factory 7 | 8 | **Deprecated in 2.0.0.** Use :meth:`cassandra.query.tuple_factory` 9 | 10 | .. function:: named_tuple_factory 11 | 12 | **Deprecated in 2.0.0.** Use :meth:`cassandra.query.named_tuple_factory` 13 | 14 | .. function:: dict_factory 15 | 16 | **Deprecated in 2.0.0.** Use :meth:`cassandra.query.dict_factory` 17 | 18 | .. function:: ordered_dict_factory 19 | 20 | **Deprecated in 2.0.0.** Use :meth:`cassandra.query.ordered_dict_factory` 21 | -------------------------------------------------------------------------------- /appveyor.yml: -------------------------------------------------------------------------------- 1 | environment: 2 | matrix: 3 | - PYTHON: "C:\\Python38-x64" 4 | cassandra_version: 3.11.2 5 | ci_type: standard 6 | os: Visual Studio 2015 7 | platform: 8 | - x64 9 | install: 10 | - "SET PATH=%PYTHON%;%PYTHON%\\Scripts;%PATH%" 11 | - ps: .\appveyor\appveyor.ps1 12 | build_script: 13 | - cmd: | 14 | "%VS140COMNTOOLS%\..\..\VC\vcvarsall.bat" x86_amd64 15 | python setup.py install --no-cython 16 | test_script: 17 | - ps: .\appveyor\run_test.ps1 18 | cache: 19 | - C:\Users\appveyor\.m2 20 | - C:\ProgramData\chocolatey\bin 21 | - C:\ProgramData\chocolatey\lib 22 | - C:\Users\appveyor\jce_policy-1.7.0.zip 23 | - C:\Users\appveyor\jce_policy-1.8.0.zip -------------------------------------------------------------------------------- /tests/integration/standard/conftest.py: -------------------------------------------------------------------------------- 1 | import pytest 2 | import logging 3 | 4 | # from https://github.com/streamlit/streamlit/pull/5047/files 5 | def pytest_sessionfinish(): 6 | # We're not waiting for scriptrunner threads to cleanly close before ending the PyTest, 7 | # which results in raised exception ValueError: I/O operation on closed file. 8 | # This is well known issue in PyTest, check out these discussions for more: 9 | # * https://github.com/pytest-dev/pytest/issues/5502 10 | # * https://github.com/pytest-dev/pytest/issues/5282 11 | # To prevent the exception from being raised on pytest_sessionfinish 12 | # we disable exception raising in logging module 13 | logging.raiseExceptions = False -------------------------------------------------------------------------------- /docs/api/cassandra/datastax/graph/fluent/index.rst: -------------------------------------------------------------------------------- 1 | :mod:`cassandra.datastax.graph.fluent` 2 | ====================================== 3 | 4 | .. module:: cassandra.datastax.graph.fluent 5 | 6 | .. autoclass:: DseGraph 7 | 8 | .. autoattribute:: DSE_GRAPH_QUERY_LANGUAGE 9 | 10 | .. automethod:: create_execution_profile 11 | 12 | .. automethod:: query_from_traversal 13 | 14 | .. automethod:: traversal_source(session=None, graph_name=None, execution_profile=EXEC_PROFILE_GRAPH_DEFAULT, traversal_class=None) 15 | 16 | .. automethod:: batch(session=None, execution_profile=None) 17 | 18 | .. autoclass:: DSESessionRemoteGraphConnection(session[, graph_name, execution_profile]) 19 | 20 | .. autoclass:: BaseGraphRowFactory 21 | 22 | .. autoclass:: graph_traversal_row_factory 23 | 24 | .. autoclass:: graph_traversal_dse_object_row_factory 25 | -------------------------------------------------------------------------------- /tests/unit/__init__.py: -------------------------------------------------------------------------------- 1 | # Licensed to the Apache Software Foundation (ASF) under one 2 | # or more contributor license agreements. See the NOTICE file 3 | # distributed with this work for additional information 4 | # regarding copyright ownership. The ASF licenses this file 5 | # to you under the Apache License, Version 2.0 (the 6 | # "License"); you may not use this file except in compliance 7 | # with the License. You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | -------------------------------------------------------------------------------- /cassandra/datastax/__init__.py: -------------------------------------------------------------------------------- 1 | # Licensed to the Apache Software Foundation (ASF) under one 2 | # or more contributor license agreements. See the NOTICE file 3 | # distributed with this work for additional information 4 | # regarding copyright ownership. The ASF licenses this file 5 | # to you under the Apache License, Version 2.0 (the 6 | # "License"); you may not use this file except in compliance 7 | # with the License. You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | -------------------------------------------------------------------------------- /cassandra/io/__init__.py: -------------------------------------------------------------------------------- 1 | # Licensed to the Apache Software Foundation (ASF) under one 2 | # or more contributor license agreements. See the NOTICE file 3 | # distributed with this work for additional information 4 | # regarding copyright ownership. The ASF licenses this file 5 | # to you under the Apache License, Version 2.0 (the 6 | # "License"); you may not use this file except in compliance 7 | # with the License. You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | -------------------------------------------------------------------------------- /tests/unit/advanced/__init__.py: -------------------------------------------------------------------------------- 1 | # Licensed to the Apache Software Foundation (ASF) under one 2 | # or more contributor license agreements. See the NOTICE file 3 | # distributed with this work for additional information 4 | # regarding copyright ownership. The ASF licenses this file 5 | # to you under the Apache License, Version 2.0 (the 6 | # "License"); you may not use this file except in compliance 7 | # with the License. You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | -------------------------------------------------------------------------------- /tests/unit/io/__init__.py: -------------------------------------------------------------------------------- 1 | # Licensed to the Apache Software Foundation (ASF) under one 2 | # or more contributor license agreements. See the NOTICE file 3 | # distributed with this work for additional information 4 | # regarding copyright ownership. The ASF licenses this file 5 | # to you under the Apache License, Version 2.0 (the 6 | # "License"); you may not use this file except in compliance 7 | # with the License. You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | -------------------------------------------------------------------------------- /tests/unit/cqlengine/__init__.py: -------------------------------------------------------------------------------- 1 | # Licensed to the Apache Software Foundation (ASF) under one 2 | # or more contributor license agreements. See the NOTICE file 3 | # distributed with this work for additional information 4 | # regarding copyright ownership. The ASF licenses this file 5 | # to you under the Apache License, Version 2.0 (the 6 | # "License"); you may not use this file except in compliance 7 | # with the License. You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | -------------------------------------------------------------------------------- /tests/unit/cython/__init__.py: -------------------------------------------------------------------------------- 1 | # Licensed to the Apache Software Foundation (ASF) under one 2 | # or more contributor license agreements. See the NOTICE file 3 | # distributed with this work for additional information 4 | # regarding copyright ownership. The ASF licenses this file 5 | # to you under the Apache License, Version 2.0 (the 6 | # "License"); you may not use this file except in compliance 7 | # with the License. You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | -------------------------------------------------------------------------------- /cassandra/datastax/insights/__init__.py: -------------------------------------------------------------------------------- 1 | # Licensed to the Apache Software Foundation (ASF) under one 2 | # or more contributor license agreements. See the NOTICE file 3 | # distributed with this work for additional information 4 | # regarding copyright ownership. The ASF licenses this file 5 | # to you under the Apache License, Version 2.0 (the 6 | # "License"); you may not use this file except in compliance 7 | # with the License. You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | -------------------------------------------------------------------------------- /tests/integration/cqlengine/columns/__init__.py: -------------------------------------------------------------------------------- 1 | # Licensed to the Apache Software Foundation (ASF) under one 2 | # or more contributor license agreements. See the NOTICE file 3 | # distributed with this work for additional information 4 | # regarding copyright ownership. The ASF licenses this file 5 | # to you under the Apache License, Version 2.0 (the 6 | # "License"); you may not use this file except in compliance 7 | # with the License. You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | -------------------------------------------------------------------------------- /tests/integration/cqlengine/connections/__init__.py: -------------------------------------------------------------------------------- 1 | # Licensed to the Apache Software Foundation (ASF) under one 2 | # or more contributor license agreements. See the NOTICE file 3 | # distributed with this work for additional information 4 | # regarding copyright ownership. The ASF licenses this file 5 | # to you under the Apache License, Version 2.0 (the 6 | # "License"); you may not use this file except in compliance 7 | # with the License. You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | -------------------------------------------------------------------------------- /tests/integration/cqlengine/model/__init__.py: -------------------------------------------------------------------------------- 1 | # Licensed to the Apache Software Foundation (ASF) under one 2 | # or more contributor license agreements. See the NOTICE file 3 | # distributed with this work for additional information 4 | # regarding copyright ownership. The ASF licenses this file 5 | # to you under the Apache License, Version 2.0 (the 6 | # "License"); you may not use this file except in compliance 7 | # with the License. You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | -------------------------------------------------------------------------------- /tests/integration/cqlengine/query/__init__.py: -------------------------------------------------------------------------------- 1 | # Licensed to the Apache Software Foundation (ASF) under one 2 | # or more contributor license agreements. See the NOTICE file 3 | # distributed with this work for additional information 4 | # regarding copyright ownership. The ASF licenses this file 5 | # to you under the Apache License, Version 2.0 (the 6 | # "License"); you may not use this file except in compliance 7 | # with the License. You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | -------------------------------------------------------------------------------- /tests/integration/cqlengine/statements/__init__.py: -------------------------------------------------------------------------------- 1 | # Licensed to the Apache Software Foundation (ASF) under one 2 | # or more contributor license agreements. See the NOTICE file 3 | # distributed with this work for additional information 4 | # regarding copyright ownership. The ASF licenses this file 5 | # to you under the Apache License, Version 2.0 (the 6 | # "License"); you may not use this file except in compliance 7 | # with the License. You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | -------------------------------------------------------------------------------- /tests/integration/simulacron/advanced/__init__.py: -------------------------------------------------------------------------------- 1 | # Licensed to the Apache Software Foundation (ASF) under one 2 | # or more contributor license agreements. See the NOTICE file 3 | # distributed with this work for additional information 4 | # regarding copyright ownership. The ASF licenses this file 5 | # to you under the Apache License, Version 2.0 (the 6 | # "License"); you may not use this file except in compliance 7 | # with the License. You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | -------------------------------------------------------------------------------- /tests/integration/cqlengine/advanced/__init__.py: -------------------------------------------------------------------------------- 1 | # Licensed to the Apache Software Foundation (ASF) under one 2 | # or more contributor license agreements. See the NOTICE file 3 | # distributed with this work for additional information 4 | # regarding copyright ownership. The ASF licenses this file 5 | # to you under the Apache License, Version 2.0 (the 6 | # "License"); you may not use this file except in compliance 7 | # with the License. You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | -------------------------------------------------------------------------------- /tests/integration/cqlengine/management/__init__.py: -------------------------------------------------------------------------------- 1 | # Licensed to the Apache Software Foundation (ASF) under one 2 | # or more contributor license agreements. See the NOTICE file 3 | # distributed with this work for additional information 4 | # regarding copyright ownership. The ASF licenses this file 5 | # to you under the Apache License, Version 2.0 (the 6 | # "License"); you may not use this file except in compliance 7 | # with the License. You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | -------------------------------------------------------------------------------- /cassandra/graph/__init__.py: -------------------------------------------------------------------------------- 1 | # Licensed to the Apache Software Foundation (ASF) under one 2 | # or more contributor license agreements. See the NOTICE file 3 | # distributed with this work for additional information 4 | # regarding copyright ownership. The ASF licenses this file 5 | # to you under the Apache License, Version 2.0 (the 6 | # "License"); you may not use this file except in compliance 7 | # with the License. You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | # This is only for backward compatibility when migrating from dse-driver. 18 | from cassandra.datastax.graph import * -------------------------------------------------------------------------------- /cassandra/graph/query.py: -------------------------------------------------------------------------------- 1 | # Licensed to the Apache Software Foundation (ASF) under one 2 | # or more contributor license agreements. See the NOTICE file 3 | # distributed with this work for additional information 4 | # regarding copyright ownership. The ASF licenses this file 5 | # to you under the Apache License, Version 2.0 (the 6 | # "License"); you may not use this file except in compliance 7 | # with the License. You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | # This is only for backward compatibility when migrating from dse-driver. 18 | from cassandra.datastax.graph.query import * 19 | -------------------------------------------------------------------------------- /cassandra/graph/types.py: -------------------------------------------------------------------------------- 1 | # Licensed to the Apache Software Foundation (ASF) under one 2 | # or more contributor license agreements. See the NOTICE file 3 | # distributed with this work for additional information 4 | # regarding copyright ownership. The ASF licenses this file 5 | # to you under the Apache License, Version 2.0 (the 6 | # "License"); you may not use this file except in compliance 7 | # with the License. You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | # This is only for backward compatibility when migrating from dse-driver. 18 | from cassandra.datastax.graph.types import * 19 | -------------------------------------------------------------------------------- /cassandra/graph/graphson.py: -------------------------------------------------------------------------------- 1 | # Licensed to the Apache Software Foundation (ASF) under one 2 | # or more contributor license agreements. See the NOTICE file 3 | # distributed with this work for additional information 4 | # regarding copyright ownership. The ASF licenses this file 5 | # to you under the Apache License, Version 2.0 (the 6 | # "License"); you may not use this file except in compliance 7 | # with the License. You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | # This is only for backward compatibility when migrating from dse-driver. 18 | from cassandra.datastax.graph.graphson import * 19 | -------------------------------------------------------------------------------- /tests/integration/long/__init__.py: -------------------------------------------------------------------------------- 1 | # Licensed to the Apache Software Foundation (ASF) under one 2 | # or more contributor license agreements. See the NOTICE file 3 | # distributed with this work for additional information 4 | # regarding copyright ownership. The ASF licenses this file 5 | # to you under the Apache License, Version 2.0 (the 6 | # "License"); you may not use this file except in compliance 7 | # with the License. You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | import unittest 17 | 18 | try: 19 | from ccmlib import common 20 | except ImportError as e: 21 | raise unittest.SkipTest('ccm is a dependency for integration tests:', e) 22 | -------------------------------------------------------------------------------- /cassandra/column_encryption/policies.py: -------------------------------------------------------------------------------- 1 | # Licensed to the Apache Software Foundation (ASF) under one 2 | # or more contributor license agreements. See the NOTICE file 3 | # distributed with this work for additional information 4 | # regarding copyright ownership. The ASF licenses this file 5 | # to you under the Apache License, Version 2.0 (the 6 | # "License"); you may not use this file except in compliance 7 | # with the License. You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | try: 18 | import cryptography 19 | from cassandra.column_encryption._policies import * 20 | except ImportError: 21 | # Cryptography is not installed 22 | pass 23 | -------------------------------------------------------------------------------- /tests/integration/standard/__init__.py: -------------------------------------------------------------------------------- 1 | # Licensed to the Apache Software Foundation (ASF) under one 2 | # or more contributor license agreements. See the NOTICE file 3 | # distributed with this work for additional information 4 | # regarding copyright ownership. The ASF licenses this file 5 | # to you under the Apache License, Version 2.0 (the 6 | # "License"); you may not use this file except in compliance 7 | # with the License. You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | import unittest 18 | 19 | try: 20 | from ccmlib import common 21 | except ImportError as e: 22 | raise unittest.SkipTest('ccm is a dependency for integration tests:', e) 23 | -------------------------------------------------------------------------------- /cassandra/bytesio.pxd: -------------------------------------------------------------------------------- 1 | # Licensed to the Apache Software Foundation (ASF) under one 2 | # or more contributor license agreements. See the NOTICE file 3 | # distributed with this work for additional information 4 | # regarding copyright ownership. The ASF licenses this file 5 | # to you under the Apache License, Version 2.0 (the 6 | # "License"); you may not use this file except in compliance 7 | # with the License. You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | cdef class BytesIOReader: 18 | cdef bytes buf 19 | cdef char *buf_ptr 20 | cdef Py_ssize_t pos 21 | cdef Py_ssize_t size 22 | cdef char *read(self, Py_ssize_t n = ?) except NULL 23 | -------------------------------------------------------------------------------- /cassandra/datastax/graph/fluent/query.py: -------------------------------------------------------------------------------- 1 | # Licensed to the Apache Software Foundation (ASF) under one 2 | # or more contributor license agreements. See the NOTICE file 3 | # distributed with this work for additional information 4 | # regarding copyright ownership. The ASF licenses this file 5 | # to you under the Apache License, Version 2.0 (the 6 | # "License"); you may not use this file except in compliance 7 | # with the License. You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | try: 18 | import gremlin_python 19 | from cassandra.datastax.graph.fluent._query import * 20 | except ImportError: 21 | # gremlinpython is not installed. 22 | pass 23 | -------------------------------------------------------------------------------- /cassandra/datastax/graph/fluent/predicates.py: -------------------------------------------------------------------------------- 1 | # Licensed to the Apache Software Foundation (ASF) under one 2 | # or more contributor license agreements. See the NOTICE file 3 | # distributed with this work for additional information 4 | # regarding copyright ownership. The ASF licenses this file 5 | # to you under the Apache License, Version 2.0 (the 6 | # "License"); you may not use this file except in compliance 7 | # with the License. You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | try: 18 | import gremlin_python 19 | from cassandra.datastax.graph.fluent._predicates import * 20 | except ImportError: 21 | # gremlinpython is not installed. 22 | pass 23 | -------------------------------------------------------------------------------- /cassandra/datastax/graph/fluent/serializers.py: -------------------------------------------------------------------------------- 1 | # Licensed to the Apache Software Foundation (ASF) under one 2 | # or more contributor license agreements. See the NOTICE file 3 | # distributed with this work for additional information 4 | # regarding copyright ownership. The ASF licenses this file 5 | # to you under the Apache License, Version 2.0 (the 6 | # "License"); you may not use this file except in compliance 7 | # with the License. You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | try: 18 | import gremlin_python 19 | from cassandra.datastax.graph.fluent._serializers import * 20 | except ImportError: 21 | # gremlinpython is not installed. 22 | pass 23 | -------------------------------------------------------------------------------- /tox.ini: -------------------------------------------------------------------------------- 1 | [tox] 2 | envlist = py{39,310,311,312,313},pypy 3 | 4 | [base] 5 | deps = pytest 6 | packaging 7 | cython>=3.0 8 | eventlet 9 | gevent 10 | twisted[tls] 11 | pure-sasl 12 | kerberos 13 | futurist 14 | lz4 15 | cryptography>=42.0 16 | 17 | [testenv] 18 | deps = {[base]deps} 19 | 20 | setenv = LIBEV_EMBED=0 21 | CARES_EMBED=0 22 | LC_ALL=en_US.UTF-8 23 | changedir = {envtmpdir} 24 | commands = pytest -v {toxinidir}/tests/unit/ 25 | 26 | 27 | [testenv:gevent_loop] 28 | deps = {[base]deps} 29 | 30 | setenv = LIBEV_EMBED=0 31 | CARES_EMBED=0 32 | EVENT_LOOP_MANAGER=gevent 33 | changedir = {envtmpdir} 34 | commands = 35 | pytest -v {toxinidir}/tests/unit/io/test_geventreactor.py 36 | 37 | 38 | [testenv:eventlet_loop] 39 | deps = {[base]deps} 40 | 41 | setenv = LIBEV_EMBED=0 42 | CARES_EMBED=0 43 | EVENT_LOOP_MANAGER=eventlet 44 | changedir = {envtmpdir} 45 | commands = 46 | pytest -v {toxinidir}/tests/unit/io/test_eventletreactor.py 47 | -------------------------------------------------------------------------------- /tests/integration/cqlengine/operators/__init__.py: -------------------------------------------------------------------------------- 1 | # Licensed to the Apache Software Foundation (ASF) under one 2 | # or more contributor license agreements. See the NOTICE file 3 | # distributed with this work for additional information 4 | # regarding copyright ownership. The ASF licenses this file 5 | # to you under the Apache License, Version 2.0 (the 6 | # "License"); you may not use this file except in compliance 7 | # with the License. You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | from cassandra.cqlengine.operators import BaseWhereOperator 18 | 19 | 20 | def check_lookup(test_case, symbol, expected): 21 | op = BaseWhereOperator.get_operator(symbol) 22 | test_case.assertEqual(op, expected) 23 | -------------------------------------------------------------------------------- /tests/integration/long/ssl/rootCa.crt: -------------------------------------------------------------------------------- 1 | -----BEGIN CERTIFICATE----- 2 | MIIDCzCCAfMCFCoTNYhIQpOXMBnAq8Bw72qfKwGLMA0GCSqGSIb3DQEBCwUAMEIx 3 | CzAJBgNVBAYTAlVTMREwDwYDVQQKDAhkYXRhc3RheDEPMA0GA1UECwwGZmllbGRz 4 | MQ8wDQYDVQQDDAZyb290Q2EwHhcNMjEwMzE3MTcwNTE2WhcNMzEwMzE1MTcwNTE2 5 | WjBCMQswCQYDVQQGEwJVUzERMA8GA1UECgwIZGF0YXN0YXgxDzANBgNVBAsMBmZp 6 | ZWxkczEPMA0GA1UEAwwGcm9vdENhMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIB 7 | CgKCAQEApFoQtNu0+XQuMBPle4WAJYIMR74HL15uk9ToKBqMEXL7ah3r23xTTeGr 8 | NyUXicM6Owiup7DK27F4vni+MYKAn7L4uZ99mW0ATYNXBDLFB+wwy1JBk4Dw5+eZ 9 | q9lz1TGK7uBvTOXCllOA2qxRqtMTl2aPy5OuciWQe794abwFqs5+1l9GEuzJGsp1 10 | P9L4yljbmijC8RmvDFAeUZoKRdKXw2G5kUOHqK9Aej5gLxIK920PezpgLxm0V/PD 11 | ZAlwlsW0vT79RgZCF/vtKcKSLtFTHgPBNPPbkZmOdE7s/6KoAkORBV/9CIsKeTC3 12 | Y/YeYQ2+G0gxiq1RcMavPw8f58POTQIDAQABMA0GCSqGSIb3DQEBCwUAA4IBAQA1 13 | MXBlk6u2oVBM+4SyYc2nsaHyerM+omUEysAUNFJq6S6i0pu32ULcusDfrnrIQoyR 14 | xPJ/GSYqZkIDX0s9LvPVD6A6bnugR+Z6VfEniLkG1+TkFC+JMCblgJyaF/EbuayU 15 | 3iJX+uj7ikTySjMSDvXxOHik2i0aOh90B/351+sFnSPQrFDQ0XqxeG8s0d7EiLTV 16 | wWJmsYglSeTo1vF3ilVRwjmHO9sX6cmQhRvRNmiQrdWaM3gLS5F6yoQ2UQQ3YdFp 17 | quhYuNwy0Ip6ZpORHYtzkCKSanz/oUh17QWvi7aaJyqD5G5hWZgn3R4RCutoOHRS 18 | TEJ+xzhY768rpsrrNUou 19 | -----END CERTIFICATE----- 20 | -------------------------------------------------------------------------------- /tests/integration/long/ssl/client.crt_signed: -------------------------------------------------------------------------------- 1 | -----BEGIN CERTIFICATE----- 2 | MIIDDjCCAfYCFAG4WryLorTXxNtrkEJ56zUg/XdDMA0GCSqGSIb3DQEBCwUAMEIx 3 | CzAJBgNVBAYTAlVTMREwDwYDVQQKDAhkYXRhc3RheDEPMA0GA1UECwwGZmllbGRz 4 | MQ8wDQYDVQQDDAZyb290Q2EwHhcNMjEwMzE3MTcwNTE4WhcNMjIwMzE3MTcwNTE4 5 | WjBFMQswCQYDVQQGEwJVUzERMA8GA1UECgwIZGF0YXN0YXgxDzANBgNVBAsMBmZp 6 | ZWxkczESMBAGA1UEAwwJMTI3LjAuMC4xMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8A 7 | MIIBCgKCAQEAnrpE3g8pbQn2tVVidX2Ww1rh/6YIH6EGW9hXMO/F506ReMruv+Al 8 | ilc7B2sPpGRDKXupy23IcpfMIe9+Lm74/yu7pW51rJ/r2jMqg+tViFa/GQxSQLKd 9 | AxDAvwJaAM41kro0DKmcm4RwfYAltupwc6pC7AfBtT08PBuDK7WfaNnFbhGAWkHv 10 | MbULNWAKbPWqITHbUEvLgS/uPj+/W4SHk5GaYk0Y2mU3aWypeDOBqEfKTi2W0ix1 11 | O7SpOHyfA0hvXS9IilF/HWURvr9u13mnvJNe8W+uqWqlQMdyFsbPCIhbVwVwGYQp 12 | yoyBrgz6y5SPwSyugAb2F8Yk3UpvqH30yQIDAQABMA0GCSqGSIb3DQEBCwUAA4IB 13 | AQB5XV+3NS5UpwpTXTYsadLL8XcdGsfITMs4MSv0N3oir++TUzTc3cOd2T6YVdEc 14 | ypw5CKTYnFTK9oF2PZXeV+aLIjdvK4AukQurB8EdXq4Hu7y1b61OaGRqiKTVsIne 15 | LwxCXpc42jqMFt4mMXpmU/hSCjRSvoumTcL1aHUzaPlSIasD2JDyLurO64gxQypi 16 | wbD9gliPJ60pdhY0m9NfF5F2PdqBuJXrhF1VuxYx1/cfo/c1A4UK2slhsZCDls7/ 17 | HbM8ri5Z74M1EtCGFcTNYvm0xlfF5arisGQSKhTw+06LnpUlQi5a8NRNBLeAmem/ 18 | cuICJJbnSzjmq9skkp8i/ejH 19 | -----END CERTIFICATE----- 20 | -------------------------------------------------------------------------------- /benchmarks/sync.py: -------------------------------------------------------------------------------- 1 | # Licensed to the Apache Software Foundation (ASF) under one 2 | # or more contributor license agreements. See the NOTICE file 3 | # distributed with this work for additional information 4 | # regarding copyright ownership. The ASF licenses this file 5 | # to you under the Apache License, Version 2.0 (the 6 | # "License"); you may not use this file except in compliance 7 | # with the License. You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | from base import benchmark, BenchmarkThread 18 | 19 | 20 | class Runner(BenchmarkThread): 21 | 22 | def run(self): 23 | self.start_profile() 24 | 25 | for _ in range(self.num_queries): 26 | self.session.execute(self.query, self.values) 27 | 28 | self.finish_profile() 29 | 30 | 31 | if __name__ == "__main__": 32 | benchmark(Runner) 33 | -------------------------------------------------------------------------------- /cassandra/cqlengine/__init__.py: -------------------------------------------------------------------------------- 1 | # Licensed to the Apache Software Foundation (ASF) under one 2 | # or more contributor license agreements. See the NOTICE file 3 | # distributed with this work for additional information 4 | # regarding copyright ownership. The ASF licenses this file 5 | # to you under the Apache License, Version 2.0 (the 6 | # "License"); you may not use this file except in compliance 7 | # with the License. You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | # Caching constants. 18 | CACHING_ALL = "ALL" 19 | CACHING_KEYS_ONLY = "KEYS_ONLY" 20 | CACHING_ROWS_ONLY = "ROWS_ONLY" 21 | CACHING_NONE = "NONE" 22 | 23 | 24 | class CQLEngineException(Exception): 25 | pass 26 | 27 | 28 | class ValidationError(CQLEngineException): 29 | pass 30 | 31 | 32 | class UnicodeMixin(object): 33 | __str__ = lambda x: x.__unicode__() 34 | -------------------------------------------------------------------------------- /tests/unit/cython/test_utils.py: -------------------------------------------------------------------------------- 1 | # Licensed to the Apache Software Foundation (ASF) under one 2 | # or more contributor license agreements. See the NOTICE file 3 | # distributed with this work for additional information 4 | # regarding copyright ownership. The ASF licenses this file 5 | # to you under the Apache License, Version 2.0 (the 6 | # "License"); you may not use this file except in compliance 7 | # with the License. You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | from tests.unit.cython.utils import cyimport, cythontest 18 | utils_testhelper = cyimport('tests.unit.cython.utils_testhelper') 19 | 20 | import unittest 21 | 22 | 23 | class UtilsTest(unittest.TestCase): 24 | """Test Cython Utils functions""" 25 | 26 | @cythontest 27 | def test_datetime_from_timestamp(self): 28 | utils_testhelper.test_datetime_from_timestamp(self.assertEqual) 29 | -------------------------------------------------------------------------------- /tests/unit/cython/utils_testhelper.pyx: -------------------------------------------------------------------------------- 1 | # Licensed to the Apache Software Foundation (ASF) under one 2 | # or more contributor license agreements. See the NOTICE file 3 | # distributed with this work for additional information 4 | # regarding copyright ownership. The ASF licenses this file 5 | # to you under the Apache License, Version 2.0 (the 6 | # "License"); you may not use this file except in compliance 7 | # with the License. You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | import datetime 18 | 19 | from cassandra.cython_utils cimport datetime_from_timestamp 20 | 21 | 22 | def test_datetime_from_timestamp(assert_equal): 23 | assert_equal(datetime_from_timestamp(1454781157.123456), datetime.datetime(2016, 2, 6, 17, 52, 37, 123456)) 24 | # PYTHON-452 25 | assert_equal(datetime_from_timestamp(2177403010.123456), datetime.datetime(2038, 12, 31, 10, 10, 10, 123456)) 26 | -------------------------------------------------------------------------------- /tests/integration/cqlengine/statements/test_base_clause.py: -------------------------------------------------------------------------------- 1 | # Licensed to the Apache Software Foundation (ASF) under one 2 | # or more contributor license agreements. See the NOTICE file 3 | # distributed with this work for additional information 4 | # regarding copyright ownership. The ASF licenses this file 5 | # to you under the Apache License, Version 2.0 (the 6 | # "License"); you may not use this file except in compliance 7 | # with the License. You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | from unittest import TestCase 18 | from cassandra.cqlengine.statements import BaseClause 19 | 20 | 21 | class BaseClauseTests(TestCase): 22 | 23 | def test_context_updating(self): 24 | ss = BaseClause('a', 'b') 25 | assert ss.get_context_size() == 1 26 | 27 | ctx = {} 28 | ss.set_context_id(10) 29 | ss.update_context(ctx) 30 | assert ctx == {'10': 'b'} 31 | 32 | 33 | -------------------------------------------------------------------------------- /cassandra/datastax/graph/__init__.py: -------------------------------------------------------------------------------- 1 | # Licensed to the Apache Software Foundation (ASF) under one 2 | # or more contributor license agreements. See the NOTICE file 3 | # distributed with this work for additional information 4 | # regarding copyright ownership. The ASF licenses this file 5 | # to you under the Apache License, Version 2.0 (the 6 | # "License"); you may not use this file except in compliance 7 | # with the License. You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | 18 | from cassandra.datastax.graph.types import Element, Vertex, VertexProperty, Edge, Path, T 19 | from cassandra.datastax.graph.query import ( 20 | GraphOptions, GraphProtocol, GraphStatement, SimpleGraphStatement, Result, 21 | graph_object_row_factory, single_object_row_factory, 22 | graph_result_row_factory, graph_graphson2_row_factory, 23 | graph_graphson3_row_factory 24 | ) 25 | from cassandra.datastax.graph.graphson import * 26 | -------------------------------------------------------------------------------- /docs/api/index.rst: -------------------------------------------------------------------------------- 1 | API Documentation 2 | ================= 3 | 4 | Core Driver 5 | ----------- 6 | .. toctree:: 7 | :maxdepth: 2 8 | 9 | cassandra 10 | cassandra/cluster 11 | cassandra/policies 12 | cassandra/auth 13 | cassandra/graph 14 | cassandra/metadata 15 | cassandra/metrics 16 | cassandra/query 17 | cassandra/pool 18 | cassandra/protocol 19 | cassandra/encoder 20 | cassandra/decoder 21 | cassandra/concurrent 22 | cassandra/connection 23 | cassandra/util 24 | cassandra/timestamps 25 | cassandra/io/asyncioreactor 26 | cassandra/io/asyncorereactor 27 | cassandra/io/eventletreactor 28 | cassandra/io/libevreactor 29 | cassandra/io/geventreactor 30 | cassandra/io/twistedreactor 31 | 32 | .. _om_api: 33 | 34 | Object Mapper 35 | ------------- 36 | .. toctree:: 37 | :maxdepth: 1 38 | 39 | cassandra/cqlengine/models 40 | cassandra/cqlengine/columns 41 | cassandra/cqlengine/query 42 | cassandra/cqlengine/connection 43 | cassandra/cqlengine/management 44 | cassandra/cqlengine/usertype 45 | 46 | DataStax Graph 47 | -------------- 48 | .. toctree:: 49 | :maxdepth: 1 50 | 51 | cassandra/datastax/graph/index 52 | cassandra/datastax/graph/fluent/index 53 | cassandra/datastax/graph/fluent/query 54 | cassandra/datastax/graph/fluent/predicates 55 | -------------------------------------------------------------------------------- /tests/unit/cython/test_types.py: -------------------------------------------------------------------------------- 1 | # Licensed to the Apache Software Foundation (ASF) under one 2 | # or more contributor license agreements. See the NOTICE file 3 | # distributed with this work for additional information 4 | # regarding copyright ownership. The ASF licenses this file 5 | # to you under the Apache License, Version 2.0 (the 6 | # "License"); you may not use this file except in compliance 7 | # with the License. You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | from tests.unit.cython.utils import cyimport, cythontest 18 | types_testhelper = cyimport('tests.unit.cython.types_testhelper') 19 | 20 | import unittest 21 | 22 | 23 | class TypesTest(unittest.TestCase): 24 | 25 | @cythontest 26 | def test_datetype(self): 27 | types_testhelper.test_datetype(self.assertEqual) 28 | 29 | @cythontest 30 | def test_date_side_by_side(self): 31 | types_testhelper.test_date_side_by_side(self.assertEqual) 32 | -------------------------------------------------------------------------------- /tests/unit/test_auth.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # # Licensed to the Apache Software Foundation (ASF) under one 3 | # or more contributor license agreements. See the NOTICE file 4 | # distributed with this work for additional information 5 | # regarding copyright ownership. The ASF licenses this file 6 | # to you under the Apache License, Version 2.0 (the 7 | # "License"); you may not use this file except in compliance 8 | # with the License. You may obtain a copy of the License at 9 | # 10 | # http://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | 18 | from cassandra.auth import PlainTextAuthenticator 19 | 20 | import unittest 21 | 22 | 23 | class TestPlainTextAuthenticator(unittest.TestCase): 24 | 25 | def test_evaluate_challenge_with_unicode_data(self): 26 | authenticator = PlainTextAuthenticator("johnӁ", "doeӁ") 27 | self.assertEqual( 28 | authenticator.evaluate_challenge(b'PLAIN-START'), 29 | "\x00johnӁ\x00doeӁ".encode('utf-8') 30 | ) 31 | -------------------------------------------------------------------------------- /docs/api/cassandra/encoder.rst: -------------------------------------------------------------------------------- 1 | ``cassandra.encoder`` - Encoders for non-prepared Statements 2 | ============================================================ 3 | 4 | .. module:: cassandra.encoder 5 | 6 | .. autoclass:: Encoder () 7 | 8 | .. autoattribute:: cassandra.encoder.Encoder.mapping 9 | 10 | .. automethod:: cassandra.encoder.Encoder.cql_encode_none () 11 | 12 | .. automethod:: cassandra.encoder.Encoder.cql_encode_object () 13 | 14 | .. automethod:: cassandra.encoder.Encoder.cql_encode_all_types () 15 | 16 | .. automethod:: cassandra.encoder.Encoder.cql_encode_sequence () 17 | 18 | .. automethod:: cassandra.encoder.Encoder.cql_encode_str () 19 | 20 | .. automethod:: cassandra.encoder.Encoder.cql_encode_unicode () 21 | 22 | .. automethod:: cassandra.encoder.Encoder.cql_encode_bytes () 23 | 24 | Converts strings, buffers, and bytearrays into CQL blob literals. 25 | 26 | .. automethod:: cassandra.encoder.Encoder.cql_encode_datetime () 27 | 28 | .. automethod:: cassandra.encoder.Encoder.cql_encode_date () 29 | 30 | .. automethod:: cassandra.encoder.Encoder.cql_encode_map_collection () 31 | 32 | .. automethod:: cassandra.encoder.Encoder.cql_encode_list_collection () 33 | 34 | .. automethod:: cassandra.encoder.Encoder.cql_encode_set_collection () 35 | 36 | .. automethod:: cql_encode_tuple () 37 | -------------------------------------------------------------------------------- /cassandra/type_codes.pxd: -------------------------------------------------------------------------------- 1 | # Licensed to the Apache Software Foundation (ASF) under one 2 | # or more contributor license agreements. See the NOTICE file 3 | # distributed with this work for additional information 4 | # regarding copyright ownership. The ASF licenses this file 5 | # to you under the Apache License, Version 2.0 (the 6 | # "License"); you may not use this file except in compliance 7 | # with the License. You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | cdef enum: 18 | CUSTOM_TYPE 19 | AsciiType 20 | LongType 21 | BytesType 22 | BooleanType 23 | CounterColumnType 24 | DecimalType 25 | DoubleType 26 | FloatType 27 | Int32Type 28 | UTF8Type 29 | DateType 30 | UUIDType 31 | VarcharType 32 | IntegerType 33 | TimeUUIDType 34 | InetAddressType 35 | SimpleDateType 36 | TimeType 37 | ShortType 38 | ByteType 39 | ListType 40 | MapType 41 | SetType 42 | UserType 43 | TupleType 44 | 45 | -------------------------------------------------------------------------------- /tests/unit/util.py: -------------------------------------------------------------------------------- 1 | # Licensed under the Apache License, Version 2.0 (the "License"); 2 | # you may not use this file except in compliance with the License. 3 | # You may obtain a copy of the License at 4 | # 5 | # http://www.apache.org/licenses/LICENSE-2.0 6 | # 7 | # Unless required by applicable law or agreed to in writing, software 8 | # distributed under the License is distributed on an "AS IS" BASIS, 9 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 10 | # See the License for the specific language governing permissions and 11 | # limitations under the License. 12 | 13 | 14 | def check_sequence_consistency(unit_test, ordered_sequence, equal=False): 15 | for i, el in enumerate(ordered_sequence): 16 | for previous in ordered_sequence[:i]: 17 | _check_order_consistency(unit_test, previous, el, equal) 18 | for posterior in ordered_sequence[i + 1:]: 19 | _check_order_consistency(unit_test, el, posterior, equal) 20 | 21 | 22 | def _check_order_consistency(unit_test, smaller, bigger, equal=False): 23 | unit_test.assertLessEqual(smaller, bigger) 24 | unit_test.assertGreaterEqual(bigger, smaller) 25 | if equal: 26 | unit_test.assertEqual(smaller, bigger) 27 | else: 28 | unit_test.assertNotEqual(smaller, bigger) 29 | unit_test.assertLess(smaller, bigger) 30 | unit_test.assertGreater(bigger, smaller) 31 | -------------------------------------------------------------------------------- /cassandra/parsing.pxd: -------------------------------------------------------------------------------- 1 | # Licensed to the Apache Software Foundation (ASF) under one 2 | # or more contributor license agreements. See the NOTICE file 3 | # distributed with this work for additional information 4 | # regarding copyright ownership. The ASF licenses this file 5 | # to you under the Apache License, Version 2.0 (the 6 | # "License"); you may not use this file except in compliance 7 | # with the License. You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | from cassandra.bytesio cimport BytesIOReader 18 | from cassandra.deserializers cimport Deserializer 19 | 20 | cdef class ParseDesc: 21 | cdef public object colnames 22 | cdef public object coltypes 23 | cdef public object column_encryption_policy 24 | cdef public list coldescs 25 | cdef Deserializer[::1] deserializers 26 | cdef public int protocol_version 27 | cdef Py_ssize_t rowsize 28 | 29 | cdef class ColumnParser: 30 | cpdef parse_rows(self, BytesIOReader reader, ParseDesc desc) 31 | 32 | cdef class RowParser: 33 | cpdef unpack_row(self, BytesIOReader reader, ParseDesc desc) 34 | 35 | -------------------------------------------------------------------------------- /benchmarks/future_full_throttle.py: -------------------------------------------------------------------------------- 1 | # Licensed to the Apache Software Foundation (ASF) under one 2 | # or more contributor license agreements. See the NOTICE file 3 | # distributed with this work for additional information 4 | # regarding copyright ownership. The ASF licenses this file 5 | # to you under the Apache License, Version 2.0 (the 6 | # "License"); you may not use this file except in compliance 7 | # with the License. You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | import logging 18 | 19 | from base import benchmark, BenchmarkThread 20 | 21 | log = logging.getLogger(__name__) 22 | 23 | class Runner(BenchmarkThread): 24 | 25 | def run(self): 26 | futures = [] 27 | 28 | self.start_profile() 29 | 30 | for i in range(self.num_queries): 31 | key = "{0}-{1}".format(self.thread_num, i) 32 | future = self.run_query(key) 33 | futures.append(future) 34 | 35 | for future in futures: 36 | future.result() 37 | 38 | self.finish_profile() 39 | 40 | 41 | if __name__ == "__main__": 42 | benchmark(Runner) 43 | -------------------------------------------------------------------------------- /tests/unit/cython/test_bytesio.py: -------------------------------------------------------------------------------- 1 | # Licensed to the Apache Software Foundation (ASF) under one 2 | # or more contributor license agreements. See the NOTICE file 3 | # distributed with this work for additional information 4 | # regarding copyright ownership. The ASF licenses this file 5 | # to you under the Apache License, Version 2.0 (the 6 | # "License"); you may not use this file except in compliance 7 | # with the License. You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | from tests.unit.cython.utils import cyimport, cythontest 18 | bytesio_testhelper = cyimport('tests.unit.cython.bytesio_testhelper') 19 | 20 | import unittest 21 | 22 | 23 | class BytesIOTest(unittest.TestCase): 24 | """Test Cython BytesIO proxy""" 25 | 26 | @cythontest 27 | def test_reading(self): 28 | bytesio_testhelper.test_read1(self.assertEqual, self.assertRaises) 29 | bytesio_testhelper.test_read2(self.assertEqual, self.assertRaises) 30 | bytesio_testhelper.test_read3(self.assertEqual, self.assertRaises) 31 | 32 | @cythontest 33 | def test_reading_error(self): 34 | bytesio_testhelper.test_read_eof(self.assertEqual, self.assertRaises) 35 | -------------------------------------------------------------------------------- /.asf.yaml: -------------------------------------------------------------------------------- 1 | # Licensed to the Apache Software Foundation (ASF) under one 2 | # or more contributor license agreements. See the NOTICE file 3 | # distributed with this work for additional information 4 | # regarding copyright ownership. The ASF licenses this file 5 | # to you under the Apache License, Version 2.0 (the 6 | # "License"); you may not use this file except in compliance 7 | # with the License. You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, 12 | # software distributed under the License is distributed on an 13 | # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 14 | # KIND, either express or implied. See the License for the 15 | # specific language governing permissions and limitations 16 | # under the License. 17 | 18 | notifications: 19 | commits: commits@cassandra.apache.org 20 | issues: commits@cassandra.apache.org 21 | pullrequests: pr@cassandra.apache.org 22 | jira_options: link worklog 23 | 24 | github: 25 | description: "Python Driver for Apache Cassandra®" 26 | homepage: https://docs.datastax.com/en/developer/python-driver/3.29/index.html 27 | enabled_merge_buttons: 28 | squash: false 29 | merge: false 30 | rebase: true 31 | features: 32 | wiki: false 33 | issues: false 34 | projects: false 35 | discussions: false 36 | autolink_jira: 37 | - CASSANDRA 38 | - CASSPYTHON 39 | protected_branches: 40 | trunk: 41 | required_linear_history: true 42 | -------------------------------------------------------------------------------- /tests/unit/utils.py: -------------------------------------------------------------------------------- 1 | # Licensed to the Apache Software Foundation (ASF) under one 2 | # or more contributor license agreements. See the NOTICE file 3 | # distributed with this work for additional information 4 | # regarding copyright ownership. The ASF licenses this file 5 | # to you under the Apache License, Version 2.0 (the 6 | # "License"); you may not use this file except in compliance 7 | # with the License. You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | from functools import wraps 18 | from unittest.mock import patch 19 | 20 | from concurrent.futures import Future 21 | from cassandra.cluster import Session 22 | 23 | 24 | def mock_session_pools(f): 25 | """ 26 | Helper decorator that allows tests to initialize :class:.`Session` objects 27 | without actually connecting to a Cassandra cluster. 28 | """ 29 | @wraps(f) 30 | def wrapper(*args, **kwargs): 31 | with patch.object(Session, "add_or_renew_pool") as mocked_add_or_renew_pool: 32 | future = Future() 33 | future.set_result(object()) 34 | mocked_add_or_renew_pool.return_value = future 35 | f(*args, **kwargs) 36 | return wrapper 37 | -------------------------------------------------------------------------------- /tests/unit/cqlengine/test_udt.py: -------------------------------------------------------------------------------- 1 | # Licensed to the Apache Software Foundation (ASF) under one 2 | # or more contributor license agreements. See the NOTICE file 3 | # distributed with this work for additional information 4 | # regarding copyright ownership. The ASF licenses this file 5 | # to you under the Apache License, Version 2.0 (the 6 | # "License"); you may not use this file except in compliance 7 | # with the License. You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | import unittest 18 | 19 | from cassandra.cqlengine import columns 20 | from cassandra.cqlengine.models import Model 21 | from cassandra.cqlengine.usertype import UserType 22 | 23 | 24 | class UDTTest(unittest.TestCase): 25 | 26 | def test_initialization_without_existing_connection(self): 27 | """ 28 | Test that users can define models with UDTs without initializing 29 | connections. 30 | 31 | Written to reproduce PYTHON-649. 32 | """ 33 | 34 | class Value(UserType): 35 | t = columns.Text() 36 | 37 | class DummyUDT(Model): 38 | __keyspace__ = 'ks' 39 | primary_key = columns.Integer(primary_key=True) 40 | value = columns.UserDefinedType(Value) 41 | -------------------------------------------------------------------------------- /tests/unit/advanced/test_execution_profile.py: -------------------------------------------------------------------------------- 1 | # Licensed to the Apache Software Foundation (ASF) under one 2 | # or more contributor license agreements. See the NOTICE file 3 | # distributed with this work for additional information 4 | # regarding copyright ownership. The ASF licenses this file 5 | # to you under the Apache License, Version 2.0 (the 6 | # "License"); you may not use this file except in compliance 7 | # with the License. You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | import unittest 18 | 19 | from cassandra.cluster import GraphExecutionProfile, GraphAnalyticsExecutionProfile 20 | from cassandra.graph import GraphOptions 21 | 22 | 23 | class GraphExecutionProfileTest(unittest.TestCase): 24 | 25 | def test_graph_source_can_be_set_with_graph_execution_profile(self): 26 | options = GraphOptions(graph_source='a') 27 | ep = GraphExecutionProfile(graph_options=options) 28 | self.assertEqual(ep.graph_options.graph_source, b'a') 29 | 30 | def test_graph_source_is_preserve_with_graph_analytics_execution_profile(self): 31 | options = GraphOptions(graph_source='doesnt_matter') 32 | ep = GraphAnalyticsExecutionProfile(graph_options=options) 33 | self.assertEqual(ep.graph_options.graph_source, b'a') # graph source is set automatically 34 | -------------------------------------------------------------------------------- /docs/api/cassandra.rst: -------------------------------------------------------------------------------- 1 | :mod:`cassandra` - Exceptions and Enums 2 | ======================================= 3 | 4 | .. module:: cassandra 5 | 6 | .. data:: __version_info__ 7 | 8 | The version of the driver in a tuple format 9 | 10 | .. data:: __version__ 11 | 12 | The version of the driver in a string format 13 | 14 | .. autoclass:: ConsistencyLevel 15 | :members: 16 | 17 | .. autoclass:: ProtocolVersion 18 | :members: 19 | 20 | .. autoclass:: UserFunctionDescriptor 21 | :members: 22 | :inherited-members: 23 | 24 | .. autoclass:: UserAggregateDescriptor 25 | :members: 26 | :inherited-members: 27 | 28 | .. autoexception:: DriverException() 29 | :members: 30 | 31 | .. autoexception:: RequestExecutionException() 32 | :members: 33 | 34 | .. autoexception:: Unavailable() 35 | :members: 36 | 37 | .. autoexception:: Timeout() 38 | :members: 39 | 40 | .. autoexception:: ReadTimeout() 41 | :members: 42 | 43 | .. autoexception:: WriteTimeout() 44 | :members: 45 | 46 | .. autoexception:: CoordinationFailure() 47 | :members: 48 | 49 | .. autoexception:: ReadFailure() 50 | :members: 51 | 52 | .. autoexception:: WriteFailure() 53 | :members: 54 | 55 | .. autoexception:: FunctionFailure() 56 | :members: 57 | 58 | .. autoexception:: RequestValidationException() 59 | :members: 60 | 61 | .. autoexception:: ConfigurationException() 62 | :members: 63 | 64 | .. autoexception:: AlreadyExists() 65 | :members: 66 | 67 | .. autoexception:: InvalidRequest() 68 | :members: 69 | 70 | .. autoexception:: Unauthorized() 71 | :members: 72 | 73 | .. autoexception:: AuthenticationFailed() 74 | :members: 75 | 76 | .. autoexception:: OperationTimedOut() 77 | :members: 78 | -------------------------------------------------------------------------------- /benchmarks/future_full_pipeline.py: -------------------------------------------------------------------------------- 1 | # Licensed to the Apache Software Foundation (ASF) under one 2 | # or more contributor license agreements. See the NOTICE file 3 | # distributed with this work for additional information 4 | # regarding copyright ownership. The ASF licenses this file 5 | # to you under the Apache License, Version 2.0 (the 6 | # "License"); you may not use this file except in compliance 7 | # with the License. You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | import logging 18 | from base import benchmark, BenchmarkThread 19 | import queue 20 | 21 | log = logging.getLogger(__name__) 22 | 23 | 24 | class Runner(BenchmarkThread): 25 | 26 | def run(self): 27 | futures = queue.Queue(maxsize=121) 28 | 29 | self.start_profile() 30 | 31 | for i in range(self.num_queries): 32 | if i >= 120: 33 | old_future = futures.get_nowait() 34 | old_future.result() 35 | 36 | key = "{}-{}".format(self.thread_num, i) 37 | future = self.run_query(key) 38 | futures.put_nowait(future) 39 | 40 | while True: 41 | try: 42 | futures.get_nowait().result() 43 | except queue.Empty: 44 | break 45 | 46 | self.finish_profile 47 | 48 | 49 | if __name__ == "__main__": 50 | benchmark(Runner) 51 | -------------------------------------------------------------------------------- /docs/api/cassandra/query.rst: -------------------------------------------------------------------------------- 1 | ``cassandra.query`` - Prepared Statements, Batch Statements, Tracing, and Row Factories 2 | ======================================================================================= 3 | 4 | .. module:: cassandra.query 5 | 6 | .. autofunction:: tuple_factory 7 | 8 | .. autofunction:: named_tuple_factory 9 | 10 | .. autofunction:: dict_factory 11 | 12 | .. autofunction:: ordered_dict_factory 13 | 14 | .. autoclass:: SimpleStatement 15 | :members: 16 | 17 | .. autoclass:: PreparedStatement () 18 | :members: 19 | 20 | .. autoclass:: BoundStatement 21 | :members: 22 | 23 | .. autoclass:: Statement () 24 | :members: 25 | 26 | .. autodata:: UNSET_VALUE 27 | :annotation: 28 | 29 | .. autoclass:: BatchStatement (batch_type=BatchType.LOGGED, retry_policy=None, consistency_level=None) 30 | :members: 31 | 32 | .. autoclass:: BatchType () 33 | 34 | .. autoattribute:: LOGGED 35 | 36 | .. autoattribute:: UNLOGGED 37 | 38 | .. autoattribute:: COUNTER 39 | 40 | .. autoclass:: cassandra.query.ValueSequence 41 | 42 | A wrapper class that is used to specify that a sequence of values should 43 | be treated as a CQL list of values instead of a single column collection when used 44 | as part of the `parameters` argument for :meth:`.Session.execute()`. 45 | 46 | This is typically needed when supplying a list of keys to select. 47 | For example:: 48 | 49 | >>> my_user_ids = ('alice', 'bob', 'charles') 50 | >>> query = "SELECT * FROM users WHERE user_id IN %s" 51 | >>> session.execute(query, parameters=[ValueSequence(my_user_ids)]) 52 | 53 | .. autoclass:: QueryTrace () 54 | :members: 55 | 56 | .. autoclass:: TraceEvent () 57 | :members: 58 | 59 | .. autoexception:: TraceUnavailable 60 | -------------------------------------------------------------------------------- /tests/unit/io/eventlet_utils.py: -------------------------------------------------------------------------------- 1 | # Licensed to the Apache Software Foundation (ASF) under one 2 | # or more contributor license agreements. See the NOTICE file 3 | # distributed with this work for additional information 4 | # regarding copyright ownership. The ASF licenses this file 5 | # to you under the Apache License, Version 2.0 (the 6 | # "License"); you may not use this file except in compliance 7 | # with the License. You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | 18 | import os 19 | import select 20 | import socket 21 | try: 22 | import thread 23 | import Queue 24 | import __builtin__ 25 | #For python3 compatibility 26 | except ImportError: 27 | import _thread as thread 28 | import queue as Queue 29 | import builtins as __builtin__ 30 | 31 | import threading 32 | import ssl 33 | import time 34 | import eventlet 35 | from imp import reload 36 | 37 | def eventlet_un_patch_all(): 38 | """ 39 | A method to unpatch eventlet monkey patching used for the reactor tests 40 | """ 41 | 42 | # These are the modules that are loaded by eventlet we reload them all 43 | modules_to_unpatch = [os, select, socket, thread, time, Queue, threading, ssl, __builtin__] 44 | for to_unpatch in modules_to_unpatch: 45 | reload(to_unpatch) 46 | 47 | def restore_saved_module(module): 48 | reload(module) 49 | del eventlet.patcher.already_patched[module.__name__] 50 | 51 | -------------------------------------------------------------------------------- /docs/api/cassandra/cqlengine/query.rst: -------------------------------------------------------------------------------- 1 | ``cassandra.cqlengine.query`` - Query and filter model objects 2 | ================================================================= 3 | 4 | .. module:: cassandra.cqlengine.query 5 | 6 | QuerySet 7 | -------- 8 | QuerySet objects are typically obtained by calling :meth:`~.cassandra.cqlengine.models.Model.objects` on a model class. 9 | The methods here are used to filter, order, and constrain results. 10 | 11 | .. autoclass:: ModelQuerySet 12 | 13 | .. automethod:: all 14 | 15 | .. automethod:: batch 16 | 17 | .. automethod:: consistency 18 | 19 | .. automethod:: count 20 | 21 | .. method:: len(queryset) 22 | 23 | Returns the number of rows matched by this query. This function uses :meth:`~.cassandra.cqlengine.query.ModelQuerySet.count` internally. 24 | 25 | *Note: This function executes a SELECT COUNT() and has a performance cost on large datasets* 26 | 27 | .. automethod:: distinct 28 | 29 | .. automethod:: filter 30 | 31 | .. automethod:: get 32 | 33 | .. automethod:: limit 34 | 35 | .. automethod:: fetch_size 36 | 37 | .. automethod:: if_not_exists 38 | 39 | .. automethod:: if_exists 40 | 41 | .. automethod:: order_by 42 | 43 | .. automethod:: allow_filtering 44 | 45 | .. automethod:: only 46 | 47 | .. automethod:: defer 48 | 49 | .. automethod:: timestamp 50 | 51 | .. automethod:: ttl 52 | 53 | .. automethod:: using 54 | 55 | .. _blind_updates: 56 | 57 | .. automethod:: update 58 | 59 | .. autoclass:: BatchQuery 60 | :members: 61 | 62 | .. automethod:: add_query 63 | .. automethod:: execute 64 | 65 | .. autoclass:: ContextQuery 66 | 67 | .. autoclass:: DoesNotExist 68 | 69 | .. autoclass:: MultipleObjectsReturned 70 | 71 | .. autoclass:: LWTException 72 | -------------------------------------------------------------------------------- /tests/integration/long/ssl/client.key: -------------------------------------------------------------------------------- 1 | -----BEGIN PRIVATE KEY----- 2 | MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCeukTeDyltCfa1 3 | VWJ1fZbDWuH/pggfoQZb2Fcw78XnTpF4yu6/4CWKVzsHaw+kZEMpe6nLbchyl8wh 4 | 734ubvj/K7ulbnWsn+vaMyqD61WIVr8ZDFJAsp0DEMC/AloAzjWSujQMqZybhHB9 5 | gCW26nBzqkLsB8G1PTw8G4MrtZ9o2cVuEYBaQe8xtQs1YAps9aohMdtQS8uBL+4+ 6 | P79bhIeTkZpiTRjaZTdpbKl4M4GoR8pOLZbSLHU7tKk4fJ8DSG9dL0iKUX8dZRG+ 7 | v27Xeae8k17xb66paqVAx3IWxs8IiFtXBXAZhCnKjIGuDPrLlI/BLK6ABvYXxiTd 8 | Sm+offTJAgMBAAECggEAN+VysRx3wy1aEvuRo7xpZjxQD/5BKBpFqfxioBogAFfb 9 | xMT6FNnzfmc/o1ohdQvV1vr0jW4Iw8oPGfhD4Eg2KW4WM6jVicf7f6i7FR+/zDZ4 10 | L3L2WFBOGLFCn0FNvrDfjt9Byx/DxcR69Mc3ANZIaYMQ9Bu7LH73AlfR9oeMLpjL 11 | +6g1qz2yz8Sm2CMCGXTyXtvUCgn2ld6nz8KlZ8FTUG9C9mAabuvV91Ko6rmTxuiv 12 | YKvHSPnIjXRjuC+Ozjf1rYTOJ5LVMNNhlbIKBG/Nx5QzL7bA3XDtMD1BEI9pdHR+ 13 | 5HwA0tV2Ex67tBCJwlBAhYLxuPjfOj1R5KV8wriE3QKBgQDNvqOaGYiXwp9Rajoo 14 | ltlOBPfnjshd9tPdc6tTUQR34vSbkHrg0HVJhvIP5LRbyx/M/8ACQxFkDRE4U7fJ 15 | xVGDs8Pi0FqcqFTnm/AYQ5eZbJkPp9qe71aDOPanncrVNEGFeW26LaeLGbTLrOMM 16 | 6mTmsfGig0MKgml35IMrP+oPuwKBgQDFf56DdaFe08xSK9pDWuKxUuBIagGExQkQ 17 | r9eYasBc336CXh3FWtpSlxl73dqtISh/HbKbv+OZfkVdbmkcTVGlWm/N/XvLqpPK 18 | 86kbKW6PY8FxIY/RxiZANf/JJ5gzPp6VQMJeSy+oepeWj11mTLcT02plvIMM0Jmg 19 | Z5B9Hw37SwKBgDR/59lDmLI47FRnCc4fp/WbmPKSYZhwimFgyZ/p9XzuAcLMXD6P 20 | ks4fTBc4IbmmnEfAHuu013QzTWiVHDm1SvaTYXG3/tcosPmkteBLJxz0NB5lk4io 21 | w+eaGn5s6jv7KJj5gkFWswDwn0y1of5CtVqUn3b7jZjZ7DW2rq3TklNPAoGAIzaW 22 | 56+AfyzaQEhrWRkKVD2HmcG01Zxf+mav1RArjiOXJd1sB3UkehdQxuIOjFHeK5P6 23 | 9YQoK4T1DyyRdydeCFJwntS0TuLyCPyaySoA+XX61pX6U5e12DsIiTATFgfzNH9g 24 | aHmVXL/G6WRUbdn9xn4qeUs8Pnuu+IeenoB7+LMCgYBBnig9nTp81U+SGsNl2D3J 25 | WUz4z+XzEfKU1nq2s4KNjIPB2T1ne+1x3Uso2hagtEHeuEbZoRY4dtCahAvYwrPM 26 | 8wtDFQXWmvFyN3X0Js65GZ++knuseQ1tdlbc/4C+k4u26tVe2GcwhKTjn08++L2E 27 | UB3pLXbssswH271OjD+QkQ== 28 | -----END PRIVATE KEY----- 29 | -------------------------------------------------------------------------------- /tests/unit/cython/utils.py: -------------------------------------------------------------------------------- 1 | # Licensed to the Apache Software Foundation (ASF) under one 2 | # or more contributor license agreements. See the NOTICE file 3 | # distributed with this work for additional information 4 | # regarding copyright ownership. The ASF licenses this file 5 | # to you under the Apache License, Version 2.0 (the 6 | # "License"); you may not use this file except in compliance 7 | # with the License. You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | from cassandra.cython_deps import HAVE_CYTHON, HAVE_NUMPY 18 | try: 19 | from tests import VERIFY_CYTHON 20 | except ImportError: 21 | VERIFY_CYTHON = False 22 | 23 | import unittest 24 | 25 | def cyimport(import_path): 26 | """ 27 | Import a Cython module if available, otherwise return None 28 | (and skip any relevant tests). 29 | """ 30 | if HAVE_CYTHON: 31 | import pyximport 32 | py_importer, pyx_importer = pyximport.install() 33 | mod = __import__(import_path, fromlist=[True]) 34 | pyximport.uninstall(py_importer, pyx_importer) 35 | return mod 36 | 37 | 38 | # @cythontest 39 | # def test_something(self): ... 40 | cythontest = unittest.skipUnless((HAVE_CYTHON or VERIFY_CYTHON) or VERIFY_CYTHON, 'Cython is not available') 41 | notcython = unittest.skipIf(HAVE_CYTHON, 'Cython not supported') 42 | numpytest = unittest.skipUnless((HAVE_CYTHON and HAVE_NUMPY) or VERIFY_CYTHON, 'NumPy is not available') 43 | -------------------------------------------------------------------------------- /tests/integration/long/ssl/client_bad.key: -------------------------------------------------------------------------------- 1 | -----BEGIN PRIVATE KEY----- 2 | MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDha8+NBvpTmTbw 3 | D2EIodXlaaAEtLmXTGoH8pdBm3JxzMuUEkYbGig3YjQ1BAKQgCB1TJGPINcHz7Jo 4 | 5aW5To1jrxhhohZYQLCNKlAONDhgJbHEPf7s8dreQ/q5ISt/2I3z68c9I0j3VoRz 5 | AxxcNktl/x+6YkXe9tXf/LWmJk/gHlu72/HuJ5oNyqOKaCCoMoib3jLTlR+lslTy 6 | Qy/CJZH6WJabLOPmppFLaxJMlSGDSTE/Xktt7+H5ssHnfQtyWyylVjZkzChJfBgh 7 | HrLpm3hO5rmqVwOhoKLKVDFMmX3aMGX2S+3KpXQ8gLnPXwfLI9J9fDg5jp7bya4k 8 | OXlZfB5hAgMBAAECggEBANQVFbmudfgPL4PeREHV2SM1JCspSW9SonOFxs8gDCWL 9 | M4HFS5YWHv40c7/pXOxMz7zsZApQMF8WBtnwLeJRSG8f/oVk9Tbk7fZyd81VTjEP 10 | ZdenKGAPEAeL16kzzvRCbxOtoc8gkna6PHTk2VrcbkWxKU23RduHSiOpY9HFO+Mz 11 | iI69tB7657NOiZCQ6xDIjKv+jR63m7VAWKT5jkN+tYpvx4K20na5t8RO1s0shqNE 12 | e2zMG8WXVl6lW4btfkt/lwWUNXu8olMTk9qN2b5Rq7BEJfKwn3lb9vCpUMyewtRB 13 | /8U+Zu7Tlwni5QagOqAUEkjuOJ8cR/Jgwu1mqV2sXxECgYEA9zXi0PjWAe2ZIALd 14 | 1iWPZCvvT7yEjt4ulhAYPqi8T38B4K5f//m5SuYPS2ebmSAd2WBTeIX2A6mHc9lk 15 | 53gnwvsgAqaFgjYeDqBThpCE8icFXEZnJbtnJyC8zC7pYjUovAHkFEdLw5kQoI6Y 16 | i9HNOS9ugSut8RnF0oSv/E2mahUCgYEA6W+ZAEneBBCsOQclVfVPLm7D+y+5SZEt 17 | zWr2b7CCnGCev/qRCllIEwQ2+W1ACEHof9xjE+aWwEQjX8YnoVbAJo2ru6FFQfI+ 18 | f/SQx7beX8jUAeJGo+CFr2ijdVmcCCbMGeAm8mpACUIQfWPHVqjtGS/CayxdfwA+ 19 | lbWPbkXCMh0CgYBfUgHRPgGW4LyoYTKUfgsaPu6ZukEKrZUc+7u9fWaO6JQaxGHz 20 | 26CcxrSjCKIwmvend8L3t/+yTc4S14JW1jfOsPIY04irOp7AWQWb32HD1VP1zpe7 21 | LtWJetARkw0edwzr4XbGcu89zmlg31rmntEY+bcMS4FYc+2ZTNxm1rISOQKBgGQZ 22 | lct44Xpux9tghBMbMUwg9WtWKKcyWSi4EFsOnsN97zU1tlJwvKZi7UwCHC4uTQvf 23 | LqFPBSAHV//u0fmuYJFnuNeprTA9N63Y6uipMyxxyu/P3yjQ06LHRSjCN1WLhYQn 24 | Cax0AWe266lJSyaPI7TkNQOOL72RFkVOaOYJhd/FAoGAPtpVPTiVK0RYwLnZqaWB 25 | fxyI6w+UjOEbP88vD7N7FEI2kQSGQ6F3pMzDK37NglJVtwjgzEIF9x9BIE8XSf16 26 | shc0U73Vg9ZsXDNPUz21hhAwYL1cCgnx0mfL88F1Icb5FfxlT/1BPHNHKowA9vST 27 | ihbxCJg/JJBzwXTxPocQisk= 28 | -----END PRIVATE KEY----- 29 | -------------------------------------------------------------------------------- /tests/integration/long/test_topology_change.py: -------------------------------------------------------------------------------- 1 | from unittest import TestCase 2 | 3 | from cassandra.policies import HostStateListener 4 | from tests.integration import get_node, use_cluster, local, TestCluster 5 | from tests.integration.long.utils import decommission 6 | from tests.util import wait_until 7 | 8 | 9 | class StateListener(HostStateListener): 10 | def __init__(self): 11 | self.downed_host = None 12 | self.removed_host = None 13 | 14 | def on_remove(self, host): 15 | self.removed_host = host 16 | 17 | def on_up(self, host): 18 | pass 19 | 20 | def on_down(self, host): 21 | self.downed_host = host 22 | 23 | def on_add(self, host): 24 | pass 25 | 26 | 27 | class TopologyChangeTests(TestCase): 28 | @local 29 | def test_removed_node_stops_reconnecting(self): 30 | """ Ensure we stop reconnecting after a node is removed. PYTHON-1181 """ 31 | use_cluster("test_down_then_removed", [3], start=True) 32 | 33 | state_listener = StateListener() 34 | cluster = TestCluster() 35 | self.addCleanup(cluster.shutdown) 36 | cluster.register_listener(state_listener) 37 | session = cluster.connect(wait_for_all_pools=True) 38 | 39 | get_node(3).nodetool("disablebinary") 40 | 41 | wait_until(condition=lambda: state_listener.downed_host is not None, delay=2, max_attempts=50) 42 | self.assertTrue(state_listener.downed_host.is_currently_reconnecting()) 43 | 44 | decommission(3) 45 | 46 | wait_until(condition=lambda: state_listener.removed_host is not None, delay=2, max_attempts=50) 47 | self.assertIs(state_listener.downed_host, state_listener.removed_host) # Just a sanity check 48 | self.assertFalse(state_listener.removed_host.is_currently_reconnecting()) 49 | -------------------------------------------------------------------------------- /tests/integration/long/ssl/client_encrypted.key: -------------------------------------------------------------------------------- 1 | -----BEGIN RSA PRIVATE KEY----- 2 | Proc-Type: 4,ENCRYPTED 3 | DEK-Info: AES-256-CBC,7288A409E846EBE2DE421B77598DAF98 4 | 5 | ahiUSf+k9POIEUJb5BGbQ6knk4+FtTz+e+6fouqVc4Lq+RXR9f0pFBi9eDEkFNiN 6 | AcUjLkxh+3TmihTZJprqXSbQ3jacwbnwDOFgtZE3PxoA1heHxADaKCNr+Ph0lC/T 7 | 3cIzsoIZ6slk+3n6ERieZRdmvoMH1SY8nXKT5+bLMR4RIjw1y7h26MRhjQS+lXaX 8 | Asd5EOGROCIgefeEBGHAbrlg0FoHy7slqVBxuZphTHKtyK/VK4fRLt6doUzBu5GJ 9 | T2jdrqJCWr5PRn3bAqMemJWxDhZLX4DyNDQPn8riZ8jMbwPOVUSnF8B8re1tNkQ0 10 | CsH77sYIIjmPdizCdvj91+jH6o7MRCZPvky+PHG/9G5WsPiw5W1i/nrPemT1XJyy 11 | oPRc/fMFfbHmW3HCGqgv2/6Wg+17un/a6UyzXsbNdhDZLCVqtAQ7PSv83z5oUazT 12 | djzFHgxSqRknUY0lOUvP8Rni67MG+Rcksj9HgszhLoC0be64IX0Ey5oc5+pBYrf9 13 | FVEPsuyyu4aDSRYYATC2E1V/EQRwcvpKEZNFTbqMpQhjrWtlBM/GgQnQBeQdLAGX 14 | yefDSzkH31y5gcdgHLElriWwbHHbcaAmf3e15W94YHgTytJBsQ9A19SmtmgUmo4h 15 | jaFoUooM5mFA8hc/snSe2PdkEefkzS72g8qxa//61LTJAAkVk43dYjoqQ34wq6WR 16 | OB4nn/W2xlfv/ClZJTWf8YvQTrQptJY5VQq/TTEcrXy67Uc0wRHXZK2rTjKeyRj9 17 | 65SkyyXhMopWEl2vX25ReITVfdJ0FgjqI/ugYSf25iOfJtsk+jgrtrswZ+8F2eMq 18 | iAQ+0JSiYmlot2Pn1QCalLjtTz8zeMfXPyo5fbKNMdp52U1cPYld90kUGHZfjqju 19 | GmY/aHa6N8lZGxj8SC/JM36GawaGKe4S/F5BetYJOpaEzkpowqlTC8Syv529rm46 20 | vvgf+EJL8gRvdtnIEe/qtzbtel299VhaBpuOcApfTDSxRHZmvkCpdHo9I3KgOZB9 21 | Cqu9Bz+FiJmTk8rGQwmI8EYj38jneEoqA+fN7tUkzxCGacg+x6ke4nOcJzgBhd94 22 | 8DvGclrcAwBY1mlNYRceFJKFXhwLZTKBojZlS8Q9863EAH3DOBLeP85V3YvBD/MK 23 | O+kzPoxN/jPVNho7y4gL7skcqe/IXePzPxBcZrHJjoU7mGVDcVcouRj16XSezMbB 24 | 5Pft0/gGiItRJ2+v9DlPjzDfjTuRdS78muaZ4nNqX6B+JmyPJtkb2CdiHz6B21RO 25 | 3hjGrffM1nhmYBegyjTVc88IxzYg0T8CZLq1FYxuTZmwyahA520IpwsbfwXxLVMU 26 | 5rmou5dj1pVlvoP3l+ivPqugeY3k7UjZ33m5H9p009JR40dybr1S2RbI8Gqhe953 27 | 0bedA4DWvPakODXgYu43al92uR/tyjazeB5t7Iu8uB5Xcm3/Mqoofe9xtdQSCWa0 28 | jKKvXzSpL1MM2C0bRyYHIkVR65K7Zmi/BzvTaPECo1+Uv+EwqRZRyBzUZKPP8LMq 29 | jTCOBmYaK8+0dTRk8MEzrPW2ihVVJYVMmFyTZKW0iK7kOMKZRkhDCaNSUlPEty7j 30 | -----END RSA PRIVATE KEY----- 31 | -------------------------------------------------------------------------------- /benchmarks/future_batches.py: -------------------------------------------------------------------------------- 1 | # Licensed to the Apache Software Foundation (ASF) under one 2 | # or more contributor license agreements. See the NOTICE file 3 | # distributed with this work for additional information 4 | # regarding copyright ownership. The ASF licenses this file 5 | # to you under the Apache License, Version 2.0 (the 6 | # "License"); you may not use this file except in compliance 7 | # with the License. You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | import logging 18 | from base import benchmark, BenchmarkThread 19 | import queue 20 | 21 | log = logging.getLogger(__name__) 22 | 23 | 24 | class Runner(BenchmarkThread): 25 | 26 | def run(self): 27 | futures = queue.Queue(maxsize=121) 28 | 29 | self.start_profile() 30 | 31 | for i in range(self.num_queries): 32 | if i > 0 and i % 120 == 0: 33 | # clear the existing queue 34 | while True: 35 | try: 36 | futures.get_nowait().result() 37 | except queue.Empty: 38 | break 39 | 40 | key = "{0}-{1}".format(self.thread_num, i) 41 | future = self.run_query(key) 42 | futures.put_nowait(future) 43 | 44 | while True: 45 | try: 46 | futures.get_nowait().result() 47 | except queue.Empty: 48 | break 49 | 50 | self.finish_profile() 51 | 52 | 53 | if __name__ == "__main__": 54 | benchmark(Runner) 55 | -------------------------------------------------------------------------------- /tests/stress_tests/test_load.py: -------------------------------------------------------------------------------- 1 | # Licensed to the Apache Software Foundation (ASF) under one 2 | # or more contributor license agreements. See the NOTICE file 3 | # distributed with this work for additional information 4 | # regarding copyright ownership. The ASF licenses this file 5 | # to you under the Apache License, Version 2.0 (the 6 | # "License"); you may not use this file except in compliance 7 | # with the License. You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | import unittest 17 | 18 | import gc 19 | 20 | from cassandra.cqlengine import columns 21 | from cassandra.cqlengine.models import Model 22 | from cassandra.cqlengine.management import sync_table 23 | 24 | from tests.integration.cqlengine.base import BaseCassEngTestCase 25 | 26 | 27 | class LoadTests(BaseCassEngTestCase): 28 | 29 | def test_lots_of_queries(self): 30 | import resource 31 | import objgraph 32 | 33 | class LoadTest(Model): 34 | k = columns.Integer(primary_key=True) 35 | v = columns.Integer() 36 | 37 | sync_table(LoadTest) 38 | gc.collect() 39 | objgraph.show_most_common_types() 40 | 41 | print("Starting...") 42 | 43 | for i in range(1000000): 44 | if i % 25000 == 0: 45 | # print memory statistic 46 | print("Memory usage: %s" % (resource.getrusage(resource.RUSAGE_SELF).ru_maxrss)) 47 | 48 | LoadTest.create(k=i, v=i) 49 | 50 | objgraph.show_most_common_types() 51 | 52 | raise Exception("you shouldn't be here") 53 | -------------------------------------------------------------------------------- /tests/integration/cqlengine/statements/test_where_clause.py: -------------------------------------------------------------------------------- 1 | # Licensed to the Apache Software Foundation (ASF) under one 2 | # or more contributor license agreements. See the NOTICE file 3 | # distributed with this work for additional information 4 | # regarding copyright ownership. The ASF licenses this file 5 | # to you under the Apache License, Version 2.0 (the 6 | # "License"); you may not use this file except in compliance 7 | # with the License. You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | import unittest 17 | 18 | from cassandra.cqlengine.operators import EqualsOperator 19 | from cassandra.cqlengine.statements import StatementException, WhereClause 20 | 21 | 22 | class TestWhereClause(unittest.TestCase): 23 | 24 | def test_operator_check(self): 25 | """ tests that creating a where statement with a non BaseWhereOperator object fails """ 26 | with self.assertRaises(StatementException): 27 | WhereClause('a', 'b', 'c') 28 | 29 | def test_where_clause_rendering(self): 30 | """ tests that where clauses are rendered properly """ 31 | wc = WhereClause('a', EqualsOperator(), 'c') 32 | wc.set_context_id(5) 33 | 34 | self.assertEqual('"a" = %(5)s', str(wc), str(wc)) 35 | self.assertEqual('"a" = %(5)s', str(wc), type(wc)) 36 | 37 | def test_equality_method(self): 38 | """ tests that 2 identical where clauses evaluate as == """ 39 | wc1 = WhereClause('a', EqualsOperator(), 'c') 40 | wc2 = WhereClause('a', EqualsOperator(), 'c') 41 | assert wc1 == wc2 42 | -------------------------------------------------------------------------------- /docs/api/cassandra/metadata.rst: -------------------------------------------------------------------------------- 1 | ``cassandra.metadata`` - Schema and Ring Topology 2 | ================================================= 3 | 4 | .. module:: cassandra.metadata 5 | 6 | .. autodata:: cql_keywords 7 | :annotation: 8 | 9 | .. autodata:: cql_keywords_unreserved 10 | :annotation: 11 | 12 | .. autodata:: cql_keywords_reserved 13 | :annotation: 14 | 15 | .. autoclass:: Metadata () 16 | :members: 17 | :exclude-members: rebuild_schema, rebuild_token_map, add_host, remove_host 18 | 19 | Schemas 20 | ------- 21 | 22 | .. autoclass:: KeyspaceMetadata () 23 | :members: 24 | 25 | .. autoclass:: UserType () 26 | :members: 27 | 28 | .. autoclass:: Function () 29 | :members: 30 | 31 | .. autoclass:: Aggregate () 32 | :members: 33 | 34 | .. autoclass:: TableMetadata () 35 | :members: 36 | 37 | .. autoclass:: TableMetadataV3 () 38 | :members: 39 | 40 | .. autoclass:: TableMetadataDSE68 () 41 | :members: 42 | 43 | .. autoclass:: ColumnMetadata () 44 | :members: 45 | 46 | .. autoclass:: IndexMetadata () 47 | :members: 48 | 49 | .. autoclass:: MaterializedViewMetadata () 50 | :members: 51 | 52 | .. autoclass:: VertexMetadata () 53 | :members: 54 | 55 | .. autoclass:: EdgeMetadata () 56 | :members: 57 | 58 | Tokens and Ring Topology 59 | ------------------------ 60 | 61 | .. autoclass:: TokenMap () 62 | :members: 63 | 64 | .. autoclass:: Token () 65 | :members: 66 | 67 | .. autoclass:: Murmur3Token 68 | :members: 69 | 70 | .. autoclass:: MD5Token 71 | :members: 72 | 73 | .. autoclass:: BytesToken 74 | :members: 75 | 76 | .. autoclass:: ReplicationStrategy 77 | :members: 78 | 79 | .. autoclass:: ReplicationFactor 80 | :members: 81 | :exclude-members: create 82 | 83 | .. autoclass:: SimpleStrategy 84 | :members: 85 | 86 | .. autoclass:: NetworkTopologyStrategy 87 | :members: 88 | 89 | .. autoclass:: LocalStrategy 90 | :members: 91 | 92 | .. autofunction:: group_keys_by_replica 93 | -------------------------------------------------------------------------------- /cassandra/tuple.pxd: -------------------------------------------------------------------------------- 1 | # Licensed to the Apache Software Foundation (ASF) under one 2 | # or more contributor license agreements. See the NOTICE file 3 | # distributed with this work for additional information 4 | # regarding copyright ownership. The ASF licenses this file 5 | # to you under the Apache License, Version 2.0 (the 6 | # "License"); you may not use this file except in compliance 7 | # with the License. You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | from cpython.tuple cimport ( 18 | PyTuple_New, 19 | # Return value: New reference. 20 | # Return a new tuple object of size len, or NULL on failure. 21 | PyTuple_SET_ITEM, 22 | # Like PyTuple_SetItem(), but does no error checking, and should 23 | # only be used to fill in brand new tuples. Note: This function 24 | # ``steals'' a reference to o. 25 | ) 26 | 27 | from cpython.ref cimport ( 28 | Py_INCREF 29 | # void Py_INCREF(object o) 30 | # Increment the reference count for object o. The object must not 31 | # be NULL; if you aren't sure that it isn't NULL, use 32 | # Py_XINCREF(). 33 | ) 34 | 35 | cdef inline tuple tuple_new(Py_ssize_t n): 36 | """Allocate a new tuple object""" 37 | return PyTuple_New(n) 38 | 39 | cdef inline void tuple_set(tuple tup, Py_ssize_t idx, object item): 40 | """Insert new object into tuple. No item must have been set yet.""" 41 | # PyTuple_SET_ITEM steals a reference, so we need to INCREF 42 | Py_INCREF(item) 43 | PyTuple_SET_ITEM(tup, idx, item) 44 | -------------------------------------------------------------------------------- /cassandra/parsing.pyx: -------------------------------------------------------------------------------- 1 | # Licensed to the Apache Software Foundation (ASF) under one 2 | # or more contributor license agreements. See the NOTICE file 3 | # distributed with this work for additional information 4 | # regarding copyright ownership. The ASF licenses this file 5 | # to you under the Apache License, Version 2.0 (the 6 | # "License"); you may not use this file except in compliance 7 | # with the License. You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | """ 18 | Module containing the definitions and declarations (parsing.pxd) for parsers. 19 | """ 20 | 21 | cdef class ParseDesc: 22 | """Description of what structure to parse""" 23 | 24 | def __init__(self, colnames, coltypes, column_encryption_policy, coldescs, deserializers, protocol_version): 25 | self.colnames = colnames 26 | self.coltypes = coltypes 27 | self.column_encryption_policy = column_encryption_policy 28 | self.coldescs = coldescs 29 | self.deserializers = deserializers 30 | self.protocol_version = protocol_version 31 | self.rowsize = len(colnames) 32 | 33 | 34 | cdef class ColumnParser: 35 | """Decode a ResultMessage into a set of columns""" 36 | 37 | cpdef parse_rows(self, BytesIOReader reader, ParseDesc desc): 38 | raise NotImplementedError 39 | 40 | 41 | cdef class RowParser: 42 | """Parser for a single row""" 43 | 44 | cpdef unpack_row(self, BytesIOReader reader, ParseDesc desc): 45 | """ 46 | Unpack a single row of data in a ResultMessage. 47 | """ 48 | raise NotImplementedError 49 | -------------------------------------------------------------------------------- /tests/unit/cython/bytesio_testhelper.pyx: -------------------------------------------------------------------------------- 1 | # Licensed to the Apache Software Foundation (ASF) under one 2 | # or more contributor license agreements. See the NOTICE file 3 | # distributed with this work for additional information 4 | # regarding copyright ownership. The ASF licenses this file 5 | # to you under the Apache License, Version 2.0 (the 6 | # "License"); you may not use this file except in compliance 7 | # with the License. You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | from cassandra.bytesio cimport BytesIOReader 18 | 19 | def test_read1(assert_equal, assert_raises): 20 | cdef BytesIOReader reader = BytesIOReader(b'abcdef') 21 | assert_equal(reader.read(2)[:2], b'ab') 22 | assert_equal(reader.read(2)[:2], b'cd') 23 | assert_equal(reader.read(0)[:0], b'') 24 | assert_equal(reader.read(2)[:2], b'ef') 25 | 26 | def test_read2(assert_equal, assert_raises): 27 | cdef BytesIOReader reader = BytesIOReader(b'abcdef') 28 | reader.read(5) 29 | reader.read(1) 30 | 31 | def test_read3(assert_equal, assert_raises): 32 | cdef BytesIOReader reader = BytesIOReader(b'abcdef') 33 | reader.read(6) 34 | 35 | def test_read_eof(assert_equal, assert_raises): 36 | cdef BytesIOReader reader = BytesIOReader(b'abcdef') 37 | reader.read(5) 38 | # cannot convert reader.read to an object, do it manually 39 | # assert_raises(EOFError, reader.read, 2) 40 | try: 41 | reader.read(2) 42 | except EOFError: 43 | pass 44 | else: 45 | raise Exception("Expected an EOFError") 46 | reader.read(1) # see that we can still read this 47 | -------------------------------------------------------------------------------- /tests/unit/advanced/test_auth.py: -------------------------------------------------------------------------------- 1 | # Licensed to the Apache Software Foundation (ASF) under one 2 | # or more contributor license agreements. See the NOTICE file 3 | # distributed with this work for additional information 4 | # regarding copyright ownership. The ASF licenses this file 5 | # to you under the Apache License, Version 2.0 (the 6 | # "License"); you may not use this file except in compliance 7 | # with the License. You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | import os 18 | from puresasl import QOP 19 | 20 | import unittest 21 | 22 | from cassandra.auth import DSEGSSAPIAuthProvider 23 | 24 | # Cannot import requiredse from tests.integration 25 | # This auth provider requires kerberos and puresals 26 | DSE_VERSION = os.getenv('DSE_VERSION', None) 27 | @unittest.skipUnless(DSE_VERSION, "DSE required") 28 | class TestGSSAPI(unittest.TestCase): 29 | 30 | def test_host_resolution(self): 31 | # resolves by default 32 | provider = DSEGSSAPIAuthProvider(service='test', qops=QOP.all) 33 | authenticator = provider.new_authenticator('127.0.0.1') 34 | self.assertEqual(authenticator.sasl.host, 'localhost') 35 | 36 | # numeric fallback okay 37 | authenticator = provider.new_authenticator('192.0.2.1') 38 | self.assertEqual(authenticator.sasl.host, '192.0.2.1') 39 | 40 | # disable explicitly 41 | provider = DSEGSSAPIAuthProvider(service='test', qops=QOP.all, resolve_host_name=False) 42 | authenticator = provider.new_authenticator('127.0.0.1') 43 | self.assertEqual(authenticator.sasl.host, '127.0.0.1') 44 | 45 | -------------------------------------------------------------------------------- /docs/geo_types.rst: -------------------------------------------------------------------------------- 1 | DSE Geometry Types 2 | ================== 3 | This section shows how to query and work with the geometric types provided by DSE. 4 | 5 | These types are enabled implicitly by creating the Session from :class:`cassandra.cluster.Cluster`. 6 | This module implicitly registers these types for use in the driver. This extension provides 7 | some simple representative types in :mod:`cassandra.util` for inserting and retrieving data:: 8 | 9 | from cassandra.cluster import Cluster 10 | from cassandra.util import Point, LineString, Polygon 11 | session = Cluster().connect() 12 | 13 | session.execute("INSERT INTO ks.geo (k, point, line, poly) VALUES (%s, %s, %s, %s)", 14 | 0, Point(1, 2), LineString(((1, 2), (3, 4))), Polygon(((1, 2), (3, 4), (5, 6)))) 15 | 16 | Queries returning geometric types return the :mod:`dse.util` types. Note that these can easily be used to construct 17 | types from third-party libraries using the common attributes:: 18 | 19 | from shapely.geometry import LineString 20 | shapely_linestrings = [LineString(res.line.coords) for res in session.execute("SELECT line FROM ks.geo")] 21 | 22 | For prepared statements, shapely geometry types can be used interchangeably with the built-in types because their 23 | defining attributes are the same:: 24 | 25 | from shapely.geometry import Point 26 | prepared = session.prepare("UPDATE ks.geo SET point = ? WHERE k = ?") 27 | session.execute(prepared, (0, Point(1.2, 3.4))) 28 | 29 | In order to use shapely types in a CQL-interpolated (non-prepared) query, one must update the encoder with those types, specifying 30 | the same string encoder as set for the internal types:: 31 | 32 | from cassandra import util 33 | from shapely.geometry import Point, LineString, Polygon 34 | 35 | encoder_func = session.encoder.mapping[util.Point] 36 | for t in (Point, LineString, Polygon): 37 | session.encoder.mapping[t] = encoder_func 38 | 39 | session.execute("UPDATE ks.geo SET point = %s where k = %s", (0, Point(1.2, 3.4))) 40 | -------------------------------------------------------------------------------- /cassandra/ioutils.pyx: -------------------------------------------------------------------------------- 1 | # Licensed to the Apache Software Foundation (ASF) under one 2 | # or more contributor license agreements. See the NOTICE file 3 | # distributed with this work for additional information 4 | # regarding copyright ownership. The ASF licenses this file 5 | # to you under the Apache License, Version 2.0 (the 6 | # "License"); you may not use this file except in compliance 7 | # with the License. You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | include 'cython_marshal.pyx' 18 | from cassandra.buffer cimport Buffer, from_ptr_and_size 19 | 20 | from libc.stdint cimport int32_t 21 | from cassandra.bytesio cimport BytesIOReader 22 | 23 | 24 | cdef inline int get_buf(BytesIOReader reader, Buffer *buf_out) except -1: 25 | """ 26 | Get a pointer into the buffer provided by BytesIOReader for the 27 | next data item in the stream of values. 28 | 29 | BEWARE: 30 | If the next item has a zero negative size, the pointer will be set to NULL. 31 | A negative size happens when the value is NULL in the database, whereas a 32 | zero size may happen either for legacy reasons, or for data types such as 33 | strings (which may be empty). 34 | """ 35 | cdef Py_ssize_t raw_val_size = read_int(reader) 36 | cdef char *ptr 37 | if raw_val_size <= 0: 38 | ptr = NULL 39 | else: 40 | ptr = reader.read(raw_val_size) 41 | 42 | from_ptr_and_size(ptr, raw_val_size, buf_out) 43 | return 0 44 | 45 | cdef inline int32_t read_int(BytesIOReader reader) except ?0xDEAD: 46 | cdef Buffer buf 47 | buf.ptr = reader.read(4) 48 | buf.size = 4 49 | return unpack_num[int32_t](&buf) 50 | -------------------------------------------------------------------------------- /cassandra/deserializers.pxd: -------------------------------------------------------------------------------- 1 | # Licensed to the Apache Software Foundation (ASF) under one 2 | # or more contributor license agreements. See the NOTICE file 3 | # distributed with this work for additional information 4 | # regarding copyright ownership. The ASF licenses this file 5 | # to you under the Apache License, Version 2.0 (the 6 | # "License"); you may not use this file except in compliance 7 | # with the License. You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | from cassandra.buffer cimport Buffer 18 | 19 | cdef class Deserializer: 20 | # The cqltypes._CassandraType corresponding to this deserializer 21 | cdef object cqltype 22 | 23 | # String may be empty, whereas other values may not be. 24 | # Other values may be NULL, in which case the integer length 25 | # of the binary data is negative. However, non-string types 26 | # may also return a zero length for legacy reasons 27 | # (see http://code.metager.de/source/xref/apache/cassandra/doc/native_protocol_v3.spec 28 | # paragraph 6) 29 | cdef bint empty_binary_ok 30 | 31 | cdef deserialize(self, Buffer *buf, int protocol_version) 32 | # cdef deserialize(self, CString byts, protocol_version) 33 | 34 | 35 | cdef inline object from_binary(Deserializer deserializer, 36 | Buffer *buf, 37 | int protocol_version): 38 | if buf.size < 0: 39 | return None 40 | elif buf.size == 0 and not deserializer.empty_binary_ok: 41 | return _ret_empty(deserializer, buf.size) 42 | else: 43 | return deserializer.deserialize(buf, protocol_version) 44 | 45 | cdef _ret_empty(Deserializer deserializer, Py_ssize_t buf_size) 46 | -------------------------------------------------------------------------------- /cassandra/bytesio.pyx: -------------------------------------------------------------------------------- 1 | # Licensed to the Apache Software Foundation (ASF) under one 2 | # or more contributor license agreements. See the NOTICE file 3 | # distributed with this work for additional information 4 | # regarding copyright ownership. The ASF licenses this file 5 | # to you under the Apache License, Version 2.0 (the 6 | # "License"); you may not use this file except in compliance 7 | # with the License. You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | cdef class BytesIOReader: 18 | """ 19 | This class provides efficient support for reading bytes from a 'bytes' buffer, 20 | by returning char * values directly without allocating intermediate objects. 21 | """ 22 | 23 | def __init__(self, bytes buf): 24 | self.buf = buf 25 | self.size = len(buf) 26 | self.buf_ptr = self.buf 27 | 28 | cdef char *read(self, Py_ssize_t n = -1) except NULL: 29 | """Read at most size bytes from the file 30 | (less if the read hits EOF before obtaining size bytes). 31 | 32 | If the size argument is negative or omitted, read all data until EOF 33 | is reached. The bytes are returned as a string object. An empty 34 | string is returned when EOF is encountered immediately. 35 | """ 36 | cdef Py_ssize_t newpos = self.pos + n 37 | if n < 0: 38 | newpos = self.size 39 | elif newpos > self.size: 40 | # Raise an error here, as we do not want the caller to consume past the 41 | # end of the buffer 42 | raise EOFError("Cannot read past the end of the file") 43 | 44 | cdef char *res = self.buf_ptr + self.pos 45 | self.pos = newpos 46 | return res 47 | -------------------------------------------------------------------------------- /docs/cqlengine/third_party.rst: -------------------------------------------------------------------------------- 1 | ======================== 2 | Third party integrations 3 | ======================== 4 | 5 | 6 | Celery 7 | ------ 8 | 9 | Here's how, in substance, CQLengine can be plugged to `Celery 10 | `_: 11 | 12 | .. code-block:: python 13 | 14 | from celery import Celery 15 | from celery.signals import worker_process_init, beat_init 16 | from cassandra.cqlengine import connection 17 | from cassandra.cqlengine.connection import ( 18 | cluster as cql_cluster, session as cql_session) 19 | 20 | def cassandra_init(**kwargs): 21 | """ Initialize a clean Cassandra connection. """ 22 | if cql_cluster is not None: 23 | cql_cluster.shutdown() 24 | if cql_session is not None: 25 | cql_session.shutdown() 26 | connection.setup() 27 | 28 | # Initialize worker context for both standard and periodic tasks. 29 | worker_process_init.connect(cassandra_init) 30 | beat_init.connect(cassandra_init) 31 | 32 | app = Celery() 33 | 34 | 35 | uWSGI 36 | ----- 37 | 38 | This is the code required for proper connection handling of CQLengine for a 39 | `uWSGI `_-run application: 40 | 41 | .. code-block:: python 42 | 43 | from cassandra.cqlengine import connection 44 | from cassandra.cqlengine.connection import ( 45 | cluster as cql_cluster, session as cql_session) 46 | 47 | try: 48 | from uwsgidecorators import postfork 49 | except ImportError: 50 | # We're not in a uWSGI context, no need to hook Cassandra session 51 | # initialization to the postfork event. 52 | pass 53 | else: 54 | @postfork 55 | def cassandra_init(**kwargs): 56 | """ Initialize a new Cassandra session in the context. 57 | 58 | Ensures that a new session is returned for every new request. 59 | """ 60 | if cql_cluster is not None: 61 | cql_cluster.shutdown() 62 | if cql_session is not None: 63 | cql_session.shutdown() 64 | connection.setup() 65 | -------------------------------------------------------------------------------- /tests/integration/standard/utils.py: -------------------------------------------------------------------------------- 1 | """ 2 | Helper module to populate a dummy Cassandra tables with data. 3 | """ 4 | 5 | from tests.integration.datatype_utils import PRIMITIVE_DATATYPES, get_sample 6 | 7 | 8 | def create_table_with_all_types(table_name, session, N): 9 | """ 10 | Method that given a table_name and session construct a table that contains 11 | all possible primitive types. 12 | 13 | :param table_name: Name of table to create 14 | :param session: session to use for table creation 15 | :param N: the number of items to insert into the table 16 | 17 | :return: a list of column names 18 | """ 19 | # create table 20 | alpha_type_list = ["primkey int PRIMARY KEY"] 21 | col_names = ["primkey"] 22 | start_index = ord('a') 23 | for i, datatype in enumerate(PRIMITIVE_DATATYPES): 24 | alpha_type_list.append("{0} {1}".format(chr(start_index + i), datatype)) 25 | col_names.append(chr(start_index + i)) 26 | 27 | session.execute("CREATE TABLE {0} ({1})".format( 28 | table_name, ', '.join(alpha_type_list)), timeout=120) 29 | 30 | # create the input 31 | 32 | for key in range(N): 33 | params = get_all_primitive_params(key) 34 | 35 | # insert into table as a simple statement 36 | columns_string = ', '.join(col_names) 37 | placeholders = ', '.join(["%s"] * len(col_names)) 38 | session.execute("INSERT INTO {0} ({1}) VALUES ({2})".format( 39 | table_name, columns_string, placeholders), params, timeout=120) 40 | return col_names 41 | 42 | 43 | def get_all_primitive_params(key): 44 | """ 45 | Simple utility method used to give back a list of all possible primitive data sample types. 46 | """ 47 | params = [key] 48 | for datatype in PRIMITIVE_DATATYPES: 49 | # Also test for empty strings 50 | if key == 1 and datatype == 'ascii': 51 | params.append('') 52 | else: 53 | params.append(get_sample(datatype)) 54 | return params 55 | 56 | 57 | def get_primitive_datatypes(): 58 | return ['int'] + list(PRIMITIVE_DATATYPES) 59 | -------------------------------------------------------------------------------- /tests/integration/standard/test_authentication_misconfiguration.py: -------------------------------------------------------------------------------- 1 | # Licensed to the Apache Software Foundation (ASF) under one 2 | # or more contributor license agreements. See the NOTICE file 3 | # distributed with this work for additional information 4 | # regarding copyright ownership. The ASF licenses this file 5 | # to you under the Apache License, Version 2.0 (the 6 | # "License"); you may not use this file except in compliance 7 | # with the License. You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | import unittest 18 | 19 | from tests.integration import USE_CASS_EXTERNAL, use_cluster, TestCluster 20 | 21 | 22 | class MisconfiguredAuthenticationTests(unittest.TestCase): 23 | """ One node (not the contact point) has password auth. The rest of the nodes have no auth """ 24 | @classmethod 25 | def setUpClass(cls): 26 | if not USE_CASS_EXTERNAL: 27 | ccm_cluster = use_cluster(cls.__name__, [3], start=False) 28 | node3 = ccm_cluster.nodes['node3'] 29 | node3.set_configuration_options(values={ 30 | 'authenticator': 'PasswordAuthenticator', 31 | 'authorizer': 'CassandraAuthorizer', 32 | }) 33 | ccm_cluster.start(wait_for_binary_proto=True) 34 | 35 | cls.ccm_cluster = ccm_cluster 36 | 37 | def test_connect_no_auth_provider(self): 38 | cluster = TestCluster() 39 | cluster.connect() 40 | cluster.refresh_nodes() 41 | down_hosts = [host for host in cluster.metadata.all_hosts() if not host.is_up] 42 | self.assertEqual(len(down_hosts), 1) 43 | cluster.shutdown() 44 | 45 | @classmethod 46 | def tearDownClass(cls): 47 | if not USE_CASS_EXTERNAL: 48 | cls.ccm_cluster.stop() 49 | -------------------------------------------------------------------------------- /tests/integration/cqlengine/statements/test_insert_statement.py: -------------------------------------------------------------------------------- 1 | # Licensed to the Apache Software Foundation (ASF) under one 2 | # or more contributor license agreements. See the NOTICE file 3 | # distributed with this work for additional information 4 | # regarding copyright ownership. The ASF licenses this file 5 | # to you under the Apache License, Version 2.0 (the 6 | # "License"); you may not use this file except in compliance 7 | # with the License. You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | import unittest 17 | 18 | from cassandra.cqlengine.columns import Column 19 | from cassandra.cqlengine.statements import InsertStatement 20 | 21 | 22 | class InsertStatementTests(unittest.TestCase): 23 | 24 | def test_statement(self): 25 | ist = InsertStatement('table', None) 26 | ist.add_assignment(Column(db_field='a'), 'b') 27 | ist.add_assignment(Column(db_field='c'), 'd') 28 | 29 | self.assertEqual( 30 | str(ist), 31 | 'INSERT INTO table ("a", "c") VALUES (%(0)s, %(1)s)' 32 | ) 33 | 34 | def test_context_update(self): 35 | ist = InsertStatement('table', None) 36 | ist.add_assignment(Column(db_field='a'), 'b') 37 | ist.add_assignment(Column(db_field='c'), 'd') 38 | 39 | ist.update_context_id(4) 40 | self.assertEqual( 41 | str(ist), 42 | 'INSERT INTO table ("a", "c") VALUES (%(4)s, %(5)s)' 43 | ) 44 | ctx = ist.get_context() 45 | self.assertEqual(ctx, {'4': 'b', '5': 'd'}) 46 | 47 | def test_additional_rendering(self): 48 | ist = InsertStatement('table', ttl=60) 49 | ist.add_assignment(Column(db_field='a'), 'b') 50 | ist.add_assignment(Column(db_field='c'), 'd') 51 | self.assertIn('USING TTL 60', str(ist)) 52 | -------------------------------------------------------------------------------- /appveyor/run_test.ps1: -------------------------------------------------------------------------------- 1 | Set-ExecutionPolicy Unrestricted 2 | Set-ExecutionPolicy -ExecutionPolicy Unrestricted -Scope Process -force 3 | Set-ExecutionPolicy -ExecutionPolicy Unrestricted -Scope CurrentUser -force 4 | Get-ExecutionPolicy -List 5 | echo $env:Path 6 | echo "JAVA_HOME: $env:JAVA_HOME" 7 | echo "PYTHONPATH: $env:PYTHONPATH" 8 | echo "Cassandra version: $env:CASSANDRA_VERSION" 9 | echo "Simulacron jar: $env:SIMULACRON_JAR" 10 | echo $env:ci_type 11 | python --version 12 | python -c "import platform; print(platform.architecture())" 13 | 14 | $wc = New-Object 'System.Net.WebClient' 15 | 16 | if($env:ci_type -eq 'unit'){ 17 | echo "Running Unit tests" 18 | pytest -s -v --junit-xml=unit_results.xml .\tests\unit 19 | 20 | $env:EVENT_LOOP_MANAGER="gevent" 21 | pytest -s -v --junit-xml=unit_results.xml .\tests\unit\io\test_geventreactor.py 22 | $env:EVENT_LOOP_MANAGER="eventlet" 23 | pytest -s -v --junit-xml=unit_results.xml .\tests\unit\io\test_eventletreactor.py 24 | $env:EVENT_LOOP_MANAGER="asyncore" 25 | 26 | echo "uploading unit results" 27 | $wc.UploadFile("https://ci.appveyor.com/api/testresults/junit/$($env:APPVEYOR_JOB_ID)", (Resolve-Path .\unit_results.xml)) 28 | 29 | } 30 | 31 | if($env:ci_type -eq 'standard'){ 32 | 33 | echo "Running CQLEngine integration tests" 34 | pytest -s -v --junit-xml=cqlengine_results.xml .\tests\integration\cqlengine 35 | $cqlengine_tests_result = $lastexitcode 36 | $wc.UploadFile("https://ci.appveyor.com/api/testresults/junit/$($env:APPVEYOR_JOB_ID)", (Resolve-Path .\cqlengine_results.xml)) 37 | echo "uploading CQLEngine test results" 38 | 39 | echo "Running standard integration tests" 40 | pytest -s -v --junit-xml=standard_results.xml .\tests\integration\standard 41 | $integration_tests_result = $lastexitcode 42 | $wc.UploadFile("https://ci.appveyor.com/api/testresults/junit/$($env:APPVEYOR_JOB_ID)", (Resolve-Path .\standard_results.xml)) 43 | echo "uploading standard integration test results" 44 | } 45 | 46 | 47 | $exit_result = $unit_tests_result + $cqlengine_tests_result + $integration_tests_result + $simulacron_tests_result 48 | echo "Exit result: $exit_result" 49 | exit $exit_result 50 | -------------------------------------------------------------------------------- /tests/unit/io/gevent_utils.py: -------------------------------------------------------------------------------- 1 | # Licensed to the Apache Software Foundation (ASF) under one 2 | # or more contributor license agreements. See the NOTICE file 3 | # distributed with this work for additional information 4 | # regarding copyright ownership. The ASF licenses this file 5 | # to you under the Apache License, Version 2.0 (the 6 | # "License"); you may not use this file except in compliance 7 | # with the License. You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | 18 | from gevent import monkey 19 | 20 | 21 | def gevent_un_patch_all(): 22 | """ 23 | A method to unpatch gevent libraries. These are unloaded 24 | in the same order that gevent monkey patch loads theirs. 25 | Order cannot be arbitrary. This is used in the unit tests to 26 | un monkey patch gevent 27 | """ 28 | restore_saved_module("os") 29 | restore_saved_module("time") 30 | restore_saved_module("thread") 31 | restore_saved_module("threading") 32 | restore_saved_module("_threading_local") 33 | restore_saved_module("stdin") 34 | restore_saved_module("stdout") 35 | restore_saved_module("socket") 36 | restore_saved_module("select") 37 | restore_saved_module("ssl") 38 | restore_saved_module("subprocess") 39 | 40 | 41 | def restore_saved_module(module): 42 | """ 43 | gevent monkey patch keeps a list of all patched modules. 44 | This will restore the original ones 45 | :param module: to unpatch 46 | :return: 47 | """ 48 | 49 | # Check the saved attributes in geven monkey patch 50 | if not (module in monkey.saved): 51 | return 52 | _module = __import__(module) 53 | 54 | # If it exist unpatch it 55 | for attr in monkey.saved[module]: 56 | if hasattr(_module, attr): 57 | setattr(_module, attr, monkey.saved[module][attr]) 58 | 59 | -------------------------------------------------------------------------------- /cassandra/type_codes.py: -------------------------------------------------------------------------------- 1 | """ 2 | Module with constants for Cassandra type codes. 3 | 4 | These constants are useful for 5 | 6 | a) mapping messages to cqltypes (cassandra/cqltypes.py) 7 | b) optimized dispatching for (de)serialization (cassandra/encoding.py) 8 | 9 | Type codes are repeated here from the Cassandra binary protocol specification: 10 | 11 | 0x0000 Custom: the value is a [string], see above. 12 | 0x0001 Ascii 13 | 0x0002 Bigint 14 | 0x0003 Blob 15 | 0x0004 Boolean 16 | 0x0005 Counter 17 | 0x0006 Decimal 18 | 0x0007 Double 19 | 0x0008 Float 20 | 0x0009 Int 21 | 0x000A Text 22 | 0x000B Timestamp 23 | 0x000C Uuid 24 | 0x000D Varchar 25 | 0x000E Varint 26 | 0x000F Timeuuid 27 | 0x0010 Inet 28 | 0x0011 SimpleDateType 29 | 0x0012 TimeType 30 | 0x0013 ShortType 31 | 0x0014 ByteType 32 | 0x0015 DurationType 33 | 0x0020 List: the value is an [option], representing the type 34 | of the elements of the list. 35 | 0x0021 Map: the value is two [option], representing the types of the 36 | keys and values of the map 37 | 0x0022 Set: the value is an [option], representing the type 38 | of the elements of the set 39 | """ 40 | 41 | CUSTOM_TYPE = 0x0000 42 | AsciiType = 0x0001 43 | LongType = 0x0002 44 | BytesType = 0x0003 45 | BooleanType = 0x0004 46 | CounterColumnType = 0x0005 47 | DecimalType = 0x0006 48 | DoubleType = 0x0007 49 | FloatType = 0x0008 50 | Int32Type = 0x0009 51 | UTF8Type = 0x000A 52 | DateType = 0x000B 53 | UUIDType = 0x000C 54 | VarcharType = 0x000D 55 | IntegerType = 0x000E 56 | TimeUUIDType = 0x000F 57 | InetAddressType = 0x0010 58 | SimpleDateType = 0x0011 59 | TimeType = 0x0012 60 | ShortType = 0x0013 61 | ByteType = 0x0014 62 | DurationType = 0x0015 63 | ListType = 0x0020 64 | MapType = 0x0021 65 | SetType = 0x0022 66 | UserType = 0x0030 67 | TupleType = 0x0031 68 | -------------------------------------------------------------------------------- /tests/integration/cqlengine/base.py: -------------------------------------------------------------------------------- 1 | # Licensed to the Apache Software Foundation (ASF) under one 2 | # or more contributor license agreements. See the NOTICE file 3 | # distributed with this work for additional information 4 | # regarding copyright ownership. The ASF licenses this file 5 | # to you under the Apache License, Version 2.0 (the 6 | # "License"); you may not use this file except in compliance 7 | # with the License. You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | import unittest 17 | 18 | import sys 19 | 20 | from cassandra.cqlengine.connection import get_session 21 | from cassandra.cqlengine.models import Model 22 | from cassandra.cqlengine import columns 23 | 24 | from uuid import uuid4 25 | 26 | class TestQueryUpdateModel(Model): 27 | 28 | partition = columns.UUID(primary_key=True, default=uuid4) 29 | cluster = columns.Integer(primary_key=True) 30 | count = columns.Integer(required=False) 31 | text = columns.Text(required=False, index=True) 32 | text_set = columns.Set(columns.Text, required=False) 33 | text_list = columns.List(columns.Text, required=False) 34 | text_map = columns.Map(columns.Text, columns.Text, required=False) 35 | 36 | class BaseCassEngTestCase(unittest.TestCase): 37 | 38 | session = None 39 | 40 | def setUp(self): 41 | self.session = get_session() 42 | 43 | def assertHasAttr(self, obj, attr): 44 | self.assertTrue(hasattr(obj, attr), 45 | "{0} doesn't have attribute: {1}".format(obj, attr)) 46 | 47 | def assertNotHasAttr(self, obj, attr): 48 | self.assertFalse(hasattr(obj, attr), 49 | "{0} shouldn't have the attribute: {1}".format(obj, attr)) 50 | 51 | if sys.version_info > (3, 0): 52 | def assertItemsEqual(self, first, second, msg=None): 53 | return self.assertCountEqual(first, second, msg) 54 | -------------------------------------------------------------------------------- /cassandra/buffer.pxd: -------------------------------------------------------------------------------- 1 | # Licensed to the Apache Software Foundation (ASF) under one 2 | # or more contributor license agreements. See the NOTICE file 3 | # distributed with this work for additional information 4 | # regarding copyright ownership. The ASF licenses this file 5 | # to you under the Apache License, Version 2.0 (the 6 | # "License"); you may not use this file except in compliance 7 | # with the License. You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | """ 18 | Simple buffer data structure that provides a view on existing memory 19 | (e.g. from a bytes object). This memory must stay alive while the 20 | buffer is in use. 21 | """ 22 | 23 | from cpython.bytes cimport PyBytes_AS_STRING 24 | # char* PyBytes_AS_STRING(object string) 25 | # Macro form of PyBytes_AsString() but without error 26 | # checking. Only string objects are supported; no Unicode objects 27 | # should be passed. 28 | 29 | 30 | cdef struct Buffer: 31 | char *ptr 32 | Py_ssize_t size 33 | 34 | 35 | cdef inline bytes to_bytes(Buffer *buf): 36 | return buf.ptr[:buf.size] 37 | 38 | cdef inline char *buf_ptr(Buffer *buf): 39 | return buf.ptr 40 | 41 | cdef inline char *buf_read(Buffer *buf, Py_ssize_t size) except NULL: 42 | if size > buf.size: 43 | raise IndexError("Requested more than length of buffer") 44 | return buf.ptr 45 | 46 | cdef inline int slice_buffer(Buffer *buf, Buffer *out, 47 | Py_ssize_t start, Py_ssize_t size) except -1: 48 | if size < 0: 49 | raise ValueError("Length must be positive") 50 | 51 | if start + size > buf.size: 52 | raise IndexError("Buffer slice out of bounds") 53 | 54 | out.ptr = buf.ptr + start 55 | out.size = size 56 | return 0 57 | 58 | cdef inline void from_ptr_and_size(char *ptr, Py_ssize_t size, Buffer *out): 59 | out.ptr = ptr 60 | out.size = size 61 | -------------------------------------------------------------------------------- /docs/api/cassandra/policies.rst: -------------------------------------------------------------------------------- 1 | ``cassandra.policies`` - Load balancing and Failure Handling Policies 2 | ===================================================================== 3 | 4 | .. module:: cassandra.policies 5 | 6 | Load Balancing 7 | -------------- 8 | 9 | .. autoclass:: HostDistance 10 | :members: 11 | 12 | .. autoclass:: LoadBalancingPolicy 13 | :members: 14 | 15 | .. autoclass:: RoundRobinPolicy 16 | :members: 17 | 18 | .. autoclass:: DCAwareRoundRobinPolicy 19 | :members: 20 | 21 | .. autoclass:: WhiteListRoundRobinPolicy 22 | :members: 23 | 24 | .. autoclass:: TokenAwarePolicy 25 | :members: 26 | 27 | .. autoclass:: HostFilterPolicy 28 | 29 | .. we document these methods manually so we can specify a param to predicate 30 | 31 | .. automethod:: predicate(host) 32 | .. automethod:: distance 33 | .. automethod:: make_query_plan 34 | 35 | .. autoclass:: DefaultLoadBalancingPolicy 36 | :members: 37 | 38 | .. autoclass:: DSELoadBalancingPolicy 39 | :members: 40 | 41 | Translating Server Node Addresses 42 | --------------------------------- 43 | 44 | .. autoclass:: AddressTranslator 45 | :members: 46 | 47 | .. autoclass:: IdentityTranslator 48 | :members: 49 | 50 | .. autoclass:: EC2MultiRegionTranslator 51 | :members: 52 | 53 | Marking Hosts Up or Down 54 | ------------------------ 55 | 56 | .. autoclass:: ConvictionPolicy 57 | :members: 58 | 59 | .. autoclass:: SimpleConvictionPolicy 60 | :members: 61 | 62 | Reconnecting to Dead Hosts 63 | -------------------------- 64 | 65 | .. autoclass:: ReconnectionPolicy 66 | :members: 67 | 68 | .. autoclass:: ConstantReconnectionPolicy 69 | :members: 70 | 71 | .. autoclass:: ExponentialReconnectionPolicy 72 | :members: 73 | 74 | Retrying Failed Operations 75 | -------------------------- 76 | 77 | .. autoclass:: WriteType 78 | :members: 79 | 80 | .. autoclass:: RetryPolicy 81 | :members: 82 | 83 | .. autoclass:: FallthroughRetryPolicy 84 | :members: 85 | 86 | .. autoclass:: DowngradingConsistencyRetryPolicy 87 | :members: 88 | 89 | Retrying Idempotent Operations 90 | ------------------------------ 91 | 92 | .. autoclass:: SpeculativeExecutionPolicy 93 | :members: 94 | 95 | .. autoclass:: ConstantSpeculativeExecutionPolicy 96 | :members: 97 | -------------------------------------------------------------------------------- /CONTRIBUTING.rst: -------------------------------------------------------------------------------- 1 | Contributing 2 | ============ 3 | 4 | Contributions are welcome in the form of bug reports or pull requests. 5 | 6 | Bug Reports 7 | ----------- 8 | Quality bug reports are welcome at the `CASSPYTHON project `_ 9 | of the ASF JIRA. 10 | 11 | There are plenty of `good resources `_ describing how to create 12 | good bug reports. They will not be repeated in detail here, but in general, the bug report include where appropriate: 13 | 14 | * relevant software versions (Python runtime, driver version, cython version, server version) 15 | * details for how to produce (e.g. a test script or written procedure) 16 | * any effort to isolate the issue in reproduction is much-appreciated 17 | * stack trace from a crashed runtime 18 | 19 | Pull Requests 20 | ------------- 21 | If you're able to fix a bug yourself, you can `fork the repository `_ and submit a `Pull Request `_ with the fix. 22 | Please include tests demonstrating the issue and fix. For examples of how to run the tests, consult the `dev README `_. 23 | 24 | Design and Implementation Guidelines 25 | ------------------------------------ 26 | - We have integrations (notably Cassandra cqlsh) that require pure Python and minimal external dependencies. We try to avoid new external dependencies. Where compiled extensions are concerned, there should always be a pure Python fallback implementation. 27 | - This project follows `semantic versioning `_, so breaking API changes will only be introduced in major versions. 28 | - Legacy ``cqlengine`` has varying degrees of overreaching client-side validation. Going forward, we will avoid client validation where server feedback is adequate and not overly expensive. 29 | - When writing tests, try to achieve maximal coverage in unit tests (where it is faster to run across many runtimes). Integration tests are good for things where we need to test server interaction, or where it is important to test across different server versions (emulating in unit tests would not be effective). 30 | -------------------------------------------------------------------------------- /docs/api/cassandra/cqlengine/columns.rst: -------------------------------------------------------------------------------- 1 | ``cassandra.cqlengine.columns`` - Column types for object mapping models 2 | ======================================================================== 3 | 4 | .. module:: cassandra.cqlengine.columns 5 | 6 | Columns 7 | ------- 8 | 9 | Columns in your models map to columns in your CQL table. You define CQL columns by defining column attributes on your model classes. 10 | For a model to be valid it needs at least one primary key column and one non-primary key column. 11 | 12 | Just as in CQL, the order you define your columns in is important, and is the same order they are defined in on a model's corresponding table. 13 | 14 | Each column on your model definitions needs to be an instance of a Column class. 15 | 16 | .. autoclass:: Column(**kwargs) 17 | 18 | .. autoattribute:: primary_key 19 | 20 | .. autoattribute:: partition_key 21 | 22 | .. autoattribute:: index 23 | 24 | .. autoattribute:: custom_index 25 | 26 | .. autoattribute:: db_field 27 | 28 | .. autoattribute:: default 29 | 30 | .. autoattribute:: required 31 | 32 | .. autoattribute:: clustering_order 33 | 34 | .. autoattribute:: discriminator_column 35 | 36 | .. autoattribute:: static 37 | 38 | Column Types 39 | ------------ 40 | 41 | Columns of all types are initialized by passing :class:`.Column` attributes to the constructor by keyword. 42 | 43 | .. autoclass:: Ascii(**kwargs) 44 | 45 | .. autoclass:: BigInt(**kwargs) 46 | 47 | .. autoclass:: Blob(**kwargs) 48 | 49 | .. autoclass:: Bytes(**kwargs) 50 | 51 | .. autoclass:: Boolean(**kwargs) 52 | 53 | .. autoclass:: Counter 54 | 55 | .. autoclass:: Date(**kwargs) 56 | 57 | .. autoclass:: DateTime(**kwargs) 58 | 59 | .. autoattribute:: truncate_microseconds 60 | 61 | .. autoclass:: Decimal(**kwargs) 62 | 63 | .. autoclass:: Double(**kwargs) 64 | 65 | .. autoclass:: Float 66 | 67 | .. autoclass:: Integer(**kwargs) 68 | 69 | .. autoclass:: List 70 | 71 | .. autoclass:: Map 72 | 73 | .. autoclass:: Set 74 | 75 | .. autoclass:: SmallInt(**kwargs) 76 | 77 | .. autoclass:: Text 78 | 79 | .. autoclass:: Time(**kwargs) 80 | 81 | .. autoclass:: TimeUUID(**kwargs) 82 | 83 | .. autoclass:: TinyInt(**kwargs) 84 | 85 | .. autoclass:: UserDefinedType 86 | 87 | .. autoclass:: UUID(**kwargs) 88 | 89 | .. autoclass:: VarInt(**kwargs) 90 | -------------------------------------------------------------------------------- /tests/unit/cqlengine/test_columns.py: -------------------------------------------------------------------------------- 1 | # Licensed to the Apache Software Foundation (ASF) under one 2 | # or more contributor license agreements. See the NOTICE file 3 | # distributed with this work for additional information 4 | # regarding copyright ownership. The ASF licenses this file 5 | # to you under the Apache License, Version 2.0 (the 6 | # "License"); you may not use this file except in compliance 7 | # with the License. You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | import unittest 18 | 19 | from cassandra.cqlengine.columns import Column 20 | 21 | 22 | class ColumnTest(unittest.TestCase): 23 | 24 | def test_comparisons(self): 25 | c0 = Column() 26 | c1 = Column() 27 | self.assertEqual(c1.position - c0.position, 1) 28 | 29 | # __ne__ 30 | self.assertNotEqual(c0, c1) 31 | self.assertNotEqual(c0, object()) 32 | 33 | # __eq__ 34 | self.assertEqual(c0, c0) 35 | self.assertFalse(c0 == object()) 36 | 37 | # __lt__ 38 | self.assertLess(c0, c1) 39 | try: 40 | c0 < object() # this raises for Python 3 41 | except TypeError: 42 | pass 43 | 44 | # __le__ 45 | self.assertLessEqual(c0, c1) 46 | self.assertLessEqual(c0, c0) 47 | try: 48 | c0 <= object() # this raises for Python 3 49 | except TypeError: 50 | pass 51 | 52 | # __gt__ 53 | self.assertGreater(c1, c0) 54 | try: 55 | c1 > object() # this raises for Python 3 56 | except TypeError: 57 | pass 58 | 59 | # __ge__ 60 | self.assertGreaterEqual(c1, c0) 61 | self.assertGreaterEqual(c1, c1) 62 | try: 63 | c1 >= object() # this raises for Python 3 64 | except TypeError: 65 | pass 66 | 67 | def test_hash(self): 68 | c0 = Column() 69 | self.assertEqual(id(c0), c0.__hash__()) 70 | 71 | -------------------------------------------------------------------------------- /benchmarks/callback_full_pipeline.py: -------------------------------------------------------------------------------- 1 | # Licensed to the Apache Software Foundation (ASF) under one 2 | # or more contributor license agreements. See the NOTICE file 3 | # distributed with this work for additional information 4 | # regarding copyright ownership. The ASF licenses this file 5 | # to you under the Apache License, Version 2.0 (the 6 | # "License"); you may not use this file except in compliance 7 | # with the License. You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | import logging 18 | 19 | from itertools import count 20 | from threading import Event 21 | 22 | from base import benchmark, BenchmarkThread 23 | 24 | log = logging.getLogger(__name__) 25 | 26 | 27 | sentinel = object() 28 | 29 | 30 | class Runner(BenchmarkThread): 31 | 32 | def __init__(self, *args, **kwargs): 33 | BenchmarkThread.__init__(self, *args, **kwargs) 34 | self.num_started = count() 35 | self.num_finished = count() 36 | self.event = Event() 37 | 38 | def insert_next(self, previous_result=sentinel): 39 | if previous_result is not sentinel: 40 | if isinstance(previous_result, BaseException): 41 | log.error("Error on insert: %r", previous_result) 42 | if next(self.num_finished) >= self.num_queries: 43 | self.event.set() 44 | 45 | i = next(self.num_started) 46 | if i <= self.num_queries: 47 | key = "{0}-{1}".format(self.thread_num, i) 48 | future = self.run_query(key, timeout=None) 49 | future.add_callbacks(self.insert_next, self.insert_next) 50 | 51 | def run(self): 52 | self.start_profile() 53 | 54 | if self.protocol_version >= 3: 55 | concurrency = 1000 56 | else: 57 | concurrency = 100 58 | 59 | for _ in range(min(concurrency, self.num_queries)): 60 | self.insert_next() 61 | 62 | self.event.wait() 63 | 64 | self.finish_profile() 65 | 66 | 67 | if __name__ == "__main__": 68 | benchmark(Runner) 69 | -------------------------------------------------------------------------------- /tests/integration/advanced/test_spark.py: -------------------------------------------------------------------------------- 1 | # Licensed to the Apache Software Foundation (ASF) under one 2 | # or more contributor license agreements. See the NOTICE file 3 | # distributed with this work for additional information 4 | # regarding copyright ownership. The ASF licenses this file 5 | # to you under the Apache License, Version 2.0 (the 6 | # "License"); you may not use this file except in compliance 7 | # with the License. You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | import logging 18 | 19 | from cassandra.cluster import EXEC_PROFILE_GRAPH_ANALYTICS_DEFAULT 20 | from cassandra.graph import SimpleGraphStatement 21 | from tests.integration import DSE_VERSION, requiredse 22 | from tests.integration.advanced import use_singledc_wth_graph_and_spark, find_spark_master 23 | from tests.integration.advanced.graph import BasicGraphUnitTestCase, ClassicGraphFixtures 24 | log = logging.getLogger(__name__) 25 | 26 | 27 | def setup_module(): 28 | if DSE_VERSION: 29 | use_singledc_wth_graph_and_spark() 30 | 31 | 32 | @requiredse 33 | class SparkLBTests(BasicGraphUnitTestCase): 34 | """ 35 | Test to validate that analytics query can run in a multi-node environment. Also check to ensure 36 | that the master spark node is correctly targeted when OLAP queries are run 37 | 38 | @since 3.20 39 | @jira_ticket PYTHON-510 40 | @expected_result OLAP results should come back correctly, master spark coordinator should always be picked. 41 | @test_category dse graph 42 | """ 43 | def test_spark_analytic_query(self): 44 | self.session.execute_graph(ClassicGraphFixtures.classic()) 45 | spark_master = find_spark_master(self.session) 46 | 47 | # Run multiple times to ensure we don't round-robin 48 | for i in range(3): 49 | to_run = SimpleGraphStatement("g.V().count()") 50 | rs = self.session.execute_graph(to_run, execution_profile=EXEC_PROFILE_GRAPH_ANALYTICS_DEFAULT) 51 | self.assertEqual(rs[0].value, 7) 52 | self.assertEqual(rs.response_future._current_host.address, spark_master) 53 | -------------------------------------------------------------------------------- /examples/concurrent_executions/execute_async_with_queue.py: -------------------------------------------------------------------------------- 1 | # Licensed to the Apache Software Foundation (ASF) under one 2 | # or more contributor license agreements. See the NOTICE file 3 | # distributed with this work for additional information 4 | # regarding copyright ownership. The ASF licenses this file 5 | # to you under the Apache License, Version 2.0 (the 6 | # "License"); you may not use this file except in compliance 7 | # with the License. You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | """ 18 | Inserts multiple rows in a table asynchronously, limiting the amount 19 | of parallel requests with a Queue. 20 | """ 21 | 22 | import time 23 | import uuid 24 | import queue 25 | 26 | from cassandra.cluster import Cluster 27 | 28 | 29 | CONCURRENCY_LEVEL = 32 30 | TOTAL_QUERIES = 10000 31 | 32 | cluster = Cluster() 33 | session = cluster.connect() 34 | 35 | session.execute(("CREATE KEYSPACE IF NOT EXISTS examples " 36 | "WITH replication = {'class': 'SimpleStrategy', 'replication_factor': '1' }")) 37 | session.execute("USE examples") 38 | session.execute("CREATE TABLE IF NOT EXISTS tbl_sample_kv (id uuid, value text, PRIMARY KEY (id))") 39 | prepared_insert = session.prepare("INSERT INTO tbl_sample_kv (id, value) VALUES (?, ?)") 40 | 41 | 42 | def clear_queue(): 43 | while True: 44 | try: 45 | futures.get_nowait().result() 46 | except queue.Empty: 47 | break 48 | 49 | 50 | start = time.time() 51 | futures = queue.Queue(maxsize=CONCURRENCY_LEVEL) 52 | 53 | # Chunking way, when the max concurrency level is reached, we 54 | # wait the current chunk of requests to finish 55 | for i in range(TOTAL_QUERIES): 56 | future = session.execute_async(prepared_insert, (uuid.uuid4(), str(i))) 57 | try: 58 | futures.put_nowait(future) 59 | except queue.Full: 60 | clear_queue() 61 | futures.put_nowait(future) 62 | 63 | clear_queue() 64 | end = time.time() 65 | 66 | print("Finished executing {} queries with a concurrency level of {} in {:.2f} seconds.". 67 | format(TOTAL_QUERIES, CONCURRENCY_LEVEL, (end-start))) 68 | -------------------------------------------------------------------------------- /cassandra/cython_utils.pyx: -------------------------------------------------------------------------------- 1 | # Licensed to the Apache Software Foundation (ASF) under one 2 | # or more contributor license agreements. See the NOTICE file 3 | # distributed with this work for additional information 4 | # regarding copyright ownership. The ASF licenses this file 5 | # to you under the Apache License, Version 2.0 (the 6 | # "License"); you may not use this file except in compliance 7 | # with the License. You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | """ 18 | Duplicate module of util.py, with some accelerated functions 19 | used for deserialization. 20 | """ 21 | 22 | from libc.math cimport modf, round, fabs 23 | 24 | from cpython.datetime cimport ( 25 | timedelta_new, 26 | # cdef inline object timedelta_new(int days, int seconds, int useconds) 27 | # Create timedelta object using DateTime CAPI factory function. 28 | # Note, there are no range checks for any of the arguments. 29 | import_datetime, 30 | # Datetime C API initialization function. 31 | # You have to call it before any usage of DateTime CAPI functions. 32 | ) 33 | 34 | import datetime 35 | import sys 36 | 37 | cdef bint is_little_endian 38 | from cassandra.util import is_little_endian 39 | 40 | import_datetime() 41 | 42 | DEF DAY_IN_SECONDS = 86400 43 | 44 | DATETIME_EPOC = datetime.datetime(1970, 1, 1) 45 | 46 | 47 | cdef datetime_from_timestamp(double timestamp): 48 | cdef int days = (timestamp / DAY_IN_SECONDS) 49 | cdef int64_t days_in_seconds = ( days) * DAY_IN_SECONDS 50 | cdef int seconds = (timestamp - days_in_seconds) 51 | cdef double tmp 52 | cdef double micros_left = modf(timestamp, &tmp) * 1000000. 53 | micros_left = modf(micros_left, &tmp) 54 | cdef int microseconds = tmp 55 | 56 | # rounding to emulate fp math in delta_new 57 | cdef int x_odd 58 | tmp = round(micros_left) 59 | if fabs(tmp - micros_left) == 0.5: 60 | x_odd = microseconds & 1 61 | tmp = 2.0 * round((micros_left + x_odd) * 0.5) - x_odd 62 | microseconds += tmp 63 | 64 | return DATETIME_EPOC + timedelta_new(days, seconds, microseconds) 65 | -------------------------------------------------------------------------------- /docs/api/cassandra/protocol.rst: -------------------------------------------------------------------------------- 1 | ``cassandra.protocol`` - Protocol Features 2 | ===================================================================== 3 | 4 | .. module:: cassandra.protocol 5 | 6 | .. _custom_payload: 7 | 8 | Custom Payloads 9 | --------------- 10 | Native protocol version 4+ allows for a custom payload to be sent between clients 11 | and custom query handlers. The payload is specified as a string:binary_type dict 12 | holding custom key/value pairs. 13 | 14 | By default these are ignored by the server. They can be useful for servers implementing 15 | a custom QueryHandler. 16 | 17 | See :meth:`.Session.execute`, ::meth:`.Session.execute_async`, :attr:`.ResponseFuture.custom_payload`. 18 | 19 | .. autoclass:: _ProtocolHandler 20 | 21 | .. autoattribute:: message_types_by_opcode 22 | :annotation: = {default mapping} 23 | 24 | .. automethod:: encode_message 25 | 26 | .. automethod:: decode_message 27 | 28 | .. _faster_deser: 29 | 30 | Faster Deserialization 31 | ---------------------- 32 | When python-driver is compiled with Cython, it uses a Cython-based deserialization path 33 | to deserialize messages. By default, the driver will use a Cython-based parser that returns 34 | lists of rows similar to the pure-Python version. In addition, there are two additional 35 | ProtocolHandler classes that can be used to deserialize response messages: ``LazyProtocolHandler`` 36 | and ``NumpyProtocolHandler``. They can be used as follows: 37 | 38 | .. code:: python 39 | 40 | from cassandra.protocol import NumpyProtocolHandler, LazyProtocolHandler 41 | from cassandra.query import tuple_factory 42 | s.client_protocol_handler = LazyProtocolHandler # for a result iterator 43 | s.row_factory = tuple_factory #required for Numpy results 44 | s.client_protocol_handler = NumpyProtocolHandler # for a dict of NumPy arrays as result 45 | 46 | These protocol handlers comprise different parsers, and return results as described below: 47 | 48 | - ProtocolHandler: this default implementation is a drop-in replacement for the pure-Python version. 49 | The rows are all parsed upfront, before results are returned. 50 | 51 | - LazyProtocolHandler: near drop-in replacement for the above, except that it returns an iterator over rows, 52 | lazily decoded into the default row format (this is more efficient since all decoded results are not materialized at once) 53 | 54 | - NumpyProtocolHander: deserializes results directly into NumPy arrays. This facilitates efficient integration with 55 | analysis toolkits such as Pandas. 56 | -------------------------------------------------------------------------------- /cassandra/row_parser.pyx: -------------------------------------------------------------------------------- 1 | # Licensed to the Apache Software Foundation (ASF) under one 2 | # or more contributor license agreements. See the NOTICE file 3 | # distributed with this work for additional information 4 | # regarding copyright ownership. The ASF licenses this file 5 | # to you under the Apache License, Version 2.0 (the 6 | # "License"); you may not use this file except in compliance 7 | # with the License. You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | from cassandra.parsing cimport ParseDesc, ColumnParser 18 | from cassandra.policies import ColDesc 19 | from cassandra.obj_parser import TupleRowParser 20 | from cassandra.deserializers import make_deserializers 21 | 22 | include "ioutils.pyx" 23 | 24 | def make_recv_results_rows(ColumnParser colparser): 25 | def recv_results_rows(self, f, int protocol_version, user_type_map, result_metadata, column_encryption_policy): 26 | """ 27 | Parse protocol data given as a BytesIO f into a set of columns (e.g. list of tuples) 28 | This is used as the recv_results_rows method of (Fast)ResultMessage 29 | """ 30 | self.recv_results_metadata(f, user_type_map) 31 | 32 | column_metadata = self.column_metadata or result_metadata 33 | 34 | self.column_names = [md[2] for md in column_metadata] 35 | self.column_types = [md[3] for md in column_metadata] 36 | 37 | desc = ParseDesc(self.column_names, self.column_types, column_encryption_policy, 38 | [ColDesc(md[0], md[1], md[2]) for md in column_metadata], 39 | make_deserializers(self.column_types), protocol_version) 40 | reader = BytesIOReader(f.read()) 41 | try: 42 | self.parsed_rows = colparser.parse_rows(reader, desc) 43 | except Exception as e: 44 | # Use explicitly the TupleRowParser to display better error messages for column decoding failures 45 | rowparser = TupleRowParser() 46 | reader.buf_ptr = reader.buf 47 | reader.pos = 0 48 | rowcount = read_int(reader) 49 | for i in range(rowcount): 50 | rowparser.unpack_row(reader, desc) 51 | 52 | return recv_results_rows 53 | -------------------------------------------------------------------------------- /tests/unit/io/test_geventreactor.py: -------------------------------------------------------------------------------- 1 | # Licensed to the Apache Software Foundation (ASF) under one 2 | # or more contributor license agreements. See the NOTICE file 3 | # distributed with this work for additional information 4 | # regarding copyright ownership. The ASF licenses this file 5 | # to you under the Apache License, Version 2.0 (the 6 | # "License"); you may not use this file except in compliance 7 | # with the License. You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | import unittest 18 | from unittest.mock import patch 19 | 20 | 21 | from tests.unit.io.utils import TimerTestMixin 22 | from tests import EVENT_LOOP_MANAGER 23 | try: 24 | from cassandra.io.geventreactor import GeventConnection 25 | import gevent.monkey 26 | except ImportError: 27 | GeventConnection = None # noqa 28 | 29 | 30 | skip_condition = GeventConnection is None or EVENT_LOOP_MANAGER != "gevent" 31 | @unittest.skipIf(skip_condition, "Skipping the gevent tests because it's not installed") 32 | class GeventTimerTest(TimerTestMixin, unittest.TestCase): 33 | 34 | connection_class = GeventConnection 35 | 36 | @classmethod 37 | def setUpClass(cls): 38 | # This is run even though the class is skipped, so we need 39 | # to make sure no monkey patching is happening 40 | if skip_condition: 41 | return 42 | # There is no unpatching because there is not a clear way 43 | # of doing it reliably 44 | gevent.monkey.patch_all() 45 | GeventConnection.initialize_reactor() 46 | 47 | def setUp(self): 48 | socket_patcher = patch('gevent.socket.socket') 49 | self.addCleanup(socket_patcher.stop) 50 | socket_patcher.start() 51 | 52 | super(GeventTimerTest, self).setUp() 53 | 54 | recv_patcher = patch.object(self.connection._socket, 55 | 'recv', 56 | return_value=b'') 57 | self.addCleanup(recv_patcher.stop) 58 | recv_patcher.start() 59 | 60 | @property 61 | def create_timer(self): 62 | return self.connection.create_timer 63 | 64 | @property 65 | def _timers(self): 66 | return self.connection._timers 67 | -------------------------------------------------------------------------------- /cassandra/cython_marshal.pyx: -------------------------------------------------------------------------------- 1 | # -- cython: profile=True 2 | # 3 | # Licensed to the Apache Software Foundation (ASF) under one 4 | # or more contributor license agreements. See the NOTICE file 5 | # distributed with this work for additional information 6 | # regarding copyright ownership. The ASF licenses this file 7 | # to you under the Apache License, Version 2.0 (the 8 | # "License"); you may not use this file except in compliance 9 | # with the License. You may obtain a copy of the License at 10 | # 11 | # http://www.apache.org/licenses/LICENSE-2.0 12 | # 13 | # Unless required by applicable law or agreed to in writing, software 14 | # distributed under the License is distributed on an "AS IS" BASIS, 15 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 16 | # See the License for the specific language governing permissions and 17 | # limitations under the License. 18 | 19 | from libc.stdint cimport (int8_t, int16_t, int32_t, int64_t, 20 | uint8_t, uint16_t, uint32_t, uint64_t) 21 | from libc.string cimport memcpy 22 | from cassandra.buffer cimport Buffer, buf_read, to_bytes 23 | 24 | cdef bint is_little_endian 25 | from cassandra.util import is_little_endian 26 | 27 | ctypedef fused num_t: 28 | int64_t 29 | int32_t 30 | int16_t 31 | int8_t 32 | uint64_t 33 | uint32_t 34 | uint16_t 35 | uint8_t 36 | double 37 | float 38 | 39 | cdef inline num_t unpack_num(Buffer *buf, num_t *dummy=NULL): # dummy pointer because cython wants the fused type as an arg 40 | """ 41 | Copy to aligned destination, conditionally swapping to native byte order 42 | """ 43 | cdef Py_ssize_t start, end, i 44 | cdef char *src = buf_read(buf, sizeof(num_t)) 45 | cdef num_t ret = 0 46 | cdef char *out = &ret 47 | 48 | if is_little_endian: 49 | for i in range(sizeof(num_t)): 50 | out[sizeof(num_t) - i - 1] = src[i] 51 | else: 52 | memcpy(out, src, sizeof(num_t)) 53 | 54 | return ret 55 | 56 | cdef varint_unpack(Buffer *term): 57 | """Unpack a variable-sized integer""" 58 | return varint_unpack_py3(to_bytes(term)) 59 | 60 | # TODO: Optimize these two functions 61 | cdef varint_unpack_py3(bytes term): 62 | val = int(''.join(["%02x" % i for i in term]), 16) 63 | if (term[0] & 128) != 0: 64 | shift = len(term) * 8 # * Note below 65 | val -= 1 << shift 66 | return val 67 | 68 | # * Note * 69 | # '1 << (len(term) * 8)' Cython tries to do native 70 | # integer shifts, which overflows. We need this to 71 | # emulate Python shifting, which will expand the long 72 | # to accommodate 73 | -------------------------------------------------------------------------------- /docs/performance.rst: -------------------------------------------------------------------------------- 1 | Performance Notes 2 | ================= 3 | The Python driver for Cassandra offers several methods for executing queries. 4 | You can synchronously block for queries to complete using 5 | :meth:`.Session.execute()`, you can obtain asynchronous request futures through 6 | :meth:`.Session.execute_async()`, and you can attach a callback to the future 7 | with :meth:`.ResponseFuture.add_callback()`. 8 | 9 | Examples of multiple request patterns can be found in the benchmark scripts included in the driver project. 10 | 11 | The choice of execution pattern will depend on the application context. For applications dealing with multiple 12 | requests in a given context, the recommended pattern is to use concurrent asynchronous 13 | requests with callbacks. For many use cases, you don't need to implement this pattern yourself. 14 | :meth:`cassandra.concurrent.execute_concurrent` and :meth:`cassandra.concurrent.execute_concurrent_with_args` 15 | provide this pattern with a synchronous API and tunable concurrency. 16 | 17 | Due to the GIL and limited concurrency, the driver can become CPU-bound pretty quickly. The sections below 18 | discuss further runtime and design considerations for mitigating this limitation. 19 | 20 | PyPy 21 | ---- 22 | `PyPy `_ is an alternative Python runtime which uses a JIT compiler to 23 | reduce CPU consumption. This leads to a huge improvement in the driver performance, 24 | more than doubling throughput for many workloads. 25 | 26 | Cython Extensions 27 | ----------------- 28 | `Cython `_ is an optimizing compiler and language that can be used to compile the core files and 29 | optional extensions for the driver. Cython is not a strict dependency, but the extensions will be built by default. 30 | 31 | See :doc:`installation` for details on controlling this build. 32 | 33 | multiprocessing 34 | --------------- 35 | All of the patterns discussed above may be used over multiple processes using the 36 | `multiprocessing `_ 37 | module. Multiple processes will scale better than multiple threads, so if high throughput is your goal, 38 | consider this option. 39 | 40 | Be sure to **never share any** :class:`~.Cluster`, :class:`~.Session`, 41 | **or** :class:`~.ResponseFuture` **objects across multiple processes**. These 42 | objects should all be created after forking the process, not before. 43 | 44 | For further discussion and simple examples using the driver with ``multiprocessing``, 45 | see `this blog post `_. 46 | -------------------------------------------------------------------------------- /tests/unit/cqlengine/test_connection.py: -------------------------------------------------------------------------------- 1 | # Licensed to the Apache Software Foundation (ASF) under one 2 | # or more contributor license agreements. See the NOTICE file 3 | # distributed with this work for additional information 4 | # regarding copyright ownership. The ASF licenses this file 5 | # to you under the Apache License, Version 2.0 (the 6 | # "License"); you may not use this file except in compliance 7 | # with the License. You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | import unittest 18 | from unittest.mock import Mock 19 | 20 | from cassandra.cluster import _ConfigMode 21 | from cassandra.cqlengine import connection 22 | from cassandra.query import dict_factory 23 | 24 | 25 | class ConnectionTest(unittest.TestCase): 26 | 27 | no_registered_connection_msg = "doesn't exist in the registry" 28 | 29 | def setUp(self): 30 | super(ConnectionTest, self).setUp() 31 | self.assertFalse( 32 | connection._connections, 33 | 'Test precondition not met: connections are registered: {cs}'.format(cs=connection._connections) 34 | ) 35 | 36 | def test_set_session_without_existing_connection(self): 37 | """ 38 | Users can set the default session without having a default connection set. 39 | """ 40 | mock_cluster = Mock( 41 | _config_mode=_ConfigMode.LEGACY, 42 | ) 43 | mock_session = Mock( 44 | row_factory=dict_factory, 45 | encoder=Mock(mapping={}), 46 | cluster=mock_cluster, 47 | ) 48 | connection.set_session(mock_session) 49 | 50 | def test_get_session_fails_without_existing_connection(self): 51 | """ 52 | Users can't get the default session without having a default connection set. 53 | """ 54 | with self.assertRaisesRegex(connection.CQLEngineException, self.no_registered_connection_msg): 55 | connection.get_session(connection=None) 56 | 57 | def test_get_cluster_fails_without_existing_connection(self): 58 | """ 59 | Users can't get the default cluster without having a default connection set. 60 | """ 61 | with self.assertRaisesRegex(connection.CQLEngineException, self.no_registered_connection_msg): 62 | connection.get_cluster(connection=None) 63 | -------------------------------------------------------------------------------- /tests/integration/cqlengine/model/test_equality_operations.py: -------------------------------------------------------------------------------- 1 | # Licensed to the Apache Software Foundation (ASF) under one 2 | # or more contributor license agreements. See the NOTICE file 3 | # distributed with this work for additional information 4 | # regarding copyright ownership. The ASF licenses this file 5 | # to you under the Apache License, Version 2.0 (the 6 | # "License"); you may not use this file except in compliance 7 | # with the License. You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | from uuid import uuid4 18 | from tests.integration.cqlengine.base import BaseCassEngTestCase 19 | 20 | from cassandra.cqlengine.management import sync_table 21 | from cassandra.cqlengine.management import drop_table 22 | from cassandra.cqlengine.models import Model 23 | from cassandra.cqlengine import columns 24 | 25 | class TestModel(Model): 26 | 27 | id = columns.UUID(primary_key=True, default=lambda:uuid4()) 28 | count = columns.Integer() 29 | text = columns.Text(required=False) 30 | 31 | class TestEqualityOperators(BaseCassEngTestCase): 32 | 33 | @classmethod 34 | def setUpClass(cls): 35 | super(TestEqualityOperators, cls).setUpClass() 36 | sync_table(TestModel) 37 | 38 | def setUp(self): 39 | super(TestEqualityOperators, self).setUp() 40 | self.t0 = TestModel.create(count=5, text='words') 41 | self.t1 = TestModel.create(count=5, text='words') 42 | 43 | @classmethod 44 | def tearDownClass(cls): 45 | super(TestEqualityOperators, cls).tearDownClass() 46 | drop_table(TestModel) 47 | 48 | def test_an_instance_evaluates_as_equal_to_itself(self): 49 | """ 50 | """ 51 | assert self.t0 == self.t0 52 | 53 | def test_two_instances_referencing_the_same_rows_and_different_values_evaluate_not_equal(self): 54 | """ 55 | """ 56 | t0 = TestModel.get(id=self.t0.id) 57 | t0.text = 'bleh' 58 | assert t0 != self.t0 59 | 60 | def test_two_instances_referencing_the_same_rows_and_values_evaluate_equal(self): 61 | """ 62 | """ 63 | t0 = TestModel.get(id=self.t0.id) 64 | assert t0 == self.t0 65 | 66 | def test_two_instances_referencing_different_rows_evaluate_to_not_equal(self): 67 | """ 68 | """ 69 | assert self.t0 != self.t1 70 | 71 | -------------------------------------------------------------------------------- /tests/unit/test_exception.py: -------------------------------------------------------------------------------- 1 | # Licensed to the Apache Software Foundation (ASF) under one 2 | # or more contributor license agreements. See the NOTICE file 3 | # distributed with this work for additional information 4 | # regarding copyright ownership. The ASF licenses this file 5 | # to you under the Apache License, Version 2.0 (the 6 | # "License"); you may not use this file except in compliance 7 | # with the License. You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | import unittest 18 | 19 | from cassandra import Unavailable, Timeout, ConsistencyLevel 20 | import re 21 | 22 | 23 | class ConsistencyExceptionTest(unittest.TestCase): 24 | """ 25 | Verify Cassandra Exception string representation 26 | """ 27 | 28 | def extract_consistency(self, msg): 29 | """ 30 | Given message that has 'consistency': 'value', extract consistency value as a string 31 | :param msg: message with consistency value 32 | :return: String representing consistency value 33 | """ 34 | match = re.search("'consistency':\s+'([\w\s]+)'", msg) 35 | return match and match.group(1) 36 | 37 | def test_timeout_consistency(self): 38 | """ 39 | Verify that Timeout exception object translates consistency from input value to correct output string 40 | """ 41 | consistency_str = self.extract_consistency(repr(Timeout("Timeout Message", consistency=None))) 42 | self.assertEqual(consistency_str, 'Not Set') 43 | for c in ConsistencyLevel.value_to_name.keys(): 44 | consistency_str = self.extract_consistency(repr(Timeout("Timeout Message", consistency=c))) 45 | self.assertEqual(consistency_str, ConsistencyLevel.value_to_name[c]) 46 | 47 | def test_unavailable_consistency(self): 48 | """ 49 | Verify that Unavailable exception object translates consistency from input value to correct output string 50 | """ 51 | consistency_str = self.extract_consistency(repr(Unavailable("Unavailable Message", consistency=None))) 52 | self.assertEqual(consistency_str, 'Not Set') 53 | for c in ConsistencyLevel.value_to_name.keys(): 54 | consistency_str = self.extract_consistency(repr(Unavailable("Timeout Message", consistency=c))) 55 | self.assertEqual(consistency_str, ConsistencyLevel.value_to_name[c]) 56 | -------------------------------------------------------------------------------- /examples/concurrent_executions/execute_with_threads.py: -------------------------------------------------------------------------------- 1 | # Licensed to the Apache Software Foundation (ASF) under one 2 | # or more contributor license agreements. See the NOTICE file 3 | # distributed with this work for additional information 4 | # regarding copyright ownership. The ASF licenses this file 5 | # to you under the Apache License, Version 2.0 (the 6 | # "License"); you may not use this file except in compliance 7 | # with the License. You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | """ 18 | Inserts multiple rows in a table limiting the amount of parallel requests. 19 | 20 | Note that the driver also provide convenient utility functions to accomplish this. 21 | See https://docs.datastax.com/en/developer/python-driver/latest/api/cassandra/concurrent/ 22 | """ 23 | 24 | import time 25 | import uuid 26 | import threading 27 | from cassandra.cluster import Cluster 28 | 29 | 30 | CONCURRENCY_LEVEL = 32 31 | TOTAL_QUERIES = 10000 32 | COUNTER = 0 33 | COUNTER_LOCK = threading.Lock() 34 | 35 | cluster = Cluster() 36 | session = cluster.connect() 37 | 38 | session.execute(("CREATE KEYSPACE IF NOT EXISTS examples " 39 | "WITH replication = {'class': 'SimpleStrategy', 'replication_factor': '1' }")) 40 | session.execute("USE examples") 41 | session.execute("CREATE TABLE IF NOT EXISTS tbl_sample_kv (id uuid, value text, PRIMARY KEY (id))") 42 | prepared_insert = session.prepare("INSERT INTO tbl_sample_kv (id, value) VALUES (?, ?)") 43 | 44 | 45 | class SimpleQueryExecutor(threading.Thread): 46 | 47 | def run(self): 48 | global COUNTER 49 | 50 | while True: 51 | with COUNTER_LOCK: 52 | current = COUNTER 53 | COUNTER += 1 54 | 55 | if current >= TOTAL_QUERIES: 56 | break 57 | 58 | session.execute(prepared_insert, (uuid.uuid4(), str(current))) 59 | 60 | 61 | # Launch in parallel n async operations (n being the concurrency level) 62 | start = time.time() 63 | threads = [] 64 | for i in range(CONCURRENCY_LEVEL): 65 | t = SimpleQueryExecutor() 66 | threads.append(t) 67 | t.start() 68 | 69 | for thread in threads: 70 | thread.join() 71 | end = time.time() 72 | 73 | print("Finished executing {} queries with a concurrency level of {} in {:.2f} seconds.". 74 | format(TOTAL_QUERIES, CONCURRENCY_LEVEL, (end-start))) 75 | -------------------------------------------------------------------------------- /tests/integration/advanced/test_unixsocketendpoint.py: -------------------------------------------------------------------------------- 1 | # Copyright DataStax, Inc. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License 14 | import unittest 15 | 16 | import time 17 | import subprocess 18 | import logging 19 | 20 | from cassandra.cluster import ExecutionProfile, EXEC_PROFILE_DEFAULT 21 | from cassandra.connection import UnixSocketEndPoint 22 | from cassandra.policies import WhiteListRoundRobinPolicy, RoundRobinPolicy 23 | 24 | from tests import notwindows 25 | from tests.integration import use_single_node, TestCluster 26 | 27 | log = logging.getLogger() 28 | log.setLevel('DEBUG') 29 | 30 | UNIX_SOCKET_PATH = '/tmp/cass.sock' 31 | 32 | 33 | def setup_module(): 34 | use_single_node() 35 | 36 | 37 | class UnixSocketWhiteListRoundRobinPolicy(WhiteListRoundRobinPolicy): 38 | def __init__(self, hosts): 39 | self._allowed_hosts = self._allowed_hosts_resolved = tuple(hosts) 40 | RoundRobinPolicy.__init__(self) 41 | 42 | 43 | @notwindows 44 | class UnixSocketTest(unittest.TestCase): 45 | 46 | @classmethod 47 | def setUpClass(cls): 48 | log.debug("Starting socat...") 49 | cls.proc = subprocess.Popen( 50 | ['socat', 51 | 'UNIX-LISTEN:%s,fork' % UNIX_SOCKET_PATH, 52 | 'TCP:localhost:9042'], 53 | stdout=subprocess.PIPE, 54 | stderr=subprocess.STDOUT) 55 | 56 | time.sleep(1) 57 | if cls.proc.poll() is not None: 58 | for line in cls.proc.stdout.readlines(): 59 | log.debug("socat: " + line.decode('utf-8')) 60 | raise Exception("Error while starting socat. Return code: %d" % cls.proc.returncode) 61 | 62 | lbp = UnixSocketWhiteListRoundRobinPolicy([UNIX_SOCKET_PATH]) 63 | ep = ExecutionProfile(load_balancing_policy=lbp) 64 | endpoint = UnixSocketEndPoint(UNIX_SOCKET_PATH) 65 | cls.cluster = TestCluster(contact_points=[endpoint], execution_profiles={EXEC_PROFILE_DEFAULT: ep}) 66 | 67 | @classmethod 68 | def tearDownClass(cls): 69 | cls.cluster.shutdown() 70 | cls.proc.terminate() 71 | 72 | def test_unix_socket_connection(self): 73 | s = self.cluster.connect() 74 | s.execute('select * from system.local') 75 | -------------------------------------------------------------------------------- /tests/unit/io/test_asyncioreactor.py: -------------------------------------------------------------------------------- 1 | AsyncioConnection, ASYNCIO_AVAILABLE = None, False 2 | try: 3 | from cassandra.io.asyncioreactor import AsyncioConnection 4 | import asynctest 5 | ASYNCIO_AVAILABLE = True 6 | except (ImportError, SyntaxError): 7 | AsyncioConnection = None 8 | ASYNCIO_AVAILABLE = False 9 | 10 | from tests import is_monkey_patched, connection_class 11 | from tests.unit.io.utils import TimerCallback, TimerTestMixin 12 | 13 | from unittest.mock import patch 14 | 15 | import unittest 16 | import time 17 | 18 | skip_me = (is_monkey_patched() or 19 | (not ASYNCIO_AVAILABLE) or 20 | (connection_class is not AsyncioConnection)) 21 | 22 | 23 | @unittest.skipIf(is_monkey_patched(), 'runtime is monkey patched for another reactor') 24 | @unittest.skipIf(connection_class is not AsyncioConnection, 25 | 'not running asyncio tests; current connection_class is {}'.format(connection_class)) 26 | @unittest.skipUnless(ASYNCIO_AVAILABLE, "asyncio is not available for this runtime") 27 | class AsyncioTimerTests(TimerTestMixin, unittest.TestCase): 28 | 29 | @classmethod 30 | def setUpClass(cls): 31 | if skip_me: 32 | return 33 | cls.connection_class = AsyncioConnection 34 | AsyncioConnection.initialize_reactor() 35 | 36 | @classmethod 37 | def tearDownClass(cls): 38 | if skip_me: 39 | return 40 | if ASYNCIO_AVAILABLE and AsyncioConnection._loop: 41 | AsyncioConnection._loop.stop() 42 | 43 | @property 44 | def create_timer(self): 45 | return self.connection.create_timer 46 | 47 | @property 48 | def _timers(self): 49 | raise RuntimeError('no TimerManager for AsyncioConnection') 50 | 51 | def setUp(self): 52 | if skip_me: 53 | return 54 | socket_patcher = patch('socket.socket') 55 | self.addCleanup(socket_patcher.stop) 56 | socket_patcher.start() 57 | 58 | old_selector = AsyncioConnection._loop._selector 59 | AsyncioConnection._loop._selector = asynctest.TestSelector() 60 | 61 | def reset_selector(): 62 | AsyncioConnection._loop._selector = old_selector 63 | 64 | self.addCleanup(reset_selector) 65 | 66 | super(AsyncioTimerTests, self).setUp() 67 | 68 | def test_timer_cancellation(self): 69 | # Various lists for tracking callback stage 70 | timeout = .1 71 | callback = TimerCallback(timeout) 72 | timer = self.create_timer(timeout, callback.invoke) 73 | timer.cancel() 74 | # Release context allow for timer thread to run. 75 | time.sleep(.2) 76 | # Assert that the cancellation was honored 77 | self.assertFalse(callback.was_invoked()) 78 | -------------------------------------------------------------------------------- /tests/util.py: -------------------------------------------------------------------------------- 1 | # Licensed to the Apache Software Foundation (ASF) under one 2 | # or more contributor license agreements. See the NOTICE file 3 | # distributed with this work for additional information 4 | # regarding copyright ownership. The ASF licenses this file 5 | # to you under the Apache License, Version 2.0 (the 6 | # "License"); you may not use this file except in compliance 7 | # with the License. You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | import time 18 | from functools import wraps 19 | 20 | 21 | def wait_until(condition, delay, max_attempts): 22 | """ 23 | Executes a function at regular intervals while the condition 24 | is false and the amount of attempts < maxAttempts. 25 | :param condition: a function 26 | :param delay: the delay in second 27 | :param max_attempts: the maximum number of attempts. So the timeout 28 | of this function is delay*max_attempts 29 | """ 30 | attempt = 0 31 | while not condition() and attempt < max_attempts: 32 | attempt += 1 33 | time.sleep(delay) 34 | 35 | if attempt >= max_attempts: 36 | raise Exception("Condition is still False after {} attempts.".format(max_attempts)) 37 | 38 | 39 | def wait_until_not_raised(condition, delay, max_attempts): 40 | """ 41 | Executes a function at regular intervals while the condition 42 | doesn't raise an exception and the amount of attempts < maxAttempts. 43 | :param condition: a function 44 | :param delay: the delay in second 45 | :param max_attempts: the maximum number of attempts. So the timeout 46 | of this function will be delay*max_attempts 47 | """ 48 | def wrapped_condition(): 49 | try: 50 | result = condition() 51 | except: 52 | return False, None 53 | 54 | return True, result 55 | 56 | attempt = 0 57 | while attempt < (max_attempts-1): 58 | attempt += 1 59 | success, result = wrapped_condition() 60 | if success: 61 | return result 62 | 63 | time.sleep(delay) 64 | 65 | # last attempt, let the exception raise 66 | return condition() 67 | 68 | 69 | def late(seconds=1): 70 | def decorator(func): 71 | @wraps(func) 72 | def wrapper(*args, **kwargs): 73 | time.sleep(seconds) 74 | func(*args, **kwargs) 75 | return wrapper 76 | return decorator 77 | -------------------------------------------------------------------------------- /tests/integration/standard/test_custom_cluster.py: -------------------------------------------------------------------------------- 1 | # Licensed to the Apache Software Foundation (ASF) under one 2 | # or more contributor license agreements. See the NOTICE file 3 | # distributed with this work for additional information 4 | # regarding copyright ownership. The ASF licenses this file 5 | # to you under the Apache License, Version 2.0 (the 6 | # "License"); you may not use this file except in compliance 7 | # with the License. You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | from cassandra.cluster import NoHostAvailable 18 | from tests.integration import use_singledc, get_cluster, remove_cluster, local, TestCluster 19 | from tests.util import wait_until, wait_until_not_raised 20 | 21 | import unittest 22 | 23 | 24 | def setup_module(): 25 | use_singledc(start=False) 26 | ccm_cluster = get_cluster() 27 | ccm_cluster.stop() 28 | config_options = {'native_transport_port': 9046} 29 | ccm_cluster.set_configuration_options(config_options) 30 | # can't use wait_for_binary_proto cause ccm tries on port 9042 31 | ccm_cluster.start(wait_for_binary_proto=False) 32 | # wait until all nodes are up 33 | wait_until_not_raised(lambda: TestCluster(contact_points=['127.0.0.1'], port=9046).connect().shutdown(), 1, 20) 34 | wait_until_not_raised(lambda: TestCluster(contact_points=['127.0.0.2'], port=9046).connect().shutdown(), 1, 20) 35 | wait_until_not_raised(lambda: TestCluster(contact_points=['127.0.0.3'], port=9046).connect().shutdown(), 1, 20) 36 | 37 | 38 | def teardown_module(): 39 | remove_cluster() 40 | 41 | 42 | class CustomClusterTests(unittest.TestCase): 43 | 44 | @local 45 | def test_connection_honor_cluster_port(self): 46 | """ 47 | Test that the initial contact point and discovered nodes honor 48 | the cluster port on new connection. 49 | 50 | All hosts should be marked as up and we should be able to execute queries on it. 51 | """ 52 | cluster = TestCluster() 53 | with self.assertRaises(NoHostAvailable): 54 | cluster.connect() # should fail on port 9042 55 | 56 | cluster = TestCluster(port=9046) 57 | session = cluster.connect(wait_for_all_pools=True) 58 | 59 | wait_until(lambda: len(cluster.metadata.all_hosts()) == 3, 1, 5) 60 | for host in cluster.metadata.all_hosts(): 61 | self.assertTrue(host.is_up) 62 | session.execute("select * from system.local", host=host) 63 | -------------------------------------------------------------------------------- /cassandra/datastax/insights/util.py: -------------------------------------------------------------------------------- 1 | # Licensed to the Apache Software Foundation (ASF) under one 2 | # or more contributor license agreements. See the NOTICE file 3 | # distributed with this work for additional information 4 | # regarding copyright ownership. The ASF licenses this file 5 | # to you under the Apache License, Version 2.0 (the 6 | # "License"); you may not use this file except in compliance 7 | # with the License. You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | import logging 18 | import traceback 19 | from warnings import warn 20 | 21 | from cassandra.util import Version 22 | 23 | 24 | DSE_60 = Version('6.0.0') 25 | DSE_51_MIN_SUPPORTED = Version('5.1.13') 26 | DSE_60_MIN_SUPPORTED = Version('6.0.5') 27 | 28 | 29 | log = logging.getLogger(__name__) 30 | 31 | 32 | def namespace(cls): 33 | """ 34 | Best-effort method for getting the namespace in which a class is defined. 35 | """ 36 | try: 37 | # __module__ can be None 38 | module = cls.__module__ or '' 39 | except Exception: 40 | warn("Unable to obtain namespace for {cls} for Insights, returning ''. " 41 | "Exception: \n{e}".format(e=traceback.format_exc(), cls=cls)) 42 | module = '' 43 | 44 | module_internal_namespace = _module_internal_namespace_or_emtpy_string(cls) 45 | if module_internal_namespace: 46 | return '.'.join((module, module_internal_namespace)) 47 | return module 48 | 49 | 50 | def _module_internal_namespace_or_emtpy_string(cls): 51 | """ 52 | Best-effort method for getting the module-internal namespace in which a 53 | class is defined -- i.e. the namespace _inside_ the module. 54 | """ 55 | try: 56 | qualname = cls.__qualname__ 57 | except AttributeError: 58 | return '' 59 | 60 | return '.'.join( 61 | # the last segment is the name of the class -- use everything else 62 | qualname.split('.')[:-1] 63 | ) 64 | 65 | 66 | def version_supports_insights(dse_version): 67 | if dse_version: 68 | try: 69 | dse_version = Version(dse_version) 70 | return (DSE_51_MIN_SUPPORTED <= dse_version < DSE_60 71 | or 72 | DSE_60_MIN_SUPPORTED <= dse_version) 73 | except Exception: 74 | warn("Unable to check version {v} for Insights compatibility, returning False. " 75 | "Exception: \n{e}".format(e=traceback.format_exc(), v=dse_version)) 76 | 77 | return False 78 | -------------------------------------------------------------------------------- /tests/integration/simulacron/__init__.py: -------------------------------------------------------------------------------- 1 | # Copyright DataStax, Inc. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License 14 | import unittest 15 | 16 | from tests.integration import requiredse, CASSANDRA_VERSION, DSE_VERSION, SIMULACRON_JAR, PROTOCOL_VERSION 17 | from tests.integration.simulacron.utils import ( 18 | clear_queries, 19 | start_and_prime_singledc, 20 | stop_simulacron, 21 | start_and_prime_cluster_defaults, 22 | ) 23 | 24 | from cassandra.cluster import Cluster 25 | 26 | from packaging.version import Version 27 | 28 | 29 | PROTOCOL_VERSION = min(4, PROTOCOL_VERSION if (DSE_VERSION is None or DSE_VERSION >= Version('5.0')) else 3) 30 | 31 | 32 | def teardown_package(): 33 | stop_simulacron() 34 | 35 | 36 | class SimulacronBase(unittest.TestCase): 37 | def tearDown(self): 38 | clear_queries() 39 | stop_simulacron() 40 | 41 | 42 | class SimulacronCluster(SimulacronBase): 43 | 44 | cluster, connect = None, True 45 | 46 | @classmethod 47 | def setUpClass(cls): 48 | if SIMULACRON_JAR is None or CASSANDRA_VERSION < Version("2.1"): 49 | return 50 | 51 | start_and_prime_singledc() 52 | if cls.connect: 53 | cls.cluster = Cluster(protocol_version=PROTOCOL_VERSION, compression=False) 54 | cls.session = cls.cluster.connect(wait_for_all_pools=True) 55 | 56 | @classmethod 57 | def tearDownClass(cls): 58 | if SIMULACRON_JAR is None or CASSANDRA_VERSION < Version("2.1"): 59 | return 60 | 61 | if cls.cluster: 62 | cls.cluster.shutdown() 63 | stop_simulacron() 64 | 65 | 66 | @requiredse 67 | class DseSimulacronCluster(SimulacronBase): 68 | 69 | simulacron_cluster = None 70 | cluster, connect = None, True 71 | nodes_per_dc = 1 72 | 73 | @classmethod 74 | def setUpClass(cls): 75 | if DSE_VERSION is None and SIMULACRON_JAR is None or CASSANDRA_VERSION < Version("2.1"): 76 | return 77 | 78 | cls.simulacron_cluster = start_and_prime_cluster_defaults(dse_version=DSE_VERSION, 79 | nodes_per_dc=cls.nodes_per_dc) 80 | if cls.connect: 81 | cls.cluster = Cluster(protocol_version=PROTOCOL_VERSION, compression=False) 82 | cls.session = cls.cluster.connect(wait_for_all_pools=True) 83 | -------------------------------------------------------------------------------- /tests/integration/util.py: -------------------------------------------------------------------------------- 1 | # Licensed to the Apache Software Foundation (ASF) under one 2 | # or more contributor license agreements. See the NOTICE file 3 | # distributed with this work for additional information 4 | # regarding copyright ownership. The ASF licenses this file 5 | # to you under the Apache License, Version 2.0 (the 6 | # "License"); you may not use this file except in compliance 7 | # with the License. You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | from itertools import chain 18 | 19 | from tests.integration import PROTOCOL_VERSION 20 | import time 21 | 22 | 23 | def assert_quiescent_pool_state(test_case, cluster, wait=None): 24 | """ 25 | Checking the quiescent pool state checks that none of the requests ids have 26 | been lost. However, the callback corresponding to a request_id is called 27 | before the request_id is returned back to the pool, therefore 28 | 29 | session.execute("SELECT * from system.local") 30 | assert_quiescent_pool_state(self, session.cluster) 31 | 32 | (with no wait) might fail because when execute comes back the request_id 33 | hasn't yet been returned to the pool, therefore the wait. 34 | """ 35 | if wait is not None: 36 | time.sleep(wait) 37 | 38 | for session in cluster.sessions: 39 | pool_states = session.get_pool_state().values() 40 | test_case.assertTrue(pool_states) 41 | 42 | for state in pool_states: 43 | test_case.assertFalse(state['shutdown']) 44 | test_case.assertGreater(state['open_count'], 0) 45 | no_in_flight = all((i == 0 for i in state['in_flights'])) 46 | orphans_and_inflights = zip(state['orphan_requests'], state['in_flights']) 47 | all_orphaned = all((len(orphans) == inflight for (orphans, inflight) in orphans_and_inflights)) 48 | test_case.assertTrue(no_in_flight or all_orphaned) 49 | 50 | for holder in cluster.get_connection_holders(): 51 | for connection in holder.get_connections(): 52 | # all ids are unique 53 | req_ids = connection.request_ids 54 | orphan_ids = connection.orphaned_request_ids 55 | test_case.assertEqual(len(req_ids), len(set(req_ids))) 56 | test_case.assertEqual(connection.highest_request_id, len(req_ids) + len(orphan_ids) - 1) 57 | test_case.assertEqual(connection.highest_request_id, max(chain(req_ids, orphan_ids))) 58 | if PROTOCOL_VERSION < 3: 59 | test_case.assertEqual(connection.highest_request_id, connection.max_request_id) 60 | -------------------------------------------------------------------------------- /tests/unit/test_endpoints.py: -------------------------------------------------------------------------------- 1 | # Copyright DataStax, Inc. 2 | # 3 | # Licensed under the DataStax DSE Driver License; 4 | # you may not use this file except in compliance with the License. 5 | # 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.datastax.com/terms/datastax-dse-driver-license-terms 9 | import unittest 10 | 11 | import itertools 12 | 13 | from cassandra.connection import DefaultEndPoint, SniEndPoint, SniEndPointFactory 14 | 15 | from unittest.mock import patch 16 | 17 | 18 | def socket_getaddrinfo(*args): 19 | return [ 20 | (0, 0, 0, '', ('127.0.0.1', 30002)), 21 | (0, 0, 0, '', ('127.0.0.2', 30002)), 22 | (0, 0, 0, '', ('127.0.0.3', 30002)) 23 | ] 24 | 25 | 26 | @patch('socket.getaddrinfo', socket_getaddrinfo) 27 | class SniEndPointTest(unittest.TestCase): 28 | 29 | endpoint_factory = SniEndPointFactory("proxy.datastax.com", 30002) 30 | 31 | def test_sni_endpoint_properties(self): 32 | 33 | endpoint = self.endpoint_factory.create_from_sni('test') 34 | self.assertEqual(endpoint.address, 'proxy.datastax.com') 35 | self.assertEqual(endpoint.port, 30002) 36 | self.assertEqual(endpoint._server_name, 'test') 37 | self.assertEqual(str(endpoint), 'proxy.datastax.com:30002:test') 38 | 39 | def test_endpoint_equality(self): 40 | self.assertNotEqual( 41 | DefaultEndPoint('10.0.0.1'), 42 | self.endpoint_factory.create_from_sni('10.0.0.1') 43 | ) 44 | 45 | self.assertEqual( 46 | self.endpoint_factory.create_from_sni('10.0.0.1'), 47 | self.endpoint_factory.create_from_sni('10.0.0.1') 48 | ) 49 | 50 | self.assertNotEqual( 51 | self.endpoint_factory.create_from_sni('10.0.0.1'), 52 | self.endpoint_factory.create_from_sni('10.0.0.0') 53 | ) 54 | 55 | self.assertNotEqual( 56 | self.endpoint_factory.create_from_sni('10.0.0.1'), 57 | SniEndPointFactory("proxy.datastax.com", 9999).create_from_sni('10.0.0.1') 58 | ) 59 | 60 | def test_endpoint_resolve(self): 61 | ips = ['127.0.0.1', '127.0.0.2', '127.0.0.3'] 62 | it = itertools.cycle(ips) 63 | 64 | endpoint = self.endpoint_factory.create_from_sni('test') 65 | for i in range(10): 66 | (address, _) = endpoint.resolve() 67 | self.assertEqual(address, next(it)) 68 | 69 | def test_sni_resolution_start_index(self): 70 | factory = SniEndPointFactory("proxy.datastax.com", 9999) 71 | initial_index = factory._init_index 72 | 73 | endpoint1 = factory.create_from_sni('sni1') 74 | self.assertEqual(factory._init_index, initial_index + 1) 75 | self.assertEqual(endpoint1._index, factory._init_index) 76 | 77 | endpoint2 = factory.create_from_sni('sni2') 78 | self.assertEqual(factory._init_index, initial_index + 2) 79 | self.assertEqual(endpoint2._index, factory._init_index) 80 | -------------------------------------------------------------------------------- /tests/unit/test_query.py: -------------------------------------------------------------------------------- 1 | # Licensed to the Apache Software Foundation (ASF) under one 2 | # or more contributor license agreements. See the NOTICE file 3 | # distributed with this work for additional information 4 | # regarding copyright ownership. The ASF licenses this file 5 | # to you under the Apache License, Version 2.0 (the 6 | # "License"); you may not use this file except in compliance 7 | # with the License. You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | import unittest 18 | 19 | from cassandra.query import BatchStatement, SimpleStatement 20 | 21 | 22 | class BatchStatementTest(unittest.TestCase): 23 | # TODO: this suite could be expanded; for now just adding a test covering a PR 24 | 25 | def test_clear(self): 26 | keyspace = 'keyspace' 27 | routing_key = 'routing_key' 28 | custom_payload = {'key': b'value'} 29 | 30 | ss = SimpleStatement('whatever', keyspace=keyspace, routing_key=routing_key, custom_payload=custom_payload) 31 | 32 | batch = BatchStatement() 33 | batch.add(ss) 34 | 35 | self.assertTrue(batch._statements_and_parameters) 36 | self.assertEqual(batch.keyspace, keyspace) 37 | self.assertEqual(batch.routing_key, routing_key) 38 | self.assertEqual(batch.custom_payload, custom_payload) 39 | 40 | batch.clear() 41 | self.assertFalse(batch._statements_and_parameters) 42 | self.assertIsNone(batch.keyspace) 43 | self.assertIsNone(batch.routing_key) 44 | self.assertFalse(batch.custom_payload) 45 | 46 | batch.add(ss) 47 | 48 | def test_clear_empty(self): 49 | batch = BatchStatement() 50 | batch.clear() 51 | self.assertFalse(batch._statements_and_parameters) 52 | self.assertIsNone(batch.keyspace) 53 | self.assertIsNone(batch.routing_key) 54 | self.assertFalse(batch.custom_payload) 55 | 56 | batch.add('something') 57 | 58 | def test_add_all(self): 59 | batch = BatchStatement() 60 | statements = ['%s'] * 10 61 | parameters = [(i,) for i in range(10)] 62 | batch.add_all(statements, parameters) 63 | bound_statements = [t[1] for t in batch._statements_and_parameters] 64 | str_parameters = [str(i) for i in range(10)] 65 | self.assertEqual(bound_statements, str_parameters) 66 | 67 | def test_len(self): 68 | for n in 0, 10, 100: 69 | batch = BatchStatement() 70 | batch.add_all(statements=['%s'] * n, 71 | parameters=[(i,) for i in range(n)]) 72 | self.assertEqual(len(batch), n) 73 | -------------------------------------------------------------------------------- /example_core.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | # Licensed to the Apache Software Foundation (ASF) under one 4 | # or more contributor license agreements. See the NOTICE file 5 | # distributed with this work for additional information 6 | # regarding copyright ownership. The ASF licenses this file 7 | # to you under the Apache License, Version 2.0 (the 8 | # "License"); you may not use this file except in compliance 9 | # with the License. You may obtain a copy of the License at 10 | # 11 | # http://www.apache.org/licenses/LICENSE-2.0 12 | # 13 | # Unless required by applicable law or agreed to in writing, software 14 | # distributed under the License is distributed on an "AS IS" BASIS, 15 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 16 | # See the License for the specific language governing permissions and 17 | # limitations under the License. 18 | 19 | import logging 20 | 21 | log = logging.getLogger() 22 | log.setLevel('DEBUG') 23 | handler = logging.StreamHandler() 24 | handler.setFormatter(logging.Formatter("%(asctime)s [%(levelname)s] %(name)s: %(message)s")) 25 | log.addHandler(handler) 26 | 27 | from cassandra import ConsistencyLevel 28 | from cassandra.cluster import Cluster 29 | from cassandra.query import SimpleStatement 30 | 31 | KEYSPACE = "testkeyspace" 32 | 33 | 34 | def main(): 35 | cluster = Cluster(['127.0.0.1']) 36 | session = cluster.connect() 37 | 38 | log.info("creating keyspace...") 39 | session.execute(""" 40 | CREATE KEYSPACE IF NOT EXISTS %s 41 | WITH replication = { 'class': 'SimpleStrategy', 'replication_factor': '2' } 42 | """ % KEYSPACE) 43 | 44 | log.info("setting keyspace...") 45 | session.set_keyspace(KEYSPACE) 46 | 47 | log.info("creating table...") 48 | session.execute(""" 49 | CREATE TABLE IF NOT EXISTS mytable ( 50 | thekey text, 51 | col1 text, 52 | col2 text, 53 | PRIMARY KEY (thekey, col1) 54 | ) 55 | """) 56 | 57 | query = SimpleStatement(""" 58 | INSERT INTO mytable (thekey, col1, col2) 59 | VALUES (%(key)s, %(a)s, %(b)s) 60 | """, consistency_level=ConsistencyLevel.ONE) 61 | 62 | prepared = session.prepare(""" 63 | INSERT INTO mytable (thekey, col1, col2) 64 | VALUES (?, ?, ?) 65 | """) 66 | 67 | for i in range(10): 68 | log.info("inserting row %d" % i) 69 | session.execute(query, dict(key="key%d" % i, a='a', b='b')) 70 | session.execute(prepared, ("key%d" % i, 'b', 'b')) 71 | 72 | future = session.execute_async("SELECT * FROM mytable") 73 | log.info("key\tcol1\tcol2") 74 | log.info("---\t----\t----") 75 | 76 | try: 77 | rows = future.result() 78 | except Exception: 79 | log.exception("Error reading rows:") 80 | return 81 | 82 | for row in rows: 83 | log.info('\t'.join(row)) 84 | 85 | session.execute("DROP KEYSPACE " + KEYSPACE) 86 | 87 | if __name__ == "__main__": 88 | main() 89 | -------------------------------------------------------------------------------- /docs/cqlengine/faq.rst: -------------------------------------------------------------------------------- 1 | ========================== 2 | Frequently Asked Questions 3 | ========================== 4 | 5 | Why don't updates work correctly on models instantiated as Model(field=value, field2=value2)? 6 | ------------------------------------------------------------------------------------------------ 7 | 8 | The recommended way to create new rows is with the models .create method. The values passed into a model's init method are interpreted by the model as the values as they were read from a row. This allows the model to "know" which rows have changed since the row was read out of cassandra, and create suitable update statements. 9 | 10 | How to preserve ordering in batch query? 11 | ------------------------------------------- 12 | 13 | Statement Ordering is not supported by CQL3 batches. Therefore, 14 | once cassandra needs resolving conflict(Updating the same column in one batch), 15 | The algorithm below would be used. 16 | 17 | * If timestamps are different, pick the column with the largest timestamp (the value being a regular column or a tombstone) 18 | * If timestamps are the same, and one of the columns in a tombstone ('null') - pick the tombstone 19 | * If timestamps are the same, and none of the columns are tombstones, pick the column with the largest value 20 | 21 | Below is an example to show this scenario. 22 | 23 | .. code-block:: python 24 | 25 | class MyMode(Model): 26 | id = columns.Integer(primary_key=True) 27 | count = columns.Integer() 28 | text = columns.Text() 29 | 30 | with BatchQuery() as b: 31 | MyModel.batch(b).create(id=1, count=2, text='123') 32 | MyModel.batch(b).create(id=1, count=3, text='111') 33 | 34 | assert MyModel.objects(id=1).first().count == 3 35 | assert MyModel.objects(id=1).first().text == '123' 36 | 37 | The largest value of count is 3, and the largest value of text would be '123'. 38 | 39 | The workaround is applying timestamp to each statement, then Cassandra would 40 | resolve to the statement with the lastest timestamp. 41 | 42 | .. code-block:: python 43 | 44 | with BatchQuery() as b: 45 | MyModel.timestamp(datetime.now()).batch(b).create(id=1, count=2, text='123') 46 | MyModel.timestamp(datetime.now()).batch(b).create(id=1, count=3, text='111') 47 | 48 | assert MyModel.objects(id=1).first().count == 3 49 | assert MyModel.objects(id=1).first().text == '111' 50 | 51 | How can I delete individual values from a row? 52 | ------------------------------------------------- 53 | 54 | When inserting with CQLEngine, ``None`` is equivalent to CQL ``NULL`` or to 55 | issuing a ``DELETE`` on that column. For example: 56 | 57 | .. code-block:: python 58 | 59 | class MyModel(Model): 60 | id = columns.Integer(primary_key=True) 61 | text = columns.Text() 62 | 63 | m = MyModel.create(id=1, text='We can delete this with None') 64 | assert MyModel.objects(id=1).first().text is not None 65 | 66 | m.update(text=None) 67 | assert MyModel.objects(id=1).first().text is None 68 | -------------------------------------------------------------------------------- /tests/unit/io/test_eventletreactor.py: -------------------------------------------------------------------------------- 1 | # Licensed to the Apache Software Foundation (ASF) under one 2 | # or more contributor license agreements. See the NOTICE file 3 | # distributed with this work for additional information 4 | # regarding copyright ownership. The ASF licenses this file 5 | # to you under the Apache License, Version 2.0 (the 6 | # "License"); you may not use this file except in compliance 7 | # with the License. You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | 18 | import unittest 19 | 20 | from tests.unit.io.utils import TimerTestMixin 21 | from tests import notpypy, EVENT_LOOP_MANAGER 22 | 23 | from eventlet import monkey_patch 24 | from unittest.mock import patch 25 | 26 | try: 27 | from cassandra.io.eventletreactor import EventletConnection 28 | except ImportError: 29 | EventletConnection = None # noqa 30 | 31 | skip_condition = EventletConnection is None or EVENT_LOOP_MANAGER != "eventlet" 32 | # There are some issues with some versions of pypy and eventlet 33 | @notpypy 34 | @unittest.skipIf(skip_condition, "Skipping the eventlet tests because it's not installed") 35 | class EventletTimerTest(TimerTestMixin, unittest.TestCase): 36 | 37 | connection_class = EventletConnection 38 | 39 | @classmethod 40 | def setUpClass(cls): 41 | # This is run even though the class is skipped, so we need 42 | # to make sure no monkey patching is happening 43 | if skip_condition: 44 | return 45 | 46 | # This is being added temporarily due to a bug in eventlet: 47 | # https://github.com/eventlet/eventlet/issues/401 48 | import eventlet 49 | eventlet.sleep() 50 | monkey_patch() 51 | # cls.connection_class = EventletConnection 52 | 53 | EventletConnection.initialize_reactor() 54 | assert EventletConnection._timers is not None 55 | 56 | def setUp(self): 57 | socket_patcher = patch('eventlet.green.socket.socket') 58 | self.addCleanup(socket_patcher.stop) 59 | socket_patcher.start() 60 | 61 | super(EventletTimerTest, self).setUp() 62 | 63 | recv_patcher = patch.object(self.connection._socket, 64 | 'recv', 65 | return_value=b'') 66 | self.addCleanup(recv_patcher.stop) 67 | recv_patcher.start() 68 | 69 | @property 70 | def create_timer(self): 71 | return self.connection.create_timer 72 | 73 | @property 74 | def _timers(self): 75 | return self.connection._timers 76 | 77 | # There is no unpatching because there is not a clear way 78 | # of doing it reliably 79 | -------------------------------------------------------------------------------- /docs/api/cassandra/datastax/graph/index.rst: -------------------------------------------------------------------------------- 1 | ``cassandra.datastax.graph`` - Graph Statements, Options, and Row Factories 2 | =========================================================================== 3 | 4 | .. _api-datastax-graph: 5 | 6 | .. module:: cassandra.datastax.graph 7 | 8 | .. autofunction:: single_object_row_factory 9 | 10 | .. autofunction:: graph_result_row_factory 11 | 12 | .. autofunction:: graph_object_row_factory 13 | 14 | .. autofunction:: graph_graphson2_row_factory 15 | 16 | .. autofunction:: graph_graphson3_row_factory 17 | 18 | .. function:: to_int(value) 19 | 20 | Wraps a value to be explicitly serialized as a graphson Int. 21 | 22 | .. function:: to_bigint(value) 23 | 24 | Wraps a value to be explicitly serialized as a graphson Bigint. 25 | 26 | .. function:: to_smallint(value) 27 | 28 | Wraps a value to be explicitly serialized as a graphson Smallint. 29 | 30 | .. function:: to_float(value) 31 | 32 | Wraps a value to be explicitly serialized as a graphson Float. 33 | 34 | .. function:: to_double(value) 35 | 36 | Wraps a value to be explicitly serialized as a graphson Double. 37 | 38 | .. autoclass:: GraphProtocol 39 | :members: 40 | 41 | .. autoclass:: GraphOptions 42 | 43 | .. autoattribute:: graph_name 44 | 45 | .. autoattribute:: graph_source 46 | 47 | .. autoattribute:: graph_language 48 | 49 | .. autoattribute:: graph_read_consistency_level 50 | 51 | .. autoattribute:: graph_write_consistency_level 52 | 53 | .. autoattribute:: is_default_source 54 | 55 | .. autoattribute:: is_analytics_source 56 | 57 | .. autoattribute:: is_graph_source 58 | 59 | .. automethod:: set_source_default 60 | 61 | .. automethod:: set_source_analytics 62 | 63 | .. automethod:: set_source_graph 64 | 65 | 66 | .. autoclass:: SimpleGraphStatement 67 | :members: 68 | 69 | .. autoclass:: Result 70 | :members: 71 | 72 | .. autoclass:: Vertex 73 | :members: 74 | 75 | .. autoclass:: VertexProperty 76 | :members: 77 | 78 | .. autoclass:: Edge 79 | :members: 80 | 81 | .. autoclass:: Path 82 | :members: 83 | 84 | .. autoclass:: T 85 | :members: 86 | 87 | .. autoclass:: GraphSON1Serializer 88 | :members: 89 | 90 | .. autoclass:: GraphSON1Deserializer 91 | 92 | .. automethod:: deserialize_date 93 | 94 | .. automethod:: deserialize_timestamp 95 | 96 | .. automethod:: deserialize_time 97 | 98 | .. automethod:: deserialize_duration 99 | 100 | .. automethod:: deserialize_int 101 | 102 | .. automethod:: deserialize_bigint 103 | 104 | .. automethod:: deserialize_double 105 | 106 | .. automethod:: deserialize_float 107 | 108 | .. automethod:: deserialize_uuid 109 | 110 | .. automethod:: deserialize_blob 111 | 112 | .. automethod:: deserialize_decimal 113 | 114 | .. automethod:: deserialize_point 115 | 116 | .. automethod:: deserialize_linestring 117 | 118 | .. automethod:: deserialize_polygon 119 | 120 | .. autoclass:: GraphSON2Reader 121 | :members: 122 | --------------------------------------------------------------------------------