# Cassandra Client for Vert.x

A Vert.x client allowing applications to interact with a Cassandra service.

Warning | This module has Tech Preview status, this means the API can change between versions.

## Using the Cassandra Client for Vert.x

To use this module, add the following to the dependencies section of your Maven POM file:

    <dependency>
     <groupId>io.vertx</groupId>
     <artifactId>vertx-lang-js</artifactId>
     <version>3.6.3</version>
    </dependency>

Or, if you use Gradle:

    compile 'io.vertx:vertx-lang-js:3.6.3'

Warning | the Cassandra client is not compatible with the Vert.x Dropwizard Metrics library. Both are using a different major version of the Dropwizard Metrics library and the Cassandra driver won’t upgrade to the most recent version due to the drop of Java 7. The next major version of the Cassandra driver (4) will uses a more recent Dropwizard Metrics library version.

## Creating a client

Cassandra is a distributed system, and it can have many nodes. To connect to Cassandra you need to specify the addresses of some cluster nodes when creating a `CassandraClientOptions` object:

    var CassandraClient = require("vertx-cassandra-js/cassandra_client");
    var options = {
      "contactPoints" : [
        "node1.address",
        "node2.address",
        "node3.address"
      ]
    };
    var client = CassandraClient.createShared(vertx, options);

Note | By default, the Cassandra client for Vert.x will connect to the local machine’s port `9042`.

### Connect/Disconnect

After the client is created you can connect using specific cluster options:

    cassandraClient.connect(function (connect, connect_err) {
      if (connect_err == null) {
        console.log("Just connected");
      } else {
        console.log("Unable to connect");
        connect_err.printStackTrace();
      }
    });

To disconnect, you can do it in a similar way:

    cassandraClient.disconnect(function (disconnect, disconnect_err) {
      if (disconnect_err == null) {
        console.log("Just disconnected");
      } else {
        console.log("Unable to disconnect");
        disconnect_err.printStackTrace();
      }
    });

## Using the API

The client API is represented by `CassandraClient`.

### Querying

You can get query results using three different ways.

#### Streaming

The streaming API is most appropriate when you need to consume results iteratively, e.g you want to process each item. This is very efficient specially for large amount of rows.

In order to give you some inspiration and ideas on how you can use the API, we’d like to you to consider this example:

    cassandraClient.queryStream("SELECT my_string_col FROM my_keyspace.my_table where my_key = 'my_value'", function (queryStream, queryStream_err) {
      if (queryStream_err == null) {
        var stream = queryStream;

        // resume stream when queue is ready to accept buffers again
        response.drainHandler(function (v) {
          stream.resume();
        });

        stream.handler(function (row) {
          var value = row.getString("my_string_col");
          response.write(value);

          // pause row stream when we buffer queue is full
          if (response.writeQueueFull()) {
            stream.pause();
          }
        });

        // end request when we reached end of the stream
        stream.endHandler(function (end) {
          response.end();
        });

      } else {
        queryStream_err.printStackTrace();
        // response with internal server error if we are not able to execute given query
        response.setStatusCode(500).end("Unable to execute the query");
      }
    });

In the example, we are executing a query, and stream results via HTTP.

#### Bulk fetching

This API should be used when you need to process all the rows at the same time.

    cassandraClient.executeWithFullFetch("SELECT * FROM my_keyspace.my_table where my_key = 'my_value'", function (executeWithFullFetch, executeWithFullFetch_err) {
      if (executeWithFullFetch_err == null) {
        var rows = executeWithFullFetch;
        Array.prototype.forEach.call(rows, function(row) {
          // handle each row here
        });
      } else {
        console.log("Unable to execute the query");
        executeWithFullFetch_err.printStackTrace();
      }
    });

Caution | Use bulk fetching only if you can afford to load the full result set in memory.

#### Low level fetch

This API provides greater control over loading at the expense of being a bit lower-level than the streaming and bulk fetching APIs.

    cassandraClient.execute("SELECT * FROM my_keyspace.my_table where my_key = 'my_value'", function (execute, execute_err) {
      if (execute_err == null) {
        var resultSet = execute;

        resultSet.one(function (one, one_err) {
          if (one_err == null) {
            var row = one;
            console.log("One row successfully fetched");
          } else {
            console.log("Unable to fetch a row");
            one_err.printStackTrace();
          }
        });

        resultSet.fetchMoreResults(function (fetchMoreResults, fetchMoreResults_err) {
          if (fetchMoreResults_err == null) {
            var availableWithoutFetching = resultSet.getAvailableWithoutFetching();
            console.log("Now we have " + availableWithoutFetching + " rows fetched, but not consumed!");
            if (resultSet.isFullyFetched()) {
              console.log("The result is fully fetched, we don't need to call this method for one more time!");
            } else {
              console.log("The result still does not fully fetched");
            }
          } else {
            console.log("Unable to fetch more results");
            fetchMoreResults_err.printStackTrace();
          }
        });

      } else {
        console.log("Unable to execute the query");
        execute_err.printStackTrace();
      }
    });

### Prepared queries

For security and efficiency reasons, it is a good idea to use prepared statements for all the queries you are using more than once.

You can prepare a query:

    cassandraClient.prepare("SELECT * FROM my_keyspace.my_table where my_key = ? ", function (preparedStatementResult, preparedStatementResult_err) {
      if (preparedStatementResult_err == null) {
        console.log("The query has successfully been prepared");
        var preparedStatement = preparedStatementResult;
        // now you can use this PreparedStatement object for the next queries
      } else {
        console.log("Unable to prepare the query");
        preparedStatementResult_err.printStackTrace();
      }
    });

And then use the `PreparedStatement` for all the next queries:

    // You can execute you prepared statement using any way to execute queries.

    // Low level fetch API
    cassandraClient.execute(preparedStatement.bind("my_value"), function (done, done_err) {
      var results = done;
      // handle results here
    });

    // Bulk fetching API
    cassandraClient.executeWithFullFetch(preparedStatement.bind("my_value"), function (done, done_err) {
      var results = done;
      // handle results here
    });

    // Streaming API
    cassandraClient.queryStream(preparedStatement.bind("my_value"), function (done, done_err) {
      var results = done;
      // handle results here
    });

### Batching

In case you’d like to execute several queries at once, you can use `BatchStatement` for that:

    var batchStatement = new (Java.type("com.datastax.driver.core.BatchStatement"))().add(new (Java.type("com.datastax.driver.core.SimpleStatement"))("INSERT INTO NAMES (name) VALUES ('Pavel')")).add(new (Java.type("com.datastax.driver.core.SimpleStatement"))("INSERT INTO NAMES (name) VALUES ('Thomas')")).add(new (Java.type("com.datastax.driver.core.SimpleStatement"))("INSERT INTO NAMES (name) VALUES ('Julien')"));

    cassandraClient.execute(batchStatement, function (result, result_err) {
      if (result_err == null) {
        console.log("The given batch executed successfully");
      } else {
        console.log("Unable to execute the batch");
        result_err.printStackTrace();
      }
    });