Module cassandra
Cassandra single-host client module.
Single host module for PUC Lua, LuaJIT and OpenResty.
Info:
- Release: 1.5.2
- Author: thibaultcha
Functions
_Host.new (opts) | Create a new Cassandra client. |
_Host:connect () | Connect to the remote node. |
_Host:settimeout (timeout) | Set the timeout value. |
_Host:setkeepalive (timeout, size) | Put the underlying socket into the cosocket connection pool. |
_Host:close (...) | Close the connection. |
_Host:change_keyspace (keyspace) | Change the client's keyspace. |
_Host:prepare (query) | Prepare a query. |
_Host:execute (query, args, options) | Execute a query. |
_Host:batch (queries, options) | Execute a batch. |
_Host:iterate (query, args, options) | Lua iterator for auto-pagination. |
_Host:get_trace (tracing_id) | Get tracing information. |
Tables
cql_errors | CQL error codes CQL error codes constant. |
consistencies | CQL consistencies. |
auth_providers | Authentication providers |
client_options | New client options. |
query_options | Query options. |
type_serializers | CQL serializers. |
Functions
- _Host.new (opts)
-
Create a new Cassandra client.
Takes a table of client_options. Does not connect automatically.
Parameters:
- opts table Options for the created client.
Returns:
-
table
client
: A table able to connect to the given host and port.Usage:
local cassandra = require "cassandra" local client = cassandra.new { host = "10.0.0.1", port = 9042, keyspace = "my_keyspace" }
- _Host:connect ()
-
Connect to the remote node.
Uses the client_options given at creation to connect to the configured
Cassandra node.
Returns:
-
boolean
ok
:true
if success,nil
if failure. -
string
err
: String describing the error if failure.
Usage:
local cassandra = require "cassandra" local client = cassandra.new() assert(client:connect())
-
boolean
- _Host:settimeout (timeout)
-
Set the timeout value.
Parameters:
- timeout number Value in milliseconds (for connect/read/write).
Returns:
-
boolean
ok
:true
if success,nil
if failure. -
string
err
: String describing the error if failure.
See also:
- _Host:setkeepalive (timeout, size)
-
Put the underlying socket into the cosocket connection pool.
Keeps the underlying socket alive until other clients use the connect
method on the same host/port combination.
Parameters:
- timeout number (optional) Value in milliseconds specifying the maximal idle timeout.
- size number (optional) Maximal number of connections allowed in the pool for the current server.
Returns:
-
number
success
:1
if success,nil
if failure. -
string
err
: String describing the error if failure.
See also:
- _Host:close (...)
-
Close the connection.
Parameters:
- ...
Returns:
-
number
success
:1
if success,nil
if failure. -
string
err
: String describing the error if failure.
See also:
- _Host:change_keyspace (keyspace)
-
Change the client's keyspace.
Closes the current connection and open a new one to the given
keyspace.
The connection is closed and reopen so that we use a different connection
pool for usage in ngx_lua.
Parameters:
- keyspace string Name of the desired keyspace.
Returns:
-
boolean
ok
:true
if success,nil
if failure. -
string
err
: String describing the error if failure.
- _Host:prepare (query)
-
Prepare a query.
Sends a PREPARE request for the given query. The result of this request will
contain a query id, which can be given to execute if the
prepared
option is enabled.Parameters:
- query string CQL query to prepare.
Returns:
-
table
res
: Table holding the query result if success,nil
if failure. -
string
err
: String describing the error if failure. -
number
cql_err
: If a server-side error occurred, the CQL error code.
Usage:
local cassandra = require "cassandra" local client = cassandra.new() assert(client:connect()) local res = assert(client:prepare("SELECT * FROM users WHERE id = ?")) local rows = assert(client:execute(res.query_id, {12345}, {prepared = true})) print(#rows) -- 1
- _Host:execute (query, args, options)
-
Execute a query.
Sends a request to execute the given query.
Parameters:
- query string CQL query to execute.
- args table (optional) Arguments to bind to the query.
- options table (optional) Options from query_options for this query.
Returns:
-
table
res
: Table holding the query result if success,nil
if failure. -
string
err
: String describing the error if failure. -
number
cql_err
: If a server-side error occurred, the CQL error code.
Usage:
local cassandra = require "cassandra" local client = cassandra.new() assert(client:connect()) local rows = assert(client:execute("SELECT * FROM users WHERE name = ? AND email = ?", { "john", "john@gmail.com" })) print(#rows) -- 1 local rows, err, cql_code = client:execute("SELECT * FROM users WHERE age = ?", { age = 21 }, { named = true, page_size = 5000 }) if not rows then -- can compare cql_code to determine error type error(err) end print(#rows) --
<= 5000
print(rows.meta.paging_state) -- pagination token - _Host:batch (queries, options)
-
Execute a batch.
Sends a request to execute the given batch.
Parameters:
- queries table Array of CQL queries to execute as a batch.
- options table (optional) Options from query_options for this query.
Returns:
-
table
res
: Table holding the query result if success,nil
if failure. -
string
err
: String describing the error if failure. -
number
cql_err
: If a server-side error occurred, the CQL error code.
Usage:
local cassandra = require "cassandra" local client = cassandra.new() assert(client:connect()) local res = assert(client:batch({ {"INSERT INTO things(id, n) VALUES(?, 1)", {123}}, {"UPDATE things SET n = 2 WHERE id = ?", {123}}, {"UPDATE things SET n = 3 WHERE id = ?", {123}} }, { logged = false }))
- _Host:iterate (query, args, options)
-
Lua iterator for auto-pagination.
Perform auto-pagination for a query when used as a Lua iterator.
Parameters:
- query string CQL query to execute.
- args table (optional) Arguments to bind to the query.
- options table (optional) Options from query_options for this query.
Usage:
local cassandra = require "cassandra" local client = cassandra.new() assert(client:connect()) for rows, err, page in client:iterate("SELECT * FROM users") do if err then error(err) end print(page) print(#rows) end
- _Host:get_trace (tracing_id)
-
Get tracing information.
Retrieves the tracing information of a query (if tracing was enabled in
its options) from its tracing id.
Parameters:
- tracing_id string The query's tracing is as returned in the results of a traced query.
Returns:
-
table
trace
: Table holding the query's tracing events if success,nil
if failure. -
string
err
: String describing the error if failure.
Usage:
local cassandra = require "cassandra" local client = cassandra.new() assert(client:connect()) local res = assert(client:execute("INSERT INTO users(id, age) VALUES(1, 33)", nil, { tracing = true })) local trace = assert(client:get_trace(res.tracing_id)) print(trace.client) -- "127.0.0.1" print(trace.command) -- "QUERY"
Tables
- cql_errors
-
CQL error codes
CQL error codes constant. Useful when it is desired to programatically
determine the type of error that occurred during a query execution.
Fields:
- SERVER Something unexpected happened. This indicates a server-side bug.
- PROTOCOL Some client message triggered a protocol violation (for instance a QUERY message is sent before a STARTUP).
- BAD_CREDENTIALS A CREDENTIALS request failed because Cassandra did not accept the provided credentials.
- UNAVAILABLE_EXCEPTION The query could not be processed with respect to the given concurrency.
- OVERLOADED The request cannot be processed because the coordinator node is overloaded.
- IS_BOOTSTRAPPING The request was a read request but the coordinator node is bootstrapping.
- TRUNCATE_ERROR Error during a truncation.
- WRITE_TIMEOUT Timeout exception during a write request.
- READ_TIMEOUT Timeout exception during a read request.
- SYNTAX_ERROR The submitted query has a syntax error.
- UNAUTHORIZED The logged-in user doesn't have the right to perform the query.
- INVALID The query is syntactically correct but invalid.
- CONFIG_ERROR The query is invalid because of some configuration issue.
- ALREADY_EXISTS The query attempted to create a keyspace or a table that is already existing.
- UNPREPARED Can be thrown while a prepared statement tries to be executed if the provided prepared query id is not known by this host.
- consistencies
-
CQL consistencies.
Fields:
- all
CQL consistency
ALL
.cassandra.consistencies.all
- each_quorum
CQL consistency
EACH_QUORUM
.cassandra.consistencies.each_quorum
- quorum
CQL consistency
QUORUM
.cassandra.consistencies.quorum
- local_quorum
CQL consistency
LOCAL_QUORUM
.cassandra.consistencies.local_quorum
- one
CQL consistency
ONE
.cassandra.consistencies.one
- two
CQL consistency
TWO
.cassandra.consistencies.two
- three
CQL consistency
THREE
.cassandra.consistencies.three
- local_one
CQL consistency
LOCAL_ONE
.cassandra.consistencies.local_one
- any
CQL consistency
ANY
.cassandra.consistencies.any
- serial
CQL consistency
SERIAL
.cassandra.consistencies.seriam
- local_serial
CQL consistency
LOCAL_SERIAL
.cassandra.consistencies.local_serial
- all
- auth_providers
-
Authentication providers
Fields:
- plain_text
The plain text auth provider.
local auth = cassandra.auth_provider.plain_text("username", "password")
- plain_text
- client_options
-
New client options.
Options taken by new upon client creation.
Fields:
- host
Address to which the client should connect.
(string, default:
"127.0.0.1"
) - port
Port to which the client should connect.
(
number
, default:9042
) - keyspace Keyspace the client should use. (string, optional)
- protocol_version
Binary protocol version the client should try to use
(
number
, default:3
) - ssl
Determines if the client should connect using SSL.
(
boolean
, default:false
) - ssl_protocol
The client encryption protocol version to use
if
ssl
is enabled (LuaSec usage only, seelua_ssl_protocols
directive for ngx_lua). (string, default:any
) - verify
Enable server certificate validation if
ssl
is enabled. (boolean
, default:false
) - cafile
Path to the server certificate (LuaSec usage only, see
lua_ssl_trusted_certificate
directive for ngx_lua). (string, optional) - cert Path to the client SSL certificate (LuaSec usage only). (string, optional)
- key Path to the client SSL key (LuaSec usage only). (string, optional)
- auth Authentication handler, created from the cassandra.auth_providers table. (optional)
- host
Address to which the client should connect.
(string, default:
- query_options
-
Query options.
Fields:
- consistency
Consistency level for this request.
See cassandra.consistencies table.
(default:
cassandra.consistencies.one
) - serial_consistency
Serial consistency level for this request.
See cassandra.consistencies table.
(default:
cassandra.consistencies.serial
) - page_size
When retrieving a set of rows (
SELECT
), determines the maximum maximum amount of rows per page. (number
, default:1000
) - paging_state String token representing the paging state. Useful for manual paging: if provided, the query will be executed starting from the given paging state. (string, optional)
- tracing
Enable query tracing. Use this option to diagnose performance
problems related to query execution.
(
boolean
, default:false
) - prepared
Determines if the argument given to execute is a prepared
query id (from prepare) to be executed.
(
boolean
, default:false
) - logged
When executing a batch, determines if the batch should be
written to the batchlog. (
boolean
, default:true
) - counter
When executing a batch, specify if the batch contains
counter updates. (
boolean
, default:false
) - timestamp
The default timestamp for the query/batch in microseconds
from unix epoch. If provided, will replace the server
side assigned timestamp as default timestamp.
(
number
, optional) - named
Determines if arguments binded to execute are key/value
indexed instead of an array. (
boolean
, default:false
)
- consistency
Consistency level for this request.
See cassandra.consistencies table.
(default:
- type_serializers
-
CQL serializers.
When binding arguments to a query, some types cannot be infered
automatically and will require manual serialization. Some other
times, it can be useful to manually enforce the type of a parameter.
For this purpose, shorthands for type serialization are available
on the cassandra module.
Fields:
- null
(native protocol v4 only) Equivalent to the
null
CQL value. Useful to unset a field.cassandra.null
- unset
Equivalent to the
not set
CQL value. Leaves field untouched for binary protocol v4+, or unset it for v2/v3.cassandra.unset
- uuid
Serialize a 32 lowercase characters string to a CQL uuid.
cassandra.uuid("123e4567-e89b-12d3-a456-426655440000")
- timestamp
Serialize a 10 digits number into a CQL timestamp.
cassandra.timestamp(1405356926)
- list
cassandra.list({"abc", "def"})
- set
cassandra.set({"abc", "def"})
- map
cassandra.map({foo = "bar"})
- udt CQL UDT.
- tuple CQL tuple.
- inet
CQL inet.
cassandra.inet("127.0.0.1") cassandra.inet("2001:0db8:85a3:0042:1000:8a2e:0370:7334")
- bigint
CQL bigint.
cassandra.bigint(42000000000)
- double
CQL double.
cassandra.bigint(1.0000000000000004)
- ascii CQL ascii.
- blob CQL blob.
- boolean
CQL boolean.
cassandra.boolean(true)
- counter
CQL counter.
cassandra.counter(1)
- decimal CQL decimal.
- float
CQL float.
cassandra.float(1.618033)
- int
CQL int.
cassandra.int(10)
- text
CQL text.
cassandra.text("hello world")
- timeuuid CQL timeuuid.
- varchar CQL varchar.
- varint CQL varint.
Usage:
local cassandra = require "cassandra" -- connect client... client:execute("SELECT * FROM users WHERE id = ?", { cassandra.uuid("123e4567-e89b-12d3-a456-426655440000") }) client:execute("INSERT INTO users(id, emails) VALUES(?, ?)", { 1, cassandra.set({"john@foo.com", "john@bar.com"}) })
- null