Elffuss BraidHub

kikocis/java-driver public

3.1.x · 12.1 KiBRenderedRawPermalink
1## Prepared statements
2
3Use [PreparedStatement] for queries that are executed multiple times in your application:
4
5```java
6PreparedStatement prepared = session.prepare(
7 "insert into product (sku, description) values (?, ?)");
8
9BoundStatement bound = prepared.bind("234827", "Mouse");
10session.execute(bound);
11
12session.execute(prepared.bind("987274", "Keyboard"));
13```
14
15When 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
19client 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
38When you bind and execute a prepared statement, the driver will only send the identifier, which allows Cassandra to
39skip the parsing phase:
40
41```ditaa
42client 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 |<--------------------------------| |
58```
59
60
61You 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
64If you execute a query only once, a prepared statement is inefficient because it requires two roundtrips. Consider a
65[simple statement](../simple/) instead.
66
67### Parameters and binding
68
69Parameters can be either anonymous or named (named parameters are only
70available with [native protocol](../../native_protocol) v2 or above):
71
72```java
73ps1 = session.prepare("insert into product (sku, description) values (?, ?)");
74ps2 = session.prepare("insert into product (sku, description) values (:s, :d)");
75```
76
77To turn the statement into its executable form, you need to *bind* it to create a [BoundStatement]. As shown previously,
78there is a shorthand to provide the parameters in the same call:
79
80```java
81BoundStatement bound = ps1.bind("324378", "LCD screen");
82```
83
84You can also bind first, then use setters, which is slightly more
85explicit:
86
87```java
88// Positional setters:
89BoundStatement bound = ps1.bind()
90 .setString(0, "324378")
91 .setString(1, "LCD screen");
92
93// Named setters:
94BoundStatement bound = ps2.bind()
95 .setString("s", "324378")
96 .setString("d", "LCD screen");
97```
98
99You can use named setters even if the query uses anonymous parameters;
100Cassandra will name the parameters after the column they apply to:
101
102```java
103BoundStatement bound = ps1.bind()
104 .setString("sku", "324378")
105 .setString("description", "LCD screen");
106```
107
108This can be ambiguous if the query uses the same column multiple times,
109for example: `select * from sales where sku = ? and date > ? and date <
110?`. In these situations, use positional setters or named parameters.
111
112For native protocol V3 or below, all variables must be bound. With native
113protocol V4 or above, variables can be left unset, in which case they
114will be ignored server side (no tombstones will be generated). If you're
115reusing a bound statement you can use the `unset` method to unset variables
116that were previously set:
117
118```java
119BoundStatement bound = ps1.bind()
120 .setString("sku", "324378")
121 .setString("description", "LCD screen");
122
123// Using the unset method to unset previously set value.
124// Positional setter:
125bound.unset("description");
126
127// Named setter:
128bound.unset(1);
129```
130
131A bound statement also has getters to retrieve the values. Note that
132this has a small performance overhead since values are stored in their
133serialized form.
134
135`BoundStatement` is **not thread-safe**. You can reuse an instance multiple times with different parameters, but only
136from a single thread and only if you use synchronous calls:
137
138```java
139BoundStatement bound = ps1.bind();
140
141// This is safe:
142bound.setString("sku", "324378");
143session.execute(bound);
144
145bound.setString("sku", "324379");
146session.execute(bound);
147
148// This is NOT SAFE. executeAsync runs concurrently with your code, so the first execution might actually read the
149// values after the second setString call, and you would insert 324381 twice:
150bound.setString("sku", "324380");
151session.executeAsync(bound);
152
153bound.setString("sku", "324381");
154session.executeAsync(bound);
155```
156
157Also, make sure you don't accidentally reuse parameters from previous executions.
158
159### Preparing on multiple nodes
160
161Cassandra does not replicate prepared statements across the cluster. It is the
162driver's responsibility to ensure that each node's cache is up to
163date. It uses a number of strategies to achieve this:
164
1651. When a statement is initially prepared, it is first sent to a single
166 node in the cluster (this avoids hitting all nodes in case
167 the query string is wrong). Once that node replies successfully, the
168 driver re-prepares on all remaining nodes:
169
170 ```ditaa
171 client driver node1 node2 node3
172 --+------------------------+----------------+--------------+------+---
173 | | | | |
174 | session.prepare(query) | | | |
175 |----------------------->| | | |
176 | | PREPARE(query) | | |
177 | |--------------->| | |
178 | | | | |
179 | | PREPARED(id) | | |
180 | |<---------------| | |
181 | | | | |
182 | | | | |
183 | | PREPARE(query) | |
184 | |------------------------------>| |
185 | | | | |
186 | | PREPARE(query) | |
187 | |------------------------------------->|
188 | | | | |
189 |<-----------------------| | | |
190 ```
191
192 The prepared statement identifier is deterministic (it's a hash of the query string), so it is the same
193 for all nodes.
194
1952. if a node crashes, it loses all of its prepared statements. So the
196 driver keeps a client-side cache; anytime a node is marked back up,
197 the driver re-prepares all statements on it;
198
1993. finally, if the driver tries to execute a statement and finds out
200 that the coordinator doesn't know about it, it will re-prepare the
201 statement on the fly (this is transparent for the client, but will cost
202 two extra roundtrips):
203
204 ```ditaa
205 client driver node1
206 --+-------------------------------+------------------------------+--
207 | | |
208 |session.execute(boundStatement)| |
209 +------------------------------>| |
210 | | EXECUTE(id, values) |
211 | |----------------------------->|
212 | | |
213 | | UNPREPARED |
214 | |<-----------------------------|
215 | | |
216 | | |
217 | | PREPARE(query) |
218 | |----------------------------->|
219 | | |
220 | | PREPARED(id) |
221 | |<-----------------------------|
222 | | |
223 | | |
224 | | EXECUTE(id, values) |
225 | |----------------------------->|
226 | | |
227 | | ROWS |
228 | |<-----------------------------|
229 | | |
230 |<------------------------------| |
231 ```
232
233You can customize these strategies through `QueryOptions`:
234
235* [setPrepareOnAllHosts] controls whether statements are initially
236 re-prepared on other hosts (step 1 above);
237* [setReprepareOnUp] controls whether statements are re-prepared on a
238 node that comes back up (step 2 above).
239
240Changing the driver's defaults should be done with care and only in
241specific situations; read each method's Javadoc for detailed
242explanations.
243
244### Avoid preparing 'SELECT *' queries
245
246Both the driver and Cassandra maintain a mapping of `PreparedStatement` queries to their
247metadata. When a change is made to a table, such as a column being added or dropped, there
248is currently no mechanism for Cassandra to invalidate the existing metadata. Because of this,
249the driver is not able to properly react to these changes and will improperly read rows after
250a schema change is made.
251
252Therefore it is currently recommended to not create prepared statements
253for 'SELECT *' queries if you plan on making schema changes involving
254adding or dropping columns. Alternatively you should list all columns of interest
255in your statement, i.e.: `SELECT a, b, c FROM tbl`.
256
257This will be addressed in a future release of both Cassandra and the driver. Follow
258[CASSANDRA-10786] and [JAVA-1196] for more information.
259
260[PreparedStatement]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/PreparedStatement.html
261[BoundStatement]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/BoundStatement.html
262[setPrepareOnAllHosts]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/QueryOptions.html#setPrepareOnAllHosts-boolean-
263[setReprepareOnUp]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/QueryOptions.html#setReprepareOnUp-boolean-
264[execute]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/Session.html#execute-com.datastax.driver.core.Statement-
265[executeAsync]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/Session.html#executeAsync-com.datastax.driver.core.Statement-
266[CASSANDRA-10786]: https://issues.apache.org/jira/browse/CASSANDRA-10786
267[JAVA-1196]: https://datastax-oss.atlassian.net/browse/JAVA-1196