Skip to content

Commit bbbd861

Browse files
committed
Update API docs, upgrade guide for 2.1
1 parent 604c80b commit bbbd861

10 files changed

Lines changed: 183 additions & 21 deletions

File tree

cassandra/cluster.py

Lines changed: 29 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -179,12 +179,29 @@ class Cluster(object):
179179

180180
protocol_version = 2
181181
"""
182-
The version of the native protocol to use. The protocol version 2
183-
add support for lightweight transactions, batch operations, and
184-
automatic query paging, but is only supported by Cassandra 2.0+. When
185-
working with Cassandra 1.2, this must be set to 1. You can also set
186-
this to 1 when working with Cassandra 2.0+, but features that require
187-
the version 2 protocol will not be enabled.
182+
The version of the native protocol to use.
183+
184+
Version 2 of the native protocol adds support for lightweight transactions,
185+
batch operations, and automatic query paging. The v2 protocol is
186+
supported by Cassandra 2.0+.
187+
188+
Version 3 of the native protocol adds support for protocol-level
189+
client-side timestamps (see :attr:`.Session.use_client_timestamp`),
190+
serial consistency levels for :class:`~.BatchStatement`, and an
191+
improved connection pool.
192+
193+
The following table describes the native protocol versions that
194+
are supported by each version of Cassandra:
195+
196+
+-------------------+-------------------+
197+
| Cassandra Version | Protocol Versions |
198+
+===================+===================+
199+
| 1.2 | 1 |
200+
+-------------------+-------------------+
201+
| 2.0 | 1, 2 |
202+
+-------------------+-------------------+
203+
| 2.1 | 1, 2, 3 |
204+
+-------------------+-------------------+
188205
"""
189206

190207
compression = True
@@ -320,8 +337,8 @@ def auth_provider(self, value):
320337
321338
* :class:`cassandra.io.asyncorereactor.AsyncoreConnection`
322339
* :class:`cassandra.io.libevreactor.LibevConnection`
323-
* :class:`cassandra.io.libevreactor.GeventConnection` (requires monkey-patching)
324-
* :class:`cassandra.io.libevreactor.TwistedConnection`
340+
* :class:`cassandra.io.geventreactor.GeventConnection` (requires monkey-patching)
341+
* :class:`cassandra.io.twistedreactor.TwistedConnection`
325342
326343
By default, ``AsyncoreConnection`` will be used, which uses
327344
the ``asyncore`` module in the Python standard library. The
@@ -1191,6 +1208,8 @@ class Session(object):
11911208
11921209
session.execute("CREATE TABLE mytable (k int PRIMARY KEY, col tuple<int, ascii>)")
11931210
session.execute("INSERT INTO mytable (k, col) VALUES (%s, %s)", [0, (123, 'abc')])
1211+
1212+
.. versionadded:: 2.1.0
11941213
"""
11951214

11961215
_lock = None
@@ -1614,6 +1633,8 @@ def get_pool_state(self):
16141633
class UserTypeDoesNotExist(Exception):
16151634
"""
16161635
An attempt was made to use a user-defined type that does not exist.
1636+
1637+
.. versionadded:: 2.1.0
16171638
"""
16181639
pass
16191640

cassandra/metadata.py

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -458,6 +458,10 @@ def make_token_replica_map(self, token_to_host_owner, ring):
458458
return replica_map
459459

460460
def export_for_schema(self):
461+
"""
462+
Returns a string version of these replication options which are
463+
suitable for use in a CREATE KEYSPACE statement.
464+
"""
461465
return "{'class': 'SimpleStrategy', 'replication_factor': '%d'}" \
462466
% (self.replication_factor,)
463467

@@ -537,6 +541,10 @@ def make_token_replica_map(self, token_to_host_owner, ring):
537541
return replica_map
538542

539543
def export_for_schema(self):
544+
"""
545+
Returns a string version of these replication options which are
546+
suitable for use in a CREATE KEYSPACE statement.
547+
"""
540548
ret = "{'class': 'NetworkTopologyStrategy'"
541549
for dc, repl_factor in self.dc_replication_factors:
542550
ret += ", '%s': '%d'" % (dc, repl_factor)
@@ -557,6 +565,10 @@ def make_token_replica_map(self, token_to_host_owner, ring):
557565
return {}
558566

559567
def export_for_schema(self):
568+
"""
569+
Returns a string version of these replication options which are
570+
suitable for use in a CREATE KEYSPACE statement.
571+
"""
560572
return "{'class': 'LocalStrategy'}"
561573

562574
def __eq__(self, other):
@@ -588,6 +600,11 @@ class KeyspaceMetadata(object):
588600
"""
589601

