| 1 | ## Prepared statements |
| 2 | |
| 3 | Use [PreparedStatement] for queries that are executed multiple times in your application: |
| 4 | |
| 5 | ```java |
| 6 | PreparedStatement prepared = session.prepare( |
| 7 | "insert into product (sku, description) values (?, ?)"); |
| 8 | |
| 9 | BoundStatement bound = prepared.bind("234827", "Mouse"); |
| 10 | session.execute(bound); |
| 11 | |
| 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 | |<--------------------------------| | |
| 58 | ``` |
| 59 | |
| 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. |
| 66 | |
| 67 | ### Parameters and binding |
| 68 | |
| 69 | Parameters can be either anonymous or named (named parameters are only |
| 70 | available with [native protocol](../../native_protocol) v2 or above): |
| 71 | |
| 72 | ```java |
| 73 | ps1 = session.prepare("insert into product (sku, description) values (?, ?)"); |
| 74 | ps2 = session.prepare("insert into product (sku, description) values (:s, :d)"); |
| 75 | ``` |
| 76 | |
| 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: |
| 79 | |
| 80 | ```java |
| 81 | BoundStatement bound = ps1.bind("324378", "LCD screen"); |
| 82 | ``` |
| 83 | |
| 84 | You can also bind first, then use setters, which is slightly more |
| 85 | explicit: |
| 86 | |
| 87 | ```java |
| 88 | // Positional setters: |
| 89 | BoundStatement bound = ps1.bind() |
| 90 | .setString(0, "324378") |
| 91 | .setString(1, "LCD screen"); |
| 92 | |
| 93 | // Named setters: |
| 94 | BoundStatement bound = ps2.bind() |
| 95 | .setString("s", "324378") |
| 96 | .setString("d", "LCD screen"); |
| 97 | ``` |
| 98 | |
| 99 | You can use named setters even if the query uses anonymous parameters; |
| 100 | Cassandra will name the parameters after the column they apply to: |
| 101 | |
| 102 | ```java |
| 103 | BoundStatement bound = ps1.bind() |
| 104 | .setString("sku", "324378") |
| 105 | .setString("description", "LCD screen"); |
| 106 | ``` |
| 107 | |
| 108 | This can be ambiguous if the query uses the same column multiple times, |
| 109 | for example: `select * from sales where sku = ? and date > ? and date < |
| 110 | ?`. In these situations, use positional setters or named parameters. |
| 111 | |
| 112 | For native protocol V3 or below, all variables must be bound. With native |
| 113 | protocol V4 or above, variables can be left unset, in which case they |
| 114 | will be ignored server side (no tombstones will be generated). If you're |
| 115 | reusing a bound statement you can use the `unset` method to unset variables |
| 116 | that were previously set: |
| 117 | |
| 118 | ```java |
| 119 | BoundStatement 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: |
| 125 | bound.unset("description"); |
| 126 | |
| 127 | // Named setter: |
| 128 | bound.unset(1); |
| 129 | ``` |
| 130 | |
| 131 | A bound statement also has getters to retrieve the values. Note that |
| 132 | this has a small performance overhead since values are stored in their |
| 133 | serialized form. |
| 134 | |
| 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 synchronous calls: |
| 137 | |
| 138 | ```java |
| 139 | BoundStatement bound = ps1.bind(); |
| 140 | |
| 141 | // This is safe: |
| 142 | bound.setString("sku", "324378"); |
| 143 | session.execute(bound); |
| 144 | |
| 145 | bound.setString("sku", "324379"); |
| 146 | session.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: |
| 150 | bound.setString("sku", "324380"); |
| 151 | session.executeAsync(bound); |
| 152 | |
| 153 | bound.setString("sku", "324381"); |
| 154 | session.executeAsync(bound); |
| 155 | ``` |
| 156 | |
| 157 | Also, make sure you don't accidentally reuse parameters from previous executions. |
| 158 | |
| 159 | ### Preparing on multiple nodes |
| 160 | |
| 161 | Cassandra does not replicate prepared statements across the cluster. It is the |
| 162 | driver's responsibility to ensure that each node's cache is up to |
| 163 | date. It uses a number of strategies to achieve this: |
| 164 | |
| 165 | 1. 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 | |
| 195 | 2. 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 | |
| 199 | 3. 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 | |
| 233 | You 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 | |
| 240 | Changing the driver's defaults should be done with care and only in |
| 241 | specific situations; read each method's Javadoc for detailed |
| 242 | explanations. |
| 243 | |
| 244 | ### Avoid preparing 'SELECT *' queries |
| 245 | |
| 246 | Both the driver and Cassandra maintain a mapping of `PreparedStatement` queries to their |
| 247 | metadata. When a change is made to a table, such as a column being added or dropped, there |
| 248 | is currently no mechanism for Cassandra to invalidate the existing metadata. Because of this, |
| 249 | the driver is not able to properly react to these changes and will improperly read rows after |
| 250 | a schema change is made. |
| 251 | |
| 252 | Therefore it is currently recommended to not create prepared statements |
| 253 | for 'SELECT *' queries if you plan on making schema changes involving |
| 254 | adding or dropping columns. Alternatively you should list all columns of interest |
| 255 | in your statement, i.e.: `SELECT a, b, c FROM tbl`. |
| 256 | |
| 257 | This 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 |