Elffuss BraidHub

kikocis/java-driver public

JAVA-1037: Allow named parameters in simple statements.
Changeset1a989219f0594970668b1e1216af7c1a2141bd53befd132d842ed3b766719623
Authorolim7t <omichallat+github@gmail.com> · 2016-01-19 18:15 +01:00
Committerolim7t <omichallat+github@gmail.com> · 2016-01-25 15:26 +01:00
Parents376b3e24535f

Browse the files at this changeset

12 files changed

modified changelog/README.md +1 −0
@@ -4,6 +4,7 @@
44
55 - [bug] JAVA-1034: fix metadata parser for collections of custom types.
66 - [improvement] JAVA-1035: Expose host broadcast_address and listen_address if available.
7+- [new feature] JAVA-1037: Allow named parameters in simple statements.
78
89 Merged from 2.1 branch:
910
modified driver-core/src/main/java/com/datastax/driver/core/AbstractSession.java +16 −0
@@ -47,6 +47,14 @@
4747 return execute(new SimpleStatement(query, values));
4848 }
4949
50+ /**
51+ * {@inheritDoc}
52+ */
53+ @Override
54+ public ResultSet execute(String query, Map<String, Object> values) {
55+ return execute(new SimpleStatement(query, values));
56+ }
57+
5058 /**
5159 * {@inheritDoc}
5260 */
@@ -63,6 +71,14 @@
6371 return executeAsync(new SimpleStatement(query));
6472 }
6573
74+ /**
75+ * {@inheritDoc}
76+ */
77+ @Override
78+ public ResultSetFuture executeAsync(String query, Map<String, Object> values) {
79+ return executeAsync(new SimpleStatement(query, values));
80+ }
81+
6682 /**
6783 * {@inheritDoc}
6884 */
modified driver-core/src/main/java/com/datastax/driver/core/BatchStatement.java +11 −3
@@ -113,6 +113,9 @@
113113 * is also allowed for convenience and is equivalent to adding all the {@code Statement}
114114 * contained in that other {@code BatchStatement}.
115115 * <p/>
116+ * Due to a protocol-level limitation, adding a {@code RegularStatement} with named values
117+ * is currently not supported; an {@code IllegalArgument} will be thrown.
118+ * <p/>
116119 * When adding a {@code BoundStatement}, all of its values must be set, otherwise an
117120 * {@code IllegalStateException} will be thrown when submitting the batch statement.
118121 * See {@link BoundStatement} for more details, in particular how to handle {@code null}
@@ -125,11 +128,16 @@
125128 *
126129 * @param statement the new statement to add.
127130 * @return this batch statement.
128- * @throws IllegalStateException if adding the new statement means that this
129- * {@code BatchStatement} has more than 65536 statements (since this is the maximum number
130- * of statements for a BatchStatement allowed by the underlying protocol).
131+ * @throws IllegalStateException if adding the new statement means that this
132+ * {@code BatchStatement} has more than 65536 statements (since this is the maximum number
133+ * of statements for a BatchStatement allowed by the underlying protocol).
134+ * @throws IllegalArgumentException if adding a regular statement that uses named values.
131135 */
132136 public BatchStatement add(Statement statement) {
137+ if ((statement instanceof RegularStatement) && ((RegularStatement) statement).usesNamedValues()) {
138+ throw new IllegalArgumentException("Batch statement cannot contain regular statements with named values ("
139+ + ((RegularStatement) statement).getQueryString() + ")");
140+ }
133141
134142 // We handle BatchStatement here (rather than in getIdAndValues) as it make it slightly
135143 // easier to avoid endless loops if the user mistakenly passes a batch that depends on this
modified driver-core/src/main/java/com/datastax/driver/core/CBUtil.java +17 −0
@@ -351,6 +351,23 @@
351351 return size;
352352 }
353353
354+ public static void writeNamedValueList(Map<String, ByteBuffer> namedValues, ByteBuf cb) {
355+ cb.writeShort(namedValues.size());
356+ for (Map.Entry<String, ByteBuffer> entry : namedValues.entrySet()) {
357+ CBUtil.writeString(entry.getKey(), cb);
358+ CBUtil.writeValue(entry.getValue(), cb);
359+ }
360+ }
361+
362+ public static int sizeOfNamedValueList(Map<String, ByteBuffer> namedValues) {
363+ int size = 2;
364+ for (Map.Entry<String, ByteBuffer> entry : namedValues.entrySet()) {
365+ size += CBUtil.sizeOfString(entry.getKey());
366+ size += CBUtil.sizeOfValue(entry.getValue());
367+ }
368+ return size;
369+ }
370+
354371 public static InetSocketAddress readInet(ByteBuf cb) {
355372 int addrSize = cb.readByte();
356373 byte[] address = new byte[addrSize];
modified driver-core/src/main/java/com/datastax/driver/core/RegularStatement.java +41 −4
@@ -21,6 +21,7 @@
2121 import com.datastax.driver.core.schemabuilder.SchemaStatement;
2222
2323 import java.nio.ByteBuffer;
24+import java.util.Map;
2425
2526 /**
2627 * A regular (non-prepared and non batched) CQL statement.
@@ -75,12 +76,15 @@
7576 }
7677
7778 /**
78- * The values to use for this statement.
79+ * The positional values to use for this statement.
7980 * <p/>
80- * Note: Values for a RegularStatement (i.e. if this method does not return
81+ * A statement can use either positional or named values, but not both. So if this method returns a non-null result,
82+ * {@link #getNamedValues(ProtocolVersion, CodecRegistry)} will return {@code null}.
83+ * <p/>
84+ * Values for a RegularStatement (i.e. if either method does not return
8185 * {@code null}) are not supported with the native protocol version 1: you
8286 * will get an {@link UnsupportedProtocolVersionException} when submitting
83- * one if version 1 of the protocol is in use (i.e. if you've force version
87+ * one if version 1 of the protocol is in use (i.e. if you've forced version
8488 * 1 through {@link Cluster.Builder#withProtocolVersion} or you use
8589 * Cassandra 1.2).
8690 *
@@ -94,6 +98,30 @@
9498 */
9599 public abstract ByteBuffer[] getValues(ProtocolVersion protocolVersion, CodecRegistry codecRegistry);
96100
101+ /**
102+ * The named values to use for this statement.
103+ * <p/>
104+ * A statement can use either positional or named values, but not both. So if this method returns a non-null result,
105+ * {@link #getValues(ProtocolVersion, CodecRegistry)} will return {@code null}.
106+ * <p/>
107+ * Values for a RegularStatement (i.e. if either method does not return
108+ * {@code null}) are not supported with the native protocol version 1: you
109+ * will get an {@link UnsupportedProtocolVersionException} when submitting
110+ * one if version 1 of the protocol is in use (i.e. if you've forced version
111+ * 1 through {@link Cluster.Builder#withProtocolVersion} or you use
112+ * Cassandra 1.2).
113+ *
114+ * @param protocolVersion the protocol version that will be used to serialize
115+ * the values.
116+ * @param codecRegistry the codec registry that will be used to serialize the
117+ * values.
118+ * @return the named values.
119+ * @throws InvalidTypeException if one of the values is not of a type
120+ * that can be serialized to a CQL3 type
121+ * @see SimpleStatement#SimpleStatement(String, Map)
122+ */
123+ public abstract Map<String, ByteBuffer> getNamedValues(ProtocolVersion protocolVersion, CodecRegistry codecRegistry);
124+
97125 /**
98126 * Whether or not this statement has values, that is if {@code getValues}
99127 * will return {@code null} or not.
@@ -104,12 +132,21 @@
104132 * Note that it might be possible to use the no-arg
105133 * {@link #hasValues()} depending on the type of
106134 * statement this is called on.
107- * @return {@code false} if {@link #getValues} returns {@code null}, {@code true}
135+ * @return {@code false} if both {@link #getValues(ProtocolVersion, CodecRegistry)}
136+ * and {@link #getNamedValues(ProtocolVersion, CodecRegistry)} return {@code null}, {@code true}
108137 * otherwise.
109138 * @see #hasValues()
110139 */
111140 public abstract boolean hasValues(CodecRegistry codecRegistry);
112141
142+ /**
143+ * Whether this statement uses named values.
144+ *
145+ * @return {@code false} if {@link #getNamedValues(ProtocolVersion, CodecRegistry)} returns {@code null},
146+ * {@code true} otherwise.
147+ */
148+ public abstract boolean usesNamedValues();
149+
113150 /**
114151 * Whether or not this statement has values, that is if {@code getValues}
115152 * will return {@code null} or not.
modified driver-core/src/main/java/com/datastax/driver/core/Requests.java +37 −12
@@ -15,6 +15,7 @@
1515 */
1616 package com.datastax.driver.core;
1717
18+import com.google.common.base.Preconditions;
1819 import com.google.common.collect.ImmutableMap;
1920 import io.netty.buffer.ByteBuf;
2021
@@ -232,6 +233,7 @@
232233
233234 static final QueryProtocolOptions DEFAULT = new QueryProtocolOptions(ConsistencyLevel.ONE,
234235 Collections.<ByteBuffer>emptyList(),
236+ Collections.<String, ByteBuffer>emptyMap(),
235237 false,
236238 -1,
237239 null,
@@ -240,7 +242,8 @@
240242
241243 private final EnumSet<QueryFlag> flags = EnumSet.noneOf(QueryFlag.class);
242244 final ConsistencyLevel consistency;
243- final List<ByteBuffer> values;
245+ final List<ByteBuffer> positionalValues;
246+ final Map<String, ByteBuffer> namedValues;
244247 final boolean skipMetadata;
245248 final int pageSize;
246249 final ByteBuffer pagingState;
@@ -248,15 +251,19 @@
248251 final long defaultTimestamp;
249252
250253 QueryProtocolOptions(ConsistencyLevel consistency,
251- List<ByteBuffer> values,
254+ List<ByteBuffer> positionalValues,
255+ Map<String, ByteBuffer> namedValues,
252256 boolean skipMetadata,
253257 int pageSize,
254258 ByteBuffer pagingState,
255259 ConsistencyLevel serialConsistency,
256260 long defaultTimestamp) {
257261
262+ Preconditions.checkArgument(positionalValues.isEmpty() || namedValues.isEmpty());
263+
258264 this.consistency = consistency;
259- this.values = values;
265+ this.positionalValues = positionalValues;
266+ this.namedValues = namedValues;
260267 this.skipMetadata = skipMetadata;
261268 this.pageSize = pageSize;
262269 this.pagingState = pagingState;
@@ -264,8 +271,12 @@
264271 this.defaultTimestamp = defaultTimestamp;
265272
266273 // Populate flags
267- if (!values.isEmpty())
274+ if (!positionalValues.isEmpty())
275+ flags.add(QueryFlag.VALUES);
276+ if (!namedValues.isEmpty()) {
268277 flags.add(QueryFlag.VALUES);
278+ flags.add(QueryFlag.VALUE_NAMES);
279+ }
269280 if (skipMetadata)
270281 flags.add(QueryFlag.SKIP_METADATA);
271282 if (pageSize >= 0)
@@ -279,14 +290,15 @@
279290 }
280291
281292 QueryProtocolOptions copy(ConsistencyLevel newConsistencyLevel) {
282- return new QueryProtocolOptions(newConsistencyLevel, values, skipMetadata, pageSize, pagingState, serialConsistency, defaultTimestamp);
293+ return new QueryProtocolOptions(newConsistencyLevel, positionalValues, namedValues, skipMetadata, pageSize, pagingState, serialConsistency, defaultTimestamp);
283294 }
284295
285296 void encode(ByteBuf dest, ProtocolVersion version) {
286297 switch (version) {
287298 case V1:
299+ // Values in protocol v1 are only for bound statements, and these are never named
288300 if (flags.contains(QueryFlag.VALUES))
289- CBUtil.writeValueList(values, dest);
301+ CBUtil.writeValueList(positionalValues, dest);
290302 CBUtil.writeConsistencyLevel(consistency, dest);
291303 break;
292304 case V2:
@@ -294,8 +306,14 @@
294306 case V4:
295307 CBUtil.writeConsistencyLevel(consistency, dest);
296308 dest.writeByte((byte) QueryFlag.serialize(flags));
297- if (flags.contains(QueryFlag.VALUES))
298- CBUtil.writeValueList(values, dest);
309+ if (flags.contains(QueryFlag.VALUES)) {
310+ if (flags.contains(QueryFlag.VALUE_NAMES)) {
311+ assert version.compareTo(ProtocolVersion.V3) >= 0;
312+ CBUtil.writeNamedValueList(namedValues, dest);
313+ } else {
314+ CBUtil.writeValueList(positionalValues, dest);
315+ }
316+ }
299317 if (flags.contains(QueryFlag.PAGE_SIZE))
300318 dest.writeInt(pageSize);
301319 if (flags.contains(QueryFlag.PAGING_STATE))
@@ -313,7 +331,7 @@
313331 int encodedSize(ProtocolVersion version) {
314332 switch (version) {
315333 case V1:
316- return CBUtil.sizeOfValueList(values)
334+ return CBUtil.sizeOfValueList(positionalValues)
317335 + CBUtil.sizeOfConsistencyLevel(consistency);
318336 case V2:
319337 case V3:
@@ -321,8 +339,14 @@
321339 int size = 0;
322340 size += CBUtil.sizeOfConsistencyLevel(consistency);
323341 size += 1; // flags
324- if (flags.contains(QueryFlag.VALUES))
325- size += CBUtil.sizeOfValueList(values);
342+ if (flags.contains(QueryFlag.VALUES)) {
343+ if (flags.contains(QueryFlag.VALUE_NAMES)) {
344+ assert version.compareTo(ProtocolVersion.V3) >= 0;
345+ size += CBUtil.sizeOfNamedValueList(namedValues);
346+ } else {
347+ size += CBUtil.sizeOfValueList(positionalValues);
348+ }
349+ }
326350 if (flags.contains(QueryFlag.PAGE_SIZE))
327351 size += 4;
328352 if (flags.contains(QueryFlag.PAGING_STATE))
@@ -339,7 +363,8 @@
339363
340364 @Override
341365 public String toString() {
342- return String.format("[cl=%s, vals=%s, skip=%b, psize=%d, state=%s, serialCl=%s]", consistency, values, skipMetadata, pageSize, pagingState, serialConsistency);
366+ return String.format("[cl=%s, positionalVals=%s, namedVals=%s, skip=%b, psize=%d, state=%s, serialCl=%s]",
367+ consistency, positionalValues, namedValues, skipMetadata, pageSize, pagingState, serialConsistency);
343368 }
344369 }
345370
modified driver-core/src/main/java/com/datastax/driver/core/Session.java +44 −5
@@ -20,6 +20,7 @@
2020
2121 import java.io.Closeable;
2222 import java.util.Collection;
23+import java.util.Map;
2324
2425 /**
2526 * A session holds connections to a Cassandra cluster, allowing it to be queried.
@@ -109,13 +110,13 @@
109110 ResultSet execute(String query);
110111
111112 /**
112- * Executes the provided query using the provided value.
113+ * Executes the provided query using the provided values.
113114 * <p/>
114115 * This is a convenience method for {@code execute(new SimpleStatement(query, values))}.
115116 *
116117 * @param query the CQL query to execute.
117118 * @param values values required for the execution of {@code query}. See
118- * {@link SimpleStatement#SimpleStatement(String, Object...)} for more detail.
119+ * {@link SimpleStatement#SimpleStatement(String, Object...)} for more details.
119120 * @return the result of the query. That result will never be null but can
120121 * be empty (and will be for any non SELECT query).
121122 * @throws NoHostAvailableException if no host in the cluster can be
@@ -126,11 +127,34 @@
126127 * @throws QueryValidationException if the query if invalid (syntax error,
127128 * unauthorized or any other validation problem).
128129 * @throws UnsupportedFeatureException if version 1 of the protocol
129- * is in use (i.e. if you've force version 1 through {@link Cluster.Builder#withProtocolVersion}
130+ * is in use (i.e. if you've forced version 1 through {@link Cluster.Builder#withProtocolVersion}
130131 * or you use Cassandra 1.2).
131132 */
132133 ResultSet execute(String query, Object... values);
133134
135+ /**
136+ * Executes the provided query using the provided named values.
137+ * <p/>
138+ * This is a convenience method for {@code execute(new SimpleStatement(query, values))}.
139+ *
140+ * @param query the CQL query to execute.
141+ * @param values values required for the execution of {@code query}. See
142+ * {@link SimpleStatement#SimpleStatement(String, Map)} for more details.
143+ * @return the result of the query. That result will never be null but can
144+ * be empty (and will be for any non SELECT query).
145+ * @throws NoHostAvailableException if no host in the cluster can be
146+ * contacted successfully to execute this query.
147+ * @throws QueryExecutionException if the query triggered an execution
148+ * exception, i.e. an exception thrown by Cassandra when it cannot execute
149+ * the query with the requested consistency level successfully.
150+ * @throws QueryValidationException if the query if invalid (syntax error,
151+ * unauthorized or any other validation problem).
152+ * @throws UnsupportedFeatureException if version 1 or 2 of the protocol
153+ * is in use (i.e. if you've forced it through {@link Cluster.Builder#withProtocolVersion}
154+ * or you use Cassandra 1.2 or 2.0).
155+ */
156+ ResultSet execute(String query, Map<String, Object> values);
157+
134158 /**
135159 * Executes the provided query.
136160 * <p/>
@@ -175,14 +199,29 @@
175199 *
176200 * @param query the CQL query to execute.
177201 * @param values values required for the execution of {@code query}. See
178- * {@link SimpleStatement#SimpleStatement(String, Object...)} for more detail.
202+ * {@link SimpleStatement#SimpleStatement(String, Object...)} for more details.
179203 * @return a future on the result of the query.
180204 * @throws UnsupportedFeatureException if version 1 of the protocol
181- * is in use (i.e. if you've force version 1 through {@link Cluster.Builder#withProtocolVersion}
205+ * is in use (i.e. if you've forced version 1 through {@link Cluster.Builder#withProtocolVersion}
182206 * or you use Cassandra 1.2).
183207 */
184208 ResultSetFuture executeAsync(String query, Object... values);
185209
210+ /**
211+ * Executes the provided query asynchronously using the provided values.
212+ * <p/>
213+ * This is a convenience method for {@code executeAsync(new SimpleStatement(query, values))}.
214+ *
215+ * @param query the CQL query to execute.
216+ * @param values values required for the execution of {@code query}. See
217+ * {@link SimpleStatement#SimpleStatement(String, Map)} for more details.
218+ * @return a future on the result of the query.
219+ * @throws UnsupportedFeatureException if version 1 or 2 of the protocol
220+ * is in use (i.e. if you've forced it through {@link Cluster.Builder#withProtocolVersion}
221+ * or you use Cassandra 1.2 or 2.0).
222+ */
223+ ResultSetFuture executeAsync(String query, Map<String, Object> values);
224+
186225 /**
187226 * Executes the provided query asynchronously.
188227 * <p/>
modified driver-core/src/main/java/com/datastax/driver/core/SessionManager.java +10 −5
@@ -545,16 +545,21 @@
545545 if (protocolVersion == ProtocolVersion.V1 && rs instanceof com.datastax.driver.core.querybuilder.BuiltStatement)
546546 ((com.datastax.driver.core.querybuilder.BuiltStatement) rs).setForceNoValues(true);
547547
548- ByteBuffer[] rawValues = rs.getValues(protocolVersion, codecRegistry);
548+ ByteBuffer[] rawPositionalValues = rs.getValues(protocolVersion, codecRegistry);
549+ Map<String, ByteBuffer> rawNamedValues = rs.getNamedValues(protocolVersion, codecRegistry);
549550
550- if (protocolVersion == ProtocolVersion.V1 && rawValues != null)
551+ if (protocolVersion == ProtocolVersion.V1 && (rawPositionalValues != null || rawNamedValues != null))
551552 throw new UnsupportedFeatureException(protocolVersion, "Binary values are not supported");
552553
553- List<ByteBuffer> values = rawValues == null ? Collections.<ByteBuffer>emptyList() : Arrays.asList(rawValues);
554+ if (protocolVersion == ProtocolVersion.V2 && rawNamedValues != null)
555+ throw new UnsupportedFeatureException(protocolVersion, "Named values are not supported");
556+
557+ List<ByteBuffer> positionalValues = rawPositionalValues == null ? Collections.<ByteBuffer>emptyList() : Arrays.asList(rawPositionalValues);
558+ Map<String, ByteBuffer> namedValues = rawNamedValues == null ? Collections.<String, ByteBuffer>emptyMap() : rawNamedValues;
554559
555560 String qString = rs.getQueryString();
556561
557- Requests.QueryProtocolOptions options = new Requests.QueryProtocolOptions(consistency, values, false,
562+ Requests.QueryProtocolOptions options = new Requests.QueryProtocolOptions(consistency, positionalValues, namedValues, false,
558563 fetchSize, usedPagingState, serialConsistency, defaultTimestamp);
559564 request = new Requests.Query(qString, options, statement.isTracing());
560565 } else if (statement instanceof BoundStatement) {
@@ -566,7 +571,7 @@
566571 if (protocolVersion.compareTo(ProtocolVersion.V4) < 0)
567572 bs.ensureAllSet();
568573 boolean skipMetadata = protocolVersion != ProtocolVersion.V1 && bs.statement.getPreparedId().resultSetMetadata != null;
569- Requests.QueryProtocolOptions options = new Requests.QueryProtocolOptions(consistency, Arrays.asList(bs.wrapper.values), skipMetadata,
574+ Requests.QueryProtocolOptions options = new Requests.QueryProtocolOptions(consistency, Arrays.asList(bs.wrapper.values), Collections.<String, ByteBuffer>emptyMap(), skipMetadata,
570575 fetchSize, usedPagingState, serialConsistency, defaultTimestamp);
571576 request = new Requests.Execute(bs.statement.getPreparedId().id, options, statement.isTracing());
572577 } else {
modified driver-core/src/main/java/com/datastax/driver/core/SimpleStatement.java +93 −22
@@ -18,6 +18,8 @@
1818 import com.datastax.driver.core.exceptions.InvalidTypeException;
1919
2020 import java.nio.ByteBuffer;
21+import java.util.HashMap;
22+import java.util.Map;
2123
2224 /**
2325 * A simple {@code RegularStatement} implementation built directly from a query
@@ -27,6 +29,7 @@
2729
2830 private final String query;
2931 private final Object[] values;
32+ private final Map<String, Object> namedValues;
3033
3134 private volatile ByteBuffer routingKey;
3235 private volatile String keyspace;
@@ -66,11 +69,11 @@
6669 * server side) once it has been executed.</li>
6770 * </ul>
6871 * <p/>
69- * Note that the type of the {@code values} provided to this method will
72+ * Note that the types of the {@code values} provided to this method will
7073 * not be validated by the driver as is done by {@link BoundStatement#bind} since
71- * {@code query} is not parsed (and hence the driver cannot know what those value
74+ * {@code query} is not parsed (and hence the driver cannot know what those values
7275 * should be). The codec to serialize each value will be chosen in the codec registry
73- * associated with this session's cluster, based on the value's Java type
76+ * associated with the cluster executing this statement, based on the value's Java type
7477 * (this is the equivalent to calling {@link CodecRegistry#codecFor(Object)}).
7578 * If too many or too few values are provided, or if a value is not a valid one for
7679 * the variable it is bound to, an
@@ -78,6 +81,14 @@
7881 * by Cassandra at execution time. A {@code CodecNotFoundException} may be
7982 * thrown by this constructor however, if the codec registry does not know how to
8083 * handle one of the values.
84+ * <p/>
85+ * If you have a single value of type {@code Map<String, Object>}, you can't call this
86+ * constructor using the varargs syntax, because the signature collides with
87+ * {@link #SimpleStatement(String, Map)}. To prevent this, pass an explicit
88+ * array object:
89+ * <pre>
90+ * new SimpleStatement("...", new Object[]{m});
91+ * </pre>
8192 *
8293 * @param query the query string.
8394 * @param values values required for the execution of {@code query}.
@@ -88,6 +99,36 @@
8899 throw new IllegalArgumentException("Too many values, the maximum allowed is 65535");
89100 this.query = query;
90101 this.values = values;
102+ this.namedValues = null;
103+ }
104+
105+ /**
106+ * Creates a new {@code SimpleStatement} with the provided query string and named values.
107+ * <p/>
108+ * This constructor requires that the query string use named placeholders, for example:
109+ * <pre>{@code
110+ * new SimpleStatement("SELECT * FROM users WHERE id = :i", ImmutableMap.<String, Object>of("i", 1));}
111+ * </pre>
112+ * Make sure that the map is correctly typed {@code Map<String, Object>}, otherwise you might
113+ * accidentally call {@link #SimpleStatement(String, Object...)} with a positional value of type map.
114+ * <p/>
115+ * The types of the values will be handled the same way as with anonymous placeholders (see
116+ * {@link #SimpleStatement(String, Object...)}).
117+ * <p/>
118+ * Simple statements with named values are only supported starting with native protocol
119+ * {@link ProtocolVersion#V3 v3}. With earlier versions, an
120+ * {@link com.datastax.driver.core.exceptions.UnsupportedFeatureException} will be thrown at execution time.
121+ *
122+ * @param query the query string.
123+ * @param values named values required for the execution of {@code query}.
124+ * @throws IllegalArgumentException if the number of values is greater than 65535.
125+ */
126+ public SimpleStatement(String query, Map<String, Object> values) {
127+ if (values.size() > 65535)
128+ throw new IllegalArgumentException("Too many values, the maximum allowed is 65535");
129+ this.query = query;
130+ this.values = null;
131+ this.namedValues = values;
91132 }
92133
93134 @Override
@@ -102,6 +143,13 @@
102143 return convert(values, protocolVersion, codecRegistry);
103144 }
104145
146+ @Override
147+ public Map<String, ByteBuffer> getNamedValues(ProtocolVersion protocolVersion, CodecRegistry codecRegistry) {
148+ if (namedValues == null)
149+ return null;
150+ return convert(namedValues, protocolVersion, codecRegistry);
151+ }
152+
105153 /**
106154 * The number of values for this statement, that is the size of the array
107155 * that will be returned by {@code getValues}.
@@ -109,12 +157,23 @@
109157 * @return the number of values.
110158 */
111159 public int valuesCount() {
112- return values == null ? 0 : values.length;
160+ if (values != null)
161+ return values.length;
162+ else if (namedValues != null)
163+ return namedValues.size();
164+ else
165+ return 0;
113166 }
114167
115168 @Override
116169 public boolean hasValues(CodecRegistry codecRegistry) {
117- return values != null && values.length > 0;
170+ return (values != null && values.length > 0)
171+ || (namedValues != null && namedValues.size() > 0);
172+ }
173+
174+ @Override
175+ public boolean usesNamedValues() {
176+ return namedValues != null && namedValues.size() > 0;
118177 }
119178
120179 /**
@@ -224,27 +283,12 @@
224283 return this;
225284 }
226285
227- /**
228- * <p/>
229- * Utility method to serialize user-provided values.
230- * <p/>
231- * This method is useful in situations where there is no metadata available and the underlying CQL
232- * type for the values is not known.
233- * <p/>
234- * This situation happens when a {@link SimpleStatement}
235- * or a {@link com.datastax.driver.core.querybuilder.BuiltStatement} (Query Builder) contain values;
236- * in these places, the driver has no way to determine the right CQL type to use.
237- * <p/>
286+ /*
238287 * This method performs a best-effort heuristic to guess which codec to use.
239288 * Note that this is not particularly efficient as the codec registry needs to iterate over
240289 * the registered codecs until it finds a suitable one.
241- *
242- * @param values The values to convert.
243- * @param protocolVersion The protocol version to use.
244- * @param codecRegistry The {@link CodecRegistry} to use.
245- * @return The converted values.
246290 */
247- public static ByteBuffer[] convert(Object[] values, ProtocolVersion protocolVersion, CodecRegistry codecRegistry) {
291+ private static ByteBuffer[] convert(Object[] values, ProtocolVersion protocolVersion, CodecRegistry codecRegistry) {
248292 ByteBuffer[] serializedValues = new ByteBuffer[values.length];
249293 for (int i = 0; i < values.length; i++) {
250294 Object value = values[i];
@@ -270,6 +314,33 @@
270314 return serializedValues;
271315 }
272316
317+ private static Map<String, ByteBuffer> convert(Map<String, Object> values, ProtocolVersion protocolVersion, CodecRegistry codecRegistry) {
318+ Map<String, ByteBuffer> serializedValues = new HashMap<String, ByteBuffer>();
319+ for (Map.Entry<String, Object> entry : values.entrySet()) {
320+ String name = entry.getKey();
321+ Object value = entry.getValue();
322+ if (value == null) {
323+ // impossible to locate the right codec when object is null,
324+ // so forcing the result to null
325+ serializedValues.put(name, null);
326+ } else {
327+ if (value instanceof Token) {
328+ // bypass CodecRegistry for Token instances
329+ serializedValues.put(name, ((Token) value).serialize(protocolVersion));
330+ } else {
331+ try {
332+ TypeCodec<Object> codec = codecRegistry.codecFor(value);
333+ serializedValues.put(name, codec.serialize(value, protocolVersion));
334+ } catch (Exception e) {
335+ // Catch and rethrow to provide a more helpful error message (one that include which value is bad)
336+ throw new InvalidTypeException(String.format("Value '%s' of type %s does not correspond to any CQL3 type", name, value.getClass()), e);
337+ }
338+ }
339+ }
340+ }
341+ return serializedValues;
342+ }
343+
273344 /**
274345 * Utility method to assemble different routing key components into a single {@link ByteBuffer}.
275346 * Mainly intended for statements that need to generate a routing key out of their current values.
modified driver-core/src/main/java/com/datastax/driver/core/querybuilder/BuiltStatement.java +12 −0
@@ -23,6 +23,7 @@
2323 import java.util.ArrayList;
2424 import java.util.Arrays;
2525 import java.util.List;
26+import java.util.Map;
2627 import java.util.regex.Pattern;
2728
2829 /**
@@ -274,6 +275,17 @@
274275 return values != null;
275276 }
276277
278+ @Override
279+ public Map<String, ByteBuffer> getNamedValues(ProtocolVersion protocolVersion, CodecRegistry codecRegistry) {
280+ // Built statements never return named values
281+ return null;
282+ }
283+
284+ @Override
285+ public boolean usesNamedValues() {
286+ return false;
287+ }
288+
277289 @Override
278290 public Boolean isIdempotent() {
279291 // If a value was forced with setIdempotent, it takes priority
modified driver-core/src/main/java/com/datastax/driver/core/schemabuilder/SchemaStatement.java +12 −0
@@ -23,6 +23,7 @@
2323 import java.nio.ByteBuffer;
2424 import java.util.Arrays;
2525 import java.util.List;
26+import java.util.Map;
2627
2728 /**
2829 * A DDL statement generated by {@link SchemaBuilder}.
@@ -61,6 +62,17 @@
6162 return false;
6263 }
6364
65+ @Override
66+ public Map<String, ByteBuffer> getNamedValues(ProtocolVersion protocolVersion, CodecRegistry codecRegistry) {
67+ // DDL statements never have values
68+ return null;
69+ }
70+
71+ @Override
72+ public boolean usesNamedValues() {
73+ return false;
74+ }
75+
6476 @Override
6577 public String getKeyspace() {
6678 // This is exposed for token-aware routing. Since there is no token awareness for DDL statements, we don't need to
added driver-core/src/test/java/com/datastax/driver/core/SimpleStatementIntegrationTest.java +117 −0
@@ -0,0 +1,117 @@
1+/*
2+ * Copyright (C) 2012-2015 DataStax Inc.
3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ */
16+package com.datastax.driver.core;
17+
18+import com.datastax.driver.core.exceptions.InvalidQueryException;
19+import com.datastax.driver.core.exceptions.UnsupportedFeatureException;
20+import com.datastax.driver.core.utils.CassandraVersion;
21+import com.google.common.collect.ImmutableMap;
22+import com.google.common.collect.Lists;
23+import org.testng.SkipException;
24+import org.testng.annotations.Test;
25+
26+import java.util.Collection;
27+
28+import static org.assertj.core.api.Assertions.assertThat;
29+
30+public class SimpleStatementIntegrationTest extends CCMTestsSupport {
31+ @Override
32+ public Collection<String> createTestFixtures() {
33+ return Lists.newArrayList(
34+ "CREATE TABLE users(id int, id2 int, name text, primary key (id, id2))",
35+ "INSERT INTO users(id, id2, name) VALUES (1, 2, 'test')"
36+ );
37+ }
38+
39+ @Test(groups = "short")
40+ @CassandraVersion(major = 2.1)
41+ public void should_execute_query_with_named_values() {
42+ // Given
43+ SimpleStatement statement = new SimpleStatement("SELECT * FROM users WHERE id = :id and id2 = :id2",
44+ ImmutableMap.<String, Object>of("id", 1, "id2", 2));
45+
46+ // When
47+ Row row = session.execute(statement).one();
48+
49+ // Then
50+ assertThat(row).isNotNull();
51+ assertThat(row.getString("name")).isEqualTo("test");
52+ }
53+
54+ @Test(groups = "short", expectedExceptions = InvalidQueryException.class)
55+ @CassandraVersion(major = 2.1)
56+ public void should_fail_if_query_with_named_values_but_missing_parameter() {
57+ // Given a Statement missing named parameters.
58+ SimpleStatement statement = new SimpleStatement("SELECT * FROM users WHERE id = :id and id2 = :id2",
59+ ImmutableMap.<String, Object>of("id2", 2));
60+
61+ // When
62+ session.execute(statement).one();
63+
64+ // Then - The driver does allow this because it doesn't know what parameters are required, but C* should
65+ // throw an InvalidQueryException.
66+ }
67+
68+ @Test(groups = "short", expectedExceptions = InvalidQueryException.class)
69+ @CassandraVersion(major = 2.1)
70+ public void should_fail_if_query_with_named_values_but_using_wrong_type() {
71+ // Given a Statement using a named parameter with the wrong value for the type (id is of type int, using double)
72+ SimpleStatement statement = new SimpleStatement("SELECT * FROM users WHERE id = :id and id2 = :id2",
73+ ImmutableMap.<String, Object>of("id", 2.7, "id2", 2));
74+
75+ // When
76+ session.execute(statement).one();
77+
78+ // Then - The driver does allow this because it doesn't know the type information, but C* should throw an
79+ // InvalidQueryException.
80+ }
81+
82+ public void useNamedValuesWithProtocol(ProtocolVersion version) {
83+ Cluster vCluster = createClusterBuilder()
84+ .addContactPointsWithPorts(getInitialContactPoints())
85+ .withProtocolVersion(version).build();
86+ try {
87+ Session vSession = vCluster.connect(this.keyspace);
88+ // Given - A simple statement with named parameters.
89+ SimpleStatement statement = new SimpleStatement("SELECT * FROM users WHERE id = :id",
90+ ImmutableMap.<String, Object>of("id", 1));
91+
92+ // When - Executing that statement against a Cluster instance using Protocol Version V2.
93+ vSession.execute(statement).one();
94+
95+ // Then - Should throw an UnsupportedFeatureException
96+ } finally {
97+ vCluster.close();
98+ }
99+ }
100+
101+ @Test(groups = "short", expectedExceptions = UnsupportedFeatureException.class)
102+ @CassandraVersion(major = 2.0)
103+ public void should_fail_if_query_with_named_values_if_protocol_is_V2() {
104+ if (ccm.getVersion().getMajor() >= 3) {
105+ throw new SkipException("Skipping since Cassandra 3.0+ does not support protocol v2");
106+ }
107+ useNamedValuesWithProtocol(ProtocolVersion.V2);
108+ }
109+
110+ @Test(groups = "short", expectedExceptions = UnsupportedFeatureException.class)
111+ public void should_fail_if_query_with_named_values_if_protocol_is_V1() {
112+ if (ccm.getVersion().getMajor() >= 3) {
113+ throw new SkipException("Skipping since Cassandra 3.0+ does not support protocol v1");
114+ }
115+ useNamedValuesWithProtocol(ProtocolVersion.V1);
116+ }
117+}