Elffuss BraidHub

kikocis/java-driver public

7ffdb0fa8a5f · 8.2 KiBRenderedRawPermalink
1## Prepared statements
2
3When Cassandra executes a query, the first thing it does is parse the
4query string to an internal representation. If the same query is used
5often, you can use a prepared statement, which allows Cassandra to cache
6that representation, and save time and resources for subsequent
7executions. Prepared statements are typically parameterized, using
8different values for each execution:
9
10```java
11PreparedStatement prepared = session.prepare(
12 "insert into product (sku, description) values (?, ?)");
13
14BoundStatement bound;
15
16bound = prepared.bind("234827", "Mouse");
17session.execute(bound);
18
19bound = prepared.bind("987274", "Keyboard");
20session.execute(bound);
21```
22
23Statements should be be prepared only once. If you call `prepare`
24multiple times with the same query string, the driver will log a
25warning. So your application should cache the `PreparedStatement` object
26once it's been created (this can be as simple as storing it as a field
27in a DAO).
28
29### Parameters and binding
30
31Parameters can be either anonymous or named (named parameters are only
32available with [native protocol](../../native_protocol) v2 or above):
33
34```java
35ps1 = session.prepare("insert into product (sku, description) values (?, ?)");
36ps2 = session.prepare("insert into product (sku, description) values (:s, :d)");
37```
38
39To turn the statement into its executable form, you need to *bind* it
40and provide values for the parameters. As shown previously, there is a
41shorthand form to do it all in one call:
42
43```java
44BoundStatement bound = ps1.bind("324378", "LCD screen");
45```
46
47You can also bind first, then use setters, which is slightly more
48explicit:
49
50```java
51// Positional setters:
52BoundStatement bound = ps1.bind()
53 .setString(0, "324378")
54 .setString(1, "LCD screen");
55
56// Named setters:
57BoundStatement bound = ps2.bind()
58 .setString("s", "324378")
59 .setString("d", "LCD screen");
60```
61
62You can use named setters even if the query uses anonymous parameters;
63Cassandra will name the parameters after the column they apply to:
64
65```java
66BoundStatement bound = ps1.bind()
67 .setString("sku", "324378")
68 .setString("description", "LCD screen");
69```
70
71This can be ambiguous if the query uses the same column multiple times,
72for example: `select * from sales where sku = ? and date > ? and date <
73?`. In these situations, use positional setters or named parameters.
74
75For native protocol V3 or below, all variables must be bound. With native
76protocol V4 or above, variables can be left unset, in which case they
77will be ignored server side (no tombstones will be generated). If you're
78reusing a bound statement you can use the `unset` method to unset variables
79that were previously set:
80
81```java
82BoundStatement bound = ps1.bind()
83 .setString("sku", "324378")
84 .setString("description", "LCD screen")
85
86// Using the unset method to unset previously set value.
87// Positional setter:
88bound.unset("description");
89
90// Named setter:
91bound.unset(1);
92```
93
94A bound statement also has getters to retrieve the values. Note that
95this has a small performance overhead since values are stored in their
96serialized form.
97
98### How the driver handles prepared statements
99
100When the driver prepares a statement, it sends the query string to
101Cassandra, which caches the statement and returns an identifier. Later,
102when the driver needs to execute the statement, it just sends the
103identifier and parameter values. Note that the identifier is
104deterministic, so it will always be the same for all nodes (it's a
105actually a hash of the query string).
106
107Prepared statements are not replicated across the cluster. It is the
108driver's responsibility to ensure that each node's cache is up to
109date. It uses a number of strategies to achieve this:
110
1111. 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
113 the query string is wrong). Once that node replies successfully, the
114 driver re-prepares on all remaining nodes:
115
116 ```ditaa
117 client driver node1 node2 node3
118 --+------------------------+----------------+--------------+------+---
119 | | | | |
120 | session.prepare(query) | | | |
121 |----------------------->| | | |
122 | | PREPARE(query) | | |
123 | |--------------->| | |
124 | | | | |
125 | | PREPARED(id) | | |
126 | |<---------------| | |
127 | | | | |
128 | | | | |
129 | | PREPARE(query) | |
130 | |------------------------------>| |
131 | | | | |
132 | | PREPARE(query) | |
133 | |------------------------------------->|
134 | | | | |
135 |<-----------------------| | | |
136 ```
137
1382. if a node crashes, it loses all of its prepared statements. So the
139 driver keeps a client-side cache; anytime a node is marked back up,
140 the driver re-prepares all statements on it;
141
1423. finally, if the driver tries to execute a statement and finds out
143 that the coordinator doesn't know about it, it will re-prepare the
144 statement on the fly (this is transparent for the client, but will cost
145 two extra roundtrips):
146
147 ```ditaa
148 client driver node1
149 --+-------------------------------+------------------------------+--
150 | | |
151 |session.execute(boundStatement)| |
152 +------------------------------>| |
153 | | EXECUTE(id, values) |
154 | |----------------------------->|
155 | | |
156 | | UNPREPARED |
157 | |<-----------------------------|
158 | | |
159 | | |
160 | | PREPARE(query) |
161 | |----------------------------->|
162 | | |
163 | | PREPARED(id) |
164 | |<-----------------------------|
165 | | |
166 | | |
167 | | EXECUTE(id, values) |
168 | |----------------------------->|
169 | | |
170 | | ROWS |
171 | |<-----------------------------|
172 | | |
173 |<------------------------------| |
174 ```
175
176You can customize these strategies through `QueryOptions`:
177
178* [setPrepareOnAllHosts] controls whether statements are initially
179 re-prepared on other hosts (step 1 above);
180* [setReprepareOnUp] controls whether statements are re-prepared on a
181 node that comes back up (step 2 above).
182
183Changing the driver's defaults should be done with care and only in
184specific situations; read each method's Javadoc for detailed
185explanations.
186
187[setPrepareOnAllHosts]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/QueryOptions.html#setPrepareOnAllHosts(boolean)
188[setReprepareOnUp]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/QueryOptions.html#setReprepareOnUp(boolean)