590602
user_types = None
603+
"""
604+
A map from user-defined type names to instances of :class:`~cassandra.metadata..UserType`.
605+
606+
.. versionadded:: 2.1.0
607+
"""
591608

592609
def __init__(self, name, durable_writes, strategy_class, strategy_options):
593610
self.name = name
@@ -597,9 +614,17 @@ def __init__(self, name, durable_writes, strategy_class, strategy_options):
597614
self.user_types = {}
598615

599616
def export_as_string(self):
617+
"""
618+
Returns a CQL query string that can be used to recreate the entire keyspace,
619+
including user-defined types and tables.
620+
"""
600621
return "\n\n".join([self.as_cql_query()] + self.user_type_strings() + [t.export_as_string() for t in self.tables.values()])
601622

602623
def as_cql_query(self):
624+
"""
625+
Returns a CQL query string that can be used to recreate just this keyspace,
626+
not including user-defined types and tables.
627+
"""
603628
ret = "CREATE KEYSPACE %s WITH replication = %s " % (
604629
protect_name(self.name),
605630
self.replication_strategy.export_for_schema())
@@ -950,6 +975,10 @@ class ColumnMetadata(object):
950975
""" The string name of this column. """
951976

952977
data_type = None
978+
"""
979+
The data type for the column in the form of an instance of one of
980+
the type classes in :mod:`cassandra.cqltypes`.
981+
"""
953982

954983
index = None
955984
"""

cassandra/query.py

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -572,11 +572,17 @@ class BatchStatement(Statement):
572572
:attr:`.BatchType.LOGGED`.
573573
"""
574574

575+
serial_consistency_level = None
576+
"""
577+
The same as :attr:`.Statement.serial_consistency_level`, but is only
578+
supported when using protocol version 3 or higher.
579+
"""
580+
575581
_statements_and_parameters = None
576582
_session = None
577583

578584
def __init__(self, batch_type=BatchType.LOGGED, retry_policy=None,
579-
consistency_level=None, session=None):
585+
consistency_level=None, serial_consistency_level=None, session=None):
580586
"""
581587
`batch_type` specifies The :class:`.BatchType` for the batch operation.
582588
Defaults to :attr:`.BatchType.LOGGED`.
@@ -609,11 +615,15 @@ def __init__(self, batch_type=BatchType.LOGGED, retry_policy=None,
609615
session.execute(batch)
610616
611617
.. versionadded:: 2.0.0
618+
619+
.. versionchanged:: 2.1.0
620+
Added `serial_consistency_level` as a parameter
612621
"""
613622
self.batch_type = batch_type
614623
self._statements_and_parameters = []
615624
self._session = session
616-
Statement.__init__(self, retry_policy=retry_policy, consistency_level=consistency_level)
625+
Statement.__init__(self, retry_policy=retry_policy, consistency_level=consistency_level,
626+
serial_consistency_level=serial_consistency_level)
617627

618628
def add(self, statement, parameters=None):
619629
"""
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
``cassandra.io.geventreactor`` - ``gevent``-compatible Event Loop
2+
=================================================================
3+
4+
.. module:: cassandra.io.geventreactor
5+
6+
.. autoclass:: GeventConnection
7+
:members:
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
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.

docs/api/index.rst

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,3 +18,5 @@ API Documentation
1818
cassandra/connection
1919
cassandra/io/asyncorereactor
2020
cassandra/io/libevreactor
21+
cassandra/io/geventreactor
22+
cassandra/io/twistedreactor

docs/getting_started.rst

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -190,6 +190,8 @@ Only data values should be supplied this way. Other items, such as keyspaces,
190190
table names, and column names should be set ahead of time (typically using
191191
normal string formatting).
192192

193+
.. _type-conversions:
194+
193195
Type Conversions
194196
^^^^^^^^^^^^^^^^
195197
For non-prepared statements, Python types are cast to CQL literals in the
@@ -360,9 +362,7 @@ handles re-preparing against new nodes and restarted nodes when necessary.
360362
361363
Note that the placeholders for prepared statements are ``?`` characters. This
362364
is different than for simple, non-prepared statements (although future versions
363-
of the driver may use the same placeholders for both). Cassandra 2.0 added
364-
support for named placeholders; the 1.0 version of the driver does not support
365-
them, but the 2.0 version will.
365+
of the driver may use the same placeholders for both).
366366
367367
Setting a Consistency Level with Prepared Statements
368368
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

docs/upgrading.rst

Lines changed: 89 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,95 @@
11
Upgrading
22
=========
33

4+
.. toctree::
5+
:maxdepth: 1
6+
7+
Upgrading to 2.1 from 2.0
8+
-------------------------
9+
Version 2.1 of the Datastax python driver for Apache Cassandra
10+
adds support for Cassandra 2.1 and version 3 of the native protocol.
11+
12+
Cassandra 1.2, 2.0, and 2.1 are all supported. However, 1.2 only
13+
supports protocol version 1, and 2.0 only supports versions 1 and
14+
2, so some features may not be available.
15+
16+
Using the v3 Native Protocol
17+
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
18+
By default, the driver will attempt to use version 2 of the
19+
native protocol. To use version 3, you must explicitly
20+
set the :attr:`~.Cluster.protocol_version`:
21+
22+
.. code-block:: python
23+
24+
from cassandra.cluster import Cluster
25+
26+
cluster = Cluster(protocol_version=3)
27+
28+
Note that protocol version 3 is only supported by Cassandra 2.1+.
29+
30+
In future releases, the driver may default to using protocol version
31+
3.
32+
33+
Working with User-Defined Types
34+
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
35+
Cassandra 2.1 introduced the ability to define new types::
36+
37+
USE KEYSPACE mykeyspace;
38+
39+
CREATE TYPE address (street text, city text, zip int);
40+
41+
The driver generally expects you to use instances of a specific
42+
class to represent column values of this type. You can let the
43+
driver know what class to use with :meth:`.Cluster.register_user_type`:
44+
45+
.. code-block:: python
46+
47+
cluster = Cluster()
48+
49+
class Address(object):
50+
51+
def __init__(self, street, city, zipcode):
52+
self.street = street
53+
self.city = text
54+
self.zipcode = zipcode
55+
56+
cluster.register_user_type('mykeyspace', 'address', Address)
57+
58+
When inserting data for ``address`` columns, you should pass in
59+
instances of ``Address``. When querying data, ``address`` column
60+
values will be instances of ``Address``.
61+
62+
If no class is registered for a user-defined type, query results
63+
will use a ``namedtuple`` class and data may only be inserted
64+
though prepared statements.
65+
66+
Customizing Encoders for Non-prepared Statements
67+
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
68+
Starting with version 2.1 of the driver, it is possible to customize
69+
how python types are converted to CQL literals when working with
70+
non-prepared statements. This is done on a per-:class:`~.Session`
71+
basis through :attr:`.Session.encoder`:
72+
73+
.. code-block:: python
74+
75+
cluster = Cluster()
76+
session = cluster.connect()
77+
session.encoder.mapping[tuple] = session.encoder.cql_encode_tuple
78+
79+
See :ref:`type-conversions` for the table of default CQL literal conversions.
80+
81+
Using Client-Side Protocol-Level Timestamps
82+
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
83+
With version 3 of the native protocol, timestamps may be supplied by the
84+
client at the protocol level. (Normally, if they are not specified within
85+
the CQL query itself, a timestamp is generated server-side.)
86+
87+
When :attr:`~.Cluster.protocol_version` is set to 3 or higher, the driver
88+
will automatically use client-side timestamps with microsecond precision
89+
unless :attr:`.Session.use_client_timestamp` is changed to :const:`False`.
90+
If a timestamp is specified within the CQL query, it will override the
91+
timestamp generated by the driver.
92+
493
Upgrading to 2.0 from 1.x
594
-------------------------
695
Version 2.0 of the DataStax python driver for Apache Cassandra

example.py

Lines changed: 2 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -33,14 +33,9 @@ def main():
3333
cluster = Cluster(['127.0.0.1'])
3434
session = cluster.connect()
3535

36-
rows = session.execute("SELECT keyspace_name FROM system.schema_keyspaces")
37-
if KEYSPACE in [row[0] for row in rows]:
38-
log.info("dropping existing keyspace...")
39-
session.execute("DROP KEYSPACE " + KEYSPACE)
40-
4136
log.info("creating keyspace...")
4237
session.execute("""
43-
CREATE KEYSPACE %s
38+
CREATE KEYSPACE IF NOT EXISTS %s
4439
WITH replication = { 'class': 'SimpleStrategy', 'replication_factor': '2' }
4540
""" % KEYSPACE)
4641

@@ -49,7 +44,7 @@ def main():
4944

5045
log.info("creating table...")
5146
session.execute("""
52-
CREATE TABLE mytable (
47+
CREATE TABLE IF NOT EXISTS mytable (
5348
thekey text,
5449
col1 text,
5550
col2 text,

setup.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -96,7 +96,7 @@ def run(self):
9696

9797
print("")
9898
print("Documentation step '%s' performed, results here:" % mode)
99-
print(" %s/" % path)
99+
print(" file://%s/%s/index.html" % (os.path.dirname(os.path.realpath(__file__)), path))
100100

101101

102102
class BuildFailed(Exception):

0 commit comments

Comments
 (0)