kikocis/java-driver public
Changesets · Branches · Tags · Compare
| Changeset | e3de241dc92a5033a7b94375a079c4674e9011eea98920e427f819dd0dd7c3bc |
|---|---|
| Author | olim7t <omichallat+github@gmail.com> · 2016-01-27 14:40 +01:00 |
| Committer | olim7t <omichallat+github@gmail.com> · 2016-01-27 15:22 +01:00 |
| Parents | 566c3d5378ff, d3d82a63787d |
7 files changed
modified driver-core/src/main/java/com/datastax/driver/core/policies/LatencyAwarePolicy.java +8 −8
| @@ -537,18 +537,18 @@ | ||
| 537 | 537 | */ |
| 538 | 538 | public static class Builder { |
| 539 | 539 | |
| 540 | - private static final double DEFAULT_EXCLUSION_THRESHOLD = 2.0; | |
| 541 | - private static final long DEFAULT_SCALE = TimeUnit.MILLISECONDS.toNanos(100); | |
| 542 | - private static final long DEFAULT_RETRY_PERIOD = TimeUnit.SECONDS.toNanos(10); | |
| 543 | - private static final long DEFAULT_UPDATE_RATE = TimeUnit.MILLISECONDS.toNanos(100); | |
| 544 | - private static final int DEFAULT_MIN_MEASURE = 50; | |
| 540 | + public static final double DEFAULT_EXCLUSION_THRESHOLD = 2.0; | |
| 541 | + public static final long DEFAULT_SCALE_NANOS = TimeUnit.MILLISECONDS.toNanos(100); | |
| 542 | + public static final long DEFAULT_RETRY_PERIOD_NANOS = TimeUnit.SECONDS.toNanos(10); | |
| 543 | + public static final long DEFAULT_UPDATE_RATE_NANOS = TimeUnit.MILLISECONDS.toNanos(100); | |
| 544 | + public static final int DEFAULT_MIN_MEASURE = 50; | |
| 545 | 545 | |
| 546 | 546 | private final LoadBalancingPolicy childPolicy; |
| 547 | 547 | |
| 548 | 548 | private double exclusionThreshold = DEFAULT_EXCLUSION_THRESHOLD; |
| 549 | - private long scale = DEFAULT_SCALE; | |
| 550 | - private long retryPeriod = DEFAULT_RETRY_PERIOD; | |
| 551 | - private long updateRate = DEFAULT_UPDATE_RATE; | |
| 549 | + private long scale = DEFAULT_SCALE_NANOS; | |
| 550 | + private long retryPeriod = DEFAULT_RETRY_PERIOD_NANOS; | |
| 551 | + private long updateRate = DEFAULT_UPDATE_RATE_NANOS; | |
| 552 | 552 | private int minMeasure = DEFAULT_MIN_MEASURE; |
| 553 | 553 | |
| 554 | 554 | /** |
modified manual/README.md +1 −1
| @@ -74,7 +74,7 @@ | ||
| 74 | 74 | * [query options][QueryOptions]; |
| 75 | 75 | * [reconnections](reconnection/); |
| 76 | 76 | * [retries](retries/); |
| 77 | -* [socket options][SocketOptions]; | |
| 77 | +* [socket options](socket_options/); | |
| 78 | 78 | * [SSL](ssl/); |
| 79 | 79 | * [speculative executions](speculative_execution/); |
| 80 | 80 | * [query timestamps](query_timestamps/). |
added manual/socket_options/README.md +130 −0
| @@ -0,0 +1,130 @@ | ||
| 1 | +## Socket options | |
| 2 | + | |
| 3 | +[SocketOptions] controls various low-level parameters related to TCP connections between the driver and Cassandra. | |
| 4 | + | |
| 5 | +You can provide these when initializing the cluster: | |
| 6 | + | |
| 7 | +```java | |
| 8 | +Cluster cluster = Cluster.builder() | |
| 9 | + .addContactPoint("127.0.0.1") | |
| 10 | + .withSocketOptions( | |
| 11 | + new SocketOptions() | |
| 12 | + .setConnectTimeoutMillis(2000)) | |
| 13 | + .build(); | |
| 14 | +``` | |
| 15 | + | |
| 16 | +If you don't, the driver uses a default configuration (see the javadocs of the setter methods of [SocketOptions] for the | |
| 17 | +default values). | |
| 18 | + | |
| 19 | +You can retrieve and change the options at runtime: | |
| 20 | + | |
| 21 | +```java | |
| 22 | +SocketOptions socketOptions = cluster.getConfiguration().getSocketOptions(); | |
| 23 | +socketOptions.setConnectTimeoutMillis(3000); | |
| 24 | +``` | |
| 25 | + | |
| 26 | +* changes to the [read timeout](#driver-read-timeout) will be taken into account for future request executions; | |
| 27 | +* changes to any other option will be taken into account for future connections (connections that were already opened at | |
| 28 | + the time of the change are unaffected, they keep the old values). | |
| 29 | + | |
| 30 | +### TCP options | |
| 31 | + | |
| 32 | +[setConnectTimeoutMillis] defines how long the driver waits to establish a new connection to a Cassandra node before | |
| 33 | +giving up. | |
| 34 | + | |
| 35 | +Other options control the usual low-level TCP parameters (refer to their individual javadoc for details): | |
| 36 | +[setKeepAlive], [setReceiveBufferSize], [setReuseAddress], [setSendBufferSize], [setSoLinger], [setTcpNoDelay]. Most of | |
| 37 | +these options are not set explicitly by the driver, so they get the default value from the underlying TCP transport. | |
| 38 | +One exception is `setTcpNoDelay`, which is forced to `true` (meaning that Nagle's algorithm is *disabled* for driver | |
| 39 | +connections). | |
| 40 | + | |
| 41 | +### Driver read timeout | |
| 42 | + | |
| 43 | +[setReadTimeoutMillis] controls how long the driver waits for a response *from a given Cassandra node* before | |
| 44 | +considering it unresponsive. | |
| 45 | + | |
| 46 | +Cassandra normally provides a guaranteed response time for each type of query, as shown by these parameters in | |
| 47 | +`cassandra.yaml` (here with their default values): | |
| 48 | + | |
| 49 | +```yaml | |
| 50 | +counter_write_request_timeout_in_ms: 5000 | |
| 51 | +range_request_timeout_in_ms: 10000 | |
| 52 | +read_request_timeout_in_ms: 5000 | |
| 53 | +request_timeout_in_ms: 10000 | |
| 54 | +truncate_request_timeout_in_ms: 60000 | |
| 55 | +write_request_timeout_in_ms: 2000 | |
| 56 | +``` | |
| 57 | + | |
| 58 | +The goal of `setReadTimeoutMillis` is to give up on a node if it took longer than these thresholds to reply, on the | |
| 59 | +assumption that there's probably something wrong with it. Therefore it should be set **higher than the server-side | |
| 60 | +timeouts**. | |
| 61 | + | |
| 62 | +The default value is **12 seconds**. For truncate queries (where the server timeout is 60 seconds) or aggregate queries | |
| 63 | +(where `read_request_timeout_in_ms` applies per page of processed data, not to the whole query), you can increase the | |
| 64 | +timeout on a specific statement: | |
| 65 | + | |
| 66 | +```java | |
| 67 | +session.execute( | |
| 68 | + new SimpleStatement("TRUNCATE tmp").setReadTimeoutMillis(65000)); | |
| 69 | +``` | |
| 70 | + | |
| 71 | +Do not set the read timeout too low, or the driver might give up on requests that had a chance of succeeding. | |
| 72 | + | |
| 73 | +If the timeout is reached, the driver will receive an [OperationTimedOutException], and invoke [onRequestError] on the | |
| 74 | +[retry policy](../retries/) to decide what to do (the default is to retry on the next node in the | |
| 75 | +[query plan](../load_balancing/#query-plan)). | |
| 76 | + | |
| 77 | +#### Limiting overall query time | |
| 78 | + | |
| 79 | +It should be clear by now that `setReadTimeoutMillis` is *per node*, not per query. If the driver retries on 4 different | |
| 80 | +nodes, the overall execution time could theoretically be up to 4 times the read timeout. If you want a per query timeout, | |
| 81 | +use the following pattern: | |
| 82 | + | |
| 83 | +```java | |
| 84 | +import com.google.common.base.Throwables; | |
| 85 | + | |
| 86 | +ResultSet execute(Statement statement, long timeout, TimeUnit unit) | |
| 87 | + throws InterruptedException, TimeoutException { | |
| 88 | + ResultSetFuture future = session.executeAsync(statement); | |
| 89 | + try { | |
| 90 | + return future.get(timeout, unit); | |
| 91 | + } catch (ExecutionException e) { | |
| 92 | + throw Throwables.propagate(e.getCause()); | |
| 93 | + } catch (TimeoutException e) { | |
| 94 | + future.cancel(true); | |
| 95 | + throw e; | |
| 96 | + } | |
| 97 | +} | |
| 98 | +``` | |
| 99 | + | |
| 100 | +A complementary approach is to enable [speculative executions](../speculative_execution/), to have the driver query | |
| 101 | +multiple nodes in parallel. This way you won't have to wait for the full timeout if the first node is unresponsive. | |
| 102 | + | |
| 103 | +#### Driver read timeout vs. server read timeout | |
| 104 | + | |
| 105 | +Unfortunately, the term "read timeout" clashes with another concept that is not directly related: a Cassandra node may | |
| 106 | +reply with a `Read_timeout` error when it didn't hear back from enough replicas during a read query. | |
| 107 | + | |
| 108 | +To clarify: | |
| 109 | + | |
| 110 | +* **driver read timeout:** the driver did not receive any response from the current coordinator within | |
| 111 | + `SocketOptions.setReadTimeoutMillis`. It invokes [onRequestError] on the [retry policy](../retries/) with an | |
| 112 | + [OperationTimedOutException] to decide what to do. | |
| 113 | +* **server read timeout:** the driver *did* receive a response, but that response indicates that the coordinator timed | |
| 114 | + out while waiting for other replicas. It invokes [onReadTimeout] on the [retry policy](../retries/) to decide what to | |
| 115 | + do. | |
| 116 | + | |
| 117 | +We might rename `SocketOptions.setReadTimeoutMillis` in a future version to clear up any confusion. | |
| 118 | + | |
| 119 | +[SocketOptions]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/SocketOptions.html | |
| 120 | +[setReadTimeoutMillis]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/SocketOptions.html#setReadTimeoutMillis-int- | |
| 121 | +[setConnectTimeoutMillis]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/SocketOptions.html#setConnectTimeoutMillis-int- | |
| 122 | +[setKeepAlive]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/SocketOptions.html#setKeepAlive-boolean- | |
| 123 | +[setReceiveBufferSize]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/SocketOptions.html#setReceiveBufferSize-int- | |
| 124 | +[setReuseAddress]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/SocketOptions.html#setReuseAddress-boolean- | |
| 125 | +[setSendBufferSize]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/SocketOptions.html#setSendBufferSize-int- | |
| 126 | +[setSoLinger]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/SocketOptions.html#setSoLinger-int- | |
| 127 | +[setTcpNoDelay]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/SocketOptions.html#setTcpNoDelay-boolean- | |
| 128 | +[onReadTimeout]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/policies/RetryPolicy.html#onReadTimeout-com.datastax.driver.core.Statement-com.datastax.driver.core.ConsistencyLevel-int-int-boolean-int- | |
| 129 | +[onRequestError]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/policies/RetryPolicy.html#onRequestError-com.datastax.driver.core.Statement-com.datastax.driver.core.ConsistencyLevel-com.datastax.driver.core.exceptions.DriverException-int- | |
| 130 | +[OperationTimedOutException]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/exceptions/OperationTimedOutException.html | |
| No newline at the end of the file |
added manual/statements/.nav +4 −0
| @@ -0,0 +1,4 @@ | ||
| 1 | +simple | |
| 2 | +prepared | |
| 3 | +built | |
| 4 | +batch | |
| No newline at the end of the file |
modified manual/statements/README.md +9 −17
| @@ -1,7 +1,7 @@ | ||
| 1 | 1 | ## Statements |
| 2 | 2 | |
| 3 | -To execute a query, you create a [Statement] instance and pass it to | |
| 4 | -`Session#execute()`. The driver provides various implementations: | |
| 3 | +To execute a query, you create a [Statement] instance and pass it to [Session#execute()][execute] or | |
| 4 | +[Session#executeAsync][executeAsync]. The driver provides various implementations: | |
| 5 | 5 | |
| 6 | 6 | * [SimpleStatement](simple/): a simple implementation built directly from a |
| 7 | 7 | character string. Typically used for queries that are executed only |
| @@ -14,16 +14,6 @@ | ||
| 14 | 14 | * [BatchStatement](batch/): a statement that groups multiple statements to be |
| 15 | 15 | executed as a batch. |
| 16 | 16 | |
| 17 | -`Session` also has a shortcut to build and execute a simple statement in | |
| 18 | -a single call: | |
| 19 | - | |
| 20 | -```java | |
| 21 | -session.execute("select release_version from system.local"); | |
| 22 | - | |
| 23 | -// Is equivalent to: | |
| 24 | -Statement s = new SimpleStatement("select release_version from system.local"); | |
| 25 | -session.execute(s); | |
| 26 | -``` | |
| 27 | 17 | |
| 28 | 18 | ### Customizing execution |
| 29 | 19 | |
| @@ -42,9 +32,11 @@ | ||
| 42 | 32 | properties that influence statement execution. To achieve this, you can |
| 43 | 33 | wrap your statements in a custom [StatementWrapper] implementation. |
| 44 | 34 | |
| 45 | -[Statement]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/Statement.html | |
| 46 | -[QueryBuilder]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/querybuilder/QueryBuilder.html | |
| 47 | -[StatementWrapper]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/StatementWrapper.html | |
| 48 | -[RetryPolicy]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/policies/RetryPolicy.html | |
| 49 | -[LoadBalancingPolicy]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/policies/LoadBalancingPolicy.html | |
| 35 | +[Statement]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/Statement.html | |
| 36 | +[QueryBuilder]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/querybuilder/QueryBuilder.html | |
| 37 | +[StatementWrapper]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/StatementWrapper.html | |
| 38 | +[RetryPolicy]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/policies/RetryPolicy.html | |
| 39 | +[LoadBalancingPolicy]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/policies/LoadBalancingPolicy.html | |
| 50 | 40 | [SpeculativeExecutionPolicy]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/policies/SpeculativeExecutionPolicy.html |
| 41 | +[execute]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/Session.html#execute-com.datastax.driver.core.Statement- | |
| 42 | +[executeAsync]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/Session.html#executeAsync-com.datastax.driver.core.Statement- |
modified manual/statements/prepared/README.md +73 −31
| @@ -1,30 +1,68 @@ | ||
| 1 | 1 | ## Prepared statements |
| 2 | 2 | |
| 3 | -When Cassandra executes a query, the first thing it does is parse the | |
| 4 | -query string to an internal representation. If the same query is used | |
| 5 | -often, you can use a prepared statement, which allows Cassandra to cache | |
| 6 | -that representation, and save time and resources for subsequent | |
| 7 | -executions. Prepared statements are typically parameterized, using | |
| 8 | -different values for each execution: | |
| 3 | +Use [PreparedStatement] for queries that are executed multiple times in your application: | |
| 9 | 4 | |
| 10 | 5 | ```java |
| 11 | 6 | PreparedStatement prepared = session.prepare( |
| 12 | 7 | "insert into product (sku, description) values (?, ?)"); |
| 13 | 8 | |
| 14 | -BoundStatement bound; | |
| 15 | - | |
| 16 | -bound = prepared.bind("234827", "Mouse"); | |
| 9 | +BoundStatement bound = prepared.bind("234827", "Mouse"); | |
| 17 | 10 | session.execute(bound); |
| 18 | 11 | |
| 19 | -bound = prepared.bind("987274", "Keyboard"); | |
| 20 | -session.execute(bound); | |
| 12 | +session.execute(prepared.bind("987274", "Keyboard")); | |
| 13 | +``` | |
| 14 | + | |
| 15 | +When you prepare the statement, Cassandra will parse the query string, cache the result and return a unique identifier | |
| 16 | +(the `PreparedStatement` object keeps an internal reference to that identifier): | |
| 17 | + | |
| 18 | +```ditaa | |
| 19 | +client driver Cassandra | |
| 20 | +--+------------------------+----------------+------ | |
| 21 | + | | | | |
| 22 | + | session.prepare(query) | | | |
| 23 | + |----------------------->| | | |
| 24 | + | | PREPARE(query) | | |
| 25 | + | |--------------->| | |
| 26 | + | | | | |
| 27 | + | | | | |
| 28 | + | | | - compute id | |
| 29 | + | | | - parse query string | |
| 30 | + | | | - cache (id, parsed) | |
| 31 | + | | | | |
| 32 | + | | PREPARED(id) | | |
| 33 | + | |<---------------| | |
| 34 | + | PreparedStatement(id) | | | |
| 35 | + |<-----------------------| | | |
| 36 | +``` | |
| 37 | + | |
| 38 | +When you bind and execute a prepared statement, the driver will only send the identifier, which allows Cassandra to | |
| 39 | +skip the parsing phase: | |
| 40 | + | |
| 41 | +```ditaa | |
| 42 | +client driver Cassandra | |
| 43 | +--+---------------------------------+---------------------+------ | |
| 44 | + | | | | |
| 45 | + | session.execute(BoundStatement) | | | |
| 46 | + |-------------------------------->| | | |
| 47 | + | | EXECUTE(id, values) | | |
| 48 | + | |-------------------->| | |
| 49 | + | | | | |
| 50 | + | | | | |
| 51 | + | | | - get cache(id) | |
| 52 | + | | | - execute query | |
| 53 | + | | | | |
| 54 | + | | ROWS | | |
| 55 | + | |<--------------------| | |
| 56 | + | | | | |
| 57 | + |<--------------------------------| | | |
| 21 | 58 | ``` |
| 22 | 59 | |
| 23 | -Statements should be be prepared only once. If you call `prepare` | |
| 24 | -multiple times with the same query string, the driver will log a | |
| 25 | -warning. So your application should cache the `PreparedStatement` object | |
| 26 | -once it's been created (this can be as simple as storing it as a field | |
| 27 | -in a DAO). | |
| 60 | + | |
| 61 | +You should prepare only once, and cache the `PreparedStatement` in your application (it is thread-safe). If you call | |
| 62 | +`prepare` multiple times with the same query string, the driver will log a warning. | |
| 63 | + | |
| 64 | +If you execute a query only once, a prepared statement is inefficient because it requires two roundtrips. Consider a | |
| 65 | +[simple statement](../simple/) instead. | |
| 28 | 66 | |
| 29 | 67 | ### Parameters and binding |
| 30 | 68 | |
| @@ -36,9 +74,8 @@ | ||
| 36 | 74 | ps2 = session.prepare("insert into product (sku, description) values (:s, :d)"); |
| 37 | 75 | ``` |
| 38 | 76 | |
| 39 | -To turn the statement into its executable form, you need to *bind* it | |
| 40 | -and provide values for the parameters. As shown previously, there is a | |
| 41 | -shorthand form to do it all in one call: | |
| 77 | +To turn the statement into its executable form, you need to *bind* it to create a [BoundStatement]. As shown previously, | |
| 78 | +there is a shorthand to provide the parameters in the same call: | |
| 42 | 79 | |
| 43 | 80 | ```java |
| 44 | 81 | BoundStatement bound = ps1.bind("324378", "LCD screen"); |
| @@ -74,7 +111,7 @@ | ||
| 74 | 111 | |
| 75 | 112 | For native protocol V3 or below, all variables must be bound. With native |
| 76 | 113 | protocol V4 or above, variables can be left unset, in which case they |
| 77 | -will be ignored server side (no tombstones will be generated). If you're | |
| 114 | +will be ignored server side (no tombstones will be generated). If you're | |
| 78 | 115 | reusing a bound statement you can use the `unset` method to unset variables |
| 79 | 116 | that were previously set: |
| 80 | 117 | |
| @@ -95,21 +132,19 @@ | ||
| 95 | 132 | this has a small performance overhead since values are stored in their |
| 96 | 133 | serialized form. |
| 97 | 134 | |
| 98 | -### How the driver handles prepared statements | |
| 135 | +`BoundStatement` is **not thread-safe**. You can reuse an instance multiple times with different parameters, but only | |
| 136 | +from a single thread, and only if you use the synchronous API ([Session#execute][execute] is fine, | |
| 137 | +[Session#executeAsync][executeAsync] is not). | |
| 138 | +Also, make sure you don't accidentally reuse parameters from previous executions. | |
| 99 | 139 | |
| 100 | -When the driver prepares a statement, it sends the query string to | |
| 101 | -Cassandra, which caches the statement and returns an identifier. Later, | |
| 102 | -when the driver needs to execute the statement, it just sends the | |
| 103 | -identifier and parameter values. Note that the identifier is | |
| 104 | -deterministic, so it will always be the same for all nodes (it's a | |
| 105 | -actually a hash of the query string). | |
| 106 | - | |
| 107 | -Prepared statements are not replicated across the cluster. It is the | |
| 140 | +### Preparing on multiple nodes | |
| 141 | + | |
| 142 | +Cassandra does not replicate prepared statements across the cluster. It is the | |
| 108 | 143 | driver's responsibility to ensure that each node's cache is up to |
| 109 | 144 | date. It uses a number of strategies to achieve this: |
| 110 | 145 | |
| 111 | 146 | 1. When a statement is initially prepared, it is first sent to a single |
| 112 | - node in the cluster (this prevents from hitting all nodes in case | |
| 147 | + node in the cluster (this avoids hitting all nodes in case | |
| 113 | 148 | the query string is wrong). Once that node replies successfully, the |
| 114 | 149 | driver re-prepares on all remaining nodes: |
| 115 | 150 | |
| @@ -135,6 +170,9 @@ | ||
| 135 | 170 | |<-----------------------| | | | |
| 136 | 171 | ``` |
| 137 | 172 | |
| 173 | + The prepared statement identifier is deterministic (it's a hash of the query string), so it is the same | |
| 174 | + for all nodes. | |
| 175 | + | |
| 138 | 176 | 2. if a node crashes, it loses all of its prepared statements. So the |
| 139 | 177 | driver keeps a client-side cache; anytime a node is marked back up, |
| 140 | 178 | the driver re-prepares all statements on it; |
| @@ -184,5 +222,9 @@ | ||
| 184 | 222 | specific situations; read each method's Javadoc for detailed |
| 185 | 223 | explanations. |
| 186 | 224 | |
| 225 | +[PreparedStatement]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/PreparedStatement.html | |
| 226 | +[BoundStatement]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/BoundStatement.html | |
| 187 | 227 | [setPrepareOnAllHosts]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/QueryOptions.html#setPrepareOnAllHosts-boolean- |
| 188 | -[setReprepareOnUp]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/QueryOptions.html#setReprepareOnUp-boolean- | |
| 228 | +[setReprepareOnUp]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/QueryOptions.html#setReprepareOnUp-boolean- | |
| 229 | +[execute]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/Session.html#execute-com.datastax.driver.core.Statement- | |
| 230 | +[executeAsync]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/Session.html#executeAsync-com.datastax.driver.core.Statement- |
modified manual/statements/simple/README.md +127 −1
| @@ -1,5 +1,131 @@ | ||
| 1 | 1 | ## Simple statements |
| 2 | 2 | |
| 3 | -*Coming soon... In the meantime, see the javadoc for [SimpleStatement].* | |
| 3 | +Use [SimpleStatement] for queries that will be executed only once (or a few times) in your application: | |
| 4 | + | |
| 5 | +```java | |
| 6 | +SimpleStatement statement = new SimpleStatement( | |
| 7 | + "SELECT value FROM application_params WHERE name = 'greeting_message'"); | |
| 8 | +session.execute(statement); | |
| 9 | +``` | |
| 10 | + | |
| 11 | +When you don't need to customize anything on the `SimpleStatement` object, there is a convenient shortcut: | |
| 12 | + | |
| 13 | +```java | |
| 14 | +session.execute("SELECT value FROM application_params WHERE name = 'greeting_message'"); | |
| 15 | +``` | |
| 16 | + | |
| 17 | +Each time you execute a simple statement, Cassandra will parse the query string again; nothing is cached (neither on the | |
| 18 | +client nor on the server): | |
| 19 | + | |
| 20 | +```ditaa | |
| 21 | +client driver Cassandra | |
| 22 | +--+----------------------------------+---------------------+------ | |
| 23 | + | | | | |
| 24 | + | session.execute(SimpleStatement) | | | |
| 25 | + |--------------------------------->| | | |
| 26 | + | | QUERY(query_string) | | |
| 27 | + | |-------------------->| | |
| 28 | + | | | | |
| 29 | + | | | | |
| 30 | + | | | - parse query string | |
| 31 | + | | | - execute query | |
| 32 | + | | | | |
| 33 | + | | ROWS | | |
| 34 | + | |<--------------------| | |
| 35 | + | | | | |
| 36 | + |<---------------------------------| | | |
| 37 | +``` | |
| 38 | + | |
| 39 | +If you execute the same query often (or a similar query with different column values), consider a | |
| 40 | +[prepared statement](../prepared/) instead. | |
| 41 | + | |
| 42 | + | |
| 43 | +### Using values | |
| 44 | + | |
| 45 | +Instead of sending a raw query string, you can use bind markers and provide values separately: | |
| 46 | + | |
| 47 | +* by position: | |
| 48 | + | |
| 49 | + ```java | |
| 50 | + String paramName = ... | |
| 51 | + session.execute( | |
| 52 | + "SELECT value FROM application_params WHERE name = ?", | |
| 53 | + paramName); | |
| 54 | + ``` | |
| 55 | +* by name: | |
| 56 | + | |
| 57 | + ```java | |
| 58 | + // Just a convenience to build a java.util.Map with a one-liner | |
| 59 | + import com.google.common.collect.ImmutableMap; | |
| 60 | + | |
| 61 | + String paramName = ... | |
| 62 | + session.execute( | |
| 63 | + "SELECT value FROM application_params WHERE name = :n", | |
| 64 | + ImmutableMap.<String, Object>of("n", paramName)); | |
| 65 | + ``` | |
| 66 | + | |
| 67 | +This syntax has a few advantages: | |
| 68 | + | |
| 69 | +* if the values already come from some other part of your code, it looks cleaner than doing the concatenation yourself; | |
| 70 | +* you don't need to translate the values to their string representation. The driver will sent them alongside the query, | |
| 71 | + in their serialized binary form. | |
| 72 | + | |
| 73 | +The number of values must match the query string, and their types must match the database schema. Note that the driver | |
| 74 | +does not parse query strings, so it cannot perform those checks on the client side; if you make a mistake, the query | |
| 75 | +will be sent anyway, and the error will be caught by Cassandra (`InvalidQueryException` is a server-side error): | |
| 76 | + | |
| 77 | +```java | |
| 78 | +session.execute( | |
| 79 | + "SELECT value FROM application_params WHERE name = ?", | |
| 80 | + "foo", "bar"); | |
| 81 | +// Exception in thread "main" com.datastax.driver.core.exceptions.InvalidQueryException: | |
| 82 | +// Invalid amount of bind variables | |
| 83 | +``` | |
| 84 | + | |
| 85 | +### Value type inference | |
| 86 | + | |
| 87 | +Another consequence of not parsing query strings is that the driver has to make a guess on how to serialize values, | |
| 88 | +based on their Java type (see the [default type mappings](../../#cql-to-java-type-mapping)). This can be tricky, in | |
| 89 | +particular for numeric types: | |
| 90 | + | |
| 91 | +```java | |
| 92 | +// schema: create table bigints(b bigint primary key) | |
| 93 | +session.execute( | |
| 94 | + "INSERT INTO bigints (b) VALUES (?)", | |
| 95 | + 1); | |
| 96 | +// Exception in thread "main" com.datastax.driver.core.exceptions.InvalidQueryException: | |
| 97 | +// Expected 8 or 0 byte long (4) | |
| 98 | +``` | |
| 99 | + | |
| 100 | +The problem here is that the literal `1` has the Java type `int`. So the driver serializes it as a CQL `int` (4 bytes), | |
| 101 | +but the server expects a CQL `bigint` (8 bytes). The fix is to specify the correct Java type: | |
| 102 | + | |
| 103 | +```java | |
| 104 | +session.execute( | |
| 105 | + "INSERT INTO bigints (b) VALUES (?)", | |
| 106 | + 1L); | |
| 107 | +``` | |
| 108 | + | |
| 109 | +In the same vein, strings are always serialized to `varchar`, so you could have a problem if you target an `ascii` | |
| 110 | +column: | |
| 111 | + | |
| 112 | +```java | |
| 113 | +// schema: create table ascii_quotes(id int primary key, t ascii) | |
| 114 | +session.execute( | |
| 115 | + "INSERT INTO ascii_quotes (id, t) VALUES (?, ?)", | |
| 116 | + 1, "Touché sir, touché..."); | |
| 117 | +// Exception in thread "main" com.datastax.driver.core.exceptions.InvalidQueryException: | |
| 118 | +// Invalid byte for ascii: -61 | |
| 119 | +``` | |
| 120 | + | |
| 121 | +In that situation, there is no way to hint at the correct type. Your only option is to serialize the value manually: | |
| 122 | + | |
| 123 | +```java | |
| 124 | +ProtocolVersion protocolVersion = cluster.getConfiguration().getProtocolOptions().getProtocolVersionEnum(); | |
| 125 | +ByteBuffer bytes = DataType.ascii().serialize("Touché sir, touché...", protocolVersion); | |
| 126 | +session.execute( | |
| 127 | + "INSERT INTO ascii_quotes (id, t) VALUES (?, ?)", | |
| 128 | + 1, bytes); | |
| 129 | +``` | |
| 4 | 130 | |
| 5 | 131 | [SimpleStatement]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/SimpleStatement.html |