Class: Client

Client(options)

Represents a database client that maintains multiple connections to the cluster nodes, providing methods to execute CQL statements.

The Client uses policies to decide which nodes to connect to, which node to use per each query execution, when it should retry failed or timed-out executions and how reconnection to down nodes should be made.

Constructor

new Client(options)

Creates a new instance of Client.

Parameters:
Name Type Description
options clientOptions.ClientOptions

The options for this instance.

Source:
Examples

Creating a new client instance

const client = new Client({
  contactPoints: ['10.0.1.101', '10.0.1.102'],
});

Executing a query

const result = await client.connect();
console.log(`Connected to ${client.hosts.length} nodes in the cluster: ${client.hosts.keys().join(', ')}`);

Executing a query

const result = await client.execute('SELECT key FROM system.local');
const row = result.first();
console.log(row['key']);

Extends

  • EventEmitter

Members

hosts :HostMap

Gets an associative array of cluster hosts. TODO: This field is currently not supported

Type:
Source:

keyspace :string|undefined

Gets the name of the active keyspace.

Type:
  • string | undefined
Source:

metadata :Metadata

Gets the schema and cluster metadata information. TODO: This field is currently not supported

Type:
  • Metadata
Source:

metrics :ClientMetrics

The ClientMetrics instance used to expose measurements of its internal behavior and of the server as seen from the driver side.

By default, a DefaultMetrics instance is used.

Type:
  • ClientMetrics
Source:

Methods

batch(queries, optionsopt, callbackopt)

Executes batch of queries on an available connection to a host.

It returns a Promise when a callback is not provided.

Parameters:
Name Type Attributes Description
queries Array.<string> | Array.<{query, params}>

The queries to execute as an Array of strings or as an array of object containing the query and params

options queryOptions.QueryOptions <optional>

The query options.

callback ResultCallback <optional>

Executes callback(err, result) when the batch was executed

Source:

connect(callbackopt)

Attempts to connect to one of the contactPoints and discovers the rest the nodes of the cluster.

When the Client is already connected, it resolves immediately.

It returns a Promise when a callback is not provided.

Parameters:
Name Type Attributes Description
callback function <optional>

The optional callback that is invoked when the pool is connected or it failed to connect.

Source:
Example

Usage example

await client.connect();

(package) createOptions(optionsopt) → {ExecOptions.ExecutionOptions}

Manually create final execution options, applying client and default setting.

Creating those options requires a native call, but they can be reused without any additional native calls, which improves performance for queries with the same QueryOptions.

Parameters:
Name Type Attributes Description
options queryOptions.QueryOptions | ExecOptions.ExecutionOptions <optional>
Source:
Returns:
Type
ExecOptions.ExecutionOptions

eachRow(query, paramsopt, optionsopt, rowCallback, callbackopt)

Executes the query and calls rowCallback for each row as soon as they are received. Calls the final callback after all rows have been sent, or when there is an error.

The query can be prepared (recommended) or not depending on the prepare flag.

Parameters:
Name Type Attributes Description
query string

The query to execute

params Array | Object <optional>

Array of parameter values or an associative array (object) containing parameter names as keys and its value.

options queryOptions.QueryOptions <optional>

The query options.

rowCallback function

Executes rowCallback(n, row) per each row received, where n is the row index and row is the current Row.

callback function <optional>

Executes callback(err, result) after all rows have been received.

When dealing with paged results, ResultSet#nextPage() method can be used to retrieve the following page. In that case, rowCallback() will be again called for each row and the final callback will be invoked when all rows in the following page has been retrieved.

Source:
Examples

Using per-row callback and arrow functions

client.eachRow(query, params, { prepare: true }, (n, row) => console.log(n, row), err => console.error(err));

Overloads

client.eachRow(query, rowCallback);
client.eachRow(query, params, rowCallback);
client.eachRow(query, params, options, rowCallback);
client.eachRow(query, params, rowCallback, callback);
client.eachRow(query, params, options, rowCallback, callback);

execute(query, paramsopt, optionsopt, callbackopt)

Executes a query on an available connection.

The query can be prepared (recommended) or not depending on the prepare flag.

Some execution failures can be handled transparently by the driver, according to the RetryPolicy or the SpeculativeExecutionPolicy used.

It returns a Promise when a callback is not provided.

Parameters:
Name Type Attributes Description
query string

The query to execute.

params Array | Object <optional>

Array of parameter values or an associative array (object) containing parameter names as keys and its value.

options queryOptions.QueryOptions <optional>

The query options for the execution.

callback ResultCallback <optional>

Executes callback(err, result) when execution completed. When not defined, the method will return a promise.

Source:
See:
Examples

Promise-based API, using async/await

const query = 'SELECT name, email FROM users WHERE id = ?';
const result = await client.execute(query, [ id ], { prepare: true });
const row = result.first();
console.log('%s: %s', row['name'], row['email']);

Callback-based API

const query = 'SELECT name, email FROM users WHERE id = ?';
client.execute(query, [ id ], { prepare: true }, function (err, result) {
  assert.ifError(err);
  const row = result.first();
  console.log('%s: %s', row['name'], row['email']);
});

executeGraph()

Deprecated:
  • Not supported by the driver. Usage will throw an error.
Source:

getReplicas(keyspace, token) → {Array.<Host>}

Gets the host that are replicas of a given token.

Parameters:
Name Type Description
keyspace string
token Buffer
Source:
Returns:
Type
Array.<Host>

getState() → {ClientState}

Deprecated:
  • This is not planned feature for the driver. Currently this remains in place, but returns Client state with no information. This endpoint may be removed at any point.
Source:
Returns:

A dummy ClientState instance.

Type
ClientState

(async, package) prepareQuery(query) → {Promise.<rust.PreparedStatementWrapper>}

Manually prepare query into prepared statement

Parameters:
Name Type Description
query string
Source:
Returns:
Type
Promise.<rust.PreparedStatementWrapper>

(async, package) rustyExecute(query, params, execOptions) → {Promise.<ResultSet>}

Wrapper for executing queries by rust driver

Parameters:
Name Type Description
query string | rust.PreparedStatementWrapper
params Array
execOptions ExecOptions.ExecutionOptions
Source:
Returns:
Type
Promise.<ResultSet>

shutdown(callbackopt)

The only effect of calling shutdown is rejecting any following queries to the database.

It returns a Promise when a callback is not provided.

Parameters:
Name Type Attributes Description
callback function <optional>

Optional callback to be invoked when finished closing all connections.

Deprecated:
  • Explicit connection shutdown is deprecated and may be removed in the future. Drop this client to close the connection to the database.
Source:

stream(query, paramsopt, optionsopt, callbackopt) → {types.types.ResultStream}

Executes the query and pushes the rows to the result stream as soon as they received.

The stream is a ReadableStream object that emits rows. It can be piped downstream and provides automatic pause/resume logic (it buffers when not read).

The query can be prepared (recommended) or not depending on QueryOptions.prepare flag. Retries on multiple hosts if needed.

Parameters:
Name Type Attributes Description
query string

The query to prepare and execute.

params Array | Object <optional>

Array of parameter values or an associative array (object) containing parameter names as keys and its value

options queryOptions.QueryOptions <optional>

The query options.

callback function <optional>

executes callback(err) after all rows have been received or if there is an error

Source:
Returns:
Type
types.types.ResultStream

Events

hostAdd

Emitted when a new host is added to the cluster.

  • Host The host being added.
Source:

hostDown

Emitted when a host in the cluster changed status from up to down.

  • host The host that changed the status.
Source:

hostRemove

Emitted when a host is removed from the cluster

  • Host The host being removed.
Source:

hostUp

Emitted when a host in the cluster changed status from down to up.

  • host The host that changed the status.
Source: