http://git-wip-us.apache.org/repos/asf/cassandra/blob/54f7335c/doc/source/cql/security.rst ---------------------------------------------------------------------- diff --git a/doc/source/cql/security.rst b/doc/source/cql/security.rst new file mode 100644 index 0000000..f119c22 --- /dev/null +++ b/doc/source/cql/security.rst @@ -0,0 +1,637 @@ +.. Licensed to the Apache Software Foundation (ASF) under one +.. or more contributor license agreements. See the NOTICE file +.. distributed with this work for additional information +.. regarding copyright ownership. The ASF licenses this file +.. to you under the Apache License, Version 2.0 (the +.. "License"); you may not use this file except in compliance +.. with the License. You may obtain a copy of the License at +.. +.. http://www.apache.org/licenses/LICENSE-2.0 +.. +.. Unless required by applicable law or agreed to in writing, software +.. distributed under the License is distributed on an "AS IS" BASIS, +.. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +.. See the License for the specific language governing permissions and +.. limitations under the License. + +.. highlight:: sql + +.. _cql-security: + +Security +-------- + +.. _roles: + +Database Roles +^^^^^^^^^^^^^^ + +CREATE ROLE +~~~~~~~~~~~ + +*Syntax:* + +| bc(syntax).. +| ::= CREATE ROLE ( IF NOT EXISTS )? ( WITH ( AND )\* )? + +| ::= PASSWORD = +| \| LOGIN = +| \| SUPERUSER = +| \| OPTIONS = +| p. + +*Sample:* + +| bc(sample). +| CREATE ROLE new\_role; +| CREATE ROLE alice WITH PASSWORD = âpassword\_aâ AND LOGIN = true; +| CREATE ROLE bob WITH PASSWORD = âpassword\_bâ AND LOGIN = true AND + SUPERUSER = true; +| CREATE ROLE carlos WITH OPTIONS = { âcustom\_option1â : + âoption1\_valueâ, âcustom\_option2â : 99 }; + +By default roles do not possess ``LOGIN`` privileges or ``SUPERUSER`` +status. + +`Permissions <#permissions>`__ on database resources are granted to +roles; types of resources include keyspaces, tables, functions and roles +themselves. Roles may be granted to other roles to create hierarchical +permissions structures; in these hierarchies, permissions and +``SUPERUSER`` status are inherited, but the ``LOGIN`` privilege is not. + +If a role has the ``LOGIN`` privilege, clients may identify as that role +when connecting. For the duration of that connection, the client will +acquire any roles and privileges granted to that role. + +Only a client with with the ``CREATE`` permission on the database roles +resource may issue ``CREATE ROLE`` requests (see the `relevant +section <#permissions>`__ below), unless the client is a ``SUPERUSER``. +Role management in Cassandra is pluggable and custom implementations may +support only a subset of the listed options. + +Role names should be quoted if they contain non-alphanumeric characters. + +.. _setting-credentials-for-internal-authentication: + +Setting credentials for internal authentication +``````````````````````````````````````````````` + +| Use the ``WITH PASSWORD`` clause to set a password for internal + authentication, enclosing the password in single quotation marks. +| If internal authentication has not been set up or the role does not + have ``LOGIN`` privileges, the ``WITH PASSWORD`` clause is not + necessary. + +Creating a role conditionally +````````````````````````````` + +Attempting to create an existing role results in an invalid query +condition unless the ``IF NOT EXISTS`` option is used. If the option is +used and the role exists, the statement is a no-op. + +| bc(sample). +| CREATE ROLE other\_role; +| CREATE ROLE IF NOT EXISTS other\_role; + +ALTER ROLE +~~~~~~~~~~ + +*Syntax:* + +| bc(syntax).. +| ::= ALTER ROLE ( WITH ( AND )\* )? + +| ::= PASSWORD = +| \| LOGIN = +| \| SUPERUSER = +| \| OPTIONS = +| p. + +*Sample:* + +| bc(sample). +| ALTER ROLE bob WITH PASSWORD = âPASSWORD\_Bâ AND SUPERUSER = false; + +Conditions on executing ``ALTER ROLE`` statements: + +- A client must have ``SUPERUSER`` status to alter the ``SUPERUSER`` + status of another role +- A client cannot alter the ``SUPERUSER`` status of any role it + currently holds +- A client can only modify certain properties of the role with which it + identified at login (e.g. ``PASSWORD``) +- To modify properties of a role, the client must be granted ``ALTER`` + `permission <#permissions>`__ on that role + +DROP ROLE +~~~~~~~~~ + +*Syntax:* + +| bc(syntax).. +| ::= DROP ROLE ( IF EXISTS )? +| p. + +*Sample:* + +| bc(sample). +| DROP ROLE alice; +| DROP ROLE IF EXISTS bob; + +| ``DROP ROLE`` requires the client to have ``DROP`` + `permission <#permissions>`__ on the role in question. In addition, + client may not ``DROP`` the role with which it identified at login. + Finaly, only a client with ``SUPERUSER`` status may ``DROP`` another + ``SUPERUSER`` role. +| Attempting to drop a role which does not exist results in an invalid + query condition unless the ``IF EXISTS`` option is used. If the option + is used and the role does not exist the statement is a no-op. + +GRANT ROLE +~~~~~~~~~~ + +*Syntax:* + +| bc(syntax). +| ::= GRANT TO + +*Sample:* + +| bc(sample). +| GRANT report\_writer TO alice; + +| This statement grants the ``report_writer`` role to ``alice``. Any + permissions granted to ``report_writer`` are also acquired by + ``alice``. +| Roles are modelled as a directed acyclic graph, so circular grants are + not permitted. The following examples result in error conditions: + +| bc(sample). +| GRANT role\_a TO role\_b; +| GRANT role\_b TO role\_a; + +| bc(sample). +| GRANT role\_a TO role\_b; +| GRANT role\_b TO role\_c; +| GRANT role\_c TO role\_a; + +REVOKE ROLE +~~~~~~~~~~~ + +*Syntax:* + +| bc(syntax). +| ::= REVOKE FROM + +*Sample:* + +| bc(sample). +| REVOKE report\_writer FROM alice; + +This statement revokes the ``report_writer`` role from ``alice``. Any +permissions that ``alice`` has acquired via the ``report_writer`` role +are also revoked. + +LIST ROLES +~~~~~~~~~~ + +*Syntax:* + +| bc(syntax). +| ::= LIST ROLES ( OF )? ( NORECURSIVE )? + +*Sample:* + +| bc(sample). +| LIST ROLES; + +Return all known roles in the system, this requires ``DESCRIBE`` +permission on the database roles resource. + +| bc(sample). +| LIST ROLES OF ``alice``; + +Enumerate all roles granted to ``alice``, including those transitively +aquired. + +| bc(sample). +| LIST ROLES OF ``bob`` NORECURSIVE + +List all roles directly granted to ``bob``. + +CREATE USER +~~~~~~~~~~~ + +Prior to the introduction of roles in Cassandra 2.2, authentication and +authorization were based around the concept of a ``USER``. For backward +compatibility, the legacy syntax has been preserved with ``USER`` +centric statments becoming synonyms for the ``ROLE`` based equivalents. + +*Syntax:* + +| bc(syntax).. +| ::= CREATE USER ( IF NOT EXISTS )? ( WITH PASSWORD )? ()? + +| ::= SUPERUSER +| \| NOSUPERUSER +| p. + +*Sample:* + +| bc(sample). +| CREATE USER alice WITH PASSWORD âpassword\_aâ SUPERUSER; +| CREATE USER bob WITH PASSWORD âpassword\_bâ NOSUPERUSER; + +``CREATE USER`` is equivalent to ``CREATE ROLE`` where the ``LOGIN`` +option is ``true``. So, the following pairs of statements are +equivalent: + +| bc(sample).. +| CREATE USER alice WITH PASSWORD âpassword\_aâ SUPERUSER; +| CREATE ROLE alice WITH PASSWORD = âpassword\_aâ AND LOGIN = true AND + SUPERUSER = true; + +| CREATE USER IF EXISTS alice WITH PASSWORD âpassword\_aâ SUPERUSER; +| CREATE ROLE IF EXISTS alice WITH PASSWORD = âpassword\_aâ AND LOGIN = + true AND SUPERUSER = true; + +| CREATE USER alice WITH PASSWORD âpassword\_aâ NOSUPERUSER; +| CREATE ROLE alice WITH PASSWORD = âpassword\_aâ AND LOGIN = true AND + SUPERUSER = false; + +| CREATE USER alice WITH PASSWORD âpassword\_aâ NOSUPERUSER; +| CREATE ROLE alice WITH PASSWORD = âpassword\_aâ WITH LOGIN = true; + +| CREATE USER alice WITH PASSWORD âpassword\_aâ; +| CREATE ROLE alice WITH PASSWORD = âpassword\_aâ WITH LOGIN = true; +| p. + +ALTER USER +~~~~~~~~~~ + +*Syntax:* + +| bc(syntax).. +| ::= ALTER USER ( WITH PASSWORD )? ( )? + +| ::= SUPERUSER +| \| NOSUPERUSER +| p. + +| bc(sample). +| ALTER USER alice WITH PASSWORD âPASSWORD\_Aâ; +| ALTER USER bob SUPERUSER; + +DROP USER +~~~~~~~~~ + +*Syntax:* + +| bc(syntax).. +| ::= DROP USER ( IF EXISTS )? +| p. + +*Sample:* + +| bc(sample). +| DROP USER alice; +| DROP USER IF EXISTS bob; + +LIST USERS +~~~~~~~~~~ + +*Syntax:* + +| bc(syntax). +| ::= LIST USERS; + +*Sample:* + +| bc(sample). +| LIST USERS; + +This statement is equivalent to + +| bc(sample). +| LIST ROLES; + +but only roles with the ``LOGIN`` privilege are included in the output. + +Data Control +^^^^^^^^^^^^ + +.. _permissions: + +Permissions +~~~~~~~~~~~ + +Permissions on resources are granted to roles; there are several +different types of resources in Cassandra and each type is modelled +hierarchically: + +- The hierarchy of Data resources, Keyspaces and Tables has the + structure ``ALL KEYSPACES`` [STRIKEOUT:> ``KEYSPACE``]> ``TABLE`` +- Function resources have the structure ``ALL FUNCTIONS`` [STRIKEOUT:> + ``KEYSPACE``]> ``FUNCTION`` +- Resources representing roles have the structure ``ALL ROLES`` -> + ``ROLE`` +- Resources representing JMX ObjectNames, which map to sets of + MBeans/MXBeans, have the structure ``ALL MBEANS`` -> ``MBEAN`` + +Permissions can be granted at any level of these hierarchies and they +flow downwards. So granting a permission on a resource higher up the +chain automatically grants that same permission on all resources lower +down. For example, granting ``SELECT`` on a ``KEYSPACE`` automatically +grants it on all ``TABLES`` in that ``KEYSPACE``. Likewise, granting a +permission on ``ALL FUNCTIONS`` grants it on every defined function, +regardless of which keyspace it is scoped in. It is also possible to +grant permissions on all functions scoped to a particular keyspace. + +Modifications to permissions are visible to existing client sessions; +that is, connections need not be re-established following permissions +changes. + +The full set of available permissions is: + +- ``CREATE`` +- ``ALTER`` +- ``DROP`` +- ``SELECT`` +- ``MODIFY`` +- ``AUTHORIZE`` +- ``DESCRIBE`` +- ``EXECUTE`` + +Not all permissions are applicable to every type of resource. For +instance, ``EXECUTE`` is only relevant in the context of functions or +mbeans; granting ``EXECUTE`` on a resource representing a table is +nonsensical. Attempting to ``GRANT`` a permission on resource to which +it cannot be applied results in an error response. The following +illustrates which permissions can be granted on which types of resource, +and which statements are enabled by that permission. + ++-----------------+---------------------------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| permission | resource | operations | ++=================+=================================+======================================================================================================================================================================+ +| ``CREATE`` | ``ALL KEYSPACES`` | ``CREATE KEYSPACE`` <br> ``CREATE TABLE`` in any keyspace | ++-----------------+---------------------------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| ``CREATE`` | ``KEYSPACE`` | ``CREATE TABLE`` in specified keyspace | ++-----------------+---------------------------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| ``CREATE`` | ``ALL FUNCTIONS`` | ``CREATE FUNCTION`` in any keyspace <br> ``CREATE AGGREGATE`` in any keyspace | ++-----------------+---------------------------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| ``CREATE`` | ``ALL FUNCTIONS IN KEYSPACE`` | ``CREATE FUNCTION`` in keyspace <br> ``CREATE AGGREGATE`` in keyspace | ++-----------------+---------------------------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| ``CREATE`` | ``ALL ROLES`` | ``CREATE ROLE`` | ++-----------------+---------------------------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| ``ALTER`` | ``ALL KEYSPACES`` | ``ALTER KEYSPACE`` <br> ``ALTER TABLE`` in any keyspace | ++-----------------+---------------------------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| ``ALTER`` | ``KEYSPACE`` | ``ALTER KEYSPACE`` <br> ``ALTER TABLE`` in keyspace | ++-----------------+---------------------------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| ``ALTER`` | ``TABLE`` | ``ALTER TABLE`` | ++-----------------+---------------------------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| ``ALTER`` | ``ALL FUNCTIONS`` | ``CREATE FUNCTION`` replacing any existing <br> ``CREATE AGGREGATE`` replacing any existing | ++-----------------+---------------------------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| ``ALTER`` | ``ALL FUNCTIONS IN KEYSPACE`` | ``CREATE FUNCTION`` replacing existing in keyspace <br> ``CREATE AGGREGATE`` replacing any existing in keyspace | ++-----------------+---------------------------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| ``ALTER`` | ``FUNCTION`` | ``CREATE FUNCTION`` replacing existing <br> ``CREATE AGGREGATE`` replacing existing | ++-----------------+---------------------------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| ``ALTER`` | ``ALL ROLES`` | ``ALTER ROLE`` on any role | ++-----------------+---------------------------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| ``ALTER`` | ``ROLE`` | ``ALTER ROLE`` | ++-----------------+---------------------------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| ``DROP`` | ``ALL KEYSPACES`` | ``DROP KEYSPACE`` <br> ``DROP TABLE`` in any keyspace | ++-----------------+---------------------------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| ``DROP`` | ``KEYSPACE`` | ``DROP TABLE`` in specified keyspace | ++-----------------+---------------------------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| ``DROP`` | ``TABLE`` | ``DROP TABLE`` | ++-----------------+---------------------------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| ``DROP`` | ``ALL FUNCTIONS`` | ``DROP FUNCTION`` in any keyspace <br> ``DROP AGGREGATE`` in any existing | ++-----------------+---------------------------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| ``DROP`` | ``ALL FUNCTIONS IN KEYSPACE`` | ``DROP FUNCTION`` in keyspace <br> ``DROP AGGREGATE`` in existing | ++-----------------+---------------------------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| ``DROP`` | ``FUNCTION`` | ``DROP FUNCTION`` | ++-----------------+---------------------------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| ``DROP`` | ``ALL ROLES`` | ``DROP ROLE`` on any role | ++-----------------+---------------------------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| ``DROP`` | ``ROLE`` | ``DROP ROLE`` | ++-----------------+---------------------------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| ``SELECT`` | ``ALL KEYSPACES`` | ``SELECT`` on any table | ++-----------------+---------------------------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| ``SELECT`` | ``KEYSPACE`` | ``SELECT`` on any table in keyspace | ++-----------------+---------------------------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| ``SELECT`` | ``TABLE`` | ``SELECT`` on specified table | ++-----------------+---------------------------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| ``SELECT`` | ``ALL MBEANS`` | Call getter methods on any mbean | ++-----------------+---------------------------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| ``SELECT`` | ``MBEANS`` | Call getter methods on any mbean matching a wildcard pattern | ++-----------------+---------------------------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| ``SELECT`` | ``MBEAN`` | Call getter methods on named mbean | ++-----------------+---------------------------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| ``MODIFY`` | ``ALL KEYSPACES`` | ``INSERT`` on any table <br> ``UPDATE`` on any table <br> ``DELETE`` on any table <br> ``TRUNCATE`` on any table | ++-----------------+---------------------------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| ``MODIFY`` | ``KEYSPACE`` | ``INSERT`` on any table in keyspace <br> ``UPDATE`` on any table in keyspace <br> ``DELETE`` on any table in keyspace <br> ``TRUNCATE`` on any table in keyspace | ++-----------------+---------------------------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| ``MODIFY`` | ``TABLE`` | ``INSERT`` <br> ``UPDATE`` <br> ``DELETE`` <br> ``TRUNCATE`` | ++-----------------+---------------------------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| ``MODIFY`` | ``ALL MBEANS`` | Call setter methods on any mbean | ++-----------------+---------------------------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| ``MODIFY`` | ``MBEANS`` | Call setter methods on any mbean matching a wildcard pattern | ++-----------------+---------------------------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| ``MODIFY`` | ``MBEAN`` | Call setter methods on named mbean | ++-----------------+---------------------------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| ``AUTHORIZE`` | ``ALL KEYSPACES`` | ``GRANT PERMISSION`` on any table <br> ``REVOKE PERMISSION`` on any table | ++-----------------+---------------------------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| ``AUTHORIZE`` | ``KEYSPACE`` | ``GRANT PERMISSION`` on table in keyspace <br> ``REVOKE PERMISSION`` on table in keyspace | ++-----------------+---------------------------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| ``AUTHORIZE`` | ``TABLE`` | ``GRANT PERMISSION`` <br> ``REVOKE PERMISSION`` | ++-----------------+---------------------------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| ``AUTHORIZE`` | ``ALL FUNCTIONS`` | ``GRANT PERMISSION`` on any function <br> ``REVOKE PERMISSION`` on any function | ++-----------------+---------------------------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| ``AUTHORIZE`` | ``ALL FUNCTIONS IN KEYSPACE`` | ``GRANT PERMISSION`` in keyspace <br> ``REVOKE PERMISSION`` in keyspace | ++-----------------+---------------------------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| ``AUTHORIZE`` | ``ALL FUNCTIONS IN KEYSPACE`` | ``GRANT PERMISSION`` in keyspace <br> ``REVOKE PERMISSION`` in keyspace | ++-----------------+---------------------------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| ``AUTHORIZE`` | ``FUNCTION`` | ``GRANT PERMISSION`` <br> ``REVOKE PERMISSION`` | ++-----------------+---------------------------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| ``AUTHORIZE`` | ``ALL MBEANS`` | ``GRANT PERMISSION`` on any mbean <br> ``REVOKE PERMISSION`` on any mbean | ++-----------------+---------------------------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| ``AUTHORIZE`` | ``MBEANS`` | ``GRANT PERMISSION`` on any mbean matching a wildcard pattern <br> ``REVOKE PERMISSION`` on any mbean matching a wildcard pattern | ++-----------------+---------------------------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| ``AUTHORIZE`` | ``MBEAN`` | ``GRANT PERMISSION`` on named mbean <br> ``REVOKE PERMISSION`` on named mbean | ++-----------------+---------------------------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| ``AUTHORIZE`` | ``ALL ROLES`` | ``GRANT ROLE`` grant any role <br> ``REVOKE ROLE`` revoke any role | ++-----------------+---------------------------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| ``AUTHORIZE`` | ``ROLES`` | ``GRANT ROLE`` grant role <br> ``REVOKE ROLE`` revoke role | ++-----------------+---------------------------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| ``DESCRIBE`` | ``ALL ROLES`` | ``LIST ROLES`` all roles or only roles granted to another, specified role | ++-----------------+---------------------------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| ``DESCRIBE`` | @ALL MBEANS | Retrieve metadata about any mbean from the platformâs MBeanServer | ++-----------------+---------------------------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| ``DESCRIBE`` | @MBEANS | Retrieve metadata about any mbean matching a wildcard patter from the platformâs MBeanServer | ++-----------------+---------------------------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| ``DESCRIBE`` | @MBEAN | Retrieve metadata about a named mbean from the platformâs MBeanServer | ++-----------------+---------------------------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| ``EXECUTE`` | ``ALL FUNCTIONS`` | ``SELECT``, ``INSERT``, ``UPDATE`` using any function <br> use of any function in ``CREATE AGGREGATE`` | ++-----------------+---------------------------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| ``EXECUTE`` | ``ALL FUNCTIONS IN KEYSPACE`` | ``SELECT``, ``INSERT``, ``UPDATE`` using any function in keyspace <br> use of any function in keyspace in ``CREATE AGGREGATE`` | ++-----------------+---------------------------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| ``EXECUTE`` | ``FUNCTION`` | ``SELECT``, ``INSERT``, ``UPDATE`` using function <br> use of function in ``CREATE AGGREGATE`` | ++-----------------+---------------------------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| ``EXECUTE`` | ``ALL MBEANS`` | Execute operations on any mbean | ++-----------------+---------------------------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| ``EXECUTE`` | ``MBEANS`` | Execute operations on any mbean matching a wildcard pattern | ++-----------------+---------------------------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| ``EXECUTE`` | ``MBEAN`` | Execute operations on named mbean | ++-----------------+---------------------------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------+ + +GRANT PERMISSION +~~~~~~~~~~~~~~~~ + +*Syntax:* + +| bc(syntax).. +| ::= GRANT ( ALL ( PERMISSIONS )? \| ( PERMISSION )? ) ON TO + + ::= CREATE \| ALTER \| DROP \| SELECT \| MODIFY \| AUTHORIZE \| DESCRIBE \| EXECUTE + +| ::= ALL KEYSPACES +| \| KEYSPACE +| \| ( TABLE )? +| \| ALL ROLES +| \| ROLE +| \| ALL FUNCTIONS ( IN KEYSPACE )? +| \| FUNCTION +| \| ALL MBEANS +| \| ( MBEAN \| MBEANS ) +| p. + +*Sample:* + +| bc(sample). +| GRANT SELECT ON ALL KEYSPACES TO data\_reader; + +This gives any user with the role ``data_reader`` permission to execute +``SELECT`` statements on any table across all keyspaces + +| bc(sample). +| GRANT MODIFY ON KEYSPACE keyspace1 TO data\_writer; + +This give any user with the role ``data_writer`` permission to perform +``UPDATE``, ``INSERT``, ``UPDATE``, ``DELETE`` and ``TRUNCATE`` queries +on all tables in the ``keyspace1`` keyspace + +| bc(sample). +| GRANT DROP ON keyspace1.table1 TO schema\_owner; + +This gives any user with the ``schema_owner`` role permissions to +``DROP`` ``keyspace1.table1``. + +| bc(sample). +| GRANT EXECUTE ON FUNCTION keyspace1.user\_function( int ) TO + report\_writer; + +This grants any user with the ``report_writer`` role permission to +execute ``SELECT``, ``INSERT`` and ``UPDATE`` queries which use the +function ``keyspace1.user_function( int )`` + +| bc(sample). +| GRANT DESCRIBE ON ALL ROLES TO role\_admin; + +This grants any user with the ``role_admin`` role permission to view any +and all roles in the system with a ``LIST ROLES`` statement + +.. _grant-all: + +GRANT ALL +````````` + +When the ``GRANT ALL`` form is used, the appropriate set of permissions +is determined automatically based on the target resource. + +Automatic Granting +`````````````````` + +When a resource is created, via a ``CREATE KEYSPACE``, ``CREATE TABLE``, +``CREATE FUNCTION``, ``CREATE AGGREGATE`` or ``CREATE ROLE`` statement, +the creator (the role the database user who issues the statement is +identified as), is automatically granted all applicable permissions on +the new resource. + +REVOKE PERMISSION +~~~~~~~~~~~~~~~~~ + +*Syntax:* + +| bc(syntax).. +| ::= REVOKE ( ALL ( PERMISSIONS )? \| ( PERMISSION )? ) ON FROM + + ::= CREATE \| ALTER \| DROP \| SELECT \| MODIFY \| AUTHORIZE \| DESCRIBE \| EXECUTE + +| ::= ALL KEYSPACES +| \| KEYSPACE +| \| ( TABLE )? +| \| ALL ROLES +| \| ROLE +| \| ALL FUNCTIONS ( IN KEYSPACE )? +| \| FUNCTION +| \| ALL MBEANS +| \| ( MBEAN \| MBEANS ) +| p. + +*Sample:* + +| bc(sample).. +| REVOKE SELECT ON ALL KEYSPACES FROM data\_reader; +| REVOKE MODIFY ON KEYSPACE keyspace1 FROM data\_writer; +| REVOKE DROP ON keyspace1.table1 FROM schema\_owner; +| REVOKE EXECUTE ON FUNCTION keyspace1.user\_function( int ) FROM + report\_writer; +| REVOKE DESCRIBE ON ALL ROLES FROM role\_admin; +| p. + +LIST PERMISSIONS +~~~~~~~~~~~~~~~~ + +*Syntax:* + +| bc(syntax).. +| ::= LIST ( ALL ( PERMISSIONS )? \| ) +| ( ON )? +| ( OF ( NORECURSIVE )? )? + +| ::= ALL KEYSPACES +| \| KEYSPACE +| \| ( TABLE )? +| \| ALL ROLES +| \| ROLE +| \| ALL FUNCTIONS ( IN KEYSPACE )? +| \| FUNCTION +| \| ALL MBEANS +| \| ( MBEAN \| MBEANS ) +| p. + +*Sample:* + +| bc(sample). +| LIST ALL PERMISSIONS OF alice; + +Show all permissions granted to ``alice``, including those acquired +transitively from any other roles. + +| bc(sample). +| LIST ALL PERMISSIONS ON keyspace1.table1 OF bob; + +Show all permissions on ``keyspace1.table1`` granted to ``bob``, +including those acquired transitively from any other roles. This also +includes any permissions higher up the resource hierarchy which can be +applied to ``keyspace1.table1``. For example, should ``bob`` have +``ALTER`` permission on ``keyspace1``, that would be included in the +results of this query. Adding the ``NORECURSIVE`` switch restricts the +results to only those permissions which were directly granted to ``bob`` +or one of ``bob``\ âs roles. + +| bc(sample). +| LIST SELECT PERMISSIONS OF carlos; + +Show any permissions granted to ``carlos`` or any of ``carlos``\ âs +roles, limited to ``SELECT`` permissions on any resource.
http://git-wip-us.apache.org/repos/asf/cassandra/blob/54f7335c/doc/source/cql/triggers.rst ---------------------------------------------------------------------- diff --git a/doc/source/cql/triggers.rst b/doc/source/cql/triggers.rst new file mode 100644 index 0000000..f3b7028 --- /dev/null +++ b/doc/source/cql/triggers.rst @@ -0,0 +1,61 @@ +.. Licensed to the Apache Software Foundation (ASF) under one +.. or more contributor license agreements. See the NOTICE file +.. distributed with this work for additional information +.. regarding copyright ownership. The ASF licenses this file +.. to you under the Apache License, Version 2.0 (the +.. "License"); you may not use this file except in compliance +.. with the License. You may obtain a copy of the License at +.. +.. http://www.apache.org/licenses/LICENSE-2.0 +.. +.. Unless required by applicable law or agreed to in writing, software +.. distributed under the License is distributed on an "AS IS" BASIS, +.. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +.. See the License for the specific language governing permissions and +.. limitations under the License. + +.. highlight:: sql + +Triggers +-------- + +CREATE TRIGGER +^^^^^^^^^^^^^^ + +*Syntax:* + +| bc(syntax).. +| ::= CREATE TRIGGER ( IF NOT EXISTS )? ( )? +| ON +| USING + +*Sample:* + +| bc(sample). +| CREATE TRIGGER myTrigger ON myTable USING + âorg.apache.cassandra.triggers.InvertedIndexâ; + +The actual logic that makes up the trigger can be written in any Java +(JVM) language and exists outside the database. You place the trigger +code in a ``lib/triggers`` subdirectory of the Cassandra installation +directory, it loads during cluster startup, and exists on every node +that participates in a cluster. The trigger defined on a table fires +before a requested DML statement occurs, which ensures the atomicity of +the transaction. + +DROP TRIGGER +^^^^^^^^^^^^ + +*Syntax:* + +| bc(syntax).. +| ::= DROP TRIGGER ( IF EXISTS )? ( )? +| ON +| p. +| *Sample:* + +| bc(sample). +| DROP TRIGGER myTrigger ON myTable; + +``DROP TRIGGER`` statement removes the registration of a trigger created +using ``CREATE TRIGGER``. http://git-wip-us.apache.org/repos/asf/cassandra/blob/54f7335c/doc/source/cql/types.rst ---------------------------------------------------------------------- diff --git a/doc/source/cql/types.rst b/doc/source/cql/types.rst new file mode 100644 index 0000000..6d7f641 --- /dev/null +++ b/doc/source/cql/types.rst @@ -0,0 +1,516 @@ +.. Licensed to the Apache Software Foundation (ASF) under one +.. or more contributor license agreements. See the NOTICE file +.. distributed with this work for additional information +.. regarding copyright ownership. The ASF licenses this file +.. to you under the Apache License, Version 2.0 (the +.. "License"); you may not use this file except in compliance +.. with the License. You may obtain a copy of the License at +.. +.. http://www.apache.org/licenses/LICENSE-2.0 +.. +.. Unless required by applicable law or agreed to in writing, software +.. distributed under the License is distributed on an "AS IS" BASIS, +.. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +.. See the License for the specific language governing permissions and +.. limitations under the License. + +.. highlight:: sql + +.. _data-types: + +Data Types +---------- + +CQL is a typed language and supports a rich set of data types, including :ref:`native types <native-types>`, +:ref:`collection types <collections>`, :ref:`user-defined types <udts>`, :ref:`tuple types <tuples>` and :ref:`custom +types <custom-types>`: + +.. productionlist:: + cql_type: `native_type` | `collection_type` | `user_defined_type` | `tuple_type` | `custom_type` + + +.. _native-types: + +Native Types +^^^^^^^^^^^^ + +The native types supported by CQL are: + +.. productionlist:: + native_type: ASCII + : | BIGINT + : | BLOB + : | BOOLEAN + : | COUNTER + : | DATE + : | DECIMAL + : | DOUBLE + : | FLOAT + : | INET + : | INT + : | SMALLINT + : | TEXT + : | TIME + : | TIMESTAMP + : | TIMEUUID + : | TINYINT + : | UUID + : | VARCHAR + : | VARINT + +The following table gives additional informations on the native data types, and on which kind of :ref:`constants +<constants>` each type supports: + +=============== ===================== ================================================================================== + type constants supported description +=============== ===================== ================================================================================== + ``ascii`` :token:`string` ASCII character string + ``bigint`` :token:`integer` 64-bit signed long + ``blob`` :token:`blob` Arbitrary bytes (no validation) + ``boolean`` :token:`boolean` Either ``true`` or ``false`` + ``counter`` :token:`integer` Counter column (64-bit signed value). See :ref:`counters` for details + ``date`` :token:`integer`, A date (with no corresponding time value). See :ref:`dates` below for details + :token:`string` + ``decimal`` :token:`integer`, Variable-precision decimal + :token:`float` + ``double`` :token:`integer` 64-bit IEEE-754 floating point + :token:`float` + ``float`` :token:`integer`, 32-bit IEEE-754 floating point + :token:`float` + ``inet`` :token:`string` An IP address, either IPv4 (4 bytes long) or IPv6 (16 bytes long). Note that + there is no ``inet`` constant, IP address should be input as strings + ``int`` :token:`integer` 32-bit signed int + ``smallint`` :token:`integer` 16-bit signed int + ``text`` :token:`string` UTF8 encoded string + ``time`` :token:`integer`, A time (with no corresponding date value) with nanosecond precision. See + :token:`string` :ref:`times` below for details + ``timestamp`` :token:`integer`, A timestamp (date and time) with millisecond precision. See :ref:`timestamps` + :token:`string` below for details + ``timeuuid`` :token:`uuid` Version 1 UUID_, generally used as a âconflict-freeâ timestamp. Also see + :ref:`timeuuid-functions` + ``tinyint`` :token:`integer` 8-bit signed int + ``uuid`` :token:`uuid` A UUID_ (of any version) + ``varchar`` :token:`string` UTF8 encoded string + ``varint`` :token:`integer` Arbitrary-precision integer +=============== ===================== ================================================================================== + +.. _counters: + +Counters +~~~~~~~~ + +The ``counter`` type is used to define *counter columns*. A counter column is a column whose value is a 64-bit signed +integer and on which 2 operations are supported: incrementing and decrementing (see the :ref:`UPDATE statement +<update-statement>` for syntax). Note that the value of a counter cannot be set: a counter does not exist until first +incremented/decremented, and that first increment/decrement is made as if the prior value was 0. + +.. _counter-limitations: + +Counters have a number of important limitations: + +- They cannot be used for columns part of the ``PRIMARY KEY`` of a table. +- A table that contains a counter can only contain counters. In other words, either all the columns of a table outside + the ``PRIMARY KEY`` have the ``counter`` type, or none of them have it. +- Counters do not support :ref:`expiration <ttls>`. +- The deletion of counters is supported, but is only guaranteed to work the first time you delete a counter. In other + words, you should not re-update a counter that you have deleted (if you do, proper behavior is not guaranteed). +- Counter updates are, by nature, not `idemptotent <https://en.wikipedia.org/wiki/Idempotence>`__. An important + consequence is that if a counter update fails unexpectedly (timeout or loss of connection to the coordinator node), + the client has no way to know if the update has been applied or not. In particular, replaying the update may or may + not lead to an over count. + +.. _timestamps: + +Working with timestamps +^^^^^^^^^^^^^^^^^^^^^^^ + +Values of the ``timestamp`` type are encoded as 64-bit signed integers representing a number of milliseconds since the +standard base time known as `the epoch <https://en.wikipedia.org/wiki/Unix_time>`__: January 1 1970 at 00:00:00 GMT. + +Timestamps can be input in CQL either using their value as an :token:`integer`, or using a :token:`string` that +represents an `ISO 8601 <https://en.wikipedia.org/wiki/ISO_8601>`__ date. For instance, all of the values below are +valid ``timestamp`` values for Mar 2, 2011, at 04:05:00 AM, GMT: + +- ``1299038700000`` +- ``'2011-02-03 04:05+0000'`` +- ``'2011-02-03 04:05:00+0000'`` +- ``'2011-02-03 04:05:00.000+0000'`` +- ``'2011-02-03T04:05+0000'`` +- ``'2011-02-03T04:05:00+0000'`` +- ``'2011-02-03T04:05:00.000+0000'`` + +The ``+0000`` above is an RFC 822 4-digit time zone specification; ``+0000`` refers to GMT. US Pacific Standard Time is +``-0800``. The time zone may be omitted if desired (``'2011-02-03 04:05:00'``), and if so, the date will be interpreted +as being in the time zone under which the coordinating Cassandra node is configured. There are however difficulties +inherent in relying on the time zone configuration being as expected, so it is recommended that the time zone always be +specified for timestamps when feasible. + +The time of day may also be omitted (``'2011-02-03'`` or ``'2011-02-03+0000'``), in which case the time of day will +default to 00:00:00 in the specified or default time zone. However, if only the date part is relevant, consider using +the :ref:`date <dates>` type. + +.. _dates: + +Working with dates +^^^^^^^^^^^^^^^^^^ + +Values of the ``date`` type are encoded as 32-bit unsigned integers representing a number of days with âthe epochâ at +the center of the range (2^31). Epoch is January 1st, 1970 + +As for :ref:`timestamp <timestamps>`, a date can be input either as an :token:`integer` or using a date +:token:`string`. In the later case, the format should be ``yyyy-mm-dd`` (so ``'2011-02-03'`` for instance). + +.. _times: + +Working with times +^^^^^^^^^^^^^^^^^^ + +Values of the ``time`` type are encoded as 64-bit signed integers representing the number of nanoseconds since midnight. + +As for :ref:`timestamp <timestamps>`, a time can be input either as an :token:`integer` or using a :token:`string` +representing the time. In the later case, the format should be ``hh:mm:ss[.fffffffff]`` (where the sub-second precision +is optional and if provided, can be less than the nanosecond). So for instance, the following are valid inputs for a +time: + +- ``'08:12:54'`` +- ``'08:12:54.123'`` +- ``'08:12:54.123456'`` +- ``'08:12:54.123456789'`` + + +.. _collections: + +Collections +^^^^^^^^^^^ + +CQL supports 3 kind of collections: :ref:`maps`, :ref:`sets` and :ref:`lists`. The types of those collections is defined +by: + +.. productionlist:: + collection_type: MAP '<' `cql_type` ',' `cql_type` '>' + : | SET '<' `cql_type` '>' + : | LIST '<' `cql_type` '>' + +and their values can be inputd using collection literals: + +.. productionlist:: + collection_literal: `map_literal` | `set_literal` | `list_literal` + map_literal: '{' [ `term` ':' `term` (',' `term` : `term`)* ] '}' + set_literal: '{' [ `term` (',' `term`)* ] '}' + list_literal: '[' [ `term` (',' `term`)* ] ']' + +Note however that neither :token:`bind_marker` nor ``NULL`` are supported inside collection literals. + +Noteworthy characteristics +~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Collections are meant for storing/denormalizing relatively small amount of data. They work well for things like âthe +phone numbers of a given userâ, âlabels applied to an emailâ, etc. But when items are expected to grow unbounded (âall +messages sent by a userâ, âevents registered by a sensorâ...), then collections are not appropriate and a specific table +(with clustering columns) should be used. Concretely, (non-frozen) collections have the following noteworthy +characteristics and limitations: + +- Individual collections are not indexed internally. Which means that even to access a single element of a collection, + the while collection has to be read (and reading one is not paged internally). +- While insertion operations on sets and maps never incur a read-before-write internally, some operations on lists do. + Further, some lists operations are not idempotent by nature (see the section on :ref:`lists <lists>` below for + details), making their retry in case of timeout problematic. It is thus advised to prefer sets over lists when + possible. + +Please note that while some of those limitations may or may not be removed/improved upon in the future, it is a +anti-pattern to use a (single) collection to store large amounts of data. + +.. _maps: + +Maps +~~~~ + +A ``map`` is a (sorted) set of key-value pairs, where keys are unique and the map is sorted by its keys. You can define +and insert a map with:: + + CREATE TABLE users ( + id text PRIMARY KEY, + name text, + favs map<text, text> // A map of text keys, and text values + ); + + INSERT INTO users (id, name, favs) + VALUES ('jsmith', 'John Smith', { 'fruit' : 'Apple', 'band' : 'Beatles' }); + + // Replace the existing map entirely. + UPDATE users SET favs = { 'fruit' : 'Banana' } WHERE id = 'jsmith'; + +Further, maps support: + +- Updating or inserting one or more elements:: + + UPDATE users SET favs['author'] = 'Ed Poe' WHERE id = 'jsmith'; + UPDATE users SET favs = favs + { 'movie' : 'Cassablanca', 'band' : 'ZZ Top' } WHERE id = 'jsmith'; + +- Removing one or more element (if an element doesn't exist, removing it is a no-op but no error is thrown):: + + DELETE favs['author'] FROM users WHERE id = 'jsmith'; + UPDATE users SET favs = favs - { 'movie', 'band'} WHERE id = 'jsmith'; + + Note that for removing multiple elements in a ``map``, you remove from it a ``set`` of keys. + +Lastly, TTLs are allowed for both ``INSERT`` and ``UPDATE``, but in both case the TTL set only apply to the newly +inserted/updated elements. In other words:: + + UPDATE users USING TTL 10 SET favs['color'] = 'green' WHERE id = 'jsmith'; + +will only apply the TTL to the ``{ 'color' : 'green' }`` record, the rest of the map remaining unaffected. + + +.. _sets: + +Sets +~~~~ + +A ``set`` is a (sorted) collection of unique values. You can define and insert a map with:: + + CREATE TABLE images ( + name text PRIMARY KEY, + owner text, + tags set<text> // A set of text values + ); + + INSERT INTO images (name, owner, tags) + VALUES ('cat.jpg', 'jsmith', { 'pet', 'cute' }); + + // Replace the existing set entirely + UPDATE images SET tags = { 'kitten', 'catâ, 'lol' } WHERE id = 'jsmith'; + +Further, sets support: + +- Adding one or multiple elements (as this is a set, inserting an already existing element is a no-op):: + + UPDATE images SET tags = tags + { 'gray', 'cuddly' } WHERE name = 'cat.jpg'; + +- Removing one or multiple elements (if an element doesn't exist, removing it is a no-op but no error is thrown):: + + UPDATE images SET tags = tags - { 'cat' } WHERE name = 'cat.jpg'; + +Lastly, as for :ref:`maps <maps>`, TTLs if used only apply to the newly inserted values. + +.. _lists: + +Lists +~~~~~ + +.. note:: As mentioned above and further discussed at the end of this section, lists have limitations and specific + performance considerations that you should take into account before using them. In general, if you can use a + :ref:`set <sets>` instead of list, always prefer a set. + +A ``list`` is a (sorted) collection of non-unique values where elements are ordered by there position in the list. You +can define and insert a list with:: + + CREATE TABLE plays ( + id text PRIMARY KEY, + game text, + players int, + scores list<int> // A list of integers + ) + + INSERT INTO plays (id, game, players, scores) + VALUES ('123-afde', 'quake', 3, [17, 4, 2]); + + // Replace the existing list entirely + UPDATE plays SET scores = [ 3, 9, 4] WHERE id = '123-afde'; + +Further, lists support: + +- Appending and prepending values to a list:: + + UPDATE plays SET players = 5, scores = scores + [ 14, 21 ] WHERE id = '123-afde'; + UPDATE plays SET players = 6, scores = [ 3 ] + scores WHERE id = '123-afde'; + +- Setting the value at a particular position in the list. This imply that the list has a pre-existing element for that + position or an error will be thrown that the list is too small:: + + UPDATE plays SET scores[1] = 7 WHERE id = '123-afde'; + +- Removing an element by its position in the list. This imply that the list has a pre-existing element for that position + or an error will be thrown that the list is too small. Further, as the operation removes an element from the list, the + list size will be diminished by 1, shifting the position of all the elements following the one deleted:: + + DELETE scores[1] FROM plays WHERE id = '123-afde'; + +- Deleting *all* the occurrences of particular values in the list (if a particular element doesn't occur at all in the + list, it is simply ignored and no error is thrown):: + + UPDATE plays SET scores = scores - [ 12, 21 ] WHERE id = '123-afde'; + +.. warning:: The append and prepend operations are not idempotent by nature. So in particular, if one of these operation + timeout, then retrying the operation is not safe and it may (or may not) lead to appending/prepending the value + twice. + +.. warning:: Setting and removing an element by position and removing occurences of particular values incur an internal + *read-before-write*. They will thus run more slowly and take more ressources than usual updates (with the exclusion + of conditional write that have their own cost). + +Lastly, as for :ref:`maps <maps>`, TTLs when used only apply to the newly inserted values. + +.. _udts: + +User-Defined Types +^^^^^^^^^^^^^^^^^^ + +CQL support the definition of user-defined types (UDT for short). Such a type can be created, modified and removed using +the :token:`create_type_statement`, :token:`alter_type_statement` and :token:`drop_type_statement` described below. But +once created, a UDT is simply referred to by its name: + +.. productionlist:: + user_defined_type: `udt_name` + udt_name: [ `keyspace_name` '.' ] `identifier` + + +Creating a UDT +~~~~~~~~~~~~~~ + +Creating a new user-defined type is done using a ``CREATE TYPE`` statement defined by: + +.. productionlist:: + create_type_statement: CREATE TYPE [ IF NOT EXISTS ] `udt_name` + : '(' `field_definition` ( ',' `field_definition` )* ')' + field_definition: `identifier` `cql_type` + +A UDT has a name (used to declared columns of that type) and is a set of named and typed fields. Fields name can be any +type, including collections or other UDT. For instance:: + + CREATE TYPE phone ( + country_code int, + number text, + ) + + CREATE TYPE address ( + street text, + city text, + zip int, + phones map<text, phone> + ) + + CREATE TABLE user ( + name text PRIMARY KEY, + addresses map<text, frozen<address>> + ) + +Note that: + +- Attempting to create an already existing type will result in an error unless the ``IF NOT EXISTS`` option is used. If + it is used, the statement will be a no-op if the type already exists. +- A type is intrinsically bound to the keyspace in which it is created, and can only be used in that keyspace. At + creation, if the type name is prefixed by a keyspace name, it is created in that keyspace. Otherwise, it is created in + the current keyspace. +- As of Cassandra |version|, UDT have to be frozen in most cases, hence the ``frozen<address>`` in the table definition + above. Please see the section on :ref:`frozen <frozen>` for more details. + +UDT literals +~~~~~~~~~~~~ + +Once a used-defined type has been created, value can be input using a UDT literal: + +.. productionlist:: + udt_literal: '{' `identifier` ':' `term` ( ',' `identifier` ':' `term` )* '}' + +In other words, a UDT literal is like a :ref:`map <maps>` literal but its keys are the names of the fields of the type. +For instance, one could insert into the table define in the previous section using:: + + INSERT INTO user (name, addresses) + VALUES ('z3 Pr3z1den7', { + 'home' : { + street: '1600 Pennsylvania Ave NW', + city: 'Washington', + zip: '20500', + phones: { 'cell' : { country_code: 1, number: '202 456-1111' }, + 'landline' : { country_code: 1, number: '...' } } + } + 'work' : { + street: '1600 Pennsylvania Ave NW', + city: 'Washington', + zip: '20500', + phones: { 'fax' : { country_code: 1, number: '...' } } + } + }) + +To be valid, a UDT literal should only include fields defined by the type it is a literal of, but it can omit some field +(in which case those will be ``null``). + +Altering a UDT +~~~~~~~~~~~~~~ + +An existing user-defined type can be modified using an ``ALTER TYPE`` statement: + +.. productionlist:: + alter_type_statement: ALTER TYPE `udt_name` `alter_type_modification` + alter_type_modification: ALTER `identifier` TYPE `cql_type` + : | ADD `field_definition` + : | RENAME `identifier` TO `identifier` ( `identifier` TO `identifier` )* + +You can: + +- modify the type of particular field (``ALTER TYPE address ALTER zip TYPE bigint``). The restrictions for such change + are the same than when :ref:`altering the type of column <alter-table>`. +- add a new field to the type (``ALTER TYPE address ADD country text``). That new field will be ``null`` for any values + of the type created before the addition. +- rename the fields of the type (``ALTER TYPE address RENAME zip TO zipcode``). + +Dropping a UDT +~~~~~~~~~~~~~~ + +You can drop an existing user-defined type using a ``DROP TYPE`` statement: + +.. productionlist:: + drop_type_statement: DROP TYPE [ IF EXISTS ] `udt_name` + +Dropping a type results in the immediate, irreversible removal of that type. However, attempting to drop a type that is +still in use by another type, table or function will result in an error. + +If the type dropped does not exist, an error will be returned unless ``IF EXISTS`` is used, in which case the operation +is a no-op. + +.. _tuples: + +Tuples +^^^^^^ + +CQL also support tuples and tuple types (where the elements can be of different types). Functionally, tuples can be +though as anonymous UDT with anonymous fields. Tuple types and tuple literals are defined by: + +.. productionlist:: + tuple_type: TUPLE '<' `cql_type` ( ',' `cql_type` )* '>' + tuple_literal: '(' `term` ( ',' `term` )* ')' + +and can be used thusly:: + + CREATE TABLE durations ( + event text, + duration tuple<int, text>, + ) + + INSERT INTO durations (event, duration) VALUES ('ev1', (3, 'hours')); + +Unlike other "composed" types (collections and UDT), a tuple is always :ref:`frozen <frozen>` (without the need of the +`frozen` keyword) and it is not possible to update only some elements of a tuple (without updating the whole tuple). +Also, a tuple literal should always have the same number of value than declared in the type it is a tuple of (some of +those values can be null but they need to be explicitly declared as so). + +.. _custom-types: + +Custom Types +^^^^^^^^^^^^ + +.. note:: Custom types exists mostly for backward compatiliby purposes and their usage is discouraged. Their usage is + complex, not user friendly and the other provided types, particularly :ref:`user-defined types <udts>`, should almost + always be enough. + +A custom type is defined by: + +.. productionlist:: + custom_type: `string` + +A custom type is a :token:`string` that contains the name of Java class that extends the server side ``AbstractType`` +class and that can be loaded by Cassandra (it should thus be in the ``CLASSPATH`` of every node running Cassandra). That +class will define what values are valid for the type and how the time sorts when used for a clustering column. For any +other purpose, a value of a custom type is the same than that of a ``blob``, and can in particular be input using the +:token:`blob` literal syntax. http://git-wip-us.apache.org/repos/asf/cassandra/blob/54f7335c/doc/source/cqlsh.rst ---------------------------------------------------------------------- diff --git a/doc/source/cqlsh.rst b/doc/source/cqlsh.rst deleted file mode 100644 index 4a1b716..0000000 --- a/doc/source/cqlsh.rst +++ /dev/null @@ -1,447 +0,0 @@ -.. highlight:: none - -.. _cqlsh: - -cqlsh -===== - -cqlsh is a command line shell for interacting with Cassandra through CQL (the Cassandra Query Language). It is shipped -with every Cassandra package, and can be found in the bin/ directory alongside the cassandra executable. cqlsh utilizes -the Python native protocol driver, and connects to the single node specified on the command line. - - -Compatibility -------------- - -cqlsh is compatible with Python 2.7. - -In general, a given version of cqlsh is only guaranteed to work with the version of Cassandra that it was released with. -In some cases, cqlsh make work with older or newer versions of Cassandra, but this is not officially supported. - - -Optional Dependencies ---------------------- - -cqlsh ships with all essential dependencies. However, there are some optional dependencies that can be installed to -improve the capabilities of cqlsh. - -pytz -^^^^ -By default, cqlsh displays all timestamps with a UTC timezone. To support display of timestamps with another timezone, -the `pytz <http://pytz.sourceforge.net/>`__ library must be installed. See the ``timezone`` option in cqlshrc_ for -specifying a timezone to use. - -cython -^^^^^^ -The performance of cqlsh's ``COPY`` operations can be improved by installing `cython <http://cython.org/>`__. This will -compile the python modules that are central to the performance of ``COPY``. - -cqlshrc -------- - -The ``cqlshrc`` file holds configuration options for cqlsh. By default this is in the user's home directory at -``~/.cassandra/cqlsh``, but a custom location can be specified with the ``--cqlshrc`` option. - -Example config values and documentation can be found in the ``conf/cqlshrc.sample`` file of a tarball installation. You -can also view the latest version of `cqlshrc online <https://github.com/apache/cassandra/blob/trunk/conf/cqlshrc.sample>`__. - - -Command Line Options --------------------- -Usage: - -``cqlsh [options] [host [port]]`` - -Options: - -``-C`` ``--color`` - Force color output - -``--no-color`` - Disable color output - -``--browser`` - Specify the browser to use for displaying cqlsh help. This can be one of the `supported browser names - <https://docs.python.org/2/library/webbrowser.html>`__ (e.g. ``firefox``) or a browser path followed by ``%s`` (e.g. - ``/usr/bin/google-chrome-stable %s``). - -``--ssl`` - Use SSL when connecting to Cassandra - -``-u`` ``--user`` - Username to authenticate against Cassandra with - -``-p`` ``--password`` - Password to authenticate against Cassandra with, should - be used in conjunction with ``--user`` - -``-k`` ``--keyspace`` - Keyspace to authenticate to, should be used in conjunction - with ``--user`` - -``-f`` ``--file`` - Execute commands from the given file, then exit - -``--debug`` - Print additional debugging information - -``--encoding`` - Specify a non-default encoding for output (defaults to UTF-8) - -``--cqlshrc`` - Specify a non-default location for the ``cqlshrc`` file - -``-e`` ``--execute`` - Execute the given statement, then exit - -``--connect-timeout`` - Specify the connection timeout in seconds (defaults to 2s) - -``--request-timeout`` - Specify the request timeout in seconds (defaults to 10s) - -``-t`` ``--tty`` - Force tty mode (command prompt) - - -Special Commands ----------------- - -In addition to supporting regular CQL statements, cqlsh also supports a number of special commands that are not part of -CQL. These are detailed below. - -``CONSISTENCY`` -^^^^^^^^^^^^^^^ - -`Usage`: ``CONSISTENCY <consistency level>`` - -Sets the consistency level for operations to follow. Valid arguments include: - -- ``ANY`` -- ``ONE`` -- ``TWO`` -- ``THREE`` -- ``QUORUM`` -- ``ALL`` -- ``LOCAL_QUORUM`` -- ``LOCAL_ONE`` -- ``SERIAL`` -- ``LOCAL_SERIAL`` - -``SERIAL CONSISTENCY`` -^^^^^^^^^^^^^^^^^^^^^^ - -`Usage`: ``SERIAL CONSISTENCY <consistency level>`` - -Sets the serial consistency level for operations to follow. Valid arguments include: - -- ``SERIAL`` -- ``LOCAL_SERIAL`` - -The serial consistency level is only used by conditional updates (``INSERT``, ``UPDATE`` and ``DELETE`` with an ``IF`` -condition). For those, the serial consistency level defines the consistency level of the serial phase (or âpaxosâ phase) -while the normal consistency level defines the consistency for the âlearnâ phase, i.e. what type of reads will be -guaranteed to see the update right away. For example, if a conditional write has a consistency level of ``QUORUM`` (and -is successful), then a ``QUORUM`` read is guaranteed to see that write. But if the regular consistency level of that -write is ``ANY``, then only a read with a consistency level of ``SERIAL`` is guaranteed to see it (even a read with -consistency ``ALL`` is not guaranteed to be enough). - -``SHOW VERSION`` -^^^^^^^^^^^^^^^^ -Prints the cqlsh, Cassandra, CQL, and native protocol versions in use. Example:: - - cqlsh> SHOW VERSION - [cqlsh 5.0.1 | Cassandra 3.8 | CQL spec 3.4.2 | Native protocol v4] - -``SHOW HOST`` -^^^^^^^^^^^^^ - -Prints the IP address and port of the Cassandra node that cqlsh is connected to in addition to the cluster name. -Example:: - - cqlsh> SHOW HOST - Connected to Prod_Cluster at 192.0.0.1:9042. - -``SHOW SESSION`` -^^^^^^^^^^^^^^^^ - -Pretty prints a specific tracing session. - -`Usage`: ``SHOW SESSION <session id>`` - -Example usage:: - - cqlsh> SHOW SESSION 95ac6470-327e-11e6-beca-dfb660d92ad8 - - Tracing session: 95ac6470-327e-11e6-beca-dfb660d92ad8 - - activity | timestamp | source | source_elapsed | client - -----------------------------------------------------------+----------------------------+-----------+----------------+----------- - Execute CQL3 query | 2016-06-14 17:23:13.979000 | 127.0.0.1 | 0 | 127.0.0.1 - Parsing SELECT * FROM system.local; [SharedPool-Worker-1] | 2016-06-14 17:23:13.982000 | 127.0.0.1 | 3843 | 127.0.0.1 - ... - - -``SOURCE`` -^^^^^^^^^^ - -Reads the contents of a file and executes each line as a CQL statement or special cqlsh command. - -`Usage`: ``SOURCE <string filename>`` - -Example usage:: - - cqlsh> SOURCE '/home/thobbs/commands.cql' - -``CAPTURE`` -^^^^^^^^^^^ - -Begins capturing command output and appending it to a specified file. Output will not be shown at the console while it -is captured. - -`Usage`:: - - CAPTURE '<file>'; - CAPTURE OFF; - CAPTURE; - -That is, the path to the file to be appended to must be given inside a string literal. The path is interpreted relative -to the current working directory. The tilde shorthand notation (``'~/mydir'``) is supported for referring to ``$HOME``. - -Only query result output is captured. Errors and output from cqlsh-only commands will still be shown in the cqlsh -session. - -To stop capturing output and show it in the cqlsh session again, use ``CAPTURE OFF``. - -To inspect the current capture configuration, use ``CAPTURE`` with no arguments. - -``HELP`` -^^^^^^^^ -Gives information about cqlsh commands. To see available topics, enter ``HELP`` without any arguments. To see help on a -topic, use ``HELP <topic>``. Also see the ``--browser`` argument for controlling what browser is used to display help. - -``TRACING`` -^^^^^^^^^^^ -Enables or disables tracing for queries. When tracing is enabled, once a query completes, a trace of the events during -the query will be printed. - -`Usage`:: - - TRACING ON - TRACING OFF - -``PAGING`` -^^^^^^^^^^ -Enables paging, disables paging, or sets the page size for read queries. When paging is enabled, only one page of data -will be fetched at a time and a prompt will appear to fetch the next page. Generally, it's a good idea to leave paging -enabled in an interactive session to avoid fetching and printing large amounts of data at once. - -`Usage`:: - - PAGING ON - PAGING OFF - PAGING <page size in rows> - -``EXPAND`` -^^^^^^^^^^ - -Enables or disables vertical printing of rows. Enabling ``EXPAND`` is useful when many columns are fetched, or the -contents of a single column are large. - -`Usage`:: - - EXPAND ON - EXPAND OFF - -``LOGIN`` -^^^^^^^^^ - -Authenticate as a specified Cassandra user for the current session. - -`Usage`:: - - LOGIN <username> [<password>] - -``EXIT`` -^^^^^^^^^ -Ends the current session and terminates the cqlsh process. - -`Usage`:: - - EXIT - QUIT - -``CLEAR`` -^^^^^^^^^ - -Clears the console. - -`Usage`:: - - CLEAR - CLS - -``DESCRIBE`` -^^^^^^^^^^^^ - -Prints a description (typically a series of DDL statements) of a schema element or the cluster. This is useful for -dumping all or portions of the schema. - -`Usage`:: - - DESCRIBE CLUSTER - DESCRIBE SCHEMA - DESCRIBE KEYSPACES - DESCRIBE KEYSPACE <keyspace name> - DESCRIBE TABLES - DESCRIBE TABLE <table name> - DESCRIBE INDEX <index name> - DESCRIBE MATERIALIZED VIEW <view name> - DESCRIBE TYPES - DESCRIBE TYPE <type name> - DESCRIBE FUNCTIONS - DESCRIBE FUNCTION <function name> - DESCRIBE AGGREGATES - DESCRIBE AGGREGATE <aggregate function name> - -In any of the commands, ``DESC`` may be used in place of ``DESCRIBE``. - -The ``DESCRIBE CLUSTER`` command prints the cluster name and partitioner:: - - cqlsh> DESCRIBE CLUSTER - - Cluster: Test Cluster - Partitioner: Murmur3Partitioner - -The ``DESCRIBE SCHEMA`` command prints the DDL statements needed to recreate the entire schema. This is especially -useful for dumping the schema in order to clone a cluster or restore from a backup. - -``COPY TO`` -^^^^^^^^^^^ -Copies data from a table to a CSV file. - -`Usage`:: - - COPY <table name> [(<column>, ...)] TO <file name> WITH <copy option> [AND <copy option> ...] - -If no columns are specified, all columns from the table will be copied to the CSV file. A subset of columns to copy may -be specified by adding a comma-separated list of column names surrounded by parenthesis after the table name. - - -The ``<file name>`` should be a string literal (with single quotes) representing a path to the destination file. This -can also the special value ``STDOUT`` (without single quotes) to print the CSV to stdout. - -See :ref:`shared-copy-options` for options that apply to both ``COPY TO`` and ``COPY FROM``. - -Options for ``COPY TO`` -~~~~~~~~~~~~~~~~~~~~~~~ - -``MAXREQUESTS`` - The maximum number token ranges to fetch simultaneously. Defaults to 6. - -``PAGESIZE`` - The number of rows to fetch in a single page. Defaults to 1000. - -``PAGETIMEOUT`` - By default the page timeout is 10 seconds per 1000 entries - in the page size or 10 seconds if pagesize is smaller. - -``BEGINTOKEN``, ``ENDTOKEN`` - Token range to export. Defaults to exporting the full ring. - -``MAXOUTPUTSIZE`` - The maximum size of the output file measured in number of lines; - beyond this maximum the output file will be split into segments. - -1 means unlimited, and is the default. - -``ENCODING`` - The encoding used for characters. Defaults to ``utf8``. - -``COPY FROM`` -^^^^^^^^^^^^^ -Copies data from a CSV file to table. - -`Usage`:: - - COPY <table name> [(<column>, ...)] FROM <file name> WITH <copy option> [AND <copy option> ...] - -If no columns are specified, all columns from the CSV file will be copied to the table. A subset -of columns to copy may be specified by adding a comma-separated list of column names surrounded -by parenthesis after the table name. - -The ``<file name>`` should be a string literal (with single quotes) representing a path to the -source file. This can also the special value ``STDIN`` (without single quotes) to read the -CSV data from stdin. - -See :ref:`shared-copy-options` for options that apply to both ``COPY TO`` and ``COPY FROM``. - -Options for ``COPY TO`` -~~~~~~~~~~~~~~~~~~~~~~~ - -``INGESTRATE`` - The maximum number of rows to process per second. Defaults to 100000. - -``MAXROWS`` - The maximum number of rows to import. -1 means unlimited, and is the default. - -``SKIPROWS`` - A number of initial rows to skip. Defaults to 0. - -``SKIPCOLS`` - A comma-separated list of column names to ignore. By default, no columns are skipped. - -``MAXPARSEERRORS`` - The maximum global number of parsing errors to ignore. -1 means unlimited, and is the default. - -``MAXINSERTERRORS`` - The maximum global number of insert errors to ignore. -1 means unlimited. The default is 1000. - -``ERRFILE`` = - A file to store all rows that could not be imported, by default this is ``import_<ks>_<table>.err`` where ``<ks>`` is - your keyspace and ``<table>`` is your table name. - -``MAXBATCHSIZE`` - The max number of rows inserted in a single batch. Defaults to 20. - -``MINBATCHSIZE`` - The min number of rows inserted in a single batch. Defaults to 2. - -``CHUNKSIZE`` - The number of rows that are passed to child worker processes from the main process at a time. Defaults to 1000. - -.. _shared-copy-options: - -Shared COPY Options -~~~~~~~~~~~~~~~~~~~ - -Options that are common to both ``COPY TO`` and ``COPY FROM``. - -``NULLVAL`` - The string placeholder for null values. Defaults to ``null``. - -``HEADER`` - For ``COPY TO``, controls whether the first line in the CSV output file will contain the column names. For COPY FROM, - specifies whether the first line in the CSV input file contains column names. Defaults to ``false``. - -``DECIMALSEP`` - The character that is used as the decimal point separator. Defaults to ``.``. - -``THOUSANDSSEP`` - The character that is used to separate thousands. Defaults to the empty string. - -``BOOLSTYlE`` - The string literal format for boolean values. Defaults to ``True,False``. - -``NUMPROCESSES`` - The number of child worker processes to create for ``COPY`` tasks. Defaults to a max of 4 for ``COPY FROM`` and 16 - for ``COPY TO``. However, at most (num_cores - 1) processes will be created. - -``MAXATTEMPTS`` - The maximum number of failed attempts to fetch a range of data (when using ``COPY TO``) or insert a chunk of data - (when using ``COPY FROM``) before giving up. Defaults to 5. - -``REPORTFREQUENCY`` - How often status updates are refreshed, in seconds. Defaults to 0.25. - -``RATEFILE`` - An optional file to output rate statistics to. By default, statistics are not output to a file. http://git-wip-us.apache.org/repos/asf/cassandra/blob/54f7335c/doc/source/data_modeling/index.rst ---------------------------------------------------------------------- diff --git a/doc/source/data_modeling/index.rst b/doc/source/data_modeling/index.rst new file mode 100644 index 0000000..dde031a --- /dev/null +++ b/doc/source/data_modeling/index.rst @@ -0,0 +1,20 @@ +.. Licensed to the Apache Software Foundation (ASF) under one +.. or more contributor license agreements. See the NOTICE file +.. distributed with this work for additional information +.. regarding copyright ownership. The ASF licenses this file +.. to you under the Apache License, Version 2.0 (the +.. "License"); you may not use this file except in compliance +.. with the License. You may obtain a copy of the License at +.. +.. http://www.apache.org/licenses/LICENSE-2.0 +.. +.. Unless required by applicable law or agreed to in writing, software +.. distributed under the License is distributed on an "AS IS" BASIS, +.. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +.. See the License for the specific language governing permissions and +.. limitations under the License. + +Data Modeling +============= + +.. todo:: TODO http://git-wip-us.apache.org/repos/asf/cassandra/blob/54f7335c/doc/source/faq.rst ---------------------------------------------------------------------- diff --git a/doc/source/faq.rst b/doc/source/faq.rst deleted file mode 100644 index 4ac0be4..0000000 --- a/doc/source/faq.rst +++ /dev/null @@ -1,20 +0,0 @@ -.. Licensed to the Apache Software Foundation (ASF) under one -.. or more contributor license agreements. See the NOTICE file -.. distributed with this work for additional information -.. regarding copyright ownership. The ASF licenses this file -.. to you under the Apache License, Version 2.0 (the -.. "License"); you may not use this file except in compliance -.. with the License. You may obtain a copy of the License at -.. -.. http://www.apache.org/licenses/LICENSE-2.0 -.. -.. Unless required by applicable law or agreed to in writing, software -.. distributed under the License is distributed on an "AS IS" BASIS, -.. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -.. See the License for the specific language governing permissions and -.. limitations under the License. - -Frequently Asked Questions -========================== - -.. TODO: todo http://git-wip-us.apache.org/repos/asf/cassandra/blob/54f7335c/doc/source/faq/index.rst ---------------------------------------------------------------------- diff --git a/doc/source/faq/index.rst b/doc/source/faq/index.rst new file mode 100644 index 0000000..4ac0be4 --- /dev/null +++ b/doc/source/faq/index.rst @@ -0,0 +1,20 @@ +.. Licensed to the Apache Software Foundation (ASF) under one +.. or more contributor license agreements. See the NOTICE file +.. distributed with this work for additional information +.. regarding copyright ownership. The ASF licenses this file +.. to you under the Apache License, Version 2.0 (the +.. "License"); you may not use this file except in compliance +.. with the License. You may obtain a copy of the License at +.. +.. http://www.apache.org/licenses/LICENSE-2.0 +.. +.. Unless required by applicable law or agreed to in writing, software +.. distributed under the License is distributed on an "AS IS" BASIS, +.. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +.. See the License for the specific language governing permissions and +.. limitations under the License. + +Frequently Asked Questions +========================== + +.. TODO: todo
