Elffuss BraidHub

kikocis/java-driver public

JAVA-1007: Make SimpleStatement and QueryBuilder "detached" again.
Changeset2b008721b1bb95a5243c6ffb084760f71f33090df4b162662d7611590f56a93e
Authorolim7t <omichallat+github@gmail.com> · 2015-12-03 18:58 +01:00
Committerolim7t <omichallat+github@gmail.com> · 2015-12-07 18:44 +01:00
Parentsa3674bcf4e77

Browse the files at this changeset

71 files changed

modified changelog/README.md +1 −0
@@ -11,6 +11,7 @@
1111 - [improvement] JAVA-863: Idempotence propagation in prepared statements.
1212 - [improvement] JAVA-996: Make CodecRegistry available to ProtocolDecoder.
1313 - [bug] JAVA-819: Driver shouldn't retry on client timeout if statement is not idempotent.
14+- [improvement] JAVA-1007: Make SimpleStatement and QueryBuilder "detached" again.
1415
1516 Merged from 2.1 branch:
1617
modified driver-core/src/main/java/com/datastax/driver/core/AbstractSession.java +7 −21
@@ -36,7 +36,7 @@
3636 */
3737 @Override
3838 public ResultSet execute(String query) {
39- return execute(newSimpleStatement(query));
39+ return execute(new SimpleStatement(query));
4040 }
4141
4242 /**
@@ -44,7 +44,7 @@
4444 */
4545 @Override
4646 public ResultSet execute(String query, Object... values) {
47- return execute(newSimpleStatement(query, values));
47+ return execute(new SimpleStatement(query, values));
4848 }
4949
5050 /**
@@ -60,7 +60,7 @@
6060 */
6161 @Override
6262 public ResultSetFuture executeAsync(String query) {
63- return executeAsync(newSimpleStatement(query));
63+ return executeAsync(new SimpleStatement(query));
6464 }
6565
6666 /**
@@ -68,23 +68,7 @@
6868 */
6969 @Override
7070 public ResultSetFuture executeAsync(String query, Object... values) {
71- return executeAsync(newSimpleStatement(query, values));
72- }
73-
74- /**
75- * {@inheritDoc}
76- */
77- @Override
78- public SimpleStatement newSimpleStatement(String query) {
79- return new SimpleStatement(query, this.getCluster());
80- }
81-
82- /**
83- * {@inheritDoc}
84- */
85- @Override
86- public SimpleStatement newSimpleStatement(String query, Object... values) {
87- return new SimpleStatement(query, this.getCluster(), values);
71+ return executeAsync(new SimpleStatement(query, values));
8872 }
8973
9074 /**
@@ -132,7 +116,9 @@
132116 return Futures.transform(prepared, new Function<PreparedStatement, PreparedStatement>() {
133117 @Override
134118 public PreparedStatement apply(PreparedStatement prepared) {
135- ByteBuffer routingKey = statement.getRoutingKey();
119+ ProtocolVersion protocolVersion = getCluster().getConfiguration().getProtocolOptions().getProtocolVersion();
120+ CodecRegistry codecRegistry = getCluster().getConfiguration().getCodecRegistry();
121+ ByteBuffer routingKey = statement.getRoutingKey(protocolVersion, codecRegistry);
136122 if (routingKey != null)
137123 prepared.setRoutingKey(routingKey);
138124 prepared.setConsistencyLevel(statement.getConsistencyLevel());
modified driver-core/src/main/java/com/datastax/driver/core/ArrayBackedResultSet.java +12 −8
@@ -45,10 +45,12 @@
4545 private final boolean wasApplied;
4646
4747 protected final ProtocolVersion protocolVersion;
48+ protected final CodecRegistry codecRegistry;
4849
49- private ArrayBackedResultSet(ColumnDefinitions metadata, Token.Factory tokenFactory, List<ByteBuffer> firstRow, ProtocolVersion protocolVersion) {
50+ private ArrayBackedResultSet(ColumnDefinitions metadata, Token.Factory tokenFactory, List<ByteBuffer> firstRow, ProtocolVersion protocolVersion, CodecRegistry codecRegistry) {
5051 this.metadata = metadata;
5152 this.protocolVersion = protocolVersion;
53+ this.codecRegistry = codecRegistry;
5254 this.tokenFactory = tokenFactory;
5355 this.wasApplied = checkWasApplied(firstRow, metadata, protocolVersion);
5456 }
@@ -79,8 +81,8 @@
7981 assert r.metadata.pagingState == null || info != null;
8082
8183 return r.metadata.pagingState == null
82- ? new SinglePage(columnDefs, tokenFactory, protocolVersion, r.data, info)
83- : new MultiPage(columnDefs, tokenFactory, protocolVersion, r.data, info, r.metadata.pagingState, session, statement);
84+ ? new SinglePage(columnDefs, tokenFactory, protocolVersion, columnDefs.codecRegistry, r.data, info)
85+ : new MultiPage(columnDefs, tokenFactory, protocolVersion, columnDefs.codecRegistry, r.data, info, r.metadata.pagingState, session, statement);
8486
8587 case SET_KEYSPACE:
8688 case SCHEMA_CHANGE:
@@ -105,7 +107,7 @@
105107
106108 private static ArrayBackedResultSet empty(ExecutionInfo info) {
107109 // We could pass the protocol version but we know we won't need it so passing a bogus value (null)
108- return new SinglePage(ColumnDefinitions.EMPTY, null, null, EMPTY_QUEUE, info);
110+ return new SinglePage(ColumnDefinitions.EMPTY, null, null, null, EMPTY_QUEUE, info);
109111 }
110112
111113 public ColumnDefinitions getColumnDefinitions() {
@@ -166,9 +168,10 @@
166168 private SinglePage(ColumnDefinitions metadata,
167169 Token.Factory tokenFactory,
168170 ProtocolVersion protocolVersion,
171+ CodecRegistry codecRegistry,
169172 Queue<List<ByteBuffer>> rows,
170173 ExecutionInfo info) {
171- super(metadata, tokenFactory, rows.peek(), protocolVersion);
174+ super(metadata, tokenFactory, rows.peek(), protocolVersion, codecRegistry);
172175 this.info = info;
173176 this.rows = rows;
174177 }
@@ -230,6 +233,7 @@
230233 private MultiPage(ColumnDefinitions metadata,
231234 Token.Factory tokenFactory,
232235 ProtocolVersion protocolVersion,
236+ CodecRegistry codecRegistry,
233237 Queue<List<ByteBuffer>> rows,
234238 ExecutionInfo info,
235239 ByteBuffer pagingState,
@@ -239,9 +243,9 @@
239243 // Note: as of Cassandra 2.1.0, it turns out that the result of a CAS update is never paged, so
240244 // we could hard-code the result of wasApplied in this class to "true". However, we can not be sure
241245 // that this will never change, so apply the generic check by peeking at the first row.
242- super(metadata, tokenFactory, rows.peek(), protocolVersion);
246+ super(metadata, tokenFactory, rows.peek(), protocolVersion, codecRegistry);
243247 this.currentPage = rows;
244- this.infos.offer(info.withPagingState(pagingState, protocolVersion).withStatement(statement));
248+ this.infos.offer(info.withPagingState(pagingState, protocolVersion, codecRegistry).withStatement(statement));
245249
246250 this.fetchState = new FetchingState(pagingState, null);
247251 this.session = session;
@@ -338,7 +342,7 @@
338342 if (rm.kind == Responses.Result.Kind.ROWS) {
339343 Responses.Result.Rows rows = (Responses.Result.Rows)rm;
340344 if (rows.metadata.pagingState != null)
341- info = info.withPagingState(rows.metadata.pagingState, protocolVersion).withStatement(statement);
345+ info = info.withPagingState(rows.metadata.pagingState, protocolVersion, codecRegistry).withStatement(statement);
342346 MultiPage.this.nextPages.offer(rows.data);
343347 MultiPage.this.fetchState = rows.metadata.pagingState == null ? null : new FetchingState(rows.metadata.pagingState, null);
344348 } else if (rm.kind == Responses.Result.Kind.VOID) {
modified driver-core/src/main/java/com/datastax/driver/core/BatchStatement.java +4 −4
@@ -81,14 +81,14 @@
8181 this.batchType = batchType;
8282 }
8383
84- IdAndValues getIdAndValues() {
84+ IdAndValues getIdAndValues(ProtocolVersion protocolVersion, CodecRegistry codecRegistry) {
8585 IdAndValues idAndVals = new IdAndValues(statements.size());
8686 for (Statement statement : statements) {
8787 if(statement instanceof StatementWrapper)
8888 statement = ((StatementWrapper) statement).getWrappedStatement();
8989 if (statement instanceof RegularStatement) {
9090 RegularStatement st = (RegularStatement)statement;
91- ByteBuffer[] vals = st.getValues();
91+ ByteBuffer[] vals = st.getValues(protocolVersion, codecRegistry);
9292 String query = st.getQueryString();
9393 idAndVals.ids.add(query);
9494 idAndVals.values.add(vals == null ? Collections.<ByteBuffer>emptyList() : Arrays.asList(vals));
@@ -213,11 +213,11 @@
213213 }
214214
215215 @Override
216- public ByteBuffer getRoutingKey() {
216+ public ByteBuffer getRoutingKey(ProtocolVersion protocolVersion, CodecRegistry codecRegistry) {
217217 for (Statement statement : statements) {
218218 if(statement instanceof StatementWrapper)
219219 statement = ((StatementWrapper) statement).getWrappedStatement();
220- ByteBuffer rk = statement.getRoutingKey();
220+ ByteBuffer rk = statement.getRoutingKey(protocolVersion, codecRegistry);
221221 if (rk != null)
222222 return rk;
223223 }
modified driver-core/src/main/java/com/datastax/driver/core/BoundStatement.java +5 −1
@@ -222,9 +222,13 @@
222222 * precedence. If the routing key has been set through {@link PreparedStatement#setRoutingKey} then that is used
223223 * next. If neither of those are set then it is computed.
224224 *
225+ * @param protocolVersion unused by this implementation (no internal serialization is required to compute the key).
226+ * @param codecRegistry unused by this implementation (no internal serialization is required to compute the key).
227+ *
225228 * @return the routing key for this statement or {@code null}.
226229 */
227- public ByteBuffer getRoutingKey() {
230+ @Override
231+ public ByteBuffer getRoutingKey(ProtocolVersion protocolVersion, CodecRegistry codecRegistry) {
228232 if (this.routingKey != null) {
229233 return this.routingKey;
230234 }
modified driver-core/src/main/java/com/datastax/driver/core/CodecRegistry.java +3 −3
@@ -88,8 +88,8 @@
8888 * <li>all driver types that implement {@link GettableByIndexData}, {@link GettableByNameData},
8989 * {@link SettableByIndexData} and/or {@link SettableByNameData}. Namely: {@link Row},
9090 * {@link BoundStatement}, {@link UDTValue} and {@link TupleValue};</li>
91- * <li>{@link Session#newSimpleStatement(String, Object...) simple statements};</li>
92- * <li>statements created with the {@link com.datastax.driver.core.querybuilder.QueryBuilder#QueryBuilder(Cluster) Query builder}.</li>
91+ * <li>{@link SimpleStatement(String, Object...) simple statements};</li>
92+ * <li>statements created with the {@link com.datastax.driver.core.querybuilder.QueryBuilder Query builder}.</li>
9393 * </ul>
9494 *
9595 * Example:
@@ -393,7 +393,7 @@
393393 * Furthermore, this method returns the first matching codec, regardless of its accepted CQL type.
394394 * It should be reserved for situations where the target CQL type is not available or unknown.
395395 * In the Java driver, this happens mainly when serializing a value in a
396- * {@link Session#newSimpleStatement(String, Object...) SimpleStatement} or in the
396+ * {@link SimpleStatement(String, Object...) SimpleStatement} or in the
397397 * {@link com.datastax.driver.core.querybuilder.QueryBuilder}, where no CQL type information is available.
398398 * <p>
399399 * Codecs returned by this method are <em>NOT</em> cached (see the {@link CodecRegistry top-level documentation}
modified driver-core/src/main/java/com/datastax/driver/core/ExecutionInfo.java +11 −9
@@ -34,17 +34,19 @@
3434 private final QueryTrace trace;
3535 private final ByteBuffer pagingState;
3636 private final ProtocolVersion protocolVersion;
37+ private final CodecRegistry codecRegistry;
3738 private final Statement statement;
3839 private volatile boolean schemaInAgreement;
3940 private final List<String> warnings;
4041 private final Map<String, ByteBuffer> incomingPayload;
4142
42- private ExecutionInfo(List<Host> triedHosts, ConsistencyLevel achievedConsistency, QueryTrace trace, ByteBuffer pagingState, ProtocolVersion protocolVersion, Statement statement, boolean schemaAgreement, List<String> warnings, Map<String, ByteBuffer> incomingPayload) {
43+ private ExecutionInfo(List<Host> triedHosts, ConsistencyLevel achievedConsistency, QueryTrace trace, ByteBuffer pagingState, ProtocolVersion protocolVersion, CodecRegistry codecRegistry, Statement statement, boolean schemaAgreement, List<String> warnings, Map<String, ByteBuffer> incomingPayload) {
4344 this.triedHosts = triedHosts;
4445 this.achievedConsistency = achievedConsistency;
4546 this.trace = trace;
4647 this.pagingState = pagingState;
4748 this.protocolVersion = protocolVersion;
49+ this.codecRegistry = codecRegistry;
4850 this.statement = statement;
4951 this.schemaInAgreement = schemaAgreement;
5052 this.warnings = warnings;
@@ -52,27 +54,27 @@
5254 }
5355
5456 ExecutionInfo(List<Host> triedHosts) {
55- this(triedHosts, null, null, null, null, null, true, Collections.<String>emptyList(), null);
57+ this(triedHosts, null, null, null, null, null, null, true, Collections.<String>emptyList(), null);
5658 }
5759
5860 ExecutionInfo withTraceAndWarnings(QueryTrace newTrace, List<String> warnings) {
59- return new ExecutionInfo(triedHosts, achievedConsistency, newTrace, pagingState, protocolVersion, statement, schemaInAgreement, warnings, incomingPayload);
61+ return new ExecutionInfo(triedHosts, achievedConsistency, newTrace, pagingState, protocolVersion, codecRegistry, statement, schemaInAgreement, warnings, incomingPayload);
6062 }
6163
6264 ExecutionInfo withAchievedConsistency(ConsistencyLevel newConsistency) {
63- return new ExecutionInfo(triedHosts, newConsistency, trace, pagingState, protocolVersion, statement, schemaInAgreement, warnings, incomingPayload);
65+ return new ExecutionInfo(triedHosts, newConsistency, trace, pagingState, protocolVersion, codecRegistry, statement, schemaInAgreement, warnings, incomingPayload);
6466 }
6567
66- ExecutionInfo withPagingState(ByteBuffer pagingState, ProtocolVersion protocolVersion) {
67- return new ExecutionInfo(triedHosts, achievedConsistency, trace, pagingState, protocolVersion, statement, schemaInAgreement, warnings, incomingPayload);
68+ ExecutionInfo withPagingState(ByteBuffer pagingState, ProtocolVersion protocolVersion, CodecRegistry codecRegistry) {
69+ return new ExecutionInfo(triedHosts, achievedConsistency, trace, pagingState, protocolVersion, codecRegistry, statement, schemaInAgreement, warnings, incomingPayload);
6870 }
6971
7072 ExecutionInfo withStatement(Statement statement) {
71- return new ExecutionInfo(triedHosts, achievedConsistency, trace, pagingState, protocolVersion, statement, schemaInAgreement, warnings, incomingPayload);
73+ return new ExecutionInfo(triedHosts, achievedConsistency, trace, pagingState, protocolVersion, codecRegistry, statement, schemaInAgreement, warnings, incomingPayload);
7274 }
7375
7476 ExecutionInfo withIncomingPayload(Map<String, ByteBuffer> incomingPayload) {
75- return new ExecutionInfo(triedHosts, achievedConsistency, trace, pagingState, protocolVersion, statement, schemaInAgreement, warnings, incomingPayload);
77+ return new ExecutionInfo(triedHosts, achievedConsistency, trace, pagingState, protocolVersion, codecRegistry, statement, schemaInAgreement, warnings, incomingPayload);
7678 }
7779
7880 /**
@@ -175,7 +177,7 @@
175177 public PagingState getPagingState() {
176178 if (this.pagingState == null)
177179 return null;
178- return new PagingState(this.pagingState, this.statement, this.protocolVersion);
180+ return new PagingState(this.pagingState, this.statement, this.protocolVersion, this.codecRegistry);
179181 }
180182
181183 /**
modified driver-core/src/main/java/com/datastax/driver/core/PagingState.java +6 −6
@@ -41,9 +41,9 @@
4141 private final byte[] hash;
4242 private final ProtocolVersion protocolVersion;
4343
44- PagingState(ByteBuffer pagingState, Statement statement, ProtocolVersion protocolVersion) {
44+ PagingState(ByteBuffer pagingState, Statement statement, ProtocolVersion protocolVersion, CodecRegistry codecRegistry) {
4545 this.pagingState = Bytes.getArray(pagingState);
46- this.hash = hash(statement);
46+ this.hash = hash(statement, protocolVersion, codecRegistry);
4747 this.protocolVersion = protocolVersion;
4848 }
4949
@@ -70,7 +70,7 @@
7070 : ProtocolVersion.V2;
7171 }
7272
73- private byte[] hash(Statement statement) {
73+ private byte[] hash(Statement statement, ProtocolVersion protocolVersion, CodecRegistry codecRegistry) {
7474 byte[] digest;
7575 ByteBuffer[] values;
7676 MessageDigest md;
@@ -85,7 +85,7 @@
8585 //it is a RegularStatement since Batch statements are not allowed
8686 RegularStatement rs = (RegularStatement)statement;
8787 md.update(rs.getQueryString().getBytes());
88- values = rs.getValues();
88+ values = rs.getValues(protocolVersion, codecRegistry);
8989 }
9090 if (values != null) {
9191 for (ByteBuffer value : values) {
@@ -101,8 +101,8 @@
101101 return digest;
102102 }
103103
104- boolean matches(Statement statement) {
105- byte[] toTest = hash(statement);
104+ boolean matches(Statement statement, CodecRegistry codecRegistry) {
105+ byte[] toTest = hash(statement, protocolVersion, codecRegistry);
106106 return Arrays.equals(toTest, this.hash);
107107 }
108108
modified driver-core/src/main/java/com/datastax/driver/core/RegularStatement.java +76 −4
@@ -19,6 +19,8 @@
1919
2020 import com.datastax.driver.core.exceptions.InvalidTypeException;
2121 import com.datastax.driver.core.exceptions.UnsupportedProtocolVersionException;
22+import com.datastax.driver.core.querybuilder.BuiltStatement;
23+import com.datastax.driver.core.schemabuilder.SchemaStatement;
2224
2325 /**
2426 * A regular (non-prepared and non batched) CQL statement.
@@ -38,9 +40,40 @@
3840 /**
3941 * Returns the query string for this statement.
4042 *
43+ * @param codecRegistry the codec registry that will be used if the actual
44+ * implementation needs to serialize Java objects in the
45+ * process of generating the query. Note that it might be
46+ * possible to use the no-arg {@link #getQueryString()}
47+ * depending on the type of statement this is called on.
48+ *
49+ * @return a valid CQL query string.
50+ *
51+ * @see #getQueryString()
52+ */
53+ public abstract String getQueryString(CodecRegistry codecRegistry);
54+
55+ /**
56+ * Returns the query string for this statement.
57+ * <p>
58+ * This method calls {@link #getQueryString(CodecRegistry)} with {@link CodecRegistry#DEFAULT_INSTANCE}.
59+ * Whether you should use this or the other variant depends on the type of statement this is
60+ * called on:
61+ * <ul>
62+ * <li>for a {@link SimpleStatement} or {@link SchemaStatement}, the codec registry isn't
63+ * actually needed, so it's always safe to use this method;</li>
64+ * <li>for a {@link BuiltStatement} you can use this method if you use no custom codecs, or if
65+ * your custom codecs are registered with the default registry. Otherwise, use the other method and
66+ * provide the registry that contains your codecs (see {@link BuiltStatement} for more explanations
67+ * on why this is so);</li>
68+ * <li>for a {@link BatchStatement}, use the first rule if it contains no built statements,
69+ * or the second rule otherwise.</li>
70+ * </ul>
71+ *
4172 * @return a valid CQL query string.
4273 */
43- public abstract String getQueryString();
74+ public String getQueryString() {
75+ return getQueryString(CodecRegistry.DEFAULT_INSTANCE);
76+ }
4477
4578 /**
4679 * The values to use for this statement.
@@ -52,20 +85,59 @@
5285 * 1 through {@link Cluster.Builder#withProtocolVersion} or you use
5386 * Cassandra 1.2).
5487 *
88+ * @param protocolVersion the protocol version that will be used to serialize
89+ * the values.
90+ * @param codecRegistry the codec registry that will be used to serialize the
91+ * values.
92+ *
5593 * @throws InvalidTypeException if one of the values is not of a type
5694 * that can be serialized to a CQL3 type
57- * @see SimpleStatement#SimpleStatement(String, Cluster, Object...)
95+ * @see SimpleStatement#SimpleStatement(String, Object...)
5896 */
59- public abstract ByteBuffer[] getValues();
97+ public abstract ByteBuffer[] getValues(ProtocolVersion protocolVersion, CodecRegistry codecRegistry);
6098
6199 /**
62100 * Whether or not this statement has values, that is if {@code getValues}
63101 * will return {@code null} or not.
64102 *
103+ * @param codecRegistry the codec registry that will be used if the actual
104+ * implementation needs to serialize Java objects in the
105+ * process of determining if the query has values.
106+ * Note that it might be possible to use the no-arg
107+ * {@link #hasValues()} depending on the type of
108+ * statement this is called on.
109+ *
110+ * @return {@code false} if {@link #getValues} returns {@code null}, {@code true}
111+ * otherwise.
112+ *
113+ * @see #hasValues()
114+ */
115+ public abstract boolean hasValues(CodecRegistry codecRegistry);
116+
117+ /**
118+ * Whether or not this statement has values, that is if {@code getValues}
119+ * will return {@code null} or not.
120+ * <p>
121+ * This method calls {@link #hasValues(CodecRegistry)} with {@link ProtocolVersion#NEWEST_SUPPORTED}.
122+ * Whether you should use this or the other variant depends on the type of statement this is
123+ * called on:
124+ * <ul>
125+ * <li>for a {@link SimpleStatement} or {@link SchemaStatement}, the codec registry isn't
126+ * actually needed, so it's always safe to use this method;</li>
127+ * <li>for a {@link BuiltStatement} you can use this method if you use no custom codecs, or if
128+ * your custom codecs are registered with the default registry. Otherwise, use the other method and
129+ * provide the registry that contains your codecs (see {@link BuiltStatement} for more explanations
130+ * on why this is so);</li>
131+ * <li>for a {@link BatchStatement}, use the first rule if it contains no built statements,
132+ * or the second rule otherwise.</li>
133+ * </ul>
134+ *
65135 * @return {@code false} if {@link #getValues} returns {@code null}, {@code true}
66136 * otherwise.
67137 */
68- public abstract boolean hasValues();
138+ public boolean hasValues() {
139+ return hasValues(CodecRegistry.DEFAULT_INSTANCE);
140+ }
69141
70142 @Override
71143 public String toString() {
modified driver-core/src/main/java/com/datastax/driver/core/Session.java +2 −64
@@ -119,7 +119,7 @@
119119 *
120120 * @param query the CQL query to execute.
121121 * @param values values required for the execution of {@code query}. See
122- * {@link #newSimpleStatement(String, Object...)} for more detail.
122+ * {@link SimpleStatement(String, Object...)} for more detail.
123123 * @return the result of the query. That result will never be null but can
124124 * be empty (and will be for any non SELECT query).
125125 *
@@ -181,7 +181,7 @@
181181 *
182182 * @param query the CQL query to execute.
183183 * @param values values required for the execution of {@code query}. See
184- * {@link #newSimpleStatement(String, Object...)} for more detail.
184+ * {@link SimpleStatement(String, Object...)} for more detail.
185185 * @return a future on the result of the query.
186186 *
187187 * @throws UnsupportedFeatureException if version 1 of the protocol
@@ -190,68 +190,6 @@
190190 */
191191 ResultSetFuture executeAsync(String query, Object... values);
192192
193- /**
194- * Builds, but does not execute, a simple statement containing the provided query.
195- *
196- * Use this method when you want to customize certain aspects of the statement before
197- * executing it (fetch size, tracing...); you can then pass the statement to
198- * {@link #execute(Statement)}.
199- *
200- * @param query the CQL query to execute.
201- * @return the simple statement.
202- */
203- SimpleStatement newSimpleStatement(String query);
204-
205- /**
206- * Builds, but does not execute, a simple statement containing the provided query with
207- * the provided parameters.
208- *
209- * Use this method when you want to customize certain aspects of the statement before
210- * executing it (fetch size, tracing...); you can then pass the statement to
211- * {@link #execute(Statement)}.
212- * <p>
213- * Parameterized simple statements are useful when you want to execute a
214- * query only once (and thus do not want to resort to prepared statements), but
215- * do not want to convert all column values to string (typically, if you have blob
216- * values, encoding them to a hexadecimal string is not very efficient). In
217- * that case, you can provide a query string with bind marker to this method,
218- * along with the values for those bind variables. When executed, the server will
219- * prepare the provided query, bind the provided values to that prepare statement and
220- * execute the resulting statement. Thus,
221- * <pre>
222- * session.execute(session.newSimpleStatement(query, value1, value2, value3));
223- * </pre>
224- * is functionally equivalent to
225- * <pre>
226- * PreparedStatement ps = session.prepare(query);
227- * session.execute(ps.bind(value1, value2, value3));
228- * </pre>
229- * except that the former version:
230- * <ul>
231- * <li>Requires only one round-trip to a Cassandra node.</li>
232- * <li>Does not leave any prepared statement stored in memory (neither client or
233- * server side) once it has been executed.</li>
234- * </ul>
235- * <p>
236- * Note that the type of the {@code values} provided to this method will
237- * not be validated by the driver as is done by {@link BoundStatement#bind} since
238- * {@code query} is not parsed (and hence the driver cannot know what those value
239- * should be). The codec to serialize each value will be chosen in the codec registry
240- * associated with this session's cluster, based on the value's Java type
241- * (this is the equivalent to calling {@link CodecRegistry#codecFor(Object)}).
242- * If too many or too few values are provided, or if a value is not a valid one for
243- * the variable it is bound to, an
244- * {@link com.datastax.driver.core.exceptions.InvalidQueryException} will be thrown
245- * by Cassandra at execution time. A {@code CodecNotFoundException} may be
246- * thrown by this constructor however, if the codec registry does not know how to
247- * handle one of the values.
248- *
249- * @param query the CQL query to execute.
250- * @param values values required for the execution of {@code query}.
251- * @return the simple statement.
252- */
253- SimpleStatement newSimpleStatement(String query, Object... values);
254-
255193 /**
256194 * Executes the provided query asynchronously.
257195 *
modified driver-core/src/main/java/com/datastax/driver/core/SessionManager.java +17 −16
@@ -478,21 +478,22 @@
478478 // init() locks, so avoid if we know we don't need it.
479479 if (!isInit)
480480 init();
481- ProtocolVersion version = cluster.manager.protocolVersion();
481+ ProtocolVersion protocolVersion = cluster.manager.protocolVersion();
482+ CodecRegistry codecRegistry = cluster.manager.configuration.getCodecRegistry();
482483
483484 ConsistencyLevel consistency = statement.getConsistencyLevel();
484485 if (consistency == null)
485486 consistency = configuration().getQueryOptions().getConsistencyLevel();
486487
487488 ConsistencyLevel serialConsistency = statement.getSerialConsistencyLevel();
488- if (version.compareTo(ProtocolVersion.V3) < 0 && statement instanceof BatchStatement) {
489+ if (protocolVersion.compareTo(ProtocolVersion.V3) < 0 && statement instanceof BatchStatement) {
489490 if (serialConsistency != null)
490- throw new UnsupportedFeatureException(version, "Serial consistency on batch statements is not supported");
491+ throw new UnsupportedFeatureException(protocolVersion, "Serial consistency on batch statements is not supported");
491492 } else if (serialConsistency == null)
492493 serialConsistency = configuration().getQueryOptions().getSerialConsistencyLevel();
493494
494495 long defaultTimestamp = Long.MIN_VALUE;
495- if (cluster.manager.protocolVersion().compareTo(ProtocolVersion.V3) >= 0) {
496+ if (protocolVersion.compareTo(ProtocolVersion.V3) >= 0) {
496497 defaultTimestamp = statement.getDefaultTimestamp();
497498 if (defaultTimestamp == Long.MIN_VALUE)
498499 defaultTimestamp = cluster.getConfiguration().getPolicies().getTimestampGenerator().next();
@@ -501,14 +502,14 @@
501502 int fetchSize = statement.getFetchSize();
502503 ByteBuffer usedPagingState = pagingState;
503504
504- if (version == ProtocolVersion.V1) {
505+ if (protocolVersion == ProtocolVersion.V1) {
505506 assert pagingState == null;
506507 // We don't let the user change the fetchSize globally if the proto v1 is used, so we just need to
507508 // check for the case of a per-statement override
508509 if (fetchSize <= 0)
509510 fetchSize = -1;
510511 else if (fetchSize != Integer.MAX_VALUE)
511- throw new UnsupportedFeatureException(version, "Paging is not supported");
512+ throw new UnsupportedFeatureException(protocolVersion, "Paging is not supported");
512513 } else if (fetchSize <= 0) {
513514 fetchSize = configuration().getQueryOptions().getFetchSize();
514515 }
@@ -531,13 +532,13 @@
531532 // It saddens me that we special case for the query builder here, but for now this is simpler.
532533 // We could provide a general API in RegularStatement instead at some point but it's unclear what's
533534 // the cleanest way to do that is right now (and it's probably not really that useful anyway).
534- if (version == ProtocolVersion.V1 && rs instanceof com.datastax.driver.core.querybuilder.BuiltStatement)
535+ if (protocolVersion == ProtocolVersion.V1 && rs instanceof com.datastax.driver.core.querybuilder.BuiltStatement)
535536 ((com.datastax.driver.core.querybuilder.BuiltStatement)rs).setForceNoValues(true);
536537
537- ByteBuffer[] rawValues = rs.getValues();
538+ ByteBuffer[] rawValues = rs.getValues(protocolVersion, codecRegistry);
538539
539- if (version == ProtocolVersion.V1 && rawValues != null)
540- throw new UnsupportedFeatureException(version, "Binary values are not supported");
540+ if (protocolVersion == ProtocolVersion.V1 && rawValues != null)
541+ throw new UnsupportedFeatureException(protocolVersion, "Binary values are not supported");
541542
542543 List<ByteBuffer> values = rawValues == null ? Collections.<ByteBuffer>emptyList() : Arrays.asList(rawValues);
543544
@@ -552,9 +553,9 @@
552553 throw new InvalidQueryException(String.format("Tried to execute unknown prepared query : %s. "
553554 + "You may have used a PreparedStatement that was created with another Cluster instance.", bs.statement.getPreparedId().id));
554555 }
555- if (version.compareTo(ProtocolVersion.V4) < 0)
556+ if (protocolVersion.compareTo(ProtocolVersion.V4) < 0)
556557 bs.ensureAllSet();
557- boolean skipMetadata = version != ProtocolVersion.V1 && bs.statement.getPreparedId().resultSetMetadata != null;
558+ boolean skipMetadata = protocolVersion != ProtocolVersion.V1 && bs.statement.getPreparedId().resultSetMetadata != null;
558559 Requests.QueryProtocolOptions options = new Requests.QueryProtocolOptions(consistency, Arrays.asList(bs.wrapper.values), skipMetadata,
559560 fetchSize, usedPagingState, serialConsistency, defaultTimestamp);
560561 request = new Requests.Execute(bs.statement.getPreparedId().id, options, statement.isTracing());
@@ -562,13 +563,13 @@
562563 assert statement instanceof BatchStatement : statement;
563564 assert pagingState == null;
564565
565- if (version == ProtocolVersion.V1)
566- throw new UnsupportedFeatureException(version, "Protocol level batching is not supported");
566+ if (protocolVersion == ProtocolVersion.V1)
567+ throw new UnsupportedFeatureException(protocolVersion, "Protocol level batching is not supported");
567568
568569 BatchStatement bs = (BatchStatement)statement;
569- if (version.compareTo(ProtocolVersion.V4) < 0)
570+ if (protocolVersion.compareTo(ProtocolVersion.V4) < 0)
570571 bs.ensureAllSet();
571- BatchStatement.IdAndValues idAndVals = bs.getIdAndValues();
572+ BatchStatement.IdAndValues idAndVals = bs.getIdAndValues(protocolVersion, codecRegistry);
572573 Requests.BatchProtocolOptions options = new Requests.BatchProtocolOptions(consistency, serialConsistency, defaultTimestamp);
573574 request = new Requests.Batch(bs.batchType, idAndVals.ids, idAndVals.values, options, statement.isTracing());
574575 }
modified driver-core/src/main/java/com/datastax/driver/core/SimpleStatement.java +59 −22
@@ -22,49 +22,83 @@
2222 /**
2323 * A simple {@code RegularStatement} implementation built directly from a query
2424 * string.
25- * <p>
26- * Use {@link Session#newSimpleStatement(String)} to create a new instance of this
27- * class.
2825 */
2926 public class SimpleStatement extends RegularStatement {
3027
3128 private final String query;
3229 private final Object[] values;
33- private final Cluster cluster;
3430
3531 private volatile ByteBuffer routingKey;
3632 private volatile String keyspace;
37-
38- protected SimpleStatement(String query, Cluster cluster) {
39- this(query, cluster, (Object[]) null);
33+
34+ /**
35+ * Creates a new {@code SimpleStatement} with the provided query string (and no values).
36+ *
37+ * @param query the query string.
38+ */
39+ public SimpleStatement(String query) {
40+ this(query, (Object[]) null);
4041 }
4142
42- protected SimpleStatement(String query, Cluster cluster, Object... values) {
43+ /**
44+ * Creates a new {@code SimpleStatement} with the provided query string and values.
45+ * <p>
46+ * This version of SimpleStatement is useful when you want to execute a
47+ * query only once (and thus do not want to resort to prepared statement), but
48+ * do not want to convert all column values to string (typically, if you have blob
49+ * values, encoding them to a hexadecimal string is not very efficient). In
50+ * that case, you can provide a query string with bind markers to this constructor
51+ * along with the values for those bind variables. When executed, the server will
52+ * prepare the provided, bind the provided values to that prepare statement and
53+ * execute the resulting statement. Thus,
54+ * <pre>
55+ * session.execute(new SimpleStatement(query, value1, value2, value3));
56+ * </pre>
57+ * is functionally equivalent to
58+ * <pre>
59+ * PreparedStatement ps = session.prepare(query);
60+ * session.execute(ps.bind(value1, value2, value3));
61+ * </pre>
62+ * except that the former version:
63+ * <ul>
64+ * <li>Requires only one round-trip to a Cassandra node.</li>
65+ * <li>Does not left any prepared statement stored in memory (neither client or
66+ * server side) once it has been executed.</li>
67+ * </ul>
68+ * <p>
69+ * Note that the type of the {@code values} provided to this method will
70+ * 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
72+ * 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
74+ * (this is the equivalent to calling {@link CodecRegistry#codecFor(Object)}).
75+ * If too many or too few values are provided, or if a value is not a valid one for
76+ * the variable it is bound to, an
77+ * {@link com.datastax.driver.core.exceptions.InvalidQueryException} will be thrown
78+ * by Cassandra at execution time. A {@code CodecNotFoundException} may be
79+ * thrown by this constructor however, if the codec registry does not know how to
80+ * handle one of the values.
81+ *
82+ * @param query the query string.
83+ * @param values values required for the execution of {@code query}.
84+ * @throws IllegalArgumentException if the number of values is greater than 65535.
85+ */
86+ public SimpleStatement(String query, Object... values) {
4387 if (values != null && values.length > 65535)
4488 throw new IllegalArgumentException("Too many values, the maximum allowed is 65535");
4589 this.query = query;
4690 this.values = values;
47- this.cluster = cluster;
4891 }
4992
5093 @Override
51- public String getQueryString() {
94+ public String getQueryString(CodecRegistry codecRegistry) {
5295 return query;
5396 }
5497
55- /**
56- * {@inheritDoc}
57- * <p>
58- * Note: Calling this method may trigger the underlying {@link Cluster} initialization.
59- */
6098 @Override
61- public ByteBuffer[] getValues() {
99+ public ByteBuffer[] getValues(ProtocolVersion protocolVersion, CodecRegistry codecRegistry) {
62100 if(values == null)
63101 return null;
64- cluster.init();
65- Configuration configuration = cluster.getConfiguration();
66- ProtocolVersion protocolVersion = configuration.getProtocolOptions().getProtocolVersion();
67- CodecRegistry codecRegistry = configuration.getCodecRegistry();
68102 return convert(values, protocolVersion, codecRegistry);
69103 }
70104
@@ -79,7 +113,7 @@
79113 }
80114
81115 @Override
82- public boolean hasValues() {
116+ public boolean hasValues(CodecRegistry codecRegistry) {
83117 return values != null && values.length > 0;
84118 }
85119
@@ -107,13 +141,16 @@
107141 * {@link #setRoutingKey}, this method will return {@code null} to
108142 * avoid having to parse the query string to retrieve the partition key.
109143 *
144+ * @param protocolVersion unused by this implementation (no internal serialization is required to compute the key).
145+ * @param codecRegistry unused by this implementation (no internal serialization is required to compute the key).
146+ *
110147 * @return the routing key set through {@link #setRoutingKey} if such a key
111148 * was set, {@code null} otherwise.
112149 *
113150 * @see Statement#getRoutingKey
114151 */
115152 @Override
116- public ByteBuffer getRoutingKey() {
153+ public ByteBuffer getRoutingKey(ProtocolVersion protocolVersion, CodecRegistry codecRegistry) {
117154 return routingKey;
118155 }
119156
modified driver-core/src/main/java/com/datastax/driver/core/Statement.java +35 −4
@@ -44,7 +44,7 @@
4444 // used when preparing a statement and for other internal queries. Do not expose publicly.
4545 static final Statement DEFAULT = new Statement() {
4646 @Override
47- public ByteBuffer getRoutingKey() {
47+ public ByteBuffer getRoutingKey(ProtocolVersion protocolVersion, CodecRegistry codecRegistry) {
4848 return null;
4949 }
5050
@@ -186,9 +186,15 @@
186186 * to fail and if the load balancing policy used is not token aware, then
187187 * the routing key can be safely ignored.
188188 *
189+ * @param protocolVersion the protocol version that will be used if the actual
190+ * implementation needs to serialize something to compute
191+ * the key.
192+ * @param codecRegistry the codec registry that will be used if the actual
193+ * implementation needs to serialize something to compute
194+ * this key.
189195 * @return the routing key for this query or {@code null}.
190196 */
191- public abstract ByteBuffer getRoutingKey();
197+ public abstract ByteBuffer getRoutingKey(ProtocolVersion protocolVersion, CodecRegistry codecRegistry);
192198
193199 /**
194200 * Returns the keyspace this query operates on.
@@ -368,17 +374,21 @@
368374 *
369375 * @param pagingState the paging state to set, or {@code null} to remove any state that was
370376 * previously set on this statement.
377+ * @param codecRegistry the codec registry that will be used if this method needs to serialize the
378+ * statement's values in order to check that the paging state matches.
371379 * @return this {@code Statement} object.
372380 *
373381 * @throws PagingStateException if the paging state does not match this statement.
382+ *
383+ * @see #setPagingState(PagingState)
374384 */
375- public Statement setPagingState(PagingState pagingState) {
385+ public Statement setPagingState(PagingState pagingState, CodecRegistry codecRegistry) {
376386 if (this instanceof BatchStatement) {
377387 throw new UnsupportedOperationException("Cannot set the paging state on a batch statement");
378388 } else {
379389 if (pagingState == null) {
380390 this.pagingState = null;
381- } else if (pagingState.matches(this)) {
391+ } else if (pagingState.matches(this, codecRegistry)) {
382392 this.pagingState = pagingState.getRawState();
383393 } else {
384394 throw new PagingStateException("Paging state mismatch, "
@@ -389,6 +399,27 @@
389399 return this;
390400 }
391401
402+ /**
403+ * Sets the paging state.
404+ * <p>
405+ * This method calls {@link #setPagingState(PagingState, CodecRegistry)} with {@link CodecRegistry#DEFAULT_INSTANCE}.
406+ * Whether you should use this or the other variant depends on the type of statement this is
407+ * called on:
408+ * <ul>
409+ * <li>for a {@link BoundStatement}, the codec registry isn't actually needed, so it's always safe to
410+ * use this method;</li>
411+ * <li>for a {@link SimpleStatement} or {@link BuiltStatement}, you can use this method if you use no
412+ * custom codecs, or if your custom codecs are registered with the default registry. Otherwise, use
413+ * the other method and provide the registry that contains your codecs.</li>
414+ * </ul>
415+ *
416+ * @param pagingState the paging state to set, or {@code null} to remove any state that was
417+ * previously set on this statement.
418+ */
419+ public Statement setPagingState(PagingState pagingState) {
420+ return setPagingState(pagingState, CodecRegistry.DEFAULT_INSTANCE);
421+ }
422+
392423 /**
393424 * Sets the paging state.
394425 * <p>
modified driver-core/src/main/java/com/datastax/driver/core/StatementWrapper.java +4 −4
@@ -111,8 +111,8 @@
111111 }
112112
113113 @Override
114- public ByteBuffer getRoutingKey() {
115- return wrapped.getRoutingKey();
114+ public ByteBuffer getRoutingKey(ProtocolVersion protocolVersion, CodecRegistry codecRegistry) {
115+ return wrapped.getRoutingKey(protocolVersion, codecRegistry);
116116 }
117117
118118 @Override
@@ -126,8 +126,8 @@
126126 }
127127
128128 @Override
129- public Statement setPagingState(PagingState pagingState) {
130- return wrapped.setPagingState(pagingState);
129+ public Statement setPagingState(PagingState pagingState, CodecRegistry codecRegistry) {
130+ return wrapped.setPagingState(pagingState, codecRegistry);
131131 }
132132
133133 @Override
modified driver-core/src/main/java/com/datastax/driver/core/policies/TokenAwarePolicy.java +6 −2
@@ -50,7 +50,9 @@
5050
5151 private final LoadBalancingPolicy childPolicy;
5252 private final boolean shuffleReplicas;
53- private Metadata clusterMetadata;
53+ private volatile Metadata clusterMetadata;
54+ private volatile ProtocolVersion protocolVersion;
55+ private volatile CodecRegistry codecRegistry;
5456
5557 /**
5658 * Creates a new {@code TokenAware} policy.
@@ -90,6 +92,8 @@
9092 @Override
9193 public void init(Cluster cluster, Collection<Host> hosts) {
9294 clusterMetadata = cluster.getMetadata();
95+ protocolVersion = cluster.getConfiguration().getProtocolOptions().getProtocolVersion();
96+ codecRegistry = cluster.getConfiguration().getCodecRegistry();
9397 childPolicy.init(cluster, hosts);
9498 }
9599
@@ -118,7 +122,7 @@
118122 @Override
119123 public Iterator<Host> newQueryPlan(final String loggedKeyspace, final Statement statement) {
120124
121- ByteBuffer partitionKey = statement.getRoutingKey();
125+ ByteBuffer partitionKey = statement.getRoutingKey(protocolVersion, codecRegistry);
122126 String keyspace = statement.getKeyspace();
123127 if (keyspace == null)
124128 keyspace = loggedKeyspace;
modified driver-core/src/main/java/com/datastax/driver/core/querybuilder/Batch.java +10 −10
@@ -33,8 +33,8 @@
3333 // Only used when we add at last one statement that is not a BuiltStatement subclass
3434 private int nonBuiltStatementValues;
3535
36- Batch(ProtocolVersion protocolVersion, CodecRegistry codecRegistry, RegularStatement[] statements, boolean logged) {
37- super((String)null, protocolVersion, codecRegistry);
36+ Batch(RegularStatement[] statements, boolean logged) {
37+ super((String)null);
3838 this.statements = statements.length == 0
3939 ? new ArrayList<RegularStatement>()
4040 : new ArrayList<RegularStatement>(statements.length);
@@ -46,7 +46,7 @@
4646 }
4747
4848 @Override
49- StringBuilder buildQueryString(List<Object> variables) {
49+ StringBuilder buildQueryString(List<Object> variables, CodecRegistry codecRegistry) {
5050 StringBuilder builder = new StringBuilder();
5151
5252 builder.append(isCounterOp()
@@ -55,7 +55,7 @@
5555
5656 if (!usings.usings.isEmpty()) {
5757 builder.append(" USING ");
58- Utils.joinAndAppend(builder, getCodecRegistry(), " AND ", usings.usings, variables);
58+ Utils.joinAndAppend(builder, codecRegistry, " AND ", usings.usings, variables);
5959 }
6060 builder.append(' ');
6161
@@ -63,7 +63,7 @@
6363 RegularStatement stmt = statements.get(i);
6464 if (stmt instanceof BuiltStatement) {
6565 BuiltStatement bst = (BuiltStatement)stmt;
66- builder.append(maybeAddSemicolon(bst.buildQueryString(variables)));
66+ builder.append(maybeAddSemicolon(bst.buildQueryString(variables, codecRegistry)));
6767
6868 } else {
6969 String str = stmt.getQueryString();
@@ -117,14 +117,14 @@
117117 }
118118
119119 @Override
120- public ByteBuffer[] getValues() {
120+ public ByteBuffer[] getValues(ProtocolVersion protocolVersion, CodecRegistry codecRegistry) {
121121 // If there is some non-BuiltStatement inside the batch with values, we shouldn't
122122 // use super.getValues() since it will ignore the values of said non-BuiltStatement.
123123 // If that's the case, we just collects all those values (and we know
124124 // super.getValues() == null in that case since we've explicitely set this.hasBindMarker
125125 // to true). Otherwise, we simply call super.getValues().
126126 if (nonBuiltStatementValues == 0)
127- return super.getValues();
127+ return super.getValues(protocolVersion, codecRegistry);
128128
129129 ByteBuffer[] values = new ByteBuffer[nonBuiltStatementValues];
130130 int i = 0;
@@ -133,7 +133,7 @@
133133 if (statement instanceof BuiltStatement)
134134 continue;
135135
136- ByteBuffer[] statementValues = statement.getValues();
136+ ByteBuffer[] statementValues = statement.getValues(protocolVersion, codecRegistry);
137137 System.arraycopy(statementValues, 0, values, i, statementValues.length);
138138 i += statementValues.length;
139139 }
@@ -157,9 +157,9 @@
157157 * @return the routing key for this batch statement.
158158 */
159159 @Override
160- public ByteBuffer getRoutingKey() {
160+ public ByteBuffer getRoutingKey(ProtocolVersion protocolVersion, CodecRegistry codecRegistry) {
161161 for (RegularStatement statement : statements) {
162- ByteBuffer routingKey = statement.getRoutingKey();
162+ ByteBuffer routingKey = statement.getRoutingKey(protocolVersion, codecRegistry);
163163 if (routingKey != null) {
164164 return routingKey;
165165 }
modified driver-core/src/main/java/com/datastax/driver/core/querybuilder/BuiltStatement.java +112 −60
@@ -22,10 +22,57 @@
2222 import java.util.regex.Pattern;
2323
2424 import com.datastax.driver.core.*;
25+import com.datastax.driver.core.exceptions.CodecNotFoundException;
2526 import com.datastax.driver.core.policies.RetryPolicy;
2627
2728 /**
28- * Common ancestor to the query builder built statements.
29+ * Common ancestor to statements generated with the {@link QueryBuilder}.
30+ * <p>
31+ * The actual query string will be generated and cached the first time it is requested,
32+ * which is either when the driver tries to execute the query, or when you call certain
33+ * public methods (for example {@link RegularStatement#getQueryString(CodecRegistry)},
34+ * {@link #getObject(int, CodecRegistry)}).
35+ * <p>
36+ * Whenever possible (and unless you call {@link #setForceNoValues(boolean)}, the builder
37+ * will try to handle values passed to its methods as standalone values bound to the query
38+ * string with placeholders. For instance:
39+ * <pre>
40+ * select().all().from("foo").where(eq("k", "the key"));
41+ * // Is equivalent to:
42+ * new SimpleStatement("SELECT * FROM foo WHERE k=?", "the key");
43+ * </pre>
44+ * There are a few exceptions to this rule:
45+ * <ul>
46+ * <li>for fixed-size number types, the builder can't guess what the actual CQL type
47+ * is. Standalone values are sent to Cassandra in their serialized form, and number
48+ * types aren't all serialized in the same way, so picking the wrong type could
49+ * lead to a query error;</li>
50+ * <li>if the value is a "special" element like a function call, it can't be serialized.
51+ * This also applies to collections mixing special elements and regular objects.</li>
52+ * </ul>
53+ * In these cases, the builder will inline the value in the query string:
54+ * <pre>
55+ * select().all().from("foo").where(eq("k", 1));
56+ * // Is equivalent to:
57+ * new SimpleStatement("SELECT * FROM foo WHERE k=1");
58+ * </pre>
59+ * One final thing to consider is {@link CodecRegistry custom codecs}. If you've registered
60+ * codecs to handle your own Java types against the cluster, then you can pass instances of
61+ * those types to query builder methods. But should the builder have to inline those values,
62+ * it needs your codecs to {@link TypeCodec#format(Object) convert them to string form}.
63+ * That is why some of the public methods of this class take a {@code CodecRegistry} as a
64+ * parameter:
65+ * <pre>
66+ * BuiltStatement s = select().all().from("foo").where(eq("k", myCustomObject));
67+ * // if we do this codecs will definitely be needed:
68+ * s.forceNoValues(true);
69+ * s.getQueryString(myCodecRegistry);
70+ * </pre>
71+ * For convenience, there are no-arg versions of those methods that use
72+ * {@link CodecRegistry#DEFAULT_INSTANCE}. But you should only use them if you are sure that
73+ * no custom values will need to be inlined while building the statement, or if you have
74+ * registered your custom codecs with the default registry instance. Otherwise, you will get
75+ * a {@link CodecNotFoundException}.
2976 */
3077 public abstract class BuiltStatement extends RegularStatement {
3178
@@ -34,8 +81,6 @@
3481 private final List<ColumnMetadata> partitionKey;
3582 private final List<Object> routingKeyValues;
3683 final String keyspace;
37- private final ProtocolVersion protocolVersion;
38- private final CodecRegistry codecRegistry;
3984
4085 private boolean dirty;
4186 private String cache;
@@ -48,20 +93,16 @@
4893 boolean hasBindMarkers;
4994 private boolean forceNoValues;
5095
51- BuiltStatement(String keyspace, ProtocolVersion protocolVersion, CodecRegistry codecRegistry) {
96+ BuiltStatement(String keyspace) {
5297 this.partitionKey = null;
5398 this.routingKeyValues = null;
5499 this.keyspace = keyspace;
55- this.protocolVersion = protocolVersion;
56- this.codecRegistry = codecRegistry;
57100 }
58101
59- BuiltStatement(TableMetadata tableMetadata, ProtocolVersion protocolVersion, CodecRegistry codecRegistry) {
102+ BuiltStatement(TableMetadata tableMetadata) {
60103 this.partitionKey = tableMetadata.getPartitionKey();
61104 this.routingKeyValues = Arrays.asList(new Object[tableMetadata.getPartitionKey().size()]);
62105 this.keyspace = escapeId(tableMetadata.getKeyspace().getName());
63- this.protocolVersion = protocolVersion;
64- this.codecRegistry = codecRegistry;
65106 }
66107
67108 // Same as Metadata.escapeId, but we don't have access to it here.
@@ -71,8 +112,8 @@
71112 }
72113
73114 @Override
74- public String getQueryString() {
75- maybeRebuildCache();
115+ public String getQueryString(CodecRegistry codecRegistry) {
116+ maybeRebuildCache(codecRegistry);
76117 return cache;
77118 }
78119
@@ -80,21 +121,45 @@
80121 * Returns the {@code i}th value as the Java type matching its CQL type.
81122 *
82123 * @param i the index to retrieve.
124+ * @param codecRegistry the codec registry that will be used if the statement must be
125+ * rebuilt in order to determine if it has values, and Java objects
126+ * must be inlined in the process (see {@link BuiltStatement} for
127+ * more explanations on why this is so).
83128 * @return the value of the {@code i}th value of this statement.
84129 *
85130 * @throws IllegalStateException if this statement does not have values.
86131 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
132+ *
133+ * @see #getObject(int)
87134 */
88- public Object getObject(int i) {
89- maybeRebuildCache();
135+ public Object getObject(int i, CodecRegistry codecRegistry) {
136+ maybeRebuildCache(codecRegistry);
90137 if (values == null || values.isEmpty())
91138 throw new IllegalStateException("This statement does not have values");
92139 if (i < 0 || i >= values.size())
93140 throw new ArrayIndexOutOfBoundsException(i);
94141 return values.get(i);
95142 }
143+ /**
144+ * Returns the {@code i}th value as the Java type matching its CQL type.
145+ * <p>
146+ * This method calls {@link #getObject(int, CodecRegistry)} with
147+ * {@link CodecRegistry#DEFAULT_INSTANCE}.
148+ * It's safe to use if you don't use any custom codecs, or if your custom codecs are in
149+ * the default registry; otherwise, use the other method and provide the registry that
150+ * contains your codecs.
151+ *
152+ * @param i the index to retrieve.
153+ * @return the value of the {@code i}th value of this statement.
154+ *
155+ * @throws IllegalStateException if this statement does not have values.
156+ * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
157+ */
158+ public Object getObject(int i) {
159+ return getObject(i, CodecRegistry.DEFAULT_INSTANCE);
160+ }
96161
97- private void maybeRebuildCache() {
162+ private void maybeRebuildCache(CodecRegistry codecRegistry) {
98163 if (!dirty && cache != null)
99164 return;
100165
@@ -102,10 +167,10 @@
102167 values = null;
103168
104169 if (hasBindMarkers || forceNoValues) {
105- sb = buildQueryString(null);
170+ sb = buildQueryString(null, codecRegistry);
106171 } else {
107172 values = new ArrayList<Object>();
108- sb = buildQueryString(values);
173+ sb = buildQueryString(values, codecRegistry);
109174
110175 if (values.size() > 65535)
111176 throw new IllegalArgumentException("Too many values for built statement, the maximum allowed is 65535");
@@ -134,7 +199,7 @@
134199 return sb;
135200 }
136201
137- abstract StringBuilder buildQueryString(List<Object> variables);
202+ abstract StringBuilder buildQueryString(List<Object> variables, CodecRegistry codecRegistry);
138203
139204 boolean isCounterOp() {
140205 return isCounterOp == null ? false : isCounterOp;
@@ -177,26 +242,17 @@
177242 }
178243 }
179244
180- CodecRegistry getCodecRegistry(){
181- return codecRegistry;
182- }
183-
184- ProtocolVersion getProtocolVersion() {
185- return protocolVersion;
186- }
187-
188245 @Override
189- public ByteBuffer getRoutingKey() {
246+ public ByteBuffer getRoutingKey(ProtocolVersion protocolVersion, CodecRegistry codecRegistry) {
190247 if (routingKeyValues == null)
191248 return null;
192249 ByteBuffer[] routingKeyParts = new ByteBuffer[partitionKey.size()];
193- CodecRegistry codecRegistry = getCodecRegistry();
194250 for (int i = 0; i < partitionKey.size(); i++) {
195251 Object value = routingKeyValues.get(i);
196252 if(value == null)
197253 return null;
198254 TypeCodec<Object> codec = codecRegistry.codecFor(partitionKey.get(i).getType(), value);
199- routingKeyParts[i] = codec.serialize(value, getProtocolVersion());
255+ routingKeyParts[i] = codec.serialize(value, protocolVersion);
200256 }
201257 return routingKeyParts.length == 1
202258 ? routingKeyParts[0]
@@ -208,20 +264,15 @@
208264 return keyspace;
209265 }
210266
211- /**
212- * {@inheritDoc}
213- * <p>
214- * Note: Calling this method may trigger the underlying {@link Cluster} initialization.
215- */
216267 @Override
217- public ByteBuffer[] getValues() {
218- maybeRebuildCache();
219- return values == null ? null : Utils.convert(values.toArray(), getProtocolVersion(), getCodecRegistry());
268+ public ByteBuffer[] getValues(ProtocolVersion protocolVersion, CodecRegistry codecRegistry) {
269+ maybeRebuildCache(codecRegistry);
270+ return values == null ? null : Utils.convert(values.toArray(), protocolVersion, codecRegistry);
220271 }
221272
222273 @Override
223- public boolean hasValues() {
224- maybeRebuildCache();
274+ public boolean hasValues(CodecRegistry codecRegistry) {
275+ maybeRebuildCache(codecRegistry);
225276 return values != null;
226277 }
227278
@@ -235,17 +286,18 @@
235286 return !hasNonIdempotentOps();
236287 }
237288
238- /**
239- * {@inheritDoc}
240- * <p>
241- * Note: Calling this method may trigger the underlying {@link Cluster} initialization.
242- */
243289 @Override
244290 public String toString() {
245- if (forceNoValues) {
246- return getQueryString();
291+ try {
292+ if (forceNoValues) {
293+ return getQueryString();
294+ }
295+ StringBuilder queryString = buildQueryString(null, CodecRegistry.DEFAULT_INSTANCE);
296+ return maybeAddSemicolon(queryString).toString();
297+ } catch (CodecNotFoundException e) {
298+ // Ugly but we have absolutely no context to get the registry from
299+ return String.format("built query (could not generate with default codec registry: %s)", e.getMessage());
247300 }
248- return maybeAddSemicolon(buildQueryString(null)).toString();
249301 }
250302
251303 /**
@@ -253,16 +305,16 @@
253305 * <p>
254306 * By default (and unless the protocol version 1 is in use, see below) and
255307 * for performance reasons, the query builder will not serialize all values
256- * provided to strings. This means that the {@link #getQueryString} may
257- * return a query string with bind markers (where and when is at the
308+ * provided to strings. This means that {@link #getQueryString(CodecRegistry)}
309+ * may return a query string with bind markers (where and when is at the
258310 * discretion of the builder) and {@link #getValues} will return the binary
259311 * values for those markers. This method allows to force the builder to not
260- * generate binary values but rather to serialize them all in the query
312+ * generate binary values but rather to inline them all in the query
261313 * string. In practice, this means that if you call {@code
262314 * setForceNoValues(true)}, you are guaranteed that {@code getValues()} will
263315 * return {@code null} and that the string returned by {@code
264- * getQueryString()} will contain no other bind markers than the one
265- * inputted by the user.
316+ * getQueryString()} will contain no other bind markers than the ones
317+ * specified by the user.
266318 * <p>
267319 * If the native protocol version 1 is in use, the driver will default
268320 * to not generating values since those are not supported by that version of
@@ -290,23 +342,23 @@
290342 T statement;
291343
292344 ForwardingStatement(T statement) {
293- super((String)null, statement.getProtocolVersion(), statement.getCodecRegistry());
345+ super((String)null);
294346 this.statement = statement;
295347 }
296348
297349 @Override
298- public String getQueryString() {
299- return statement.getQueryString();
350+ public String getQueryString(CodecRegistry codecRegistry) {
351+ return statement.getQueryString(codecRegistry);
300352 }
301353
302354 @Override
303- StringBuilder buildQueryString(List<Object> values) {
304- return statement.buildQueryString(values);
355+ StringBuilder buildQueryString(List<Object> values, CodecRegistry codecRegistry) {
356+ return statement.buildQueryString(values, codecRegistry);
305357 }
306358
307359 @Override
308- public ByteBuffer getRoutingKey() {
309- return statement.getRoutingKey();
360+ public ByteBuffer getRoutingKey(ProtocolVersion protocolVersion, CodecRegistry codecRegistry) {
361+ return statement.getRoutingKey(protocolVersion, codecRegistry);
310362 }
311363
312364 @Override
@@ -370,8 +422,8 @@
370422 }
371423
372424 @Override
373- public ByteBuffer[] getValues() {
374- return statement.getValues();
425+ public ByteBuffer[] getValues(ProtocolVersion protocolVersion, CodecRegistry codecRegistry) {
426+ return statement.getValues(protocolVersion, codecRegistry);
375427 }
376428
377429 @Override
modified driver-core/src/main/java/com/datastax/driver/core/querybuilder/Delete.java +9 −23
@@ -18,9 +18,7 @@
1818 import java.util.ArrayList;
1919 import java.util.List;
2020
21-import com.datastax.driver.core.Cluster;
2221 import com.datastax.driver.core.CodecRegistry;
23-import com.datastax.driver.core.ProtocolVersion;
2422 import com.datastax.driver.core.TableMetadata;
2523
2624 /**
@@ -35,8 +33,8 @@
3533 private final Conditions conditions;
3634 private boolean ifExists;
3735
38- Delete(ProtocolVersion protocolVersion, CodecRegistry codecRegistry, String keyspace, String table, List<Selector> columns) {
39- super(keyspace, protocolVersion, codecRegistry);
36+ Delete(String keyspace, String table, List<Selector> columns) {
37+ super(keyspace);
4038 this.table = table;
4139 this.columns = columns;
4240 this.where = new Where(this);
@@ -44,8 +42,8 @@
4442 this.conditions = new Conditions(this);
4543 }
4644
47- Delete(ProtocolVersion protocolVersion, CodecRegistry codecRegistry, TableMetadata table, List<Selector> columns) {
48- super(table, protocolVersion, codecRegistry);
45+ Delete(TableMetadata table, List<Selector> columns) {
46+ super(table);
4947 this.table = escapeId(table.getName());
5048 this.columns = columns;
5149 this.where = new Where(this);
@@ -54,10 +52,9 @@
5452 }
5553
5654 @Override
57- StringBuilder buildQueryString(List<Object> variables) {
55+ StringBuilder buildQueryString(List<Object> variables, CodecRegistry codecRegistry) {
5856 StringBuilder builder = new StringBuilder();
5957
60- CodecRegistry codecRegistry = getCodecRegistry();
6158 builder.append("DELETE");
6259 if (!columns.isEmpty())
6360 Utils.joinAndAppend(builder.append(" "), codecRegistry, ",", columns, variables);
@@ -278,19 +275,12 @@
278275 */
279276 public static class Builder {
280277
281- private final ProtocolVersion protocolVersion;
282- private final CodecRegistry codecRegistry;
283-
284278 List<Selector> columns = new ArrayList<Selector>();
285279
286- Builder(ProtocolVersion protocolVersion, CodecRegistry codecRegistry) {
287- this.protocolVersion = protocolVersion;
288- this.codecRegistry = codecRegistry;
280+ Builder() {
289281 }
290282
291- Builder(ProtocolVersion protocolVersion, CodecRegistry codecRegistry, String... columnNames) {
292- this.protocolVersion = protocolVersion;
293- this.codecRegistry = codecRegistry;
283+ Builder(String... columnNames) {
294284 for (String columnName : columnNames) {
295285 this.columns.add(new Selector(columnName));
296286 }
@@ -314,7 +304,7 @@
314304 * @return a newly built DELETE statement that deletes from {@code keyspace.table}.
315305 */
316306 public Delete from(String keyspace, String table) {
317- return new Delete(protocolVersion, codecRegistry, keyspace, table, columns);
307+ return new Delete(keyspace, table, columns);
318308 }
319309
320310 /**
@@ -324,7 +314,7 @@
324314 * @return a newly built DELETE statement that deletes from {@code table}.
325315 */
326316 public Delete from(TableMetadata table) {
327- return new Delete(protocolVersion, codecRegistry, table, columns);
317+ return new Delete(table, columns);
328318 }
329319 }
330320
@@ -333,10 +323,6 @@
333323 */
334324 public static class Selection extends Builder {
335325
336- Selection(ProtocolVersion protocolVersion, CodecRegistry codecRegistry) {
337- super(protocolVersion, codecRegistry);
338- }
339-
340326 /**
341327 * Deletes all columns (i.e. "DELETE FROM ...")
342328 *
modified driver-core/src/main/java/com/datastax/driver/core/querybuilder/Insert.java +5 −8
@@ -19,9 +19,7 @@
1919 import java.util.Arrays;
2020 import java.util.List;
2121
22-import com.datastax.driver.core.Cluster;
2322 import com.datastax.driver.core.CodecRegistry;
24-import com.datastax.driver.core.ProtocolVersion;
2523 import com.datastax.driver.core.TableMetadata;
2624
2725 /**
@@ -35,23 +33,22 @@
3533 private final Options usings;
3634 private boolean ifNotExists;
3735
38- Insert(ProtocolVersion protocolVersion, CodecRegistry codecRegistry, String keyspace, String table) {
39- super(keyspace, protocolVersion, codecRegistry);
36+ Insert(String keyspace, String table) {
37+ super(keyspace);
4038 this.table = table;
4139 this.usings = new Options(this);
4240 }
4341
44- Insert(ProtocolVersion protocolVersion, CodecRegistry codecRegistry, TableMetadata table) {
45- super(table, protocolVersion, codecRegistry);
42+ Insert(TableMetadata table) {
43+ super(table);
4644 this.table = escapeId(table.getName());
4745 this.usings = new Options(this);
4846 }
4947
5048 @Override
51- StringBuilder buildQueryString(List<Object> variables) {
49+ StringBuilder buildQueryString(List<Object> variables, CodecRegistry codecRegistry) {
5250 StringBuilder builder = new StringBuilder();
5351
54- CodecRegistry codecRegistry = getCodecRegistry();
5552 builder.append("INSERT INTO ");
5653 if (keyspace != null)
5754 Utils.appendName(keyspace, builder).append('.');
modified driver-core/src/main/java/com/datastax/driver/core/querybuilder/QueryBuilder.java +31 −65
@@ -38,41 +38,7 @@
3838 */
3939 public final class QueryBuilder {
4040
41- private final ProtocolVersion protocolVersion;
42- private final CodecRegistry codecRegistry;
43-
44- /**
45- * Create a new QueryBuilder instance and associate it with the given {@link Cluster}.
46- * Note: if the {@link Cluster} is not yet initialized, this method
47- * will trigger its initialization.
48- *
49- * @param cluster The {@link Cluster} instance this object should be attached to.
50- */
51- public QueryBuilder(Cluster cluster) {
52- this(getProtocolVersion(cluster), cluster.getConfiguration().getCodecRegistry());
53- }
54-
55- private static ProtocolVersion getProtocolVersion(Cluster cluster) {
56- cluster.init();
57- return cluster.getConfiguration().getProtocolOptions().getProtocolVersion();
58- }
59-
60- /**
61- * Create a "disconnected" QueryBuilder instance (<b>you should prefer
62- * {@link #QueryBuilder(Cluster)} whenever possible</b>).
63- * <p>
64- * This constructor is only exposed for situations where you don't have a {@code Cluster}
65- * instance available. If you use this constructor, and use statements built from it
66- * with a {@code Cluster} later, you won't be able to rely on custom codecs registered
67- * against the cluster, or you might get errors if the protocol versions don't match.
68- *
69- * @param protocolVersion the protocol version.
70- * @param codecRegistry the codec registry.
71- */
72- public QueryBuilder(ProtocolVersion protocolVersion, CodecRegistry codecRegistry) {
73- this.protocolVersion = protocolVersion;
74- this.codecRegistry = codecRegistry;
75- }
41+ private QueryBuilder() {}
7642
7743 /**
7844 * Start building a new SELECT query that selects the provided names.
@@ -83,8 +49,8 @@
8349 * @return an in-construction SELECT query (you will need to provide at
8450 * least a FROM clause to complete the query).
8551 */
86- public Select.Builder select(String... columns) {
87- return new Select.Builder(protocolVersion, codecRegistry, Arrays.asList((Object[])columns));
52+ public static Select.Builder select(String... columns) {
53+ return new Select.Builder(Arrays.asList((Object[])columns));
8854 }
8955
9056 /**
@@ -93,9 +59,9 @@
9359 * @return an in-construction SELECT query (you will need to provide a
9460 * column selection and at least a FROM clause to complete the query).
9561 */
96- public Select.Selection select() {
62+ public static Select.Selection select() {
9763 // Note: the fact we return Select.Selection as return type is on purpose.
98- return new Select.SelectionOrAlias(protocolVersion, codecRegistry);
64+ return new Select.SelectionOrAlias();
9965 }
10066
10167 /**
@@ -104,8 +70,8 @@
10470 * @param table the name of the table in which to insert.
10571 * @return an in-construction INSERT query.
10672 */
107- public Insert insertInto(String table) {
108- return new Insert(protocolVersion, codecRegistry, null, table);
73+ public static Insert insertInto(String table) {
74+ return new Insert(null, table);
10975 }
11076
11177 /**
@@ -115,8 +81,8 @@
11581 * @param table the name of the table to insert into.
11682 * @return an in-construction INSERT query.
11783 */
118- public Insert insertInto(String keyspace, String table) {
119- return new Insert(protocolVersion, codecRegistry, keyspace, table);
84+ public static Insert insertInto(String keyspace, String table) {
85+ return new Insert(keyspace, table);
12086 }
12187
12288 /**
@@ -125,8 +91,8 @@
12591 * @param table the name of the table to insert into.
12692 * @return an in-construction INSERT query.
12793 */
128- public Insert insertInto(TableMetadata table) {
129- return new Insert(protocolVersion, codecRegistry, table);
94+ public static Insert insertInto(TableMetadata table) {
95+ return new Insert(table);
13096 }
13197
13298 /**
@@ -136,8 +102,8 @@
136102 * @return an in-construction UPDATE query (at least a SET and a WHERE
137103 * clause needs to be provided to complete the query).
138104 */
139- public Update update(String table) {
140- return new Update(protocolVersion, codecRegistry, null, table);
105+ public static Update update(String table) {
106+ return new Update(null, table);
141107 }
142108
143109 /**
@@ -148,8 +114,8 @@
148114 * @return an in-construction UPDATE query (at least a SET and a WHERE
149115 * clause needs to be provided to complete the query).
150116 */
151- public Update update(String keyspace, String table) {
152- return new Update(protocolVersion, codecRegistry, keyspace, table);
117+ public static Update update(String keyspace, String table) {
118+ return new Update(keyspace, table);
153119 }
154120
155121 /**
@@ -159,8 +125,8 @@
159125 * @return an in-construction UPDATE query (at least a SET and a WHERE
160126 * clause needs to be provided to complete the query).
161127 */
162- public Update update(TableMetadata table) {
163- return new Update(protocolVersion, codecRegistry, table);
128+ public static Update update(TableMetadata table) {
129+ return new Update(table);
164130 }
165131
166132 /**
@@ -170,8 +136,8 @@
170136 * @return an in-construction DELETE query (At least a FROM and a WHERE
171137 * clause needs to be provided to complete the query).
172138 */
173- public Delete.Builder delete(String... columns) {
174- return new Delete.Builder(protocolVersion, codecRegistry, columns);
139+ public static Delete.Builder delete(String... columns) {
140+ return new Delete.Builder(columns);
175141 }
176142
177143 /**
@@ -181,8 +147,8 @@
181147 * column selection and at least a FROM and a WHERE clause to complete the
182148 * query).
183149 */
184- public Delete.Selection delete() {
185- return new Delete.Selection(protocolVersion, codecRegistry);
150+ public static Delete.Selection delete() {
151+ return new Delete.Selection();
186152 }
187153
188154 /**
@@ -198,8 +164,8 @@
198164 * @param statements the statements to batch.
199165 * @return a new {@code RegularStatement} that batch {@code statements}.
200166 */
201- public Batch batch(RegularStatement... statements) {
202- return new Batch(protocolVersion, codecRegistry, statements, true);
167+ public static Batch batch(RegularStatement... statements) {
168+ return new Batch(statements, true);
203169 }
204170
205171 /**
@@ -219,8 +185,8 @@
219185 * @return a new {@code RegularStatement} that batch {@code statements} without
220186 * using the batch log.
221187 */
222- public Batch unloggedBatch(RegularStatement... statements) {
223- return new Batch(protocolVersion, codecRegistry, statements, false);
188+ public static Batch unloggedBatch(RegularStatement... statements) {
189+ return new Batch(statements, false);
224190 }
225191
226192 /**
@@ -229,8 +195,8 @@
229195 * @param table the name of the table to truncate.
230196 * @return the truncation query.
231197 */
232- public Truncate truncate(String table) {
233- return new Truncate(protocolVersion, codecRegistry, null, table);
198+ public static Truncate truncate(String table) {
199+ return new Truncate(null, table);
234200 }
235201
236202 /**
@@ -240,8 +206,8 @@
240206 * @param table the name of the table to truncate.
241207 * @return the truncation query.
242208 */
243- public Truncate truncate(String keyspace, String table) {
244- return new Truncate(protocolVersion, codecRegistry, keyspace, table);
209+ public static Truncate truncate(String keyspace, String table) {
210+ return new Truncate(keyspace, table);
245211 }
246212
247213 /**
@@ -250,8 +216,8 @@
250216 * @param table the table to truncate.
251217 * @return the truncation query.
252218 */
253- public Truncate truncate(TableMetadata table) {
254- return new Truncate(protocolVersion, codecRegistry, table);
219+ public static Truncate truncate(TableMetadata table) {
220+ return new Truncate(table);
255221 }
256222
257223 /**
modified driver-core/src/main/java/com/datastax/driver/core/querybuilder/Select.java +9 −26
@@ -20,9 +20,7 @@
2020 import java.util.Collections;
2121 import java.util.List;
2222
23-import com.datastax.driver.core.Cluster;
2423 import com.datastax.driver.core.CodecRegistry;
25-import com.datastax.driver.core.ProtocolVersion;
2624 import com.datastax.driver.core.TableMetadata;
2725
2826 /**
@@ -40,16 +38,16 @@
4038 private Object limit;
4139 private boolean allowFiltering;
4240
43- Select(ProtocolVersion protocolVersion, CodecRegistry codecRegistry, String keyspace, String table, List<Object> columnNames, boolean isDistinct) {
44- super(keyspace, protocolVersion, codecRegistry);
41+ Select(String keyspace, String table, List<Object> columnNames, boolean isDistinct) {
42+ super(keyspace);
4543 this.table = table;
4644 this.isDistinct = isDistinct;
4745 this.columnNames = columnNames;
4846 this.where = new Where(this);
4947 }
5048
51- Select(ProtocolVersion protocolVersion, CodecRegistry codecRegistry, TableMetadata table, List<Object> columnNames, boolean isDistinct) {
52- super(table, protocolVersion, codecRegistry);
49+ Select(TableMetadata table, List<Object> columnNames, boolean isDistinct) {
50+ super(table);
5351 this.table = escapeId(table.getName());
5452 this.isDistinct = isDistinct;
5553 this.columnNames = columnNames;
@@ -57,10 +55,9 @@
5755 }
5856
5957 @Override
60- StringBuilder buildQueryString(List<Object> variables) {
58+ StringBuilder buildQueryString(List<Object> variables, CodecRegistry codecRegistry) {
6159 StringBuilder builder = new StringBuilder();
6260
63- CodecRegistry codecRegistry = getCodecRegistry();
6461 builder.append("SELECT ");
6562 if (isDistinct)
6663 builder.append("DISTINCT ");
@@ -258,19 +255,13 @@
258255 */
259256 public static class Builder {
260257
261- private final ProtocolVersion protocolVersion;
262- private final CodecRegistry codecRegistry;
263258 List<Object> columnNames;
264259 boolean isDistinct;
265260
266- Builder(ProtocolVersion protocolVersion, CodecRegistry codecRegistry) {
267- this.protocolVersion = protocolVersion;
268- this.codecRegistry = codecRegistry;
261+ Builder() {
269262 }
270263
271- Builder(ProtocolVersion protocolVersion, CodecRegistry codecRegistry, List<Object> columnNames) {
272- this.protocolVersion = protocolVersion;
273- this.codecRegistry = codecRegistry;
264+ Builder(List<Object> columnNames) {
274265 this.columnNames = columnNames;
275266 }
276267
@@ -302,7 +293,7 @@
302293 * @return a newly built SELECT statement that selects from {@code keyspace.table}.
303294 */
304295 public Select from(String keyspace, String table) {
305- return new Select(protocolVersion, codecRegistry, keyspace, table, columnNames, isDistinct);
296+ return new Select(keyspace, table, columnNames, isDistinct);
306297 }
307298
308299 /**
@@ -312,7 +303,7 @@
312303 * @return a newly built SELECT statement that selects from {@code table}.
313304 */
314305 public Select from(TableMetadata table) {
315- return new Select(protocolVersion, codecRegistry, table, columnNames, isDistinct);
306+ return new Select(table, columnNames, isDistinct);
316307 }
317308 }
318309
@@ -321,10 +312,6 @@
321312 */
322313 public static abstract class Selection extends Builder {
323314
324- Selection(ProtocolVersion protocolVersion, CodecRegistry codecRegistry) {
325- super(protocolVersion, codecRegistry);
326- }
327-
328315 /**
329316 * Uses DISTINCT selection.
330317 *
@@ -409,10 +396,6 @@
409396
410397 private Object previousSelection;
411398
412- SelectionOrAlias(ProtocolVersion protocolVersion, CodecRegistry codecRegistry) {
413- super(protocolVersion, codecRegistry);
414- }
415-
416399 /**
417400 * Adds an alias for the just selected item.
418401 *
modified driver-core/src/main/java/com/datastax/driver/core/querybuilder/Truncate.java +5 −7
@@ -17,9 +17,7 @@
1717
1818 import java.util.List;
1919
20-import com.datastax.driver.core.Cluster;
2120 import com.datastax.driver.core.CodecRegistry;
22-import com.datastax.driver.core.ProtocolVersion;
2321 import com.datastax.driver.core.TableMetadata;
2422
2523 /**
@@ -29,18 +27,18 @@
2927
3028 private final String table;
3129
32- Truncate(ProtocolVersion protocolVersion, CodecRegistry codecRegistry, String keyspace, String table) {
33- super(keyspace, protocolVersion, codecRegistry);
30+ Truncate(String keyspace, String table) {
31+ super(keyspace);
3432 this.table = table;
3533 }
3634
37- Truncate(ProtocolVersion protocolVersion, CodecRegistry codecRegistry, TableMetadata table) {
38- super(table, protocolVersion, codecRegistry);
35+ Truncate(TableMetadata table) {
36+ super(table);
3937 this.table = escapeId(table.getName());
4038 }
4139
4240 @Override
43- protected StringBuilder buildQueryString(List<Object> variables) {
41+ protected StringBuilder buildQueryString(List<Object> variables, CodecRegistry codecRegistry) {
4442 StringBuilder builder = new StringBuilder();
4543
4644 builder.append("TRUNCATE ");
modified driver-core/src/main/java/com/datastax/driver/core/querybuilder/Update.java +5 −8
@@ -18,9 +18,7 @@
1818 import java.util.ArrayList;
1919 import java.util.List;
2020
21-import com.datastax.driver.core.Cluster;
2221 import com.datastax.driver.core.CodecRegistry;
23-import com.datastax.driver.core.ProtocolVersion;
2422 import com.datastax.driver.core.TableMetadata;
2523 import com.datastax.driver.core.querybuilder.Assignment.CounterAssignment;
2624
@@ -36,8 +34,8 @@
3634 private final Conditions conditions;
3735 private boolean ifExists;
3836
39- Update(ProtocolVersion protocolVersion, CodecRegistry codecRegistry, String keyspace, String table) {
40- super(keyspace, protocolVersion, codecRegistry);
37+ Update(String keyspace, String table) {
38+ super(keyspace);
4139 this.table = table;
4240 this.assignments = new Assignments(this);
4341 this.where = new Where(this);
@@ -46,8 +44,8 @@
4644 this.ifExists = false;
4745 }
4846
49- Update(ProtocolVersion protocolVersion, CodecRegistry codecRegistry, TableMetadata table) {
50- super(table, protocolVersion, codecRegistry);
47+ Update(TableMetadata table) {
48+ super(table);
5149 this.table = escapeId(table.getName());
5250 this.assignments = new Assignments(this);
5351 this.where = new Where(this);
@@ -57,7 +55,7 @@
5755 }
5856
5957 @Override
60- StringBuilder buildQueryString(List<Object> variables) {
58+ StringBuilder buildQueryString(List<Object> variables, CodecRegistry codecRegistry) {
6159 StringBuilder builder = new StringBuilder();
6260
6361 builder.append("UPDATE ");
@@ -65,7 +63,6 @@
6563 Utils.appendName(keyspace, builder).append('.');
6664 Utils.appendName(table, builder);
6765
68- CodecRegistry codecRegistry = getCodecRegistry();
6966 if (!usings.usings.isEmpty()) {
7067 builder.append(" USING ");
7168 Utils.joinAndAppend(builder, codecRegistry, " AND ", usings.usings, variables);
modified driver-core/src/main/java/com/datastax/driver/core/schemabuilder/SchemaStatement.java +12 −4
@@ -21,6 +21,8 @@
2121
2222 import com.google.common.base.Strings;
2323
24+import com.datastax.driver.core.CodecRegistry;
25+import com.datastax.driver.core.ProtocolVersion;
2426 import com.datastax.driver.core.RegularStatement;
2527
2628 /**
@@ -42,7 +44,7 @@
4244 abstract String buildInternal();
4345
4446 @Override
45- public String getQueryString() {
47+ public String getQueryString(CodecRegistry codecRegistry) {
4648 if (cache == null) {
4749 cache = buildInternal();
4850 }
@@ -50,13 +52,13 @@
5052 }
5153
5254 @Override
53- public ByteBuffer[] getValues() {
55+ public ByteBuffer[] getValues(ProtocolVersion protocolVersion, CodecRegistry codecRegistry) {
5456 // DDL statements never have values
5557 return new ByteBuffer[0];
5658 }
5759
5860 @Override
59- public boolean hasValues() {
61+ public boolean hasValues(CodecRegistry codecRegistry) {
6062 return false;
6163 }
6264
@@ -67,8 +69,14 @@
6769 return null;
6870 }
6971
72+ /**
73+ * {@inheritDoc}
74+ *
75+ * @param protocolVersion unused by this implementation (the key is always null for schema statements).
76+ * @param codecRegistry unused by this implementation (the key is always null for schema statements).
77+ */
7078 @Override
71- public ByteBuffer getRoutingKey() {
79+ public ByteBuffer getRoutingKey(ProtocolVersion protocolVersion, CodecRegistry codecRegistry) {
7280 return null; // there is no token awareness for DDL statements
7381 }
7482
modified driver-core/src/test/java/com/datastax/driver/core/AbstractPoliciesTest.java +6 −6
@@ -24,12 +24,12 @@
2424 import static org.testng.Assert.assertTrue;
2525 import static org.testng.Assert.fail;
2626
27-import com.datastax.driver.core.querybuilder.QueryBuilder;
28-
2927 import static com.datastax.driver.core.TestUtils.CREATE_KEYSPACE_GENERIC_FORMAT;
3028 import static com.datastax.driver.core.TestUtils.CREATE_KEYSPACE_SIMPLE_FORMAT;
3129 import static com.datastax.driver.core.TestUtils.SIMPLE_KEYSPACE;
3230 import static com.datastax.driver.core.TestUtils.SIMPLE_TABLE;
31+import static com.datastax.driver.core.querybuilder.QueryBuilder.batch;
32+import static com.datastax.driver.core.querybuilder.QueryBuilder.insertInto;
3333
3434 public abstract class AbstractPoliciesTest {
3535 private static final boolean DEBUG = false;
@@ -184,11 +184,11 @@
184184 for (int i = 0; i < n; ++i)
185185 if (batch)
186186 // BUG: WriteType == SIMPLE
187- c.session.execute(new QueryBuilder(c.cluster).batch()
188- .add(new QueryBuilder(c.cluster).insertInto(SIMPLE_TABLE).values(new String[]{ "k", "i"}, new Object[]{ 0, 0 }))
187+ c.session.execute(batch()
188+ .add(insertInto(SIMPLE_TABLE).values(new String[]{ "k", "i"}, new Object[]{ 0, 0 }))
189189 .setConsistencyLevel(cl));
190190 else
191- c.session.execute(c.session.newSimpleStatement(String.format("INSERT INTO %s(k, i) VALUES (0, 0)", SIMPLE_TABLE)).setConsistencyLevel(cl));
191+ c.session.execute(new SimpleStatement(String.format("INSERT INTO %s(k, i) VALUES (0, 0)", SIMPLE_TABLE)).setConsistencyLevel(cl));
192192 }
193193
194194
@@ -216,7 +216,7 @@
216216 ByteBuffer routingKey = ByteBuffer.allocate(4);
217217 routingKey.putInt(0, 0);
218218 for (int i = 0; i < n; ++i)
219- addCoordinator(c.session.execute(c.session.newSimpleStatement(String.format("SELECT * FROM %s WHERE k = 0", SIMPLE_TABLE)).setRoutingKey(routingKey).setConsistencyLevel(cl)));
219+ addCoordinator(c.session.execute(new SimpleStatement(String.format("SELECT * FROM %s WHERE k = 0", SIMPLE_TABLE)).setRoutingKey(routingKey).setConsistencyLevel(cl)));
220220 }
221221 }
222222 }
modified driver-core/src/test/java/com/datastax/driver/core/AsyncResultSetTest.java +1 −1
@@ -57,7 +57,7 @@
5757 for (int i = 0; i < totalCount; i++)
5858 session.execute(String.format("insert into ints (i) values (%d)", i));
5959
60- Statement statement = session.newSimpleStatement("select * from ints").setFetchSize(fetchSize);
60+ Statement statement = new SimpleStatement("select * from ints").setFetchSize(fetchSize);
6161 ResultsAccumulator results = new ResultsAccumulator();
6262
6363 ListenableFuture<ResultSet> future = Futures.transform(
modified driver-core/src/test/java/com/datastax/driver/core/BatchStatementTest.java +2 −2
@@ -40,7 +40,7 @@
4040
4141 BatchStatement batch = new BatchStatement();
4242
43- batch.add(session.newSimpleStatement("INSERT INTO test (k, v) VALUES (?, ?)", "key1", 0));
43+ batch.add(new SimpleStatement("INSERT INTO test (k, v) VALUES (?, ?)", "key1", 0));
4444 batch.add(st.bind("key1", 1));
4545 batch.add(st.bind("key2", 0));
4646
@@ -87,7 +87,7 @@
8787
8888 BatchStatement batch = new BatchStatement();
8989
90- batch.add(session.newSimpleStatement("INSERT INTO test (k, v) VALUES (?, ?)", "key1", 0));
90+ batch.add(new SimpleStatement("INSERT INTO test (k, v) VALUES (?, ?)", "key1", 0));
9191 batch.add(st.bind("key1", 1));
9292 batch.add(st.bind("key1", 2));
9393
modified driver-core/src/test/java/com/datastax/driver/core/ConditionalUpdateTest.java +1 −1
@@ -78,7 +78,7 @@
7878
7979 // This is really contrived, we just want to cover the code path in ArrayBackedResultSet#MultiPage.
8080 // Currently CAS update results are never multipage, so it's hard to come up with a meaningful example.
81- ResultSet rs = session.execute(session.newSimpleStatement("SELECT * FROM test WHERE k1 = 1").setFetchSize(1));
81+ ResultSet rs = session.execute(new SimpleStatement("SELECT * FROM test WHERE k1 = 1").setFetchSize(1));
8282
8383 assertTrue(rs.wasApplied());
8484 }
modified driver-core/src/test/java/com/datastax/driver/core/CustomPayloadTest.java +15 −16
@@ -35,11 +35,11 @@
3535
3636 import com.datastax.driver.core.exceptions.NoHostAvailableException;
3737 import com.datastax.driver.core.exceptions.UnsupportedFeatureException;
38-import com.datastax.driver.core.querybuilder.QueryBuilder;
3938 import com.datastax.driver.core.utils.CassandraVersion;
4039
4140 import static com.datastax.driver.core.ProtocolVersion.V3;
4241 import static com.datastax.driver.core.querybuilder.QueryBuilder.eq;
42+import static com.datastax.driver.core.querybuilder.QueryBuilder.select;
4343
4444 @CassandraVersion(major = 2.2)
4545 public class CustomPayloadTest extends CCMBridge.PerClassSingleNodeCluster {
@@ -64,7 +64,7 @@
6464
6565 @Test(groups = "short")
6666 public void should_echo_custom_payload_when_executing_statement() throws Exception {
67- Statement statement = session.newSimpleStatement("SELECT c2 FROM t1 where c1 = ?", 1);
67+ Statement statement = new SimpleStatement("SELECT c2 FROM t1 where c1 = ?", 1);
6868 statement.setOutgoingPayload(payload1);
6969 ResultSet rows = session.execute(statement);
7070 Map<String, ByteBuffer> actual = rows.getExecutionInfo().getIncomingPayload();
@@ -73,7 +73,7 @@
7373
7474 @Test(groups = "short")
7575 public void should_echo_custom_payload_when_executing_batch_statement() throws Exception {
76- Statement statement = new BatchStatement().add(session.newSimpleStatement("INSERT INTO t1 (c1, c2) values (1, 'foo')"));
76+ Statement statement = new BatchStatement().add(new SimpleStatement("INSERT INTO t1 (c1, c2) values (1, 'foo')"));
7777 statement.setOutgoingPayload(payload1);
7878 ResultSet rows = session.execute(statement);
7979 Map<String, ByteBuffer> actual = rows.getExecutionInfo().getIncomingPayload();
@@ -82,8 +82,7 @@
8282
8383 @Test(groups = "short")
8484 public void should_echo_custom_payload_when_building_statement() throws Exception {
85- QueryBuilder builder = new QueryBuilder(cluster);
86- Statement statement = builder.select("c2").from("t1").where(eq("c1", 1)).setOutgoingPayload(payload1);
85+ Statement statement = select("c2").from("t1").where(eq("c1", 1)).setOutgoingPayload(payload1);
8786 ResultSet rows = session.execute(statement);
8887 Map<String, ByteBuffer> actual = rows.getExecutionInfo().getIncomingPayload();
8988 assertThat(actual).isEqualTo(payload1);
@@ -97,7 +96,7 @@
9796 */
9897 @Test(groups = "short")
9998 public void should_propagate_incoming_payload_to_bound_statement() throws Exception {
100- RegularStatement statement = session.newSimpleStatement("SELECT c2 as col1 FROM t1 where c1 = ?");
99+ RegularStatement statement = new SimpleStatement("SELECT c2 as col1 FROM t1 where c1 = ?");
101100 statement.setOutgoingPayload(payload1);
102101 PreparedStatement ps = session.prepare(statement);
103102 // Prepared statement should inherit outgoing payload
@@ -124,7 +123,7 @@
124123 */
125124 @Test(groups = "short")
126125 public void should_override_incoming_payload_when_outgoing_payload_explicitly_set_on_preparing_statement() throws Exception {
127- RegularStatement statement = session.newSimpleStatement("SELECT c2 as col2 FROM t1 where c1 = ?");
126+ RegularStatement statement = new SimpleStatement("SELECT c2 as col2 FROM t1 where c1 = ?");
128127 statement.setOutgoingPayload(payload1);
129128 PreparedStatement ps = session.prepare(statement);
130129 // Prepared statement should inherit outgoing payload
@@ -151,7 +150,7 @@
151150 */
152151 @Test(groups = "short")
153152 public void should_not_set_any_payload_on_bound_statement() throws Exception {
154- RegularStatement statement = session.newSimpleStatement("SELECT c2 as col3 FROM t1 where c1 = ?");
153+ RegularStatement statement = new SimpleStatement("SELECT c2 as col3 FROM t1 where c1 = ?");
155154 PreparedStatement ps = session.prepare(statement);
156155 assertThat(ps.getOutgoingPayload()).isNull();
157156 assertThat(ps.getIncomingPayload()).isNull();
@@ -182,7 +181,7 @@
182181 public void should_echo_custom_payload_when_paginating() throws Exception {
183182 session.execute("INSERT INTO t1 (c1, c2) VALUES (1, 'a')");
184183 session.execute("INSERT INTO t1 (c1, c2) VALUES (1, 'b')");
185- Statement statement = session.newSimpleStatement("SELECT c2 FROM t1 where c1 = 1");
184+ Statement statement = new SimpleStatement("SELECT c2 FROM t1 where c1 = 1");
186185 statement.setFetchSize(1);
187186 statement.setOutgoingPayload(payload1);
188187 ResultSet rows = session.execute(statement);
@@ -198,7 +197,7 @@
198197 public void should_encode_null_values() throws Exception {
199198 Map<String, ByteBuffer> payload = new HashMap<String, ByteBuffer>();
200199 payload.put("k1", Statement.NULL_PAYLOAD_VALUE);
201- Statement statement = session.newSimpleStatement("SELECT c2 FROM t1 where c1 = ?", 1);
200+ Statement statement = new SimpleStatement("SELECT c2 FROM t1 where c1 = ?", 1);
202201 statement.setOutgoingPayload(payload);
203202 ResultSet rows = session.execute(statement);
204203 Map<String, ByteBuffer> actual = rows.getExecutionInfo().getIncomingPayload();
@@ -209,28 +208,28 @@
209208 public void should_throw_npe_when_null_key_on_regular_statement() throws Exception {
210209 Map<String, ByteBuffer> payload = new HashMap<String, ByteBuffer>();
211210 payload.put(null, ByteBuffer.wrap(new byte[]{ 1 }));
212- session.newSimpleStatement("SELECT c2 FROM t1 where c1 = ?", 1).setOutgoingPayload(payload);
211+ new SimpleStatement("SELECT c2 FROM t1 where c1 = ?", 1).setOutgoingPayload(payload);
213212 }
214213
215214 @Test(groups = "unit", expectedExceptions = NullPointerException.class)
216215 public void should_throw_npe_when_null_value_on_regular_statement() throws Exception {
217216 Map<String, ByteBuffer> payload = new HashMap<String, ByteBuffer>();
218217 payload.put("k1", null);
219- session.newSimpleStatement("SELECT c2 FROM t1 where c1 = ?", 1).setOutgoingPayload(payload);
218+ new SimpleStatement("SELECT c2 FROM t1 where c1 = ?", 1).setOutgoingPayload(payload);
220219 }
221220
222221 @Test(groups = "short", expectedExceptions = NullPointerException.class)
223222 public void should_throw_npe_when_null_key_on_prepared_statement() throws Exception {
224223 Map<String, ByteBuffer> payload = new HashMap<String, ByteBuffer>();
225224 payload.put(null, ByteBuffer.wrap(new byte[]{ 1 }));
226- session.prepare(session.newSimpleStatement("SELECT c2 FROM t1 where c1 = 1")).setOutgoingPayload(payload);
225+ session.prepare(new SimpleStatement("SELECT c2 FROM t1 where c1 = 1")).setOutgoingPayload(payload);
227226 }
228227
229228 @Test(groups = "short", expectedExceptions = NullPointerException.class)
230229 public void should_throw_npe_when_null_value_on_prepared_statement() throws Exception {
231230 Map<String, ByteBuffer> payload = new HashMap<String, ByteBuffer>();
232231 payload.put("k1", null);
233- session.prepare(session.newSimpleStatement("SELECT c2 FROM t1 where c1 = 2")).setOutgoingPayload(payload);
232+ session.prepare(new SimpleStatement("SELECT c2 FROM t1 where c1 = 2")).setOutgoingPayload(payload);
234233 }
235234
236235 @Test(groups = "short")
@@ -244,7 +243,7 @@
244243 .build()
245244 .init();
246245 v3session = v3cluster.connect();
247- Statement statement = session.newSimpleStatement("SELECT c2 FROM t1 where c1 = ?", 1);
246+ Statement statement = new SimpleStatement("SELECT c2 FROM t1 where c1 = ?", 1);
248247 statement.setOutgoingPayload(payload1);
249248 v3session.execute(statement);
250249 fail("Should not send custom payloads with protocol V3");
@@ -280,7 +279,7 @@
280279 try {
281280 logger.setLevel(TRACE);
282281 logger.addAppender(appender);
283- Statement statement = session.newSimpleStatement("SELECT c2 FROM t1 where c1 = ?", 1);
282+ Statement statement = new SimpleStatement("SELECT c2 FROM t1 where c1 = ?", 1);
284283 statement.setOutgoingPayload(payload1);
285284 session.execute(statement);
286285 String logs = appender.waitAndGet(10000);
modified driver-core/src/test/java/com/datastax/driver/core/DataTypeIntegrationTest.java +2 −2
@@ -106,7 +106,7 @@
106106 session.execute(query);
107107 break;
108108 case SIMPLE_WITH_PARAM:
109- SimpleStatement statement = session.newSimpleStatement(table.insertStatement, table.sampleValue);
109+ SimpleStatement statement = new SimpleStatement(table.insertStatement, table.sampleValue);
110110 checkGetValuesReturnsSerializedValue(protocolVersion, statement, table);
111111 session.execute(statement);
112112 break;
@@ -157,7 +157,7 @@
157157
158158 public void checkGetValuesReturnsSerializedValue(ProtocolVersion protocolVersion, SimpleStatement statement, TestTable table) {
159159 CodecRegistry codecRegistry = cluster.getConfiguration().getCodecRegistry();
160- ByteBuffer[] values = statement.getValues();
160+ ByteBuffer[] values = statement.getValues(protocolVersion, codecRegistry);
161161 assertThat(values.length).isEqualTo(1);
162162 assertThat(values[0])
163163 .as("Value not serialized as expected for " + table.sampleValue)
modified driver-core/src/test/java/com/datastax/driver/core/FetchingTest.java +1 −1
@@ -43,7 +43,7 @@
4343 for (int i = 0; i < 100; i++)
4444 session.execute(String.format("INSERT INTO test (k, v) VALUES ('%s', %d)", key, i));
4545
46- SimpleStatement st = session.newSimpleStatement(String.format("SELECT v FROM test WHERE k='%s'", key));
46+ SimpleStatement st = new SimpleStatement(String.format("SELECT v FROM test WHERE k='%s'", key));
4747 st.setFetchSize(5); // Ridiculously small fetch size for testing purpose. Don't do at home.
4848 ResultSet rs = session.execute(st);
4949
modified driver-core/src/test/java/com/datastax/driver/core/LargeDataTest.java +14 −17
@@ -24,11 +24,13 @@
2424
2525 import com.datastax.driver.core.querybuilder.Batch;
2626 import com.datastax.driver.core.querybuilder.Insert;
27-import com.datastax.driver.core.querybuilder.QueryBuilder;
2827 import com.datastax.driver.core.utils.CassandraVersion;
2928
3029 import static com.datastax.driver.core.TestUtils.CREATE_KEYSPACE_SIMPLE_FORMAT;
30+import static com.datastax.driver.core.querybuilder.QueryBuilder.batch;
3131 import static com.datastax.driver.core.querybuilder.QueryBuilder.eq;
32+import static com.datastax.driver.core.querybuilder.QueryBuilder.insertInto;
33+import static com.datastax.driver.core.querybuilder.QueryBuilder.select;
3234
3335 /**
3436 * Test limitations when using large amounts of data with the driver
@@ -43,13 +45,12 @@
4345 */
4446 private void testWideRows(CCMBridge.CCMCluster c, int key) throws Throwable {
4547 // Write data
46- QueryBuilder builder = new QueryBuilder(c.cluster);
4748 for (int i = 0; i < 1000000; ++i) {
48- c.session.execute(builder.insertInto("wide_rows").value("k", key).value("i", i).setConsistencyLevel(ConsistencyLevel.QUORUM));
49+ c.session.execute(insertInto("wide_rows").value("k", key).value("i", i).setConsistencyLevel(ConsistencyLevel.QUORUM));
4950 }
5051
5152 // Read data
52- ResultSet rs = c.session.execute(builder.select("i").from("wide_rows").where(eq("k", key)));
53+ ResultSet rs = c.session.execute(select("i").from("wide_rows").where(eq("k", key)));
5354
5455 // Verify data
5556 int i = 0;
@@ -66,15 +67,14 @@
6667 */
6768 private void testWideBatchRows(CCMBridge.CCMCluster c, int key) throws Throwable {
6869 // Write data
69- QueryBuilder builder = new QueryBuilder(c.cluster);
70- Batch q = builder.batch();
70+ Batch q = batch();
7171 for (int i = 0; i < 4000; ++i) {
72- q = q.add(builder.insertInto("wide_batch_rows").value("k", key).value("i", i));
72+ q = q.add(insertInto("wide_batch_rows").value("k", key).value("i", i));
7373 }
7474 c.session.execute(q.setConsistencyLevel(ConsistencyLevel.QUORUM));
7575
7676 // Read data
77- ResultSet rs = c.session.execute(builder.select("i").from("wide_batch_rows").where(eq("k", key)));
77+ ResultSet rs = c.session.execute(select("i").from("wide_batch_rows").where(eq("k", key)));
7878
7979 // Verify data
8080 int i = 0;
@@ -96,13 +96,12 @@
9696 bb.flip();
9797
9898 // Write data
99- QueryBuilder builder = new QueryBuilder(c.cluster);
10099 for (int i = 0; i < 1000000; ++i) {
101- c.session.execute(builder.insertInto("wide_byte_rows").value("k", key).value("i", bb).setConsistencyLevel(ConsistencyLevel.QUORUM));
100+ c.session.execute(insertInto("wide_byte_rows").value("k", key).value("i", bb).setConsistencyLevel(ConsistencyLevel.QUORUM));
102101 }
103102
104103 // Read data
105- ResultSet rs = c.session.execute(builder.select("i").from("wide_byte_rows").where(eq("k", key)));
104+ ResultSet rs = c.session.execute(select("i").from("wide_byte_rows").where(eq("k", key)));
106105
107106 // Verify data
108107 for (Row row : rs) {
@@ -118,16 +117,15 @@
118117 */
119118 private void testLargeText(CCMBridge.CCMCluster c, int key) throws Throwable {
120119 // Write data
121- QueryBuilder builder = new QueryBuilder(c.cluster);
122120 StringBuilder b = new StringBuilder();
123121 for (int i = 0; i < 1000000; ++i) {
124122 // Create ultra-long text
125123 b.append(i);
126124 }
127- c.session.execute(builder.insertInto("large_text").value("k", key).value("txt", b.toString()).setConsistencyLevel(ConsistencyLevel.QUORUM));
125+ c.session.execute(insertInto("large_text").value("k", key).value("txt", b.toString()).setConsistencyLevel(ConsistencyLevel.QUORUM));
128126
129127 // Read data
130- Row row = c.session.execute(builder.select().all().from("large_text").where(eq("k", key))).one();
128+ Row row = c.session.execute(select().all().from("large_text").where(eq("k", key))).one();
131129
132130 // Verify data
133131 assertTrue(b.toString().equals(row.getString("txt")));
@@ -167,15 +165,14 @@
167165 */
168166 private void testWideTable(CCMBridge.CCMCluster c, int key) throws Throwable {
169167 // Write data
170- QueryBuilder builder = new QueryBuilder(c.cluster);
171- Insert insertStatement = builder.insertInto("wide_table").value("k", key);
168+ Insert insertStatement = insertInto("wide_table").value("k", key);
172169 for (int i = 0; i < 330; ++i) {
173170 insertStatement = insertStatement.value(createColumnName(i), i);
174171 }
175172 c.session.execute(insertStatement.setConsistencyLevel(ConsistencyLevel.QUORUM));
176173
177174 // Read data
178- Row row = c.session.execute(builder.select().all().from("wide_table").where(eq("k", key))).one();
175+ Row row = c.session.execute(select().all().from("wide_table").where(eq("k", key))).one();
179176
180177 // Verify data
181178 for (int i = 0; i < 330; ++i) {
modified driver-core/src/test/java/com/datastax/driver/core/MetricsTest.java +1 −1
@@ -82,7 +82,7 @@
8282 retryDecision = RetryDecision.retry(ConsistencyLevel.ONE);
8383
8484 // We only have one node, this will throw an unavailable exception
85- Statement statement = session.newSimpleStatement("SELECT v FROM test WHERE k = 1").setConsistencyLevel(ConsistencyLevel.TWO);
85+ Statement statement = new SimpleStatement("SELECT v FROM test WHERE k = 1").setConsistencyLevel(ConsistencyLevel.TWO);
8686 session.execute(statement);
8787
8888 Errors errors = cluster.getMetrics().getErrorMetrics();
modified driver-core/src/test/java/com/datastax/driver/core/PagingStateTest.java +8 −8
@@ -55,12 +55,12 @@
5555 */
5656 @Test(groups = "short")
5757 public void should_complete_when_using_paging_state() {
58- SimpleStatement st = session.newSimpleStatement(String.format("SELECT v FROM test WHERE k='%s'", KEY));
58+ SimpleStatement st = new SimpleStatement(String.format("SELECT v FROM test WHERE k='%s'", KEY));
5959 ResultSet result = session.execute(st.setFetchSize(20));
6060 int pageSize = result.getAvailableWithoutFetching();
6161 String savedPagingStateString = result.getExecutionInfo().getPagingState().toString();
6262
63- st = session.newSimpleStatement(String.format("SELECT v FROM test WHERE k='%s'", KEY));
63+ st = new SimpleStatement(String.format("SELECT v FROM test WHERE k='%s'", KEY));
6464 result = session.execute(st.setFetchSize(20).setPagingState(PagingState.fromString(savedPagingStateString)));
6565
6666 //We have the result starting from the next page we stopped
@@ -85,7 +85,7 @@
8585 boolean setWithFalseContent = false;
8686 boolean setWithWrongStatement = false;
8787
88- SimpleStatement st = session.newSimpleStatement(String.format("SELECT v FROM test WHERE k='%s'", KEY));
88+ SimpleStatement st = new SimpleStatement(String.format("SELECT v FROM test WHERE k='%s'", KEY));
8989 ResultSet result = session.execute(st.setFetchSize(20));
9090
9191 PagingState savedPagingState = result.getExecutionInfo().getPagingState();
@@ -106,7 +106,7 @@
106106 }
107107
108108 // Changing the statement
109- st = session.newSimpleStatement(String.format("SELECT v FROM test WHERE k='%s'", "paging"));
109+ st = new SimpleStatement(String.format("SELECT v FROM test WHERE k='%s'", "paging"));
110110 try {
111111 st.setFetchSize(20).setPagingState(PagingState.fromString(savedPagingStateString));
112112 } catch (PagingStateException e) {
@@ -170,7 +170,7 @@
170170 */
171171 @Test(groups = "short")
172172 public void should_return_no_rows_when_paged_to_end() {
173- SimpleStatement st = session.newSimpleStatement(String.format("SELECT v FROM test WHERE k='%s'", KEY));
173+ SimpleStatement st = new SimpleStatement(String.format("SELECT v FROM test WHERE k='%s'", KEY));
174174 ResultSet result = session.execute(st.setFetchSize(20));
175175
176176 // Consume enough of the iterator to cause all the results to be paged in.
@@ -181,7 +181,7 @@
181181
182182 String savedPagingStateString = result.getExecutionInfo().getPagingState().toString();
183183
184- st = session.newSimpleStatement(String.format("SELECT v FROM test WHERE k='%s'", KEY));
184+ st = new SimpleStatement(String.format("SELECT v FROM test WHERE k='%s'", KEY));
185185 result = session.execute(st.setFetchSize(20).setPagingState(PagingState.fromString(savedPagingStateString)));
186186
187187 assertThat(result.one()).isNull();
@@ -218,12 +218,12 @@
218218 */
219219 @Test(groups = "short")
220220 public void should_complete_when_using_unsafe_paging_state() {
221- SimpleStatement st = session.newSimpleStatement(String.format("SELECT v FROM test WHERE k='%s'", KEY));
221+ SimpleStatement st = new SimpleStatement(String.format("SELECT v FROM test WHERE k='%s'", KEY));
222222 ResultSet result = session.execute(st.setFetchSize(20));
223223 int pageSize = result.getAvailableWithoutFetching();
224224 byte[] savedPagingState = result.getExecutionInfo().getPagingStateUnsafe();
225225
226- st = session.newSimpleStatement(String.format("SELECT v FROM test WHERE k='%s'", KEY));
226+ st = new SimpleStatement(String.format("SELECT v FROM test WHERE k='%s'", KEY));
227227 result = session.execute(st.setFetchSize(20).setPagingStateUnsafe(savedPagingState));
228228
229229 //We have the result starting from the next page we stopped
modified driver-core/src/test/java/com/datastax/driver/core/PreparedStatementTest.java +11 −11
@@ -341,7 +341,7 @@
341341 @Test(groups = "short")
342342 public void prepareStatementInheritPropertiesTest() {
343343
344- RegularStatement toPrepare = session.newSimpleStatement("SELECT * FROM test WHERE k=?");
344+ RegularStatement toPrepare = new SimpleStatement("SELECT * FROM test WHERE k=?");
345345 toPrepare.setConsistencyLevel(ConsistencyLevel.QUORUM);
346346 toPrepare.enableTracing();
347347
@@ -373,7 +373,7 @@
373373 BatchStatement bs = new BatchStatement();
374374 bs.add(ps1.bind("one", "foo"));
375375 bs.add(ps2.bind("two"));
376- bs.add(session.newSimpleStatement("INSERT INTO " + SIMPLE_TABLE2 + " (k, v) VALUES ('three', 'foobar')"));
376+ bs.add(new SimpleStatement("INSERT INTO " + SIMPLE_TABLE2 + " (k, v) VALUES ('three', 'foobar')"));
377377
378378 session.execute(bs);
379379
@@ -400,7 +400,7 @@
400400
401401 PreparedStatement ps = session.prepare(String.format("INSERT INTO %s.foo (i) VALUES (?)", keyspace));
402402 BoundStatement bs = ps.bind(1);
403- assertThat(bs.getRoutingKey()).isNotNull();
403+ assertThat(bs.getRoutingKey(ProtocolVersion.NEWEST_SUPPORTED, CodecRegistry.DEFAULT_INSTANCE)).isNotNull();
404404 }
405405
406406 @Test(groups = "short")
@@ -413,7 +413,7 @@
413413
414414 PreparedStatement ps = session.prepare("INSERT INTO \"Test\".\"Foo\" (i) VALUES (?)");
415415 BoundStatement bs = ps.bind(1);
416- assertThat(bs.getRoutingKey()).isNotNull();
416+ assertThat(bs.getRoutingKey(ProtocolVersion.NEWEST_SUPPORTED, CodecRegistry.DEFAULT_INSTANCE)).isNotNull();
417417 }
418418
419419 @Test(groups = "short", expectedExceptions = InvalidQueryException.class)
@@ -517,7 +517,7 @@
517517 st2.setString(0, "foo");
518518 // i is UNSET
519519 session.execute(st2);
520- Statement st3 = session.newSimpleStatement("SELECT i from " + SIMPLE_TABLE + " where k = 'foo'");
520+ Statement st3 = new SimpleStatement("SELECT i from " + SIMPLE_TABLE + " where k = 'foo'");
521521 st3.enableTracing();
522522 ResultSet rows = session.execute(st3);
523523 assertThat(rows.one().getInt("i")).isEqualTo(1234);
@@ -546,7 +546,7 @@
546546 session.execute(bound);
547547
548548 ResultSet rows = session.execute(
549- session.newSimpleStatement("SELECT i from " + SIMPLE_TABLE + " where k = 'foo'")
549+ new SimpleStatement("SELECT i from " + SIMPLE_TABLE + " where k = 'foo'")
550550 .enableTracing());
551551
552552 assertThat(rows.one().isNull("i"));
@@ -575,7 +575,7 @@
575575 session.execute(bound);
576576
577577 ResultSet rows = session.execute(
578- session.newSimpleStatement("SELECT i from " + SIMPLE_TABLE + " where k = 'foo'")
578+ new SimpleStatement("SELECT i from " + SIMPLE_TABLE + " where k = 'foo'")
579579 .enableTracing());
580580
581581 assertThat(rows.one().isNull("i"));
@@ -604,7 +604,7 @@
604604 st2.setString(0, "foo");
605605 // i is UNSET
606606 session.execute(new BatchStatement().add(st2));
607- Statement st3 = session.newSimpleStatement("SELECT i from " + SIMPLE_TABLE + " where k = 'foo'");
607+ Statement st3 = new SimpleStatement("SELECT i from " + SIMPLE_TABLE + " where k = 'foo'");
608608 st3.enableTracing();
609609 ResultSet rows = session.execute(st3);
610610 assertThat(rows.one().getInt("i")).isEqualTo(1234);
@@ -626,7 +626,7 @@
626626 st1.setString(0, "foo");
627627 st1.setToNull(1);
628628 session.execute(st1);
629- Statement st2 = session.newSimpleStatement("SELECT i from " + SIMPLE_TABLE + " where k = 'foo'");
629+ Statement st2 = new SimpleStatement("SELECT i from " + SIMPLE_TABLE + " where k = 'foo'");
630630 st2.enableTracing();
631631 ResultSet rows = session.execute(st2);
632632 assertThat(rows.one().isNull(0)).isTrue();
@@ -649,7 +649,7 @@
649649 st1.setString(0, "foo");
650650 st1.setToNull(1);
651651 session.execute(new BatchStatement().add(st1));
652- Statement st2 = session.newSimpleStatement("SELECT i from " + SIMPLE_TABLE + " where k = 'foo'");
652+ Statement st2 = new SimpleStatement("SELECT i from " + SIMPLE_TABLE + " where k = 'foo'");
653653 st2.enableTracing();
654654 ResultSet rows = session.execute(st2);
655655 assertThat(rows.one().isNull(0)).isTrue();
@@ -673,7 +673,7 @@
673673 PreparedStatement prepared;
674674 BoundStatement bound;
675675
676- statement = session.newSimpleStatement(String.format("SELECT * FROM %s.idempotencetest WHERE i = ?", keyspace));
676+ statement = new SimpleStatement(String.format("SELECT * FROM %s.idempotencetest WHERE i = ?", keyspace));
677677
678678 prepared = session.prepare(statement);
679679 bound = prepared.bind(1);
modified driver-core/src/test/java/com/datastax/driver/core/QueryLoggerTest.java +1 −1
@@ -274,7 +274,7 @@
274274 normal.setLevel(DEBUG);
275275 Statement unknownStatement = new Statement() {
276276 @Override
277- public ByteBuffer getRoutingKey() {
277+ public ByteBuffer getRoutingKey(ProtocolVersion protocolVersion, CodecRegistry codecRegistry) {
278278 return null;
279279 }
280280
modified driver-core/src/test/java/com/datastax/driver/core/QueryTimestampTest.java +9 −9
@@ -62,7 +62,7 @@
6262 public void should_use_CQL_timestamp_over_anything_else() {
6363 timestampFromGenerator = 10;
6464 String query = "INSERT INTO foo (k, v) VALUES (1, 1) USING TIMESTAMP 20";
65- session.execute(session.newSimpleStatement(query).setDefaultTimestamp(30));
65+ session.execute(new SimpleStatement(query).setDefaultTimestamp(30));
6666
6767 long writeTime = session.execute("SELECT writeTime(v) FROM foo WHERE k = 1").one().getLong(0);
6868 assertEquals(writeTime, 20);
@@ -72,7 +72,7 @@
7272 public void should_use_statement_timestamp_over_generator() {
7373 timestampFromGenerator = 10;
7474 String query = "INSERT INTO foo (k, v) VALUES (1, 1)";
75- session.execute(session.newSimpleStatement(query).setDefaultTimestamp(30));
75+ session.execute(new SimpleStatement(query).setDefaultTimestamp(30));
7676
7777 long writeTime = session.execute("SELECT writeTime(v) FROM foo WHERE k = 1").one().getLong(0);
7878 assertEquals(writeTime, 30);
@@ -102,8 +102,8 @@
102102 @Test(groups = "short")
103103 public void should_apply_statement_timestamp_only_to_batched_queries_without_timestamp() {
104104 BatchStatement batch = new BatchStatement();
105- batch.add(session.newSimpleStatement("INSERT INTO foo (k, v) VALUES (1, 1)"));
106- batch.add(session.newSimpleStatement("INSERT INTO foo (k, v) VALUES (2, 1) USING TIMESTAMP 20"));
105+ batch.add(new SimpleStatement("INSERT INTO foo (k, v) VALUES (1, 1)"));
106+ batch.add(new SimpleStatement("INSERT INTO foo (k, v) VALUES (2, 1) USING TIMESTAMP 20"));
107107 batch.setDefaultTimestamp(10);
108108 session.execute(batch);
109109
@@ -117,8 +117,8 @@
117117 public void should_apply_generator_timestamp_only_to_batched_queries_without_timestamp() {
118118 timestampFromGenerator = 10;
119119 BatchStatement batch = new BatchStatement();
120- batch.add(session.newSimpleStatement("INSERT INTO foo (k, v) VALUES (1, 1)"));
121- batch.add(session.newSimpleStatement("INSERT INTO foo (k, v) VALUES (2, 1) USING TIMESTAMP 20"));
120+ batch.add(new SimpleStatement("INSERT INTO foo (k, v) VALUES (1, 1)"));
121+ batch.add(new SimpleStatement("INSERT INTO foo (k, v) VALUES (2, 1) USING TIMESTAMP 20"));
122122 session.execute(batch);
123123
124124 long writeTime1 = session.execute("SELECT writeTime(v) FROM foo WHERE k = 1").one().getLong(0);
@@ -132,8 +132,8 @@
132132 timestampFromGenerator = Long.MIN_VALUE;
133133 long clientTime = System.currentTimeMillis() * 1000;
134134 BatchStatement batch = new BatchStatement();
135- batch.add(session.newSimpleStatement("INSERT INTO foo (k, v) VALUES (1, 1)"));
136- batch.add(session.newSimpleStatement("INSERT INTO foo (k, v) VALUES (2, 1) USING TIMESTAMP 20"));
135+ batch.add(new SimpleStatement("INSERT INTO foo (k, v) VALUES (1, 1)"));
136+ batch.add(new SimpleStatement("INSERT INTO foo (k, v) VALUES (2, 1) USING TIMESTAMP 20"));
137137 session.execute(batch);
138138
139139 long writeTime1 = session.execute("SELECT writeTime(v) FROM foo WHERE k = 1").one().getLong(0);
@@ -144,7 +144,7 @@
144144
145145 @Test(groups = "short")
146146 public void should_preserve_timestamp_when_retrying() {
147- SimpleStatement statement = session.newSimpleStatement("INSERT INTO foo (k, v) VALUES (1, 1)");
147+ SimpleStatement statement = new SimpleStatement("INSERT INTO foo (k, v) VALUES (1, 1)");
148148 statement.setDefaultTimestamp(10);
149149 // This will fail since we test against a single-host cluster. The DowngradingConsistencyRetryPolicy
150150 // will retry it at ONE.
modified driver-core/src/test/java/com/datastax/driver/core/QueryTracker.java +1 −1
@@ -48,7 +48,7 @@
4848 }
4949
5050 public void query(Session session, int times, ConsistencyLevel cl, Class<? extends Exception> expectedException) {
51- Statement statement = session.newSimpleStatement(QUERY);
51+ Statement statement = new SimpleStatement(QUERY);
5252 if(cl != null) {
5353 statement.setConsistencyLevel(cl);
5454 }
modified driver-core/src/test/java/com/datastax/driver/core/SessionTest.java +4 −4
@@ -62,11 +62,11 @@
6262
6363 // execute
6464 checkExecuteResultSet(session.execute(String.format(TestUtils.SELECT_ALL_FORMAT, TABLE1)), key);
65- checkExecuteResultSet(session.execute(session.newSimpleStatement(String.format(TestUtils.SELECT_ALL_FORMAT, TABLE1)).setConsistencyLevel(ConsistencyLevel.ONE)), key);
65+ checkExecuteResultSet(session.execute(new SimpleStatement(String.format(TestUtils.SELECT_ALL_FORMAT, TABLE1)).setConsistencyLevel(ConsistencyLevel.ONE)), key);
6666
6767 // executeAsync
6868 checkExecuteResultSet(session.executeAsync(String.format(TestUtils.SELECT_ALL_FORMAT, TABLE1)).getUninterruptibly(), key);
69- checkExecuteResultSet(session.executeAsync(session.newSimpleStatement(String.format(TestUtils.SELECT_ALL_FORMAT, TABLE1)).setConsistencyLevel(ConsistencyLevel.ONE)).getUninterruptibly(), key);
69+ checkExecuteResultSet(session.executeAsync(new SimpleStatement(String.format(TestUtils.SELECT_ALL_FORMAT, TABLE1)).setConsistencyLevel(ConsistencyLevel.ONE)).getUninterruptibly(), key);
7070 }
7171
7272 @Test(groups = "short")
@@ -151,11 +151,11 @@
151151
152152 // execute
153153 checkExecuteResultSet(compressedSession.execute(SELECT_ALL), key);
154- checkExecuteResultSet(compressedSession.execute(session.newSimpleStatement(SELECT_ALL).setConsistencyLevel(ConsistencyLevel.ONE)), key);
154+ checkExecuteResultSet(compressedSession.execute(new SimpleStatement(SELECT_ALL).setConsistencyLevel(ConsistencyLevel.ONE)), key);
155155
156156 // executeAsync
157157 checkExecuteResultSet(compressedSession.executeAsync(SELECT_ALL).getUninterruptibly(), key);
158- checkExecuteResultSet(compressedSession.executeAsync(session.newSimpleStatement(SELECT_ALL).setConsistencyLevel(ConsistencyLevel.ONE)).getUninterruptibly(), key);
158+ checkExecuteResultSet(compressedSession.executeAsync(new SimpleStatement(SELECT_ALL).setConsistencyLevel(ConsistencyLevel.ONE)).getUninterruptibly(), key);
159159
160160 } finally {
161161 cluster.getConfiguration().getProtocolOptions().setCompression(ProtocolOptions.Compression.NONE);
modified driver-core/src/test/java/com/datastax/driver/core/SimpleStatementTest.java +6 −22
@@ -18,58 +18,42 @@
1818 import java.util.Collections;
1919 import java.util.List;
2020
21-import org.testng.annotations.BeforeClass;
2221 import org.testng.annotations.Test;
2322
2423 import static org.assertj.core.api.Assertions.assertThat;
2524
26-import static org.mockito.Mockito.mock;
27-import static org.mockito.Mockito.when;
28-
2925 public class SimpleStatementTest {
3026
31- Cluster cluster;
32- CodecRegistry codecRegistry = new CodecRegistry();
33-
34- @BeforeClass(groups = "unit")
35- public void setup() {
36- cluster = mock(Cluster.class);
37- Configuration configuration = mock(Configuration.class);
38- when(cluster.getConfiguration()).thenReturn(configuration);
39- ProtocolOptions protocolOptions = mock(ProtocolOptions.class);
40- when(configuration.getProtocolOptions()).thenReturn(protocolOptions);
41- }
42-
4327 @Test(groups = "unit", expectedExceptions = { IllegalArgumentException.class })
4428 public void should_fail_if_too_many_variables() {
4529 List<Object> args = Collections.nCopies(1 << 16, (Object)1);
46- new SimpleStatement("mock query", cluster, args.toArray());
30+ new SimpleStatement("mock query", args.toArray());
4731 }
4832
4933 @Test(groups = "unit", expectedExceptions = { IllegalStateException.class })
5034 public void should_throw_ISE_if_getObject_called_on_statement_without_values() {
51- new SimpleStatement("doesn't matter", cluster).getObject(0);
35+ new SimpleStatement("doesn't matter").getObject(0);
5236 }
5337
5438 @Test(groups = "unit", expectedExceptions = { IndexOutOfBoundsException.class })
5539 public void should_throw_IOOBE_if_getObject_called_with_wrong_index() {
56- new SimpleStatement("doesn't matter", cluster, new Object()).getObject(1);
40+ new SimpleStatement("doesn't matter", new Object()).getObject(1);
5741 }
5842
5943 @Test(groups = "unit")
6044 public void should_return_object_at_ith_index() {
6145 Object expected = new Object();
62- Object actual = new SimpleStatement("doesn't matter", cluster, expected).getObject(0);
46+ Object actual = new SimpleStatement("doesn't matter", expected).getObject(0);
6347 assertThat(actual).isSameAs(expected);
6448 }
6549
6650 @Test(groups = "unit")
6751 public void should_return_number_of_values() {
6852 assertThat(
69- new SimpleStatement("doesn't matter", cluster).valuesCount()
53+ new SimpleStatement("doesn't matter").valuesCount()
7054 ).isEqualTo(0);
7155 assertThat(
72- new SimpleStatement("doesn't matter", cluster, 1, 2).valuesCount()
56+ new SimpleStatement("doesn't matter", 1, 2).valuesCount()
7357 ).isEqualTo(2);
7458 }
7559
modified driver-core/src/test/java/com/datastax/driver/core/SpeculativeExecutionIntegrationTest.java +1 −1
@@ -67,7 +67,7 @@
6767
6868 BatchStatement batch = new BatchStatement();
6969 for (int k = 0; k < 1000; k++) {
70- batch.add(session.newSimpleStatement("insert into foo(k,v) values (?,1)", k));
70+ batch.add(new SimpleStatement("insert into foo(k,v) values (?,1)", k));
7171 }
7272 session.execute(batch);
7373
modified driver-core/src/test/java/com/datastax/driver/core/SpeculativeExecutionTest.java +1 −1
@@ -119,7 +119,7 @@
119119 long execStartCount = errors.getSpeculativeExecutions().getCount();
120120 long retriesStartCount = errors.getRetriesOnUnavailable().getCount();
121121
122- SimpleStatement statement = session.newSimpleStatement("mock query");
122+ SimpleStatement statement = new SimpleStatement("mock query");
123123 statement.setConsistencyLevel(ConsistencyLevel.TWO);
124124 ResultSet rs = session.execute(statement);
125125 Row row = rs.one();
modified driver-core/src/test/java/com/datastax/driver/core/StatementIdempotenceTest.java +38 −42
@@ -27,7 +27,6 @@
2727 import static org.mockito.Mockito.when;
2828
2929 import com.datastax.driver.core.querybuilder.BuiltStatement;
30-import com.datastax.driver.core.querybuilder.QueryBuilder;
3130
3231 import static com.datastax.driver.core.querybuilder.QueryBuilder.*;
3332
@@ -35,8 +34,6 @@
3534
3635 private Cluster cluster;
3736
38- private QueryBuilder builder;
39-
4037 @BeforeMethod(groups = "unit")
4138 public void setUpQueryBuilder() throws Exception {
4239 CodecRegistry codecRegistry = new CodecRegistry();
@@ -47,7 +44,6 @@
4744 when(configuration.getCodecRegistry()).thenReturn(codecRegistry);
4845 when(configuration.getProtocolOptions()).thenReturn(protocolOptions);
4946 when(protocolOptions.getProtocolVersion()).thenReturn(TestUtils.getDesiredProtocolVersion());
50- builder = new QueryBuilder(cluster);
5147 }
5248
5349 @Test(groups = "unit")
@@ -112,66 +108,66 @@
112108
113109 private ImmutableList<BuiltStatement> idempotentBuiltStatements() {
114110 return ImmutableList.<BuiltStatement>of(
115- builder.update("foo").with(set("v", 1)).where(eq("k", 1)), // set simple value
116- builder.update("foo").with(add("s", 1)).where(eq("k", 1)), // add to set
117- builder.update("foo").with(put("m", "a", 1)).where(eq("k", 1)), // put in map
111+ update("foo").with(set("v", 1)).where(eq("k", 1)), // set simple value
112+ update("foo").with(add("s", 1)).where(eq("k", 1)), // add to set
113+ update("foo").with(put("m", "a", 1)).where(eq("k", 1)), // put in map
118114
119115 // select statements should be idempotent even with function calls
120- builder.select().countAll() .from("foo").where(eq("k", 1)),
121- builder.select().ttl("v") .from("foo").where(eq("k", 1)),
122- builder.select().writeTime("v") .from("foo").where(eq("k", 1)),
123- builder.select().fcall("token", "k").from("foo").where(eq("k", 1))
116+ select().countAll() .from("foo").where(eq("k", 1)),
117+ select().ttl("v") .from("foo").where(eq("k", 1)),
118+ select().writeTime("v") .from("foo").where(eq("k", 1)),
119+ select().fcall("token", "k").from("foo").where(eq("k", 1))
124120
125121 );
126122 }
127123
128124 private ImmutableList<BuiltStatement> nonIdempotentBuiltStatements() {
129125 return ImmutableList.of(
130- builder.update("foo").with(append("l", 1)).where(eq("k", 1)), // append to list
131- builder.update("foo").with(set("v", 1)).and(prepend("l", 1)).where(eq("k", 1)), // prepend to list
132- builder.update("foo").with(incr("c")).where(eq("k", 1)), // counter update
126+ update("foo").with(append("l", 1)).where(eq("k", 1)), // append to list
127+ update("foo").with(set("v", 1)).and(prepend("l", 1)).where(eq("k", 1)), // prepend to list
128+ update("foo").with(incr("c")).where(eq("k", 1)), // counter update
133129
134130 // function calls
135131
136- builder.insertInto("foo").value("k", 1).value("v", fcall("token", "k")),
137- builder.insertInto("foo").value("k", 1).value("v", now()),
138- builder.insertInto("foo").value("k", 1).value("v", uuid()),
132+ insertInto("foo").value("k", 1).value("v", fcall("token", "k")),
133+ insertInto("foo").value("k", 1).value("v", now()),
134+ insertInto("foo").value("k", 1).value("v", uuid()),
139135
140- builder.insertInto("foo").value("k", 1).value("v", Sets.newHashSet(fcall("token", "k"))),
141- builder.insertInto("foo").value("k", 1).value("v", Sets.newHashSet(now())),
142- builder.insertInto("foo").value("k", 1).value("v", Sets.newHashSet(uuid())),
136+ insertInto("foo").value("k", 1).value("v", Sets.newHashSet(fcall("token", "k"))),
137+ insertInto("foo").value("k", 1).value("v", Sets.newHashSet(now())),
138+ insertInto("foo").value("k", 1).value("v", Sets.newHashSet(uuid())),
143139
144- builder.insertInto("foo").values(new String[]{"k", "v"}, new Object[]{1, fcall("token", "k")}),
145- builder.insertInto("foo").values(new String[]{"k", "v"}, new Object[]{1, now()}),
146- builder.insertInto("foo").values(new String[]{"k", "v"}, new Object[]{1, uuid()}),
140+ insertInto("foo").values(new String[]{"k", "v"}, new Object[]{1, fcall("token", "k")}),
141+ insertInto("foo").values(new String[]{"k", "v"}, new Object[]{1, now()}),
142+ insertInto("foo").values(new String[]{"k", "v"}, new Object[]{1, uuid()}),
147143
148- builder.insertInto("foo").values(new String[]{"k", "v"}, new Object[]{1, ImmutableMap.of("foo", fcall("token", "k"))}),
149- builder.insertInto("foo").values(new String[]{"k", "v"}, new Object[]{1, ImmutableMap.of("foo", now())}),
150- builder.insertInto("foo").values(new String[]{"k", "v"}, new Object[]{1, ImmutableMap.of("foo", uuid())}),
144+ insertInto("foo").values(new String[]{"k", "v"}, new Object[]{1, ImmutableMap.of("foo", fcall("token", "k"))}),
145+ insertInto("foo").values(new String[]{"k", "v"}, new Object[]{1, ImmutableMap.of("foo", now())}),
146+ insertInto("foo").values(new String[]{"k", "v"}, new Object[]{1, ImmutableMap.of("foo", uuid())}),
151147
152- builder.insertInto("foo").values(new String[]{"k", "v"}, new Object[]{1, ImmutableMap.of(fcall("token", "k"), "foo")}),
153- builder.insertInto("foo").values(new String[]{"k", "v"}, new Object[]{1, ImmutableMap.of(now() , "foo")}),
154- builder.insertInto("foo").values(new String[]{"k", "v"}, new Object[]{1, ImmutableMap.of(uuid() , "foo")}),
148+ insertInto("foo").values(new String[]{"k", "v"}, new Object[]{1, ImmutableMap.of(fcall("token", "k"), "foo")}),
149+ insertInto("foo").values(new String[]{"k", "v"}, new Object[]{1, ImmutableMap.of(now() , "foo")}),
150+ insertInto("foo").values(new String[]{"k", "v"}, new Object[]{1, ImmutableMap.of(uuid() , "foo")}),
155151
156- builder.update("foo").with(set("v", fcall("token", "k"))) .where(eq("k", 1)),
157- builder.update("foo").with(set("v", now())) .where(eq("k", 1)),
158- builder.update("foo").with(set("v", uuid())) .where(eq("k", 1)),
152+ update("foo").with(set("v", fcall("token", "k"))) .where(eq("k", 1)),
153+ update("foo").with(set("v", now())) .where(eq("k", 1)),
154+ update("foo").with(set("v", uuid())) .where(eq("k", 1)),
159155
160- builder.update("foo").with(set("v", Lists.newArrayList(fcall("token", "k")))).where(eq("k", 1)),
161- builder.update("foo").with(set("v", Lists.newArrayList(now()))) .where(eq("k", 1)),
162- builder.update("foo").with(set("v", Lists.newArrayList(uuid()))) .where(eq("k", 1)),
156+ update("foo").with(set("v", Lists.newArrayList(fcall("token", "k")))).where(eq("k", 1)),
157+ update("foo").with(set("v", Lists.newArrayList(now()))) .where(eq("k", 1)),
158+ update("foo").with(set("v", Lists.newArrayList(uuid()))) .where(eq("k", 1)),
163159
164160 // raw() calls
165161
166- builder.insertInto("foo").value("k", 1).value("v", raw("foo()")),
167- builder.insertInto("foo").value("k", 1).value("v", Sets.newHashSet(raw("foo()"))),
162+ insertInto("foo").value("k", 1).value("v", raw("foo()")),
163+ insertInto("foo").value("k", 1).value("v", Sets.newHashSet(raw("foo()"))),
168164
169- builder.insertInto("foo").values(new String[]{"k", "v"}, new Object[]{1, raw("foo()")}),
170- builder.insertInto("foo").values(new String[]{"k", "v"}, new Object[]{1, ImmutableMap.of("foo", raw("foo()"))}),
171- builder.insertInto("foo").values(new String[]{"k", "v"}, new Object[]{1, ImmutableMap.of(raw("foo()"), "foo")}),
165+ insertInto("foo").values(new String[]{"k", "v"}, new Object[]{1, raw("foo()")}),
166+ insertInto("foo").values(new String[]{"k", "v"}, new Object[]{1, ImmutableMap.of("foo", raw("foo()"))}),
167+ insertInto("foo").values(new String[]{"k", "v"}, new Object[]{1, ImmutableMap.of(raw("foo()"), "foo")}),
172168
173- builder.update("foo").with(set("v", raw("foo()"))) .where(eq("k", 1)),
174- builder.update("foo").with(set("v", Lists.newArrayList(raw("foo()")))).where(eq("k", 1))
169+ update("foo").with(set("v", raw("foo()"))) .where(eq("k", 1)),
170+ update("foo").with(set("v", Lists.newArrayList(raw("foo()")))).where(eq("k", 1))
175171
176172 );
177173 }
modified driver-core/src/test/java/com/datastax/driver/core/StatementWrapperTest.java +3 −3
@@ -49,7 +49,7 @@
4949 public void should_pass_wrapped_statement_to_load_balancing_policy() {
5050 loadBalancingPolicy.customStatementsHandled.set(0);
5151
52- SimpleStatement s = session.newSimpleStatement("select * from system.local");
52+ SimpleStatement s = new SimpleStatement("select * from system.local");
5353 session.execute(s);
5454 assertThat(loadBalancingPolicy.customStatementsHandled.get()).isEqualTo(0);
5555
@@ -61,7 +61,7 @@
6161 public void should_pass_wrapped_statement_to_speculative_execution_policy() {
6262 speculativeExecutionPolicy.customStatementsHandled.set(0);
6363
64- SimpleStatement s = session.newSimpleStatement("select * from system.local");
64+ SimpleStatement s = new SimpleStatement("select * from system.local");
6565 session.execute(s);
6666 assertThat(speculativeExecutionPolicy.customStatementsHandled.get()).isEqualTo(0);
6767
@@ -75,7 +75,7 @@
7575
7676 // Set CL TWO with only one node, so the statement will always cause UNAVAILABLE,
7777 // which our custom policy ignores.
78- Statement s = session.newSimpleStatement("select * from system.local")
78+ Statement s = new SimpleStatement("select * from system.local")
7979 .setConsistencyLevel(ConsistencyLevel.TWO);
8080
8181 session.execute(s);
modified driver-core/src/test/java/com/datastax/driver/core/TracingTest.java +2 −2
@@ -58,7 +58,7 @@
5858 */
5959 @Test(groups = "short")
6060 public void should_have_a_different_tracingId_for_each_page() {
61- SimpleStatement st = session.newSimpleStatement(String.format("SELECT v FROM test WHERE k='%s'", KEY));
61+ SimpleStatement st = new SimpleStatement(String.format("SELECT v FROM test WHERE k='%s'", KEY));
6262 ResultSet result = session.execute(st.setFetchSize(40).enableTracing());
6363 result.all();
6464
@@ -87,7 +87,7 @@
8787 */
8888 @Test(groups = "short")
8989 public void should_preserve_tracing_status_across_retries() {
90- SimpleStatement st = session.newSimpleStatement(String.format("SELECT v FROM test WHERE k='%s'", KEY));
90+ SimpleStatement st = new SimpleStatement(String.format("SELECT v FROM test WHERE k='%s'", KEY));
9191 st.setConsistencyLevel(ConsistencyLevel.THREE).enableTracing();
9292
9393 ResultSet result = session.execute(st);
modified driver-core/src/test/java/com/datastax/driver/core/TypeCodecCollectionsIntegrationTest.java +5 −7
@@ -22,8 +22,6 @@
2222 import java.util.Map;
2323 import java.util.Set;
2424
25-import com.datastax.driver.core.querybuilder.QueryBuilder;
26-import com.datastax.driver.core.utils.CassandraVersion;
2725 import com.google.common.collect.ImmutableMap;
2826 import com.google.common.reflect.TypeToken;
2927 import org.testng.annotations.BeforeMethod;
@@ -34,12 +32,12 @@
3432 import static org.assertj.core.api.Assertions.assertThat;
3533
3634 import com.datastax.driver.core.querybuilder.BuiltStatement;
35+import com.datastax.driver.core.utils.CassandraVersion;
3736
38-import static com.datastax.driver.core.TypeTokens.listOf;
39-import static com.datastax.driver.core.TypeTokens.mapOf;
40-import static com.datastax.driver.core.TypeTokens.setOf;
4137 import static com.datastax.driver.core.querybuilder.QueryBuilder.bindMarker;
4238 import static com.datastax.driver.core.querybuilder.QueryBuilder.eq;
39+import static com.datastax.driver.core.querybuilder.QueryBuilder.insertInto;
40+import static com.datastax.driver.core.querybuilder.QueryBuilder.select;
4341
4442 @CassandraVersion(major=2.0)
4543 public class TypeCodecCollectionsIntegrationTest extends CCMBridge.PerClassSingleNodeCluster {
@@ -75,7 +73,7 @@
7573
7674 @BeforeMethod(groups = "short")
7775 public void createBuiltStatements() throws Exception {
78- insertStmt = new QueryBuilder(cluster).insertInto("\"myTable2\"")
76+ insertStmt = insertInto("\"myTable2\"")
7977 .value("c_int", bindMarker())
8078 .value("l_int", bindMarker())
8179 .value("l_bigint", bindMarker())
@@ -83,7 +81,7 @@
8381 .value("s_double", bindMarker())
8482 .value("m_varint", bindMarker())
8583 .value("m_decimal", bindMarker());
86- selectStmt = new QueryBuilder(cluster).select("c_int", "l_int", "l_bigint", "s_float", "s_double", "m_varint", "m_decimal")
84+ selectStmt = select("c_int", "l_int", "l_bigint", "s_float", "s_double", "m_varint", "m_decimal")
8785 .from("\"myTable2\"")
8886 .where(eq("c_int", bindMarker()));
8987 }
modified driver-core/src/test/java/com/datastax/driver/core/TypeCodecEncapsulationIntegrationTest.java +4 −3
@@ -31,11 +31,12 @@
3131
3232 import com.datastax.driver.core.exceptions.InvalidTypeException;
3333 import com.datastax.driver.core.querybuilder.BuiltStatement;
34-import com.datastax.driver.core.querybuilder.QueryBuilder;
3534 import com.datastax.driver.core.utils.CassandraVersion;
3635
3736 import static com.datastax.driver.core.querybuilder.QueryBuilder.bindMarker;
3837 import static com.datastax.driver.core.querybuilder.QueryBuilder.eq;
38+import static com.datastax.driver.core.querybuilder.QueryBuilder.insertInto;
39+import static com.datastax.driver.core.querybuilder.QueryBuilder.select;
3940
4041 public class TypeCodecEncapsulationIntegrationTest extends CCMBridge.PerClassSingleNodeCluster {
4142
@@ -85,14 +86,14 @@
8586
8687 @BeforeMethod(groups = "short")
8788 public void createBuiltStatements() throws Exception {
88- insertStmt = new QueryBuilder(cluster).insertInto("\"myTable\"")
89+ insertStmt = insertInto("\"myTable\"")
8990 .value("c_int", bindMarker())
9091 .value("c_bigint", bindMarker())
9192 .value("c_float", bindMarker())
9293 .value("c_double", bindMarker())
9394 .value("c_varint", bindMarker())
9495 .value("c_decimal", bindMarker());
95- selectStmt = new QueryBuilder(cluster).select("c_int", "c_bigint", "c_float", "c_double", "c_varint", "c_decimal")
96+ selectStmt = select("c_int", "c_bigint", "c_float", "c_double", "c_varint", "c_decimal")
9697 .from("\"myTable\"")
9798 .where(eq("c_int", bindMarker()))
9899 .and(eq("c_bigint", bindMarker()));
modified driver-core/src/test/java/com/datastax/driver/core/TypeCodecNestedCollectionsIntegrationTest.java +4 −3
@@ -30,11 +30,12 @@
3030
3131 import com.datastax.driver.core.exceptions.InvalidTypeException;
3232 import com.datastax.driver.core.querybuilder.BuiltStatement;
33-import com.datastax.driver.core.querybuilder.QueryBuilder;
3433 import com.datastax.driver.core.utils.CassandraVersion;
3534
3635 import static com.datastax.driver.core.querybuilder.QueryBuilder.bindMarker;
3736 import static com.datastax.driver.core.querybuilder.QueryBuilder.eq;
37+import static com.datastax.driver.core.querybuilder.QueryBuilder.insertInto;
38+import static com.datastax.driver.core.querybuilder.QueryBuilder.select;
3839
3940 /**
4041 * Validates that nested collections are properly encoded,
@@ -84,10 +85,10 @@
8485
8586 @BeforeMethod(groups = "short")
8687 public void createBuiltStatements() throws Exception {
87- insertStmt = new QueryBuilder(cluster).insertInto("\"myTable\"")
88+ insertStmt = insertInto("\"myTable\"")
8889 .value("pk", bindMarker())
8990 .value("v", bindMarker());
90- selectStmt = new QueryBuilder(cluster).select("pk", "v")
91+ selectStmt = select("pk", "v")
9192 .from("\"myTable\"")
9293 .where(eq("pk", bindMarker()));
9394 }
modified driver-core/src/test/java/com/datastax/driver/core/policies/DowngradingConsistencyRetryPolicyIntegrationTest.java +1 −1
@@ -90,7 +90,7 @@
9090 RetryPolicy retryPolicy = session.getCluster().getConfiguration().getPolicies().getRetryPolicy();
9191 Mockito.reset(retryPolicy);
9292
93- Statement s = session.newSimpleStatement("SELECT * FROM test.foo WHERE k = 0")
93+ Statement s = new SimpleStatement("SELECT * FROM test.foo WHERE k = 0")
9494 .setConsistencyLevel(requested);
9595
9696 ResultSet rs = session.execute(s);
modified driver-core/src/test/java/com/datastax/driver/core/policies/IdempotenceAwareRetryPolicyIntegrationTest.java +3 −3
@@ -63,7 +63,7 @@
6363 @Test(groups = "short")
6464 public void should_retry_on_write_timeout_if_statement_idempotent() {
6565 simulateError(1, write_request_timeout);
66- session.execute(session.newSimpleStatement("mock query").setIdempotent(true));
66+ session.execute(new SimpleStatement("mock query").setIdempotent(true));
6767 assertOnWriteTimeoutWasCalled(1);
6868 assertThat(errors.getWriteTimeouts().getCount()).isEqualTo(1);
6969 assertThat(errors.getRetries().getCount()).isEqualTo(1);
@@ -111,7 +111,7 @@
111111 .withQuery("mock query")
112112 .withThen(then().withFixedDelay(1000L).withRows(row("result", "result1")))
113113 .build());
114- session.execute(session.newSimpleStatement("mock query").setIdempotent(true));
114+ session.execute(new SimpleStatement("mock query").setIdempotent(true));
115115 assertOnRequestErrorWasCalled(1, OperationTimedOutException.class);
116116 assertThat(errors.getClientTimeouts().getCount()).isEqualTo(1);
117117 assertThat(errors.getRetries().getCount()).isEqualTo(1);
@@ -157,7 +157,7 @@
157157 simulateError(2, error);
158158 simulateError(3, error);
159159 try {
160- session.execute(session.newSimpleStatement("mock query").setIdempotent(true));
160+ session.execute(new SimpleStatement("mock query").setIdempotent(true));
161161 fail("expected a NoHostAvailableException");
162162 } catch (NoHostAvailableException e) {
163163 assertThat(e.getErrors().keySet()).hasSize(3).containsOnly(
modified driver-core/src/test/java/com/datastax/driver/core/policies/TokenAwarePolicyTest.java +4 −4
@@ -97,7 +97,7 @@
9797
9898 // then: generating a query plan on a statement using that routing key should properly prioritize node 6 and its replicas.
9999 // Actual query does not matter, only the keyspace and routing key will be used
100- SimpleStatement statement = session.newSimpleStatement("select * from table where k=5");
100+ SimpleStatement statement = new SimpleStatement("select * from table where k=5");
101101 statement.setRoutingKey(routingKey);
102102 statement.setKeyspace("keyspace");
103103
@@ -154,7 +154,7 @@
154154
155155 // Encodes into murmur hash '4557949199137838892' which should belong be owned by node 3.
156156 ByteBuffer routingKey = TypeCodec.varchar().serialize("should_choose_proper_host_based_on_routing_key", ProtocolVersion.NEWEST_SUPPORTED);
157- SimpleStatement statement = session.newSimpleStatement("select * from table where k=5")
157+ SimpleStatement statement = new SimpleStatement("select * from table where k=5")
158158 .setRoutingKey(routingKey)
159159 .setKeyspace("keyspace");
160160
@@ -200,7 +200,7 @@
200200
201201 // Encodes into murmur hash '-8124212968526248339' which should belong to 1:1 in DC1 and 2:1 in DC2.
202202 ByteBuffer routingKey = TypeCodec.varchar().serialize("should_choose_host_in_local_dc_when_using_network_topology_strategy_and_dc_aware", ProtocolVersion.NEWEST_SUPPORTED);
203- SimpleStatement statement = session.newSimpleStatement("select * from table where k=5")
203+ SimpleStatement statement = new SimpleStatement("select * from table where k=5")
204204 .setRoutingKey(routingKey)
205205 .setKeyspace("keyspace");
206206
@@ -243,7 +243,7 @@
243243 // when: A query is made with a routing key and both hosts having that key's token are down.
244244 // Encodes into murmur hash '6444339665561646341' which should belong to node 4.
245245 ByteBuffer routingKey = TypeCodec.varchar().serialize("should_use_other_nodes_when_replicas_having_token_are_down", ProtocolVersion.NEWEST_SUPPORTED);
246- SimpleStatement statement = session.newSimpleStatement("select * from table where k=5")
246+ SimpleStatement statement = new SimpleStatement("select * from table where k=5")
247247 .setRoutingKey(routingKey)
248248 .setKeyspace("keyspace");
249249
modified driver-core/src/test/java/com/datastax/driver/core/querybuilder/QueryBuilder21ExecutionTest.java +13 −18
@@ -15,26 +15,26 @@
1515 */
1616 package com.datastax.driver.core.querybuilder;
1717
18+import java.util.Arrays;
19+import java.util.Collection;
20+
21+import org.testng.annotations.Test;
22+
1823 import com.datastax.driver.core.CCMBridge;
1924 import com.datastax.driver.core.PreparedStatement;
2025 import com.datastax.driver.core.ResultSet;
2126 import com.datastax.driver.core.Row;
2227 import com.datastax.driver.core.utils.CassandraVersion;
2328
24-import org.testng.annotations.BeforeMethod;
25-import org.testng.annotations.Test;
26-
27-import java.util.Arrays;
28-import java.util.Collection;
29-
3029 import static com.datastax.driver.core.Assertions.assertThat;
31-import static com.datastax.driver.core.querybuilder.QueryBuilder.*;
30+import static com.datastax.driver.core.querybuilder.QueryBuilder.bindMarker;
31+import static com.datastax.driver.core.querybuilder.QueryBuilder.contains;
32+import static com.datastax.driver.core.querybuilder.QueryBuilder.containsKey;
33+import static com.datastax.driver.core.querybuilder.QueryBuilder.select;
3234
3335 @CassandraVersion(major=2.1)
3436 public class QueryBuilder21ExecutionTest extends CCMBridge.PerClassSingleNodeCluster {
3537
36- private QueryBuilder builder;
37-
3838 @Override
3939 protected Collection<String> getTableDefinitions() {
4040 // Taken from http://www.datastax.com/dev/blog/cql-in-2-1
@@ -53,14 +53,9 @@
5353 );
5454 }
5555
56- @BeforeMethod(groups = "short")
57- public void setUpQueryBuilder() throws Exception {
58- builder = new QueryBuilder(cluster);
59- }
60-
6156 @Test(groups="short")
6257 public void should_handle_contains_on_set_with_index() {
63- PreparedStatement byCategory = session.prepare(builder.select("id", "description", "categories")
58+ PreparedStatement byCategory = session.prepare(select("id", "description", "categories")
6459 .from("products")
6560 .where(contains("categories", bindMarker("category"))));
6661
@@ -74,7 +69,7 @@
7469
7570 @Test(groups="short")
7671 public void should_handle_contains_on_list_with_index() {
77- PreparedStatement byBuyer = session.prepare(builder.select("id", "description", "buyers")
72+ PreparedStatement byBuyer = session.prepare(select("id", "description", "buyers")
7873 .from("products")
7974 .where(contains("buyers", bindMarker("buyer"))));
8075
@@ -88,7 +83,7 @@
8883
8984 @Test(groups="short")
9085 public void should_handle_contains_on_map_with_index() {
91- PreparedStatement byFeatures = session.prepare(builder.select("id", "description", "features_values")
86+ PreparedStatement byFeatures = session.prepare(select("id", "description", "features_values")
9287 .from("products")
9388 .where(contains("features_values", bindMarker("feature"))));
9489
@@ -103,7 +98,7 @@
10398
10499 @Test(groups="short")
105100 public void should_handle_contains_key_on_map_with_index() {
106- PreparedStatement byFeatures = session.prepare(builder.select("id", "description", "features_keys")
101+ PreparedStatement byFeatures = session.prepare(select("id", "description", "features_keys")
107102 .from("products")
108103 .where(containsKey("features_keys", bindMarker("feature"))));
109104
modified driver-core/src/test/java/com/datastax/driver/core/querybuilder/QueryBuilderExecutionTest.java +18 −26
@@ -17,7 +17,6 @@
1717
1818 import java.util.*;
1919
20-import org.testng.annotations.BeforeMethod;
2120 import org.testng.annotations.Test;
2221
2322 import static org.assertj.core.api.Assertions.assertThat;
@@ -34,8 +33,6 @@
3433
3534 private static final String TABLE1 = "test1";
3635
37- private QueryBuilder builder;
38-
3936 @Override
4037 protected Collection<String> getTableDefinitions() {
4138 return Arrays.asList(
@@ -44,18 +41,13 @@
4441 "CREATE TABLE test_coll (k int PRIMARY KEY, a list<int>, b map<int,text>, c set<text>)");
4542 }
4643
47- @BeforeMethod(groups = "short")
48- public void setUpQueryBuilder() throws Exception {
49- builder = new QueryBuilder(cluster);
50- }
51-
5244 @Test(groups = "short")
5345 public void executeTest() throws Exception {
5446
55- session.execute(builder.insertInto(TABLE1).value("k", "k1").value("t", "This is a test").value("i", 3).value("f", 0.42));
56- session.execute(builder.update(TABLE1).with(set("t", "Another test")).where(eq("k", "k2")));
47+ session.execute(insertInto(TABLE1).value("k", "k1").value("t", "This is a test").value("i", 3).value("f", 0.42));
48+ session.execute(update(TABLE1).with(set("t", "Another test")).where(eq("k", "k2")));
5749
58- List<Row> rows = session.execute(builder.select().from(TABLE1).where(in("k", "k1", "k2"))).all();
50+ List<Row> rows = session.execute(select().from(TABLE1).where(in("k", "k1", "k2"))).all();
5951
6052 assertEquals(2, rows.size());
6153
@@ -76,8 +68,8 @@
7668 public void dateHandlingTest() throws Exception {
7769
7870 Date d = new Date();
79- session.execute(builder.insertInto("dateTest").value("t", d));
80- String query = builder.select().from("dateTest").where(eq(token("t"), fcall("token", d))).toString();
71+ session.execute(insertInto("dateTest").value("t", d));
72+ String query = select().from("dateTest").where(eq(token("t"), fcall("token", d))).toString();
8173 List<Row> rows = session.execute(query).all();
8274
8375 assertEquals(1, rows.size());
@@ -90,21 +82,21 @@
9082 public void prepareTest() throws Exception {
9183 // Just check we correctly avoid values when there is a bind marker
9284 String query = "INSERT INTO foo (a,b,c,d) VALUES ('foo','bar',?,0);";
93- BuiltStatement stmt = builder.insertInto("foo").value("a", "foo").value("b", "bar").value("c", bindMarker()).value("d", 0);
85+ BuiltStatement stmt = insertInto("foo").value("a", "foo").value("b", "bar").value("c", bindMarker()).value("d", 0);
9486 assertEquals(stmt.getQueryString(), query);
9587
9688 query = "INSERT INTO foo (a,b,c,d) VALUES ('foo','bar',:c,0);";
97- stmt = builder.insertInto("foo").value("a", "foo").value("b", "bar").value("c", bindMarker("c")).value("d", 0);
89+ stmt = insertInto("foo").value("a", "foo").value("b", "bar").value("c", bindMarker("c")).value("d", 0);
9890 assertEquals(stmt.getQueryString(), query);
9991 }
10092
10193 @Test(groups = "short")
10294 public void batchNonBuiltStatementTest() throws Exception {
103- SimpleStatement simple = session.newSimpleStatement("INSERT INTO " + TABLE1 + " (k, t) VALUES ('batchTest1', 'val1')");
104- RegularStatement built = builder.insertInto(TABLE1).value("k", "batchTest2").value("t", "val2");
105- session.execute(builder.batch().add(simple).add(built));
106-
107- List<Row> rows = session.execute(builder.select().from(TABLE1).where(in("k", "batchTest1", "batchTest2"))).all();
95+ SimpleStatement simple = new SimpleStatement("INSERT INTO " + TABLE1 + " (k, t) VALUES ('batchTest1', 'val1')");
96+ RegularStatement built = insertInto(TABLE1).value("k", "batchTest2").value("t", "val2");
97+ session.execute(batch().add(simple).add(built));
98+
99+ List<Row> rows = session.execute(select().from(TABLE1).where(in("k", "batchTest1", "batchTest2"))).all();
108100 assertEquals(2, rows.size());
109101
110102 Row r1 = rows.get(0);
@@ -121,7 +113,7 @@
121113 //given
122114 session.execute("INSERT INTO test_coll (k, a, b) VALUES (1, [1,2,3], null)");
123115 //when
124- BuiltStatement statement = builder.delete().listElt("a", 1).from("test_coll").where(eq("k", 1));
116+ BuiltStatement statement = delete().listElt("a", 1).from("test_coll").where(eq("k", 1));
125117 session.execute(statement);
126118 //then
127119 List<Integer> actual = session.execute("SELECT a FROM test_coll WHERE k = 1").one().getList("a", Integer.class);
@@ -133,7 +125,7 @@
133125 //given
134126 session.execute("INSERT INTO test_coll (k, a) VALUES (1, [1,2,3])");
135127 //when
136- BuiltStatement statement = builder.delete().listElt("a", bindMarker()).from("test_coll").where(eq("k", 1));
128+ BuiltStatement statement = delete().listElt("a", bindMarker()).from("test_coll").where(eq("k", 1));
137129 PreparedStatement ps = session.prepare(statement);
138130 session.execute(ps.bind(1));
139131 //then
@@ -146,7 +138,7 @@
146138 //given
147139 session.execute("INSERT INTO test_coll (k, c) VALUES (1, {'foo','bar','qix'})");
148140 //when
149- BuiltStatement statement = builder.delete().setElt("c", "foo").from("test_coll").where(eq("k", 1));
141+ BuiltStatement statement = delete().setElt("c", "foo").from("test_coll").where(eq("k", 1));
150142 session.execute(statement);
151143 //then
152144 Set<String> actual = session.execute("SELECT c FROM test_coll WHERE k = 1").one().getSet("c", String.class);
@@ -158,7 +150,7 @@
158150 //given
159151 session.execute("INSERT INTO test_coll (k, c) VALUES (1, {'foo','bar','qix'})");
160152 //when
161- BuiltStatement statement = builder.delete().setElt("c", bindMarker()).from("test_coll").where(eq("k", 1));
153+ BuiltStatement statement = delete().setElt("c", bindMarker()).from("test_coll").where(eq("k", 1));
162154 PreparedStatement ps = session.prepare(statement);
163155 session.execute(ps.bind("foo"));
164156 //then
@@ -171,7 +163,7 @@
171163 //given
172164 session.execute("INSERT INTO test_coll (k, b) VALUES (1, {1:'foo', 2:'bar'})");
173165 //when
174- BuiltStatement statement = builder.delete().mapElt("b", 1).from("test_coll").where(eq("k", 1));
166+ BuiltStatement statement = delete().mapElt("b", 1).from("test_coll").where(eq("k", 1));
175167 session.execute(statement);
176168 //then
177169 Map<Integer, String> actual = session.execute("SELECT b FROM test_coll WHERE k = 1").one().getMap("b", Integer.class, String.class);
@@ -183,7 +175,7 @@
183175 //given
184176 session.execute("INSERT INTO test_coll (k, a, b) VALUES (1, null, {1:'foo', 2:'bar'})");
185177 //when
186- BuiltStatement statement = builder.delete().mapElt("b", bindMarker()).from("test_coll").where(eq("k", 1));
178+ BuiltStatement statement = delete().mapElt("b", bindMarker()).from("test_coll").where(eq("k", 1));
187179 PreparedStatement ps = session.prepare(statement);
188180 session.execute(ps.bind().setInt(0, 1));
189181 //then
modified driver-core/src/test/java/com/datastax/driver/core/querybuilder/QueryBuilderITest.java +37 −44
@@ -19,7 +19,6 @@
1919 import java.util.Collection;
2020 import java.util.TreeSet;
2121
22-import org.testng.annotations.BeforeMethod;
2322 import org.testng.annotations.Test;
2423
2524 import static org.testng.Assert.*;
@@ -34,7 +33,6 @@
3433
3534 private static final String TABLE_TEXT = "test_text";
3635 private static final String TABLE_INT = "test_int";
37- private QueryBuilder builder;
3836
3937 @Override
4038 protected Collection<String> getTableDefinitions() {
@@ -51,11 +49,6 @@
5149 );
5250 }
5351
54- @BeforeMethod(groups = "short")
55- public void setUpQueryBuilder() throws Exception {
56- builder = new QueryBuilder(cluster);
57- }
58-
5952 @Test(groups = "short")
6053 public void remainingDeleteTests() throws Exception {
6154
@@ -64,7 +57,7 @@
6457 assertNotNull(table);
6558
6659 String expected = String.format("DELETE k FROM %s.test_text;", keyspace);
67- query = builder.delete("k").from(table);
60+ query = delete("k").from(table);
6861 assertEquals(query.toString(), expected);
6962 try {
7063 session.execute(query);
@@ -87,52 +80,52 @@
8780 session.execute("USE foo");
8881
8982 query = "SELECT * FROM foo WHERE k=?;";
90- select = builder.select().all().from("foo").where(eq("k", QueryBuilder.bindMarker()));
83+ select = select().all().from("foo").where(eq("k", QueryBuilder.bindMarker()));
9184 ps = session.prepare(select.toString());
9285 bs = ps.bind();
9386 assertEquals(select.toString(), query);
9487 session.execute(bs.setString("k", "4 AND c=5"));
9588
9689 query = "SELECT * FROM foo WHERE k='4'' AND c=''5';";
97- select = builder.select().all().from("foo").where(eq("k", "4' AND c='5"));
90+ select = select().all().from("foo").where(eq("k", "4' AND c='5"));
9891 assertEquals(select.toString(), query);
9992
10093 query = "SELECT * FROM foo WHERE k='4'' OR ''1''=''1';";
101- select = builder.select().all().from("foo").where(eq("k", "4' OR '1'='1"));
94+ select = select().all().from("foo").where(eq("k", "4' OR '1'='1"));
10295 assertEquals(select.toString(), query);
10396
10497 query = "SELECT * FROM foo WHERE k='4; --test comment;';";
105- select = builder.select().all().from("foo").where(eq("k", "4; --test comment;"));
98+ select = select().all().from("foo").where(eq("k", "4; --test comment;"));
10699 assertEquals(select.toString(), query);
107100
108101 query = "SELECT \"*\" FROM foo;";
109- select = builder.select("*").from("foo");
102+ select = select("*").from("foo");
110103 assertEquals(select.toString(), query);
111104
112105 query = "SELECT a,b FROM foo WHERE a IN ('b','c''); --comment');";
113- select = builder.select("a", "b").from("foo")
106+ select = select("a", "b").from("foo")
114107 .where(in("a", "b", "c'); --comment"));
115108 assertEquals(select.toString(), query);
116109
117110 // User Injection?
118111 query = "SELECT * FROM bar; --(b) FROM foo;";
119- select = builder.select().fcall("* FROM bar; --", column("b")).from("foo");
112+ select = select().fcall("* FROM bar; --", column("b")).from("foo");
120113 assertEquals(select.toString(), query);
121114
122115 query = "SELECT writetime(\"a) FROM bar; --\"),ttl(a) FROM foo ALLOW FILTERING;";
123- select = builder.select().writeTime("a) FROM bar; --").ttl("a").from("foo").allowFiltering();
116+ select = select().writeTime("a) FROM bar; --").ttl("a").from("foo").allowFiltering();
124117 assertEquals(select.toString(), query);
125118
126119 query = "SELECT writetime(a),ttl(\"a) FROM bar; --\") FROM foo ALLOW FILTERING;";
127- select = builder.select().writeTime("a").ttl("a) FROM bar; --").from("foo").allowFiltering();
120+ select = select().writeTime("a").ttl("a) FROM bar; --").from("foo").allowFiltering();
128121 assertEquals(select.toString(), query);
129122
130123 query = "SELECT * FROM foo WHERE \"k=1 OR k\">42 LIMIT 42;";
131- select = builder.select().all().from("foo").where(gt("k=1 OR k", 42)).limit(42);
124+ select = select().all().from("foo").where(gt("k=1 OR k", 42)).limit(42);
132125 assertEquals(select.toString(), query);
133126
134127 query = "SELECT * FROM foo WHERE token(\"k)>0 OR token(k\")>token(42);";
135- select = builder.select().all().from("foo").where(gt(token("k)>0 OR token(k"), fcall("token", 42)));
128+ select = select().all().from("foo").where(gt(token("k)>0 OR token(k"), fcall("token", 42)));
136129 assertEquals(select.toString(), query);
137130 }
138131
@@ -144,17 +137,17 @@
144137 Statement insert;
145138
146139 query = "INSERT INTO foo (a) VALUES ('123); --comment');";
147- insert = builder.insertInto("foo")
140+ insert = insertInto("foo")
148141 .value("a", "123); --comment");
149142 assertEquals(insert.toString(), query);
150143
151144 query = "INSERT INTO foo (\"a,b\") VALUES (123);";
152- insert = builder.insertInto("foo")
145+ insert = insertInto("foo")
153146 .value("a,b", 123);
154147 assertEquals(insert.toString(), query);
155148
156149 query = "INSERT INTO foo (a,b) VALUES ({'2''} space','3','4'},3.4) USING TTL 24 AND TIMESTAMP 42;";
157- insert = builder.insertInto("foo").values(new String[]{ "a", "b"}, new Object[]{ new TreeSet<String>(){{ add("2'} space"); add("3"); add("4"); }}, 3.4 }).using(ttl(24)).and(timestamp(42));
150+ insert = insertInto("foo").values(new String[]{ "a", "b"}, new Object[]{ new TreeSet<String>(){{ add("2'} space"); add("3"); add("4"); }}, 3.4 }).using(ttl(24)).and(timestamp(42));
158151 assertEquals(insert.toString(), query);
159152 }
160153
@@ -165,15 +158,15 @@
165158 Statement update;
166159
167160 query = "UPDATE foo.bar USING TIMESTAMP 42 SET a=12 WHERE k='2 OR 1=1';";
168- update = builder.update("foo", "bar").using(timestamp(42)).with(set("a", 12)).where(eq("k", "2 OR 1=1"));
161+ update = update("foo", "bar").using(timestamp(42)).with(set("a", 12)).where(eq("k", "2 OR 1=1"));
169162 assertEquals(update.toString(), query);
170163
171164 query = "UPDATE foo SET b='null WHERE k=1; --comment' WHERE k=2;";
172- update = builder.update("foo").where().and(eq("k", 2)).with(set("b", "null WHERE k=1; --comment"));
165+ update = update("foo").where().and(eq("k", 2)).with(set("b", "null WHERE k=1; --comment"));
173166 assertEquals(update.toString(), query);
174167
175168 query = "UPDATE foo USING TIMESTAMP 42 SET \"b WHERE k=1; --comment\"=[3,2,1]+\"b WHERE k=1; --comment\" WHERE k=2;";
176- update = builder.update("foo").where().and(eq("k", 2)).with(prependAll("b WHERE k=1; --comment", Arrays.asList(3, 2, 1))).using(timestamp(42));
169+ update = update("foo").where().and(eq("k", 2)).with(prependAll("b WHERE k=1; --comment", Arrays.asList(3, 2, 1))).using(timestamp(42));
177170 assertEquals(update.toString(), query);
178171 }
179172
@@ -184,40 +177,40 @@
184177 Statement delete;
185178
186179 query = "DELETE FROM \"foo WHERE k=4\";";
187- delete = builder.delete().from("foo WHERE k=4");
180+ delete = delete().from("foo WHERE k=4");
188181 assertEquals(delete.toString(), query);
189182
190183 query = "DELETE FROM foo WHERE k='4 AND c=5';";
191- delete = builder.delete().from("foo").where(eq("k", "4 AND c=5"));
184+ delete = delete().from("foo").where(eq("k", "4 AND c=5"));
192185 assertEquals(delete.toString(), query);
193186
194187 query = "DELETE FROM foo WHERE k='4'' AND c=''5';";
195- delete = builder.delete().from("foo").where(eq("k", "4' AND c='5"));
188+ delete = delete().from("foo").where(eq("k", "4' AND c='5"));
196189 assertEquals(delete.toString(), query);
197190
198191 query = "DELETE FROM foo WHERE k='4'' OR ''1''=''1';";
199- delete = builder.delete().from("foo").where(eq("k", "4' OR '1'='1"));
192+ delete = delete().from("foo").where(eq("k", "4' OR '1'='1"));
200193 assertEquals(delete.toString(), query);
201194
202195 query = "DELETE FROM foo WHERE k='4; --test comment;';";
203- delete = builder.delete().from("foo").where(eq("k", "4; --test comment;"));
196+ delete = delete().from("foo").where(eq("k", "4; --test comment;"));
204197 assertEquals(delete.toString(), query);
205198
206199 query = "DELETE \"*\" FROM foo;";
207- delete = builder.delete("*").from("foo");
200+ delete = delete("*").from("foo");
208201 assertEquals(delete.toString(), query);
209202
210203 query = "DELETE a,b FROM foo WHERE a IN ('b','c''); --comment');";
211- delete = builder.delete("a", "b").from("foo")
204+ delete = delete("a", "b").from("foo")
212205 .where(in("a", "b", "c'); --comment"));
213206 assertEquals(delete.toString(), query);
214207
215208 query = "DELETE FROM foo WHERE \"k=1 OR k\">42;";
216- delete = builder.delete().from("foo").where(gt("k=1 OR k", 42));
209+ delete = delete().from("foo").where(gt("k=1 OR k", 42));
217210 assertEquals(delete.toString(), query);
218211
219212 query = "DELETE FROM foo WHERE token(\"k)>0 OR token(k\")>token(42);";
220- delete = builder.delete().from("foo").where(gt(token("k)>0 OR token(k"), fcall("token", 42)));
213+ delete = delete().from("foo").where(gt(token("k)>0 OR token(k"), fcall("token", 42)));
221214 assertEquals(delete.toString(), query);
222215 }
223216
@@ -228,21 +221,21 @@
228221
229222 Statement delete;
230223 Row row;
231- delete = builder.delete().from(keyspace, TABLE_INT).where(eq("k", 2)).ifExists();
224+ delete = delete().from(keyspace, TABLE_INT).where(eq("k", 2)).ifExists();
232225 row = session.execute(delete).one();
233226 assertFalse(row.getBool("[applied]"));
234227
235- delete = builder.delete().from(keyspace, TABLE_INT).where(eq("k", 1)).ifExists();
228+ delete = delete().from(keyspace, TABLE_INT).where(eq("k", 1)).ifExists();
236229 row = session.execute(delete).one();
237230 assertTrue(row.getBool("[applied]"));
238231
239232 session.execute(String.format("INSERT INTO %s.test_int (k, a, b) VALUES (1, 1, 1)", keyspace));
240233
241- delete = builder.delete().from(keyspace, TABLE_INT).where(eq("k", 1)).onlyIf(eq("a", 1)).and(eq("b", 2));
234+ delete = delete().from(keyspace, TABLE_INT).where(eq("k", 1)).onlyIf(eq("a", 1)).and(eq("b", 2));
242235 row = session.execute(delete).one();
243236 assertFalse(row.getBool("[applied]"));
244237
245- delete = builder.delete().from(keyspace, TABLE_INT).where(eq("k", 1)).onlyIf(eq("a", 1)).and(eq("b", 1));
238+ delete = delete().from(keyspace, TABLE_INT).where(eq("k", 1)).onlyIf(eq("a", 1)).and(eq("b", 1));
246239 row = session.execute(delete).one();
247240 assertTrue(row.getBool("[applied]"));
248241 }
@@ -254,27 +247,27 @@
254247
255248 Statement update;
256249 Row row;
257- update = builder.update(TABLE_INT).with(set("a", 2)).and(set("b", 2)).where(eq("k", 2)).ifExists();
250+ update = update(TABLE_INT).with(set("a", 2)).and(set("b", 2)).where(eq("k", 2)).ifExists();
258251 row = session.execute(update).one();
259252 assertFalse(row.getBool("[applied]"));
260253
261- update = builder.update(TABLE_INT).with(set("a", 2)).and(set("b", 2)).where(eq("k", 1)).ifExists();
254+ update = update(TABLE_INT).with(set("a", 2)).and(set("b", 2)).where(eq("k", 1)).ifExists();
262255 row = session.execute(update).one();
263256 assertTrue(row.getBool("[applied]"));
264257
265- update = builder.update(TABLE_INT).with(set("a", 2)).and(set("b", 2)).where(eq("k", 2)).onlyIf(eq("a", 1)).and(eq("b", 2));
258+ update = update(TABLE_INT).with(set("a", 2)).and(set("b", 2)).where(eq("k", 2)).onlyIf(eq("a", 1)).and(eq("b", 2));
266259 row = session.execute(update).one();
267260 assertFalse(row.getBool("[applied]"));
268261
269- update = builder.update(TABLE_INT).with(set("a", 3)).and(set("b", 3)).where(eq("k", 1)).onlyIf(eq("a", 2)).and(eq("b", 2));
262+ update = update(TABLE_INT).with(set("a", 3)).and(set("b", 3)).where(eq("k", 1)).onlyIf(eq("a", 2)).and(eq("b", 2));
270263 row = session.execute(update).one();
271264 assertTrue(row.getBool("[applied]"));
272265
273- update = builder.update(TABLE_INT).with(set("a", 4)).and(set("b", 4)).onlyIf(eq("a", 2)).and(eq("b", 2)).where(eq("k", 1));
266+ update = update(TABLE_INT).with(set("a", 4)).and(set("b", 4)).onlyIf(eq("a", 2)).and(eq("b", 2)).where(eq("k", 1));
274267 row = session.execute(update).one();
275268 assertFalse(row.getBool("[applied]"));
276269
277- update = builder.update(TABLE_INT).with(set("a", 4)).and(set("b", 4)).onlyIf(eq("a", 3)).and(eq("b", 3)).where(eq("k", 1));
270+ update = update(TABLE_INT).with(set("a", 4)).and(set("b", 4)).onlyIf(eq("a", 3)).and(eq("b", 3)).where(eq("k", 1));
278271 row = session.execute(update).one();
279272 assertTrue(row.getBool("[applied]"));
280273 }
modified driver-core/src/test/java/com/datastax/driver/core/querybuilder/QueryBuilderRoutingKeyTest.java +25 −21
@@ -54,15 +54,16 @@
5454 BuiltStatement query;
5555 TableMetadata table = cluster.getMetadata().getKeyspace(keyspace).getTable(TABLE_TEXT);
5656 assertNotNull(table);
57+ ProtocolVersion protocolVersion = cluster.getConfiguration().getProtocolOptions().getProtocolVersion();
58+ CodecRegistry codecRegistry = CodecRegistry.DEFAULT_INSTANCE;
5759
5860 String txt = "If she weighs the same as a duck... she's made of wood.";
59- QueryBuilder builder = new QueryBuilder(cluster);
60- query = builder.insertInto(table).values(new String[]{"k", "a", "b"}, new Object[]{txt, 1, 2});
61- assertEquals(query.getRoutingKey(), ByteBuffer.wrap(txt.getBytes()));
61+ query = insertInto(table).values(new String[]{"k", "a", "b"}, new Object[]{txt, 1, 2});
62+ assertEquals(query.getRoutingKey(protocolVersion, codecRegistry), ByteBuffer.wrap(txt.getBytes()));
6263 session.execute(query);
6364
64- query = builder.select().from(table).where(eq("k", txt));
65- assertEquals(query.getRoutingKey(), ByteBuffer.wrap(txt.getBytes()));
65+ query = select().from(table).where(eq("k", txt));
66+ assertEquals(query.getRoutingKey(protocolVersion, codecRegistry), ByteBuffer.wrap(txt.getBytes()));
6667 Row row = session.execute(query).one();
6768 assertEquals(row.getString("k"), txt);
6869 assertEquals(row.getInt("a"), 1);
@@ -75,15 +76,17 @@
7576 BuiltStatement query;
7677 TableMetadata table = cluster.getMetadata().getKeyspace(keyspace).getTable(TABLE_INT);
7778 assertNotNull(table);
79+ ProtocolVersion protocolVersion = cluster.getConfiguration().getProtocolOptions().getProtocolVersion();
80+ CodecRegistry codecRegistry = CodecRegistry.DEFAULT_INSTANCE;
7881
79- query = new QueryBuilder(cluster).insertInto(table).values(new String[]{"k", "a", "b"}, new Object[]{42, 1, 2});
82+ query = insertInto(table).values(new String[]{"k", "a", "b"}, new Object[]{42, 1, 2});
8083 ByteBuffer bb = ByteBuffer.allocate(4);
8184 bb.putInt(0, 42);
82- assertEquals(query.getRoutingKey(), bb);
85+ assertEquals(query.getRoutingKey(protocolVersion, codecRegistry), bb);
8386 session.execute(query);
8487
85- query = new QueryBuilder(cluster).select().from(table).where(eq("k", 42));
86- assertEquals(query.getRoutingKey(), bb);
88+ query = select().from(table).where(eq("k", 42));
89+ assertEquals(query.getRoutingKey(protocolVersion, codecRegistry), bb);
8790 Row row = session.execute(query).one();
8891 assertEquals(row.getInt("k"), 42);
8992 assertEquals(row.getInt("a"), 1);
@@ -96,6 +99,8 @@
9699 BuiltStatement query;
97100 TableMetadata table = cluster.getMetadata().getKeyspace(keyspace).getTable(TABLE_INT);
98101 assertNotNull(table);
102+ ProtocolVersion protocolVersion = cluster.getConfiguration().getProtocolOptions().getProtocolVersion();
103+ CodecRegistry codecRegistry = CodecRegistry.DEFAULT_INSTANCE;
99104
100105 ByteBuffer bb = ByteBuffer.allocate(4);
101106 bb.putInt(0, 42);
@@ -103,41 +108,40 @@
103108 String batch_query;
104109 BuiltStatement batch;
105110
106- QueryBuilder builder = new QueryBuilder(cluster);
107- query = builder.select().from(table).where(eq("k", 42));
111+ query = select().from(table).where(eq("k", 42));
108112
109113 batch_query = "BEGIN BATCH ";
110114 batch_query += String.format("INSERT INTO %s.test_int (k,a) VALUES (42,1);", keyspace);
111115 batch_query += String.format("UPDATE %s.test_int USING TTL 400;", keyspace);
112116 batch_query += "APPLY BATCH;";
113- batch = builder.batch()
114- .add(builder.insertInto(table).values(new String[]{"k", "a"}, new Object[]{42, 1}))
115- .add(builder.update(table).using(ttl(400)));
116- assertEquals(batch.getRoutingKey(), bb);
117+ batch = batch()
118+ .add(insertInto(table).values(new String[]{ "k", "a" }, new Object[]{ 42, 1 }))
119+ .add(update(table).using(ttl(400)));
120+ assertEquals(batch.getRoutingKey(protocolVersion, codecRegistry), bb);
117121 assertEquals(batch.toString(), batch_query);
118122 // TODO: rs = session.execute(batch); // Not guaranteed to be valid CQL
119123
120124 batch_query = "BEGIN BATCH ";
121125 batch_query += String.format("SELECT * FROM %s.test_int WHERE k=42;", keyspace);
122126 batch_query += "APPLY BATCH;";
123- batch = builder.batch(query);
124- assertEquals(batch.getRoutingKey(), bb);
127+ batch = batch(query);
128+ assertEquals(batch.getRoutingKey(protocolVersion, codecRegistry), bb);
125129 assertEquals(batch.toString(), batch_query);
126130 // TODO: rs = session.execute(batch); // Not guaranteed to be valid CQL
127131
128132 batch_query = "BEGIN BATCH ";
129133 batch_query += "SELECT * FROM foo WHERE k=42;";
130134 batch_query += "APPLY BATCH;";
131- batch = builder.batch().add(builder.select().from("foo").where(eq("k", 42)));
132- assertEquals(batch.getRoutingKey(), null);
135+ batch = batch().add(select().from("foo").where(eq("k", 42)));
136+ assertEquals(batch.getRoutingKey(protocolVersion, codecRegistry), null);
133137 assertEquals(batch.toString(), batch_query);
134138 // TODO: rs = session.execute(batch); // Not guaranteed to be valid CQL
135139
136140 batch_query = "BEGIN BATCH USING TIMESTAMP 42 ";
137141 batch_query += "INSERT INTO foo.bar (a) VALUES (123);";
138142 batch_query += "APPLY BATCH;";
139- batch = builder.batch().using(timestamp(42)).add(builder.insertInto("foo", "bar").value("a", 123));
140- assertEquals(batch.getRoutingKey(), null);
143+ batch = batch().using(timestamp(42)).add(insertInto("foo", "bar").value("a", 123));
144+ assertEquals(batch.getRoutingKey(protocolVersion, codecRegistry), null);
141145 assertEquals(batch.toString(), batch_query);
142146 // TODO: rs = session.execute(batch); // Not guaranteed to be valid CQL
143147 }
modified driver-core/src/test/java/com/datastax/driver/core/querybuilder/QueryBuilderTest.java +172 −173
@@ -41,8 +41,6 @@
4141
4242 public class QueryBuilderTest {
4343
44- private QueryBuilder builder = new QueryBuilder(TestUtils.getDesiredProtocolVersion(), CodecRegistry.DEFAULT_INSTANCE);
45-
4644 @Test(groups = "unit")
4745 public void selectTest() throws Exception {
4846
@@ -50,15 +48,15 @@
5048 Statement select;
5149
5250 query = "SELECT * FROM foo WHERE k=4 AND c>'a' AND c<='z';";
53- select = builder.select().all().from("foo").where(eq("k", 4)).and(gt("c", "a")).and(lte("c", "z"));
51+ select = select().all().from("foo").where(eq("k", 4)).and(gt("c", "a")).and(lte("c", "z"));
5452 assertEquals(select.toString(), query);
5553
5654 // Ensure where() and where(...) are equal
57- select = builder.select().all().from("foo").where().and(eq("k", 4)).and(gt("c", "a")).and(lte("c", "z"));
55+ select = select().all().from("foo").where().and(eq("k", 4)).and(gt("c", "a")).and(lte("c", "z"));
5856 assertEquals(select.toString(), query);
5957
6058 query = "SELECT a,b,\"C\" FROM foo WHERE a IN ('127.0.0.1','127.0.0.3') AND \"C\"='foo' ORDER BY a ASC,b DESC LIMIT 42;";
61- select = builder.select("a", "b", quote("C")).from("foo")
59+ select = select("a", "b", quote("C")).from("foo")
6260 .where(in("a", InetAddress.getByName("127.0.0.1"), InetAddress.getByName("127.0.0.3")))
6361 .and(eq(quote("C"), "foo"))
6462 .orderBy(asc("a"), desc("b"))
@@ -66,113 +64,113 @@
6664 assertEquals(select.toString(), query);
6765
6866 query = "SELECT writetime(a),ttl(a) FROM foo ALLOW FILTERING;";
69- select = builder.select().writeTime("a").ttl("a").from("foo").allowFiltering();
67+ select = select().writeTime("a").ttl("a").from("foo").allowFiltering();
7068 assertEquals(select.toString(), query);
7169
7270 query = "SELECT DISTINCT longName AS a,ttl(longName) AS ttla FROM foo LIMIT :limit;";
73- select = builder.select().distinct().column("longName").as("a").ttl("longName").as("ttla").from("foo").limit(bindMarker("limit"));
71+ select = select().distinct().column("longName").as("a").ttl("longName").as("ttla").from("foo").limit(bindMarker("limit"));
7472 assertEquals(select.toString(), query);
7573
7674 query = "SELECT DISTINCT longName AS a,ttl(longName) AS ttla FROM foo WHERE k IN () LIMIT :limit;";
77- select = builder.select().distinct().column("longName").as("a").ttl("longName").as("ttla").from("foo").where(in("k")).limit(bindMarker("limit"));
75+ select = select().distinct().column("longName").as("a").ttl("longName").as("ttla").from("foo").where(in("k")).limit(bindMarker("limit"));
7876 assertEquals(select.toString(), query);
7977
8078 query = "SELECT * FROM foo WHERE bar=:barmark AND baz=:bazmark LIMIT :limit;";
81- select = builder.select().all().from("foo").where().and(eq("bar", bindMarker("barmark"))).and(eq("baz", bindMarker("bazmark"))).limit(bindMarker("limit"));
79+ select = select().all().from("foo").where().and(eq("bar", bindMarker("barmark"))).and(eq("baz", bindMarker("bazmark"))).limit(bindMarker("limit"));
8280 assertEquals(select.toString(), query);
8381
8482 query = "SELECT a FROM foo WHERE k IN ();";
85- select = builder.select("a").from("foo").where(in("k"));
83+ select = select("a").from("foo").where(in("k"));
8684 assertEquals(select.toString(), query);
8785
8886 query = "SELECT a FROM foo WHERE k IN ?;";
89- select = builder.select("a").from("foo").where(in("k", bindMarker()));
87+ select = select("a").from("foo").where(in("k", bindMarker()));
9088 assertEquals(select.toString(), query);
9189
9290 query = "SELECT DISTINCT a FROM foo WHERE k=1;";
93- select = builder.select("a").distinct().from("foo").where(eq("k", 1));
91+ select = select("a").distinct().from("foo").where(eq("k", 1));
9492 assertEquals(select.toString(), query);
9593
9694 query = "SELECT DISTINCT a,b FROM foo WHERE k=1;";
97- select = builder.select("a", "b").distinct().from("foo").where(eq("k", 1));
95+ select = select("a", "b").distinct().from("foo").where(eq("k", 1));
9896 assertEquals(select.toString(), query);
9997
10098 query = "SELECT count(*) FROM foo;";
101- select = builder.select().countAll().from("foo");
99+ select = select().countAll().from("foo");
102100 assertEquals(select.toString(), query);
103101
104102 query = "SELECT intToBlob(b) FROM foo;";
105- select = builder.select().fcall("intToBlob", column("b")).from("foo");
103+ select = select().fcall("intToBlob", column("b")).from("foo");
106104 assertEquals(select.toString(), query);
107105
108106 query = "SELECT * FROM foo WHERE k>42 LIMIT 42;";
109- select = builder.select().all().from("foo").where(gt("k", 42)).limit(42);
107+ select = select().all().from("foo").where(gt("k", 42)).limit(42);
110108 assertEquals(select.toString(), query);
111109
112110 query = "SELECT * FROM foo WHERE token(k)>token(42);";
113- select = builder.select().all().from("foo").where(gt(token("k"), fcall("token", 42)));
111+ select = select().all().from("foo").where(gt(token("k"), fcall("token", 42)));
114112 assertEquals(select.toString(), query);
115113
116114 query = "SELECT * FROM foo2 WHERE token(a,b)>token(42,101);";
117- select = builder.select().all().from("foo2").where(gt(token("a", "b"), fcall("token", 42, 101)));
115+ select = select().all().from("foo2").where(gt(token("a", "b"), fcall("token", 42, 101)));
118116 assertEquals(select.toString(), query);
119117
120118 query = "SELECT * FROM words WHERE w='):,ydL ;O,D';";
121- select = builder.select().all().from("words").where(eq("w", "):,ydL ;O,D"));
119+ select = select().all().from("words").where(eq("w", "):,ydL ;O,D"));
122120 assertEquals(select.toString(), query);
123121
124122 query = "SELECT * FROM words WHERE w='WA(!:gS)r(UfW';";
125- select = builder.select().all().from("words").where(eq("w", "WA(!:gS)r(UfW"));
123+ select = select().all().from("words").where(eq("w", "WA(!:gS)r(UfW"));
126124 assertEquals(select.toString(), query);
127125
128126 Date date = new Date();
129127 date.setTime(1234325);
130128 query = "SELECT * FROM foo WHERE d=1234325;";
131- select = builder.select().all().from("foo").where(eq("d", date));
129+ select = select().all().from("foo").where(eq("d", date));
132130 assertEquals(select.toString(), query);
133131
134132 query = "SELECT * FROM foo WHERE b=0xcafebabe;";
135- select = builder.select().all().from("foo").where(eq("b", Bytes.fromHexString("0xCAFEBABE")));
133+ select = select().all().from("foo").where(eq("b", Bytes.fromHexString("0xCAFEBABE")));
136134 assertEquals(select.toString(), query);
137135
138136 query = "SELECT * FROM foo WHERE e CONTAINS 'text';";
139- select = builder.select().from("foo").where(contains("e", "text"));
137+ select = select().from("foo").where(contains("e", "text"));
140138 assertEquals(select.toString(), query);
141139
142140 query = "SELECT * FROM foo WHERE e CONTAINS KEY 'key1';";
143- select = builder.select().from("foo").where(containsKey("e", "key1"));
141+ select = select().from("foo").where(containsKey("e", "key1"));
144142 assertEquals(select.toString(), query);
145143
146144 try {
147- builder.select().countAll().from("foo").orderBy(asc("a"), desc("b")).orderBy(asc("a"), desc("b"));
145+ select().countAll().from("foo").orderBy(asc("a"), desc("b")).orderBy(asc("a"), desc("b"));
148146 fail();
149147 } catch (IllegalStateException e) {
150148 assertEquals(e.getMessage(), "An ORDER BY clause has already been provided");
151149 }
152150
153151 try {
154- builder.select().column("a").all().from("foo");
152+ select().column("a").all().from("foo");
155153 fail();
156154 } catch (IllegalStateException e) {
157155 assertEquals(e.getMessage(), "Some columns ([a]) have already been selected.");
158156 }
159157
160158 try {
161- builder.select().column("a").countAll().from("foo");
159+ select().column("a").countAll().from("foo");
162160 fail();
163161 } catch (IllegalStateException e) {
164162 assertEquals(e.getMessage(), "Some columns ([a]) have already been selected.");
165163 }
166164
167165 try {
168- builder.select().all().from("foo").limit(-42);
166+ select().all().from("foo").limit(-42);
169167 fail();
170168 } catch (IllegalArgumentException e) {
171169 assertEquals(e.getMessage(), "Invalid LIMIT value, must be strictly positive");
172170 }
173171
174172 try {
175- builder.select().all().from("foo").limit(42).limit(42);
173+ select().all().from("foo").limit(42).limit(42);
176174 fail();
177175 } catch (IllegalStateException e) {
178176 assertEquals(e.getMessage(), "A LIMIT value has already been provided");
@@ -187,7 +185,7 @@
187185 Statement insert;
188186
189187 query = "INSERT INTO foo (a,b,\"C\",d) VALUES (123,'127.0.0.1','foo''bar',{'x':3,'y':2}) USING TIMESTAMP 42 AND TTL 24;";
190- insert = builder.insertInto("foo")
188+ insert = insertInto("foo")
191189 .value("a", 123)
192190 .value("b", InetAddress.getByName("127.0.0.1"))
193191 .value(quote("C"), "foo'bar")
@@ -199,13 +197,13 @@
199197 assertEquals(insert.toString(), query);
200198
201199 query = "INSERT INTO foo (a,b) VALUES (2,null);";
202- insert = builder.insertInto("foo")
200+ insert = insertInto("foo")
203201 .value("a", 2)
204202 .value("b", null);
205203 assertEquals(insert.toString(), query);
206204
207205 query = "INSERT INTO foo (a,b) VALUES ({2,3,4},3.4) USING TTL 24 AND TIMESTAMP 42;";
208- insert = builder.insertInto("foo").values(new String[]{ "a", "b" }, new Object[]{ new TreeSet<Integer>() {{
206+ insert = insertInto("foo").values(new String[]{ "a", "b" }, new Object[]{ new TreeSet<Integer>() {{
209207 add(2);
210208 add(3);
211209 add(4);
@@ -213,7 +211,7 @@
213211 assertEquals(insert.toString(), query);
214212
215213 query = "INSERT INTO foo.bar (a,b) VALUES ({2,3,4},3.4) USING TTL ? AND TIMESTAMP ?;";
216- insert = builder.insertInto("foo", "bar")
214+ insert = insertInto("foo", "bar")
217215 .values(new String[]{ "a", "b" }, new Object[]{ new TreeSet<Integer>() {{
218216 add(2);
219217 add(3);
@@ -225,7 +223,7 @@
225223
226224 // commutative result of TIMESTAMP
227225 query = "INSERT INTO foo.bar (a,b,c) VALUES ({2,3,4},3.4,123) USING TIMESTAMP 42;";
228- insert = builder.insertInto("foo", "bar")
226+ insert = insertInto("foo", "bar")
229227 .using(timestamp(42))
230228 .values(new String[]{ "a", "b" }, new Object[]{ new TreeSet<Integer>() {{
231229 add(2);
@@ -237,7 +235,7 @@
237235
238236 // commutative result of value() and values()
239237 query = "INSERT INTO foo (c,a,b) VALUES (123,{2,3,4},3.4) USING TIMESTAMP 42;";
240- insert = builder.insertInto("foo")
238+ insert = insertInto("foo")
241239 .using(timestamp(42))
242240 .value("c", 123)
243241 .values(new String[]{ "a", "b" }, new Object[]{ new TreeSet<Integer>() {{
@@ -248,7 +246,7 @@
248246 assertEquals(insert.toString(), query);
249247
250248 try {
251- builder.insertInto("foo").values(new String[]{ "a", "b"}, new Object[]{ 1, 2, 3 });
249+ insertInto("foo").values(new String[]{ "a", "b"}, new Object[]{ 1, 2, 3 });
252250 fail();
253251 } catch (IllegalArgumentException e) {
254252 assertEquals(e.getMessage(), "Got 2 names but 3 values");
@@ -256,7 +254,7 @@
256254
257255 // CAS test
258256 query = "INSERT INTO foo (k,x) VALUES (0,1) IF NOT EXISTS;";
259- insert = builder.insertInto("foo").value("k", 0).value("x", 1).ifNotExists();
257+ insert = insertInto("foo").value("k", 0).value("x", 1).ifNotExists();
260258 assertEquals(insert.toString(), query);
261259
262260 // Tuples: see QueryBuilderTupleExecutionTest
@@ -271,23 +269,23 @@
271269 Statement update;
272270
273271 query = "UPDATE foo.bar USING TIMESTAMP 42 SET a=12,b=[3,2,1],c=c+3 WHERE k=2;";
274- update = builder.update("foo", "bar").using(timestamp(42)).with(set("a", 12)).and(set("b", Arrays.asList(3, 2, 1))).and(incr("c", 3)).where(eq("k", 2));
272+ update = update("foo", "bar").using(timestamp(42)).with(set("a", 12)).and(set("b", Arrays.asList(3, 2, 1))).and(incr("c", 3)).where(eq("k", 2));
275273 assertEquals(update.toString(), query);
276274
277275 query = "UPDATE foo SET b=null WHERE k=2;";
278- update = builder.update("foo").where().and(eq("k", 2)).with(set("b", null));
276+ update = update("foo").where().and(eq("k", 2)).with(set("b", null));
279277 assertEquals(update.toString(), query);
280278
281279 query = "UPDATE foo SET a[2]='foo',b=[3,2,1]+b,c=c-{'a'} WHERE k=2 AND l='foo' AND m<4 AND n>=1;";
282- update = builder.update("foo").with(setIdx("a", 2, "foo")).and(prependAll("b", Arrays.asList(3, 2, 1))).and(remove("c", "a")).where(eq("k", 2)).and(eq("l", "foo")).and(lt("m", 4)).and(gte("n", 1));
280+ update = update("foo").with(setIdx("a", 2, "foo")).and(prependAll("b", Arrays.asList(3, 2, 1))).and(remove("c", "a")).where(eq("k", 2)).and(eq("l", "foo")).and(lt("m", 4)).and(gte("n", 1));
283281 assertEquals(update.toString(), query);
284282
285283 query = "UPDATE foo SET b=[3]+b,c=c+['a'],d=d+[1,2,3],e=e-[1];";
286- update = builder.update("foo").with().and(prepend("b", 3)).and(append("c", "a")).and(appendAll("d", Arrays.asList(1, 2, 3))).and(discard("e", 1));
284+ update = update("foo").with().and(prepend("b", 3)).and(append("c", "a")).and(appendAll("d", Arrays.asList(1, 2, 3))).and(discard("e", 1));
287285 assertEquals(update.toString(), query);
288286
289287 query = "UPDATE foo SET b=b-[1,2,3],c=c+{1},d=d+{2,3,4};";
290- update = builder.update("foo").with(discardAll("b", Arrays.asList(1, 2, 3))).and(add("c", 1)).and(addAll("d", new TreeSet<Integer>() {{
288+ update = update("foo").with(discardAll("b", Arrays.asList(1, 2, 3))).and(add("c", 1)).and(addAll("d", new TreeSet<Integer>() {{
291289 add(2);
292290 add(3);
293291 add(4);
@@ -295,7 +293,7 @@
295293 assertEquals(update.toString(), query);
296294
297295 query = "UPDATE foo SET b=b-{2,3,4},c['k']='v',d=d+{'x':3,'y':2};";
298- update = builder.update("foo").with(removeAll("b", new TreeSet<Integer>() {{
296+ update = update("foo").with(removeAll("b", new TreeSet<Integer>() {{
299297 add(2);
300298 add(3);
301299 add(4);
@@ -308,27 +306,27 @@
308306 assertEquals(update.toString(), query);
309307
310308 query = "UPDATE foo USING TTL 400;";
311- update = builder.update("foo").using(ttl(400));
309+ update = update("foo").using(ttl(400));
312310 assertEquals(update.toString(), query);
313311
314312 query = "UPDATE foo SET a=" + new BigDecimal(3.2) + ",b=42 WHERE k=2;";
315- update = builder.update("foo").with(set("a", new BigDecimal(3.2))).and(set("b", new BigInteger("42"))).where(eq("k", 2));
313+ update = update("foo").with(set("a", new BigDecimal(3.2))).and(set("b", new BigInteger("42"))).where(eq("k", 2));
316314 assertEquals(update.toString(), query);
317315
318316 query = "UPDATE foo USING TIMESTAMP 42 SET b=[3,2,1]+b WHERE k=2 AND l='foo';";
319- update = builder.update("foo").where().and(eq("k", 2)).and(eq("l", "foo")).with(prependAll("b", Arrays.asList(3, 2, 1))).using(timestamp(42));
317+ update = update("foo").where().and(eq("k", 2)).and(eq("l", "foo")).with(prependAll("b", Arrays.asList(3, 2, 1))).using(timestamp(42));
320318 assertEquals(update.toString(), query);
321319
322320 // Test commutative USING
323- update = builder.update("foo").where().and(eq("k", 2)).and(eq("l", "foo")).using(timestamp(42)).with(prependAll("b", Arrays.asList(3, 2, 1)));
321+ update = update("foo").where().and(eq("k", 2)).and(eq("l", "foo")).using(timestamp(42)).with(prependAll("b", Arrays.asList(3, 2, 1)));
324322 assertEquals(update.toString(), query);
325323
326324 // Test commutative USING
327- update = builder.update("foo").using(timestamp(42)).where(eq("k", 2)).and(eq("l", "foo")).with(prependAll("b", Arrays.asList(3, 2, 1)));
325+ update = update("foo").using(timestamp(42)).where(eq("k", 2)).and(eq("l", "foo")).with(prependAll("b", Arrays.asList(3, 2, 1)));
328326 assertEquals(update.toString(), query);
329327
330328 try {
331- builder.update("foo").using(ttl(-400));
329+ update("foo").using(ttl(-400));
332330 fail();
333331 } catch (IllegalArgumentException e) {
334332 assertEquals(e.getMessage(), "Invalid ttl, must be positive");
@@ -336,11 +334,11 @@
336334
337335 // CAS test
338336 query = "UPDATE foo SET x=4 WHERE k=0 IF x=1;";
339- update = builder.update("foo").with(set("x", 4)).where(eq("k", 0)).onlyIf(eq("x", 1));
337+ update = update("foo").with(set("x", 4)).where(eq("k", 0)).onlyIf(eq("x", 1));
340338 assertEquals(update.toString(), query);
341339
342340 // IF EXISTS CAS test
343- update = builder.update("foo").with(set("x", 3)).where(eq("k", 2)).ifExists();
341+ update = update("foo").with(set("x", 3)).where(eq("k", 2)).ifExists();
344342 assertThat(update.toString()).isEqualTo("UPDATE foo SET x=3 WHERE k=2 IF EXISTS;");
345343 }
346344
@@ -351,60 +349,60 @@
351349 Statement delete;
352350
353351 query = "DELETE a,b,c FROM foo USING TIMESTAMP 0 WHERE k=1;";
354- delete = builder.delete("a", "b", "c").from("foo").using(timestamp(0)).where(eq("k", 1));
352+ delete = delete("a", "b", "c").from("foo").using(timestamp(0)).where(eq("k", 1));
355353 assertEquals(delete.toString(), query);
356354
357355 query = "DELETE a[3],b['foo'],c FROM foo WHERE k=1;";
358- delete = builder.delete().listElt("a", 3).mapElt("b", "foo").column("c").from("foo").where(eq("k", 1));
356+ delete = delete().listElt("a", 3).mapElt("b", "foo").column("c").from("foo").where(eq("k", 1));
359357 assertEquals(delete.toString(), query);
360358
361359 query = "DELETE a[?],b[?],c FROM foo WHERE k=1;";
362- delete = builder.delete().listElt("a", bindMarker()).mapElt("b", bindMarker()).column("c").from("foo").where(eq("k", 1));
360+ delete = delete().listElt("a", bindMarker()).mapElt("b", bindMarker()).column("c").from("foo").where(eq("k", 1));
363361 assertEquals(delete.toString(), query);
364362
365363 // Invalid CQL, testing edge case
366364 query = "DELETE a,b,c FROM foo;";
367- delete = builder.delete("a", "b", "c").from("foo");
365+ delete = delete("a", "b", "c").from("foo");
368366 assertEquals(delete.toString(), query);
369367
370368 query = "DELETE FROM foo USING TIMESTAMP 1240003134 WHERE k='value';";
371- delete = builder.delete().all().from("foo").using(timestamp(1240003134L)).where(eq("k", "value"));
369+ delete = delete().all().from("foo").using(timestamp(1240003134L)).where(eq("k", "value"));
372370 assertEquals(delete.toString(), query);
373- delete = builder.delete().from("foo").using(timestamp(1240003134L)).where(eq("k", "value"));
371+ delete = delete().from("foo").using(timestamp(1240003134L)).where(eq("k", "value"));
374372 assertEquals(delete.toString(), query);
375373
376374 query = "DELETE a,b,c FROM foo.bar USING TIMESTAMP 1240003134 WHERE k=1;";
377- delete = builder.delete("a", "b", "c").from("foo", "bar").where().and(eq("k", 1)).using(timestamp(1240003134L));
375+ delete = delete("a", "b", "c").from("foo", "bar").where().and(eq("k", 1)).using(timestamp(1240003134L));
378376 assertEquals(delete.toString(), query);
379377
380378 query = "DELETE FROM foo.bar WHERE k1='foo' AND k2=1;";
381- delete = builder.delete().from("foo", "bar").where(eq("k1", "foo")).and(eq("k2", 1));
379+ delete = delete().from("foo", "bar").where(eq("k1", "foo")).and(eq("k2", 1));
382380 assertEquals(delete.toString(), query);
383381
384382 try {
385- builder.delete().column("a").all().from("foo");
383+ delete().column("a").all().from("foo");
386384 fail();
387385 } catch (IllegalStateException e) {
388386 assertEquals(e.getMessage(), "Some columns ([a]) have already been selected.");
389387 }
390388
391389 try {
392- builder.delete().from("foo").using(timestamp(-1240003134L));
390+ delete().from("foo").using(timestamp(-1240003134L));
393391 fail();
394392 } catch (IllegalArgumentException e) {
395393 assertEquals(e.getMessage(), "Invalid timestamp, must be positive");
396394 }
397395
398396 query = "DELETE FROM foo.bar WHERE k1='foo' IF EXISTS;";
399- delete = builder.delete().from("foo", "bar").where(eq("k1", "foo")).ifExists();
397+ delete = delete().from("foo", "bar").where(eq("k1", "foo")).ifExists();
400398 assertEquals(delete.toString(), query);
401399
402400 query = "DELETE FROM foo.bar WHERE k1='foo' IF a=1 AND b=2;";
403- delete = builder.delete().from("foo", "bar").where(eq("k1", "foo")).onlyIf(eq("a", 1)).and(eq("b", 2));
401+ delete = delete().from("foo", "bar").where(eq("k1", "foo")).onlyIf(eq("a", 1)).and(eq("b", 2));
404402 assertEquals(delete.toString(), query);
405403
406404 query = "DELETE FROM foo WHERE k=:key;";
407- delete = builder.delete().from("foo").where(eq("k", bindMarker("key")));
405+ delete = delete().from("foo").where(eq("k", bindMarker("key")));
408406 assertEquals(delete.toString(), query);
409407 }
410408
@@ -419,14 +417,14 @@
419417 query += "UPDATE foo SET a[2]='foo',b=[3,2,1]+b,c=c-{'a'} WHERE k=2;";
420418 query += "DELETE a[3],b['foo'],c FROM foo WHERE k=1;";
421419 query += "APPLY BATCH;";
422- batch = builder.batch()
423- .add(builder.insertInto("foo").values(new String[]{ "a", "b" }, new Object[]{ new TreeSet<Integer>() {{
420+ batch = batch()
421+ .add(insertInto("foo").values(new String[]{ "a", "b" }, new Object[]{ new TreeSet<Integer>() {{
424422 add(2);
425423 add(3);
426424 add(4);
427425 }}, 3.4 }))
428- .add(builder.update("foo").with(setIdx("a", 2, "foo")).and(prependAll("b", Arrays.asList(3, 2, 1))).and(remove("c", "a")).where(eq("k", 2)))
429- .add(builder.delete().listElt("a", 3).mapElt("b", "foo").column("c").from("foo").where(eq("k", 1)))
426+ .add(update("foo").with(setIdx("a", 2, "foo")).and(prependAll("b", Arrays.asList(3, 2, 1))).and(remove("c", "a")).where(eq("k", 2)))
427+ .add(delete().listElt("a", 3).mapElt("b", "foo").column("c").from("foo").where(eq("k", 1)))
430428 .using(timestamp(42));
431429 assertEquals(batch.toString(), query);
432430
@@ -434,10 +432,10 @@
434432 query = "BEGIN BATCH ";
435433 query += "DELETE a[3] FROM foo WHERE k=1;";
436434 query += "APPLY BATCH;";
437- batch = builder.batch(builder.delete().listElt("a", 3).from("foo").where(eq("k", 1)));
435+ batch = batch(delete().listElt("a", 3).from("foo").where(eq("k", 1)));
438436 assertEquals(batch.toString(), query);
439437
440- assertEquals(builder.batch().toString(), "BEGIN BATCH APPLY BATCH;");
438+ assertEquals(batch().toString(), "BEGIN BATCH APPLY BATCH;");
441439 }
442440
443441 @Test(groups = "unit")
@@ -451,10 +449,10 @@
451449 query += "UPDATE foo SET b=b+2;";
452450 query += "UPDATE foo SET c=c+3;";
453451 query += "APPLY BATCH;";
454- batch = builder.batch()
455- .add(builder.update("foo").with(incr("a", 1)))
456- .add(builder.update("foo").with(incr("b", 2)))
457- .add(builder.update("foo").with(incr("c", 3)))
452+ batch = batch()
453+ .add(update("foo").with(incr("a", 1)))
454+ .add(update("foo").with(incr("b", 2)))
455+ .add(update("foo").with(incr("c", 3)))
458456 .using(timestamp(42));
459457 assertEquals(batch.toString(), query);
460458
@@ -464,10 +462,10 @@
464462 query += "UPDATE foo SET b=b+1;";
465463 query += "UPDATE foo SET c=c+1;";
466464 query += "APPLY BATCH;";
467- batch = builder.batch()
468- .add(builder.update("foo").with(incr("a")))
469- .add(builder.update("foo").with(incr("b")))
470- .add(builder.update("foo").with(incr("c")))
465+ batch = batch()
466+ .add(update("foo").with(incr("a")))
467+ .add(update("foo").with(incr("b")))
468+ .add(update("foo").with(incr("c")))
471469 .using(timestamp(42));
472470 assertEquals(batch.toString(), query);
473471
@@ -477,10 +475,10 @@
477475 query += "UPDATE foo SET b=b-2;";
478476 query += "UPDATE foo SET c=c-3;";
479477 query += "APPLY BATCH;";
480- batch = builder.batch()
481- .add(builder.update("foo").with(decr("a", 1)))
482- .add(builder.update("foo").with(decr("b", 2)))
483- .add(builder.update("foo").with(decr("c", 3)))
478+ batch = batch()
479+ .add(update("foo").with(decr("a", 1)))
480+ .add(update("foo").with(decr("b", 2)))
481+ .add(update("foo").with(decr("c", 3)))
484482 .using(timestamp(42));
485483 assertEquals(batch.toString(), query);
486484
@@ -490,10 +488,10 @@
490488 query += "UPDATE foo SET b=b-1;";
491489 query += "UPDATE foo SET c=c-1;";
492490 query += "APPLY BATCH;";
493- batch = builder.batch()
494- .add(builder.update("foo").with(decr("a")))
495- .add(builder.update("foo").with(decr("b")))
496- .add(builder.update("foo").with(decr("c")))
491+ batch = batch()
492+ .add(update("foo").with(decr("a")))
493+ .add(update("foo").with(decr("b")))
494+ .add(update("foo").with(decr("c")))
497495 .using(timestamp(42));
498496 assertEquals(batch.toString(), query);
499497
@@ -503,20 +501,20 @@
503501 query += "UPDATE foo SET b=b+-2;";
504502 query += "UPDATE foo SET c=c-3;";
505503 query += "APPLY BATCH;";
506- batch = builder.batch()
507- .add(builder.update("foo").with(decr("a", -1)))
508- .add(builder.update("foo").with(incr("b", -2)))
509- .add(builder.update("foo").with(decr("c", 3)))
504+ batch = batch()
505+ .add(update("foo").with(decr("a", -1)))
506+ .add(update("foo").with(incr("b", -2)))
507+ .add(update("foo").with(decr("c", 3)))
510508 .using(timestamp(42));
511509 assertEquals(batch.toString(), query);
512510 }
513511
514512 @Test(groups = "unit", expectedExceptions = { IllegalArgumentException.class })
515513 public void batchMixedCounterTest() throws Exception {
516- builder.batch()
517- .add(builder.update("foo").with(incr("a", 1)))
518- .add(builder.update("foo").with(set("b", 2)))
519- .add(builder.update("foo").with(incr("c", 3)))
514+ batch()
515+ .add(update("foo").with(incr("a", 1)))
516+ .add(update("foo").with(set("b", 2)))
517+ .add(update("foo").with(incr("c", 3)))
520518 .using(timestamp(42));
521519 }
522520
@@ -526,7 +524,7 @@
526524 Statement insert;
527525
528526 query = "INSERT INTO test (k,c) VALUES (0,?);";
529- insert = builder.insertInto("test")
527+ insert = insertInto("test")
530528 .value("k", 0)
531529 .value("c", bindMarker());
532530 assertEquals(insert.toString(), query);
@@ -539,19 +537,19 @@
539537 Statement select;
540538
541539 query = "SELECT * FROM t WHERE c='C''est la vie!';";
542- select = builder.select().from("t").where(eq("c", "C'est la vie!"));
540+ select = select().from("t").where(eq("c", "C'est la vie!"));
543541 assertEquals(select.toString(), query);
544542
545543 query = "SELECT * FROM t WHERE c=C'est la vie!;";
546- select = builder.select().from("t").where(eq("c", raw("C'est la vie!")));
544+ select = select().from("t").where(eq("c", raw("C'est la vie!")));
547545 assertEquals(select.toString(), query);
548546
549547 query = "SELECT * FROM t WHERE c=now();";
550- select = builder.select().from("t").where(eq("c", fcall("now")));
548+ select = select().from("t").where(eq("c", fcall("now")));
551549 assertEquals(select.toString(), query);
552550
553551 query = "SELECT * FROM t WHERE c='now()';";
554- select = builder.select().from("t").where(eq("c", raw("'now()'")));
552+ select = select().from("t").where(eq("c", raw("'now()'")));
555553 assertEquals(select.toString(), query);
556554 }
557555
@@ -562,52 +560,52 @@
562560 Statement select;
563561
564562 query = "SELECT * FROM \"foo WHERE k=4\";";
565- select = builder.select().all().from("foo WHERE k=4");
563+ select = select().all().from("foo WHERE k=4");
566564 assertEquals(select.toString(), query);
567565
568566 query = "SELECT * FROM foo WHERE k='4 AND c=5';";
569- select = builder.select().all().from("foo").where(eq("k", "4 AND c=5"));
567+ select = select().all().from("foo").where(eq("k", "4 AND c=5"));
570568 assertEquals(select.toString(), query);
571569
572570 query = "SELECT * FROM foo WHERE k='4'' AND c=''5';";
573- select = builder.select().all().from("foo").where(eq("k", "4' AND c='5"));
571+ select = select().all().from("foo").where(eq("k", "4' AND c='5"));
574572 assertEquals(select.toString(), query);
575573
576574 query = "SELECT * FROM foo WHERE k='4'' OR ''1''=''1';";
577- select = builder.select().all().from("foo").where(eq("k", "4' OR '1'='1"));
575+ select = select().all().from("foo").where(eq("k", "4' OR '1'='1"));
578576 assertEquals(select.toString(), query);
579577
580578 query = "SELECT * FROM foo WHERE k='4; --test comment;';";
581- select = builder.select().all().from("foo").where(eq("k", "4; --test comment;"));
579+ select = select().all().from("foo").where(eq("k", "4; --test comment;"));
582580 assertEquals(select.toString(), query);
583581
584582 query = "SELECT \"*\" FROM foo;";
585- select = builder.select("*").from("foo");
583+ select = select("*").from("foo");
586584 assertEquals(select.toString(), query);
587585
588586 query = "SELECT a,b FROM foo WHERE a IN ('b','c''); --comment');";
589- select = builder.select("a", "b").from("foo").where(in("a", "b", "c'); --comment"));
587+ select = select("a", "b").from("foo").where(in("a", "b", "c'); --comment"));
590588 assertEquals(select.toString(), query);
591589
592590 // User Injection?
593591 query = "SELECT * FROM bar; --(b) FROM foo;";
594- select = builder.select().fcall("* FROM bar; --", column("b")).from("foo");
592+ select = select().fcall("* FROM bar; --", column("b")).from("foo");
595593 assertEquals(select.toString(), query);
596594
597595 query = "SELECT writetime(\"a) FROM bar; --\"),ttl(a) FROM foo ALLOW FILTERING;";
598- select = builder.select().writeTime("a) FROM bar; --").ttl("a").from("foo").allowFiltering();
596+ select = select().writeTime("a) FROM bar; --").ttl("a").from("foo").allowFiltering();
599597 assertEquals(select.toString(), query);
600598
601599 query = "SELECT writetime(a),ttl(\"a) FROM bar; --\") FROM foo ALLOW FILTERING;";
602- select = builder.select().writeTime("a").ttl("a) FROM bar; --").from("foo").allowFiltering();
600+ select = select().writeTime("a").ttl("a) FROM bar; --").from("foo").allowFiltering();
603601 assertEquals(select.toString(), query);
604602
605603 query = "SELECT * FROM foo WHERE \"k=1 OR k\">42 LIMIT 42;";
606- select = builder.select().all().from("foo").where(gt("k=1 OR k", 42)).limit(42);
604+ select = select().all().from("foo").where(gt("k=1 OR k", 42)).limit(42);
607605 assertEquals(select.toString(), query);
608606
609607 query = "SELECT * FROM foo WHERE token(\"k)>0 OR token(k\")>token(42);";
610- select = builder.select().all().from("foo").where(gt(token("k)>0 OR token(k"), fcall("token", 42)));
608+ select = select().all().from("foo").where(gt(token("k)>0 OR token(k"), fcall("token", 42)));
611609 assertEquals(select.toString(), query);
612610 }
613611
@@ -619,15 +617,15 @@
619617 Statement insert;
620618
621619 query = "INSERT INTO foo (a) VALUES ('123); --comment');";
622- insert = builder.insertInto("foo").value("a", "123); --comment");
620+ insert = insertInto("foo").value("a", "123); --comment");
623621 assertEquals(insert.toString(), query);
624622
625623 query = "INSERT INTO foo (\"a,b\") VALUES (123);";
626- insert = builder.insertInto("foo").value("a,b", 123);
624+ insert = insertInto("foo").value("a,b", 123);
627625 assertEquals(insert.toString(), query);
628626
629627 query = "INSERT INTO foo (a,b) VALUES ({'2''} space','3','4'},3.4) USING TTL 24 AND TIMESTAMP 42;";
630- insert = builder.insertInto("foo").values(new String[]{ "a", "b" }, new Object[]{ new TreeSet<String>() {{
628+ insert = insertInto("foo").values(new String[]{ "a", "b" }, new Object[]{ new TreeSet<String>() {{
631629 add("2'} space");
632630 add("3");
633631 add("4");
@@ -642,15 +640,15 @@
642640 Statement update;
643641
644642 query = "UPDATE foo.bar USING TIMESTAMP 42 SET a=12 WHERE k='2 OR 1=1';";
645- update = builder.update("foo", "bar").using(timestamp(42)).with(set("a", 12)).where(eq("k", "2 OR 1=1"));
643+ update = update("foo", "bar").using(timestamp(42)).with(set("a", 12)).where(eq("k", "2 OR 1=1"));
646644 assertEquals(update.toString(), query);
647645
648646 query = "UPDATE foo SET b='null WHERE k=1; --comment' WHERE k=2;";
649- update = builder.update("foo").where().and(eq("k", 2)).with(set("b", "null WHERE k=1; --comment"));
647+ update = update("foo").where().and(eq("k", 2)).with(set("b", "null WHERE k=1; --comment"));
650648 assertEquals(update.toString(), query);
651649
652650 query = "UPDATE foo USING TIMESTAMP 42 SET \"b WHERE k=1; --comment\"=[3,2,1]+\"b WHERE k=1; --comment\" WHERE k=2;";
653- update = builder.update("foo").where().and(eq("k", 2)).with(prependAll("b WHERE k=1; --comment", Arrays.asList(3, 2, 1))).using(timestamp(42));
651+ update = update("foo").where().and(eq("k", 2)).with(prependAll("b WHERE k=1; --comment", Arrays.asList(3, 2, 1))).using(timestamp(42));
654652 assertEquals(update.toString(), query);
655653 }
656654
@@ -661,47 +659,47 @@
661659 Statement delete;
662660
663661 query = "DELETE FROM \"foo WHERE k=4\";";
664- delete = builder.delete().from("foo WHERE k=4");
662+ delete = delete().from("foo WHERE k=4");
665663 assertEquals(delete.toString(), query);
666664
667665 query = "DELETE FROM foo WHERE k='4 AND c=5';";
668- delete = builder.delete().from("foo").where(eq("k", "4 AND c=5"));
666+ delete = delete().from("foo").where(eq("k", "4 AND c=5"));
669667 assertEquals(delete.toString(), query);
670668
671669 query = "DELETE FROM foo WHERE k='4'' AND c=''5';";
672- delete = builder.delete().from("foo").where(eq("k", "4' AND c='5"));
670+ delete = delete().from("foo").where(eq("k", "4' AND c='5"));
673671 assertEquals(delete.toString(), query);
674672
675673 query = "DELETE FROM foo WHERE k='4'' OR ''1''=''1';";
676- delete = builder.delete().from("foo").where(eq("k", "4' OR '1'='1"));
674+ delete = delete().from("foo").where(eq("k", "4' OR '1'='1"));
677675 assertEquals(delete.toString(), query);
678676
679677 query = "DELETE FROM foo WHERE k='4; --test comment;';";
680- delete = builder.delete().from("foo").where(eq("k", "4; --test comment;"));
678+ delete = delete().from("foo").where(eq("k", "4; --test comment;"));
681679 assertEquals(delete.toString(), query);
682680
683681 query = "DELETE \"*\" FROM foo;";
684- delete = builder.delete("*").from("foo");
682+ delete = delete("*").from("foo");
685683 assertEquals(delete.toString(), query);
686684
687685 query = "DELETE a,b FROM foo WHERE a IN ('b','c''); --comment');";
688- delete = builder.delete("a", "b").from("foo")
686+ delete = delete("a", "b").from("foo")
689687 .where(in("a", "b", "c'); --comment"));
690688 assertEquals(delete.toString(), query);
691689
692690 query = "DELETE FROM foo WHERE \"k=1 OR k\">42;";
693- delete = builder.delete().from("foo").where(gt("k=1 OR k", 42));
691+ delete = delete().from("foo").where(gt("k=1 OR k", 42));
694692 assertEquals(delete.toString(), query);
695693
696694 query = "DELETE FROM foo WHERE token(\"k)>0 OR token(k\")>token(42);";
697- delete = builder.delete().from("foo").where(gt(token("k)>0 OR token(k"), fcall("token", 42)));
695+ delete = delete().from("foo").where(gt(token("k)>0 OR token(k"), fcall("token", 42)));
698696 assertEquals(delete.toString(), query);
699697 }
700698
701699 @Test(groups = "unit")
702700 public void statementForwardingTest() throws Exception {
703701
704- Update upd = builder.update("foo");
702+ Update upd = update("foo");
705703 upd.setConsistencyLevel(ConsistencyLevel.QUORUM);
706704 upd.enableTracing();
707705
@@ -714,9 +712,10 @@
714712 @Test(groups = "unit")
715713 public void rejectUnknownValueTest() throws Exception {
716714 try {
717- //noinspection ResultOfMethodCallIgnored
718- builder.update("foo").with(set("a", new byte[13])).where(eq("k", 2)).toString();
719- fail("Byte arrays should not be valid, ByteBuffer should be used instead");
715+ RegularStatement s = update("foo").with(set("a", new byte[13])).where(eq("k", 2))
716+ .setForceNoValues(true);
717+ s.getQueryString();
718+ fail("should have failed to inline a byte[]");
720719 } catch (CodecNotFoundException e) {
721720 // Ok, that's what we expect
722721 }
@@ -724,28 +723,28 @@
724723
725724 @Test(groups = "unit")
726725 public void truncateTest() throws Exception {
727- assertEquals(builder.truncate("foo").toString(), "TRUNCATE foo;");
728- assertEquals(builder.truncate("foo", quote("Bar")).toString(), "TRUNCATE foo.\"Bar\";");
726+ assertEquals(truncate("foo").toString(), "TRUNCATE foo;");
727+ assertEquals(truncate("foo", quote("Bar")).toString(), "TRUNCATE foo.\"Bar\";");
729728 }
730729
731730 @Test(groups = "unit")
732731 public void quotingTest() {
733- assertEquals(builder.select().from("Metrics", "epochs").toString(),
732+ assertEquals(select().from("Metrics", "epochs").toString(),
734733 "SELECT * FROM Metrics.epochs;");
735- assertEquals(builder.select().from("Metrics", quote("epochs")).toString(),
734+ assertEquals(select().from("Metrics", quote("epochs")).toString(),
736735 "SELECT * FROM Metrics.\"epochs\";");
737- assertEquals(builder.select().from(quote("Metrics"), "epochs").toString(),
736+ assertEquals(select().from(quote("Metrics"), "epochs").toString(),
738737 "SELECT * FROM \"Metrics\".epochs;");
739- assertEquals(builder.select().from(quote("Metrics"), quote("epochs")).toString(),
738+ assertEquals(select().from(quote("Metrics"), quote("epochs")).toString(),
740739 "SELECT * FROM \"Metrics\".\"epochs\";");
741740
742- assertEquals(builder.insertInto("Metrics", "epochs").toString(),
741+ assertEquals(insertInto("Metrics", "epochs").toString(),
743742 "INSERT INTO Metrics.epochs () VALUES ();");
744- assertEquals(builder.insertInto("Metrics", quote("epochs")).toString(),
743+ assertEquals(insertInto("Metrics", quote("epochs")).toString(),
745744 "INSERT INTO Metrics.\"epochs\" () VALUES ();");
746- assertEquals(builder.insertInto(quote("Metrics"), "epochs").toString(),
745+ assertEquals(insertInto(quote("Metrics"), "epochs").toString(),
747746 "INSERT INTO \"Metrics\".epochs () VALUES ();");
748- assertEquals(builder.insertInto(quote("Metrics"), quote("epochs")).toString(),
747+ assertEquals(insertInto(quote("Metrics"), quote("epochs")).toString(),
749748 "INSERT INTO \"Metrics\".\"epochs\" () VALUES ();");
750749 }
751750
@@ -755,23 +754,23 @@
755754 Statement select;
756755
757756 query = "SELECT * FROM foo WHERE k=4 AND (c1,c2)>('a',2);";
758- select = builder.select().all().from("foo").where(eq("k", 4)).and(gt(Arrays.asList("c1", "c2"), Arrays.<Object>asList("a", 2)));
757+ select = select().all().from("foo").where(eq("k", 4)).and(gt(Arrays.asList("c1", "c2"), Arrays.<Object>asList("a", 2)));
759758 assertEquals(select.toString(), query);
760759
761760 query = "SELECT * FROM foo WHERE k=4 AND (c1,c2)>=('a',2) AND (c1,c2)<('b',0);";
762- select = builder.select().all().from("foo").where(eq("k", 4)).and(gte(Arrays.asList("c1", "c2"), Arrays.<Object>asList("a", 2)))
761+ select = select().all().from("foo").where(eq("k", 4)).and(gte(Arrays.asList("c1", "c2"), Arrays.<Object>asList("a", 2)))
763762 .and(lt(Arrays.asList("c1", "c2"), Arrays.<Object>asList("b", 0)));
764763 assertEquals(select.toString(), query);
765764
766765 query = "SELECT * FROM foo WHERE k=4 AND (c1,c2)<=('a',2);";
767- select = builder.select().all().from("foo").where(eq("k", 4)).and(lte(Arrays.asList("c1", "c2"), Arrays.<Object>asList("a", 2)));
766+ select = select().all().from("foo").where(eq("k", 4)).and(lte(Arrays.asList("c1", "c2"), Arrays.<Object>asList("a", 2)));
768767 assertEquals(select.toString(), query);
769768 }
770769
771770 @Test(groups = "unit", expectedExceptions = IllegalArgumentException.class)
772771 public void should_fail_if_in_clause_has_too_many_values() {
773772 List<Object> values = Collections.<Object>nCopies(65536, "a");
774- builder.select().all().from("foo").where(in("bar", values.toArray()));
773+ select().all().from("foo").where(in("bar", values.toArray()));
775774 }
776775
777776 @Test(groups = "unit", expectedExceptions = IllegalArgumentException.class)
@@ -779,13 +778,13 @@
779778 List<Object> values = Collections.<Object>nCopies(65535, "a");
780779
781780 // If the excessive count results from successive DSL calls, we don't check it on the fly so this statement works:
782- BuiltStatement statement = builder.select().all().from("foo")
781+ BuiltStatement statement = select().all().from("foo")
783782 .where(eq("bar", "a"))
784783 .and(in("baz", values.toArray()));
785784
786785 // But we still want to check it client-side, to fail fast instead of sending a bad query to Cassandra.
787786 // getValues() is called on any RegularStatement before we send it (see SessionManager.makeRequestMessage).
788- statement.getValues();
787+ statement.getValues(ProtocolVersion.NEWEST_SUPPORTED, CodecRegistry.DEFAULT_INSTANCE);
789788 }
790789
791790 @Test(groups = "unit")
@@ -796,57 +795,57 @@
796795
797796 query = "UPDATE foo SET l=[[1],[2]] WHERE k=1;";
798797 ImmutableList<ImmutableList<Integer>> list = ImmutableList.of(ImmutableList.of(1), ImmutableList.of(2));
799- statement = builder.update("foo").with(set("l", list)).where(eq("k", 1));
798+ statement = update("foo").with(set("l", list)).where(eq("k", 1));
800799 assertThat(statement.toString()).isEqualTo(query);
801800
802801 query = "UPDATE foo SET m={1:[[1],[2]],2:[[1],[2]]} WHERE k=1;";
803- statement = builder.update("foo").with(set("m", ImmutableMap.of(1, list, 2, list))).where(eq("k", 1));
802+ statement = update("foo").with(set("m", ImmutableMap.of(1, list, 2, list))).where(eq("k", 1));
804803 assertThat(statement.toString()).isEqualTo(query);
805804
806805 query = "UPDATE foo SET m=m+{1:[[1],[2]],2:[[1],[2]]} WHERE k=1;";
807- statement = builder.update("foo").with(putAll("m", ImmutableMap.of(1, list, 2, list))).where(eq("k", 1));
806+ statement = update("foo").with(putAll("m", ImmutableMap.of(1, list, 2, list))).where(eq("k", 1));
808807 assertThat(statement.toString()).isEqualTo(query);
809808
810809 query = "UPDATE foo SET l=[[1]]+l WHERE k=1;";
811- statement = builder.update("foo").with(prepend("l", ImmutableList.of(1))).where(eq("k", 1));
810+ statement = update("foo").with(prepend("l", ImmutableList.of(1))).where(eq("k", 1));
812811 assertThat(statement.toString()).isEqualTo(query);
813812
814813 query = "UPDATE foo SET l=[[1],[2]]+l WHERE k=1;";
815- statement = builder.update("foo").with(prependAll("l", list)).where(eq("k", 1));
814+ statement = update("foo").with(prependAll("l", list)).where(eq("k", 1));
816815 assertThat(statement.toString()).isEqualTo(query);
817816 }
818817
819818 @Test(groups = "unit", expectedExceptions = InvalidQueryException.class)
820819 public void should_not_allow_bind_marker_for_add() {
821820 // This generates the query "UPDATE foo SET s = s + {?} WHERE k = 1", which is invalid in Cassandra
822- builder.update("foo").with(add("s", bindMarker())).where(eq("k", 1));
821+ update("foo").with(add("s", bindMarker())).where(eq("k", 1));
823822 }
824823
825824 @Test(groups = "unit", expectedExceptions = InvalidQueryException.class)
826825 public void should_now_allow_bind_marker_for_prepend() {
827- builder.update("foo").with(prepend("l", bindMarker())).where(eq("k", 1));
826+ update("foo").with(prepend("l", bindMarker())).where(eq("k", 1));
828827 }
829828
830829 @Test(groups = "unit", expectedExceptions = InvalidQueryException.class)
831830 public void should_not_allow_bind_marker_for_append() {
832- builder.update("foo").with(append("l", bindMarker())).where(eq("k", 1));
831+ update("foo").with(append("l", bindMarker())).where(eq("k", 1));
833832 }
834833
835834 @Test(groups = "unit", expectedExceptions = InvalidQueryException.class)
836835 public void should_not_allow_bind_marker_for_remove() {
837- builder.update("foo").with(remove("s", bindMarker())).where(eq("k", 1));
836+ update("foo").with(remove("s", bindMarker())).where(eq("k", 1));
838837 }
839838
840839 @Test(groups = "unit", expectedExceptions = InvalidQueryException.class)
841840 public void should_not_allow_bind_marker_for_discard() {
842- builder.update("foo").with(discard("l", bindMarker())).where(eq("k", 1));
841+ update("foo").with(discard("l", bindMarker())).where(eq("k", 1));
843842 }
844843
845844 @Test(groups = "unit")
846845 public void should_quote_complex_column_names() {
847846 // A column name can be anything as long as it's quoted, so "foo.bar" is a valid name
848847 String query = "SELECT * FROM foo WHERE \"foo.bar\"=1;";
849- Statement statement = builder.select().from("foo").where(eq(quote("foo.bar"), 1));
848+ Statement statement = select().from("foo").where(eq(quote("foo.bar"), 1));
850849
851850 assertThat(statement.toString()).isEqualTo(query);
852851 }
@@ -855,32 +854,32 @@
855854 public void should_quote_column_names_with_escaped_quotes() {
856855 // A column name can include quotes as long as it is escaped with another set of quotes, so "foo""bar" is a valid name.
857856 String query = "SELECT * FROM foo WHERE \"foo \"\" bar\"=1;";
858- Statement statement = builder.select().from("foo").where(eq(quote("foo \"\" bar"), 1));
857+ Statement statement = select().from("foo").where(eq(quote("foo \"\" bar"), 1));
859858
860859 assertThat(statement.toString()).isEqualTo(query);
861860 }
862861
863862 @Test(groups = "unit")
864863 public void should_not_serialize_raw_query_values() {
865- RegularStatement select = builder.select().from("test").where(gt("i", raw("1")));
864+ RegularStatement select = select().from("test").where(gt("i", raw("1")));
866865 assertThat(select.getQueryString()).doesNotContain("?");
867- assertThat(select.getValues()).isNull();
866+ assertThat(select.getValues(ProtocolVersion.NEWEST_SUPPORTED, CodecRegistry.DEFAULT_INSTANCE)).isNull();
868867 }
869868
870869 @Test(groups = "unit", expectedExceptions = { IllegalStateException.class })
871870 public void should_throw_ISE_if_getObject_called_on_statement_without_values() {
872- builder.select().from("test").where(eq("foo", 42)).getObject(0); // integers are appended to the CQL string
871+ select().from("test").where(eq("foo", 42)).getObject(0); // integers are appended to the CQL string
873872 }
874873
875874 @Test(groups = "unit", expectedExceptions = { IndexOutOfBoundsException.class })
876875 public void should_throw_IOOBE_if_getObject_called_with_wrong_index() {
877- builder.select().from("test").where(eq("foo", new Object())).getObject(1);
876+ select().from("test").where(eq("foo", new Object())).getObject(1);
878877 }
879878
880879 @Test(groups = "unit")
881880 public void should_return_object_at_ith_index() {
882881 Object expected = new Object();
883- Object actual = builder.select().from("test").where(eq("foo", expected)).getObject(0);
882+ Object actual = select().from("test").where(eq("foo", expected)).getObject(0);
884883 assertThat(actual).isSameAs(expected);
885884 }
886885
@@ -890,13 +889,13 @@
890889 Set<UUID> set = Sets.newHashSet(UUID.randomUUID());
891890 List<Date> list = Lists.newArrayList(new Date());
892891 Map<BigInteger, String> map = ImmutableMap.of(new BigInteger("1"), "foo");
893- BuiltStatement query = builder.insertInto("foo").value("v", set);
892+ BuiltStatement query = insertInto("foo").value("v", set);
894893 assertThat(query.getQueryString()).isEqualTo("INSERT INTO foo (v) VALUES (?);");
895894 assertThat(query.getObject(0)).isEqualTo(set);
896- query = builder.insertInto("foo").value("v", list);
895+ query = insertInto("foo").value("v", list);
897896 assertThat(query.getQueryString()).isEqualTo("INSERT INTO foo (v) VALUES (?);");
898897 assertThat(query.getObject(0)).isEqualTo(list);
899- query = builder.insertInto("foo").value("v", map);
898+ query = insertInto("foo").value("v", map);
900899 assertThat(query.getQueryString()).isEqualTo("INSERT INTO foo (v) VALUES (?);");
901900 assertThat(query.getObject(0)).isEqualTo(map);
902901 }
@@ -904,17 +903,17 @@
904903 @Test(groups = "unit")
905904 @CassandraVersion(major = 2.1)
906905 public void should_not_attempt_to_serialize_function_calls_in_collections() {
907- BuiltStatement query = builder.insertInto("foo").value("v", Sets.newHashSet(fcall("func", 1)));
906+ BuiltStatement query = insertInto("foo").value("v", Sets.newHashSet(fcall("func", 1)));
908907 assertThat(query.getQueryString()).isEqualTo("INSERT INTO foo (v) VALUES ({func(1)});");
909- assertThat(query.getValues()).isNullOrEmpty();
908+ assertThat(query.getValues(ProtocolVersion.NEWEST_SUPPORTED, CodecRegistry.DEFAULT_INSTANCE)).isNullOrEmpty();
910909 }
911910
912911 @Test(groups = "unit")
913912 @CassandraVersion(major = 2.1)
914913 public void should_not_attempt_to_serialize_raw_values_in_collections() {
915- BuiltStatement query = builder.insertInto("foo").value("v", ImmutableMap.of(1, raw("x")));
914+ BuiltStatement query = insertInto("foo").value("v", ImmutableMap.of(1, raw("x")));
916915 assertThat(query.getQueryString()).isEqualTo("INSERT INTO foo (v) VALUES ({1:x});");
917- assertThat(query.getValues()).isNullOrEmpty();
916+ assertThat(query.getValues(ProtocolVersion.NEWEST_SUPPORTED, CodecRegistry.DEFAULT_INSTANCE)).isNullOrEmpty();
918917 }
919918
920919 @Test(groups = "unit")
@@ -923,17 +922,17 @@
923922 BuiltStatement query;
924923 // lists
925924 List<Integer> list = Lists.newArrayList(1, 2, 3);
926- query = builder.insertInto("foo").value("v", list);
925+ query = insertInto("foo").value("v", list);
927926 assertThat(query.getQueryString()).isEqualTo("INSERT INTO foo (v) VALUES ([1,2,3]);");
928927 assertThat(query.hasValues()).isFalse();
929928 // sets
930929 Set<Integer> set = Sets.newHashSet(1, 2, 3);
931- query = builder.insertInto("foo").value("v", set);
930+ query = insertInto("foo").value("v", set);
932931 assertThat(query.getQueryString()).isEqualTo("INSERT INTO foo (v) VALUES ({1,2,3});");
933932 assertThat(query.hasValues()).isFalse();
934933 // maps
935934 Map<Integer, Float> map = ImmutableMap.of(1, 12.34f);
936- query = builder.insertInto("foo").value("v", map);
935+ query = insertInto("foo").value("v", map);
937936 assertThat(query.getQueryString()).isEqualTo("INSERT INTO foo (v) VALUES ({1:12.34});");
938937 assertThat(query.hasValues()).isFalse();
939938 }
modified driver-core/src/test/java/com/datastax/driver/core/querybuilder/QueryBuilderTupleExecutionTest.java +4 −2
@@ -32,7 +32,9 @@
3232
3333 import static com.datastax.driver.core.DataType.cint;
3434 import static com.datastax.driver.core.querybuilder.QueryBuilder.eq;
35+import static com.datastax.driver.core.querybuilder.QueryBuilder.insertInto;
3536 import static com.datastax.driver.core.querybuilder.QueryBuilder.set;
37+import static com.datastax.driver.core.querybuilder.QueryBuilder.update;
3638
3739 @CassandraVersion(major=2.1, minor=3)
3840 public class QueryBuilderTupleExecutionTest extends CCMBridge.PerClassSingleNodeCluster {
@@ -46,7 +48,7 @@
4648 public void should_handle_tuple() throws Exception {
4749 String query = "INSERT INTO foo (k,x) VALUES (0,(1));";
4850 TupleType tupleType = cluster.getMetadata().newTupleType(cint());
49- BuiltStatement insert = new QueryBuilder(cluster).insertInto("foo").value("k", 0).value("x", tupleType.newValue(1));
51+ BuiltStatement insert = insertInto("foo").value("k", 0).value("x", tupleType.newValue(1));
5052 assertEquals(insert.toString(), query);
5153 }
5254
@@ -58,7 +60,7 @@
5860 query = "UPDATE foo SET l=[(1,2)] WHERE k=1;";
5961 TupleType tupleType = cluster.getMetadata().newTupleType(cint(), cint());
6062 List<TupleValue> list = ImmutableList.of(tupleType.newValue(1, 2));
61- statement = new QueryBuilder(cluster).update("foo").with(set("l", list)).where(eq("k", 1));
63+ statement = update("foo").with(set("l", list)).where(eq("k", 1));
6264 assertThat(statement.toString()).isEqualTo(query);
6365 }
6466
modified driver-core/src/test/java/com/datastax/driver/core/querybuilder/QueryBuilderUDTExecutionTest.java +7 −8
@@ -31,8 +31,7 @@
3131 import com.datastax.driver.core.*;
3232 import com.datastax.driver.core.utils.CassandraVersion;
3333
34-import static com.datastax.driver.core.querybuilder.QueryBuilder.eq;
35-import static com.datastax.driver.core.querybuilder.QueryBuilder.putAll;
34+import static com.datastax.driver.core.querybuilder.QueryBuilder.*;
3635
3736 @CassandraVersion(major=2.1, minor=3)
3837 public class QueryBuilderUDTExecutionTest extends CCMBridge.PerClassSingleNodeCluster {
@@ -48,12 +47,12 @@
4847 UserType udtType = cluster.getMetadata().getKeyspace(keyspace).getUserType("udt");
4948 UDTValue udtValue = udtType.newValue().setInt("i", 2).setInet("a", InetAddress.getByName("localhost"));
5049
51- Statement insert = new QueryBuilder(cluster).insertInto("udtTest").value("k", 1).value("t", udtValue);
50+ Statement insert = insertInto("udtTest").value("k", 1).value("t", udtValue);
5251 assertEquals(insert.toString(), "INSERT INTO udtTest (k,t) VALUES (1,{i:2,a:'127.0.0.1'});");
5352
5453 session.execute(insert);
5554
56- List<Row> rows = session.execute(new QueryBuilder(cluster).select().from("udtTest").where(eq("k", 1))).all();
55+ List<Row> rows = session.execute(select().from("udtTest").where(eq("k", 1))).all();
5756
5857 assertEquals(rows.size(), 1);
5958
@@ -67,12 +66,12 @@
6766 UDTValue udtValue = udtType.newValue().setInt("i", 2).setInet("a", InetAddress.getByName("localhost"));
6867 UDTValue udtValue2 = udtType.newValue().setInt("i", 3).setInet("a", InetAddress.getByName("localhost"));
6968
70- Statement insert = new QueryBuilder(cluster).insertInto("udtTest").value("k", 1).value("l", ImmutableList.of(udtValue));
69+ Statement insert = insertInto("udtTest").value("k", 1).value("l", ImmutableList.of(udtValue));
7170 assertThat(insert.toString()).isEqualTo("INSERT INTO udtTest (k,l) VALUES (1,[{i:2,a:'127.0.0.1'}]);");
7271
7372 session.execute(insert);
7473
75- List<Row> rows = session.execute(new QueryBuilder(cluster).select().from("udtTest").where(eq("k", 1))).all();
74+ List<Row> rows = session.execute(select().from("udtTest").where(eq("k", 1))).all();
7675
7776 assertThat(rows.size()).isEqualTo(1);
7877
@@ -82,13 +81,13 @@
8281 Map<Integer, UDTValue> map = Maps.newHashMap();
8382 map.put(0, udtValue);
8483 map.put(2, udtValue2);
85- Statement updateMap = new QueryBuilder(cluster).update("udtTest").with(putAll("m", map)).where(eq("k", 1));
84+ Statement updateMap = update("udtTest").with(putAll("m", map)).where(eq("k", 1));
8685 assertThat(updateMap.toString())
8786 .isEqualTo("UPDATE udtTest SET m=m+{0:{i:2,a:'127.0.0.1'},2:{i:3,a:'127.0.0.1'}} WHERE k=1;");
8887
8988 session.execute(updateMap);
9089
91- rows = session.execute(new QueryBuilder(cluster).select().from("udtTest").where(eq("k", 1))).all();
90+ rows = session.execute(select().from("udtTest").where(eq("k", 1))).all();
9291 r1 = rows.get(0);
9392 assertThat(r1.getMap("m", Integer.class, UDTValue.class)).isEqualTo(map);
9493 }
modified driver-examples/osgi/src/main/java/com/datastax/driver/osgi/impl/MailboxImpl.java +4 −7
@@ -22,14 +22,12 @@
2222
2323 import com.datastax.driver.core.*;
2424 import com.datastax.driver.core.exceptions.InvalidQueryException;
25-import com.datastax.driver.core.querybuilder.QueryBuilder;
2625 import com.datastax.driver.core.utils.UUIDs;
2726 import com.datastax.driver.osgi.api.MailboxException;
2827 import com.datastax.driver.osgi.api.MailboxMessage;
2928 import com.datastax.driver.osgi.api.MailboxService;
3029
31-import static com.datastax.driver.core.querybuilder.QueryBuilder.bindMarker;
32-import static com.datastax.driver.core.querybuilder.QueryBuilder.eq;
30+import static com.datastax.driver.core.querybuilder.QueryBuilder.*;
3331
3432 public class MailboxImpl implements MailboxService {
3533
@@ -71,18 +69,17 @@
7169 "PRIMARY KEY (recipient, time))");
7270 }
7371
74- QueryBuilder builder = new QueryBuilder(session.getCluster());
75- retrieveStatement = session.prepare(builder.select()
72+ retrieveStatement = session.prepare(select()
7673 .from(keyspace, TABLE)
7774 .where(eq("recipient", bindMarker())));
7875
79- insertStatement = session.prepare(builder.insertInto(keyspace, TABLE)
76+ insertStatement = session.prepare(insertInto(keyspace, TABLE)
8077 .value("recipient", bindMarker())
8178 .value("time", bindMarker())
8279 .value("sender", bindMarker())
8380 .value("body", bindMarker()));
8481
85- deleteStatement = session.prepare(builder.delete().from(keyspace, TABLE)
82+ deleteStatement = session.prepare(delete().from(keyspace, TABLE)
8683 .where(eq("recipient", bindMarker())));
8784
8885 initialized = true;
modified driver-examples/stress/src/main/java/com/datastax/driver/stress/Generators.java +2 −2
@@ -124,7 +124,7 @@
124124 }
125125 sb.append(" WHERE key = ").append(prefix | iteration);
126126 ++iteration;
127- return new QueryGenerator.Request.SimpleQuery(session.newSimpleStatement(sb.toString()));
127+ return new QueryGenerator.Request.SimpleQuery(new SimpleStatement(sb.toString()));
128128 }
129129 };
130130 }
@@ -196,7 +196,7 @@
196196 StringBuilder sb = new StringBuilder();
197197 sb.append("SELECT * FROM standard1 WHERE key = ").append(prefix | iteration);
198198 ++iteration;
199- return new QueryGenerator.Request.SimpleQuery(session.newSimpleStatement(sb.toString()));
199+ return new QueryGenerator.Request.SimpleQuery(new SimpleStatement(sb.toString()));
200200 }
201201 };
202202 }
modified driver-extras/src/test/java/com/datastax/driver/extras/codecs/guava/OptionalCodecTest.java +4 −3
@@ -30,7 +30,6 @@
3030 import com.datastax.driver.core.*;
3131 import com.datastax.driver.core.CCMBridge.PerClassSingleNodeCluster;
3232 import com.datastax.driver.core.querybuilder.BuiltStatement;
33-import com.datastax.driver.core.querybuilder.QueryBuilder;
3433 import com.datastax.driver.core.utils.CassandraVersion;
3534
3635 import static com.datastax.driver.core.TypeCodec.bigint;
@@ -39,6 +38,8 @@
3938 import static com.datastax.driver.core.TypeCodec.varchar;
4039 import static com.datastax.driver.core.querybuilder.QueryBuilder.bindMarker;
4140 import static com.datastax.driver.core.querybuilder.QueryBuilder.eq;
41+import static com.datastax.driver.core.querybuilder.QueryBuilder.insertInto;
42+import static com.datastax.driver.core.querybuilder.QueryBuilder.select;
4243
4344 public class OptionalCodecTest extends PerClassSingleNodeCluster {
4445
@@ -62,8 +63,8 @@
6263
6364 @BeforeMethod(groups = "short")
6465 public void createBuiltStatements() throws Exception {
65- insertStmt = new QueryBuilder(cluster).insertInto("foo").value("c1", bindMarker()).value("c2", bindMarker()).value("c3", bindMarker());
66- selectStmt = new QueryBuilder(cluster).select("c2", "c3").from("foo").where(eq("c1", bindMarker()));
66+ insertStmt = insertInto("foo").value("c1", bindMarker()).value("c2", bindMarker()).value("c3", bindMarker());
67+ selectStmt = select("c2", "c3").from("foo").where(eq("c1", bindMarker()));
6768 }
6869
6970 /**
modified driver-extras/src/test/java/com/datastax/driver/extras/codecs/jdk8/OptionalCodecTest.java +4 −3
@@ -30,7 +30,6 @@
3030 import com.datastax.driver.core.*;
3131 import com.datastax.driver.core.CCMBridge.PerClassSingleNodeCluster;
3232 import com.datastax.driver.core.querybuilder.BuiltStatement;
33-import com.datastax.driver.core.querybuilder.QueryBuilder;
3433 import com.datastax.driver.core.utils.CassandraVersion;
3534
3635 import static com.datastax.driver.core.TypeCodec.bigint;
@@ -39,6 +38,8 @@
3938 import static com.datastax.driver.core.TypeCodec.varchar;
4039 import static com.datastax.driver.core.querybuilder.QueryBuilder.bindMarker;
4140 import static com.datastax.driver.core.querybuilder.QueryBuilder.eq;
41+import static com.datastax.driver.core.querybuilder.QueryBuilder.insertInto;
42+import static com.datastax.driver.core.querybuilder.QueryBuilder.select;
4243
4344 public class OptionalCodecTest extends PerClassSingleNodeCluster {
4445
@@ -62,8 +63,8 @@
6263
6364 @BeforeMethod(groups = "short")
6465 public void createBuiltStatements() throws Exception {
65- insertStmt = new QueryBuilder(cluster).insertInto("foo").value("c1", bindMarker()).value("c2", bindMarker()).value("c3", bindMarker());
66- selectStmt = new QueryBuilder(cluster).select("c2", "c3").from("foo").where(eq("c1", bindMarker()));
66+ insertStmt = insertInto("foo").value("c1", bindMarker()).value("c2", bindMarker()).value("c3", bindMarker());
67+ selectStmt = select("c2", "c3").from("foo").where(eq("c1", bindMarker()));
6768 }
6869
6970 /**
modified driver-extras/src/test/java/com/datastax/driver/extras/codecs/json/JacksonJsonCodecTest.java +6 −6
@@ -28,12 +28,12 @@
2828
2929 import com.datastax.driver.core.*;
3030 import com.datastax.driver.core.querybuilder.BuiltStatement;
31-import com.datastax.driver.core.querybuilder.QueryBuilder;
3231 import com.datastax.driver.core.utils.CassandraVersion;
33-import com.datastax.driver.extras.codecs.json.JacksonJsonCodec;
3432
3533 import static com.datastax.driver.core.querybuilder.QueryBuilder.bindMarker;
3634 import static com.datastax.driver.core.querybuilder.QueryBuilder.eq;
35+import static com.datastax.driver.core.querybuilder.QueryBuilder.insertInto;
36+import static com.datastax.driver.core.querybuilder.QueryBuilder.select;
3737
3838 public class JacksonJsonCodecTest extends CCMBridge.PerClassSingleNodeCluster {
3939
@@ -97,11 +97,11 @@
9797
9898 @Test(groups = "short")
9999 public void should_use_custom_codec_with_built_statements_1() {
100- BuiltStatement insertStmt = new QueryBuilder(cluster).insertInto("t1")
100+ BuiltStatement insertStmt = insertInto("t1")
101101 .value("c1", bindMarker())
102102 .value("c2", bindMarker())
103103 .value("c3", bindMarker());
104- BuiltStatement selectStmt = new QueryBuilder(cluster).select("c1", "c2", "c3")
104+ BuiltStatement selectStmt = select("c1", "c2", "c3")
105105 .from("t1")
106106 .where(eq("c1", bindMarker()))
107107 .and(eq("c2", bindMarker()));
@@ -113,12 +113,12 @@
113113
114114 @Test(groups = "short")
115115 public void should_use_custom_codec_with_built_statements_2() {
116- BuiltStatement insertStmt = new QueryBuilder(cluster).insertInto("t1")
116+ BuiltStatement insertStmt = insertInto("t1")
117117 .value("c1", notAJsonString)
118118 .value("c2", alice)
119119 .value("c3", bobAndCharlie);
120120 BuiltStatement selectStmt =
121- new QueryBuilder(cluster).select("c1", "c2", "c3")
121+ select("c1", "c2", "c3")
122122 .from("t1")
123123 .where(eq("c1", notAJsonString))
124124 .and(eq("c2", alice));
modified driver-extras/src/test/java/com/datastax/driver/extras/codecs/json/Jsr353JsonCodecTest.java +6 −6
@@ -28,12 +28,12 @@
2828
2929 import com.datastax.driver.core.*;
3030 import com.datastax.driver.core.querybuilder.BuiltStatement;
31-import com.datastax.driver.core.querybuilder.QueryBuilder;
3231 import com.datastax.driver.core.utils.CassandraVersion;
33-import com.datastax.driver.extras.codecs.json.Jsr353JsonCodec;
3432
3533 import static com.datastax.driver.core.querybuilder.QueryBuilder.bindMarker;
3634 import static com.datastax.driver.core.querybuilder.QueryBuilder.eq;
35+import static com.datastax.driver.core.querybuilder.QueryBuilder.insertInto;
36+import static com.datastax.driver.core.querybuilder.QueryBuilder.select;
3737
3838 public class Jsr353JsonCodecTest extends CCMBridge.PerClassSingleNodeCluster {
3939
@@ -99,10 +99,10 @@
9999
100100 @Test(groups = "short", dataProvider = "Jsr353JsonCodecTest")
101101 public void should_use_custom_codec_with_built_statements_1(JsonStructure object) throws IOException {
102- BuiltStatement insertStmt = new QueryBuilder(cluster).insertInto("t1")
102+ BuiltStatement insertStmt = insertInto("t1")
103103 .value("c1", bindMarker())
104104 .value("c2", bindMarker());
105- BuiltStatement selectStmt = new QueryBuilder(cluster).select("c1", "c2")
105+ BuiltStatement selectStmt = select("c1", "c2")
106106 .from("t1")
107107 .where(eq("c1", bindMarker()))
108108 .and(eq("c2", bindMarker()));
@@ -114,11 +114,11 @@
114114
115115 @Test(groups = "short", dataProvider = "Jsr353JsonCodecTest")
116116 public void should_use_custom_codec_with_built_statements_2(JsonStructure object) throws IOException {
117- BuiltStatement insertStmt = new QueryBuilder(cluster).insertInto("t1")
117+ BuiltStatement insertStmt = insertInto("t1")
118118 .value("c1", notAJsonString)
119119 .value("c2", object);
120120 BuiltStatement selectStmt =
121- new QueryBuilder(cluster).select("c1", "c2")
121+ select("c1", "c2")
122122 .from("t1")
123123 .where(eq("c1", notAJsonString))
124124 .and(eq("c2", object));
modified driver-mapping/src/main/java/com/datastax/driver/mapping/QueryType.java +7 −9
@@ -25,7 +25,6 @@
2525 import com.datastax.driver.core.TableMetadata;
2626 import com.datastax.driver.core.querybuilder.Delete;
2727 import com.datastax.driver.core.querybuilder.Insert;
28-import com.datastax.driver.core.querybuilder.QueryBuilder;
2928 import com.datastax.driver.core.querybuilder.Select;
3029
3130 import static com.datastax.driver.core.querybuilder.QueryBuilder.*;
@@ -59,12 +58,11 @@
5958 }
6059
6160 String makePreparedQueryString(TableMetadata table, EntityMapper<?> mapper, MappingManager manager, Set<ColumnMapper<?>> columns, Collection<Mapper.Option> options) {
62- QueryBuilder builder = new QueryBuilder(manager.getSession().getCluster());
6361 switch (kind) {
6462 case SAVE: {
6563 Insert insert = table == null
66- ? builder.insertInto(mapper.getKeyspace(), mapper.getTable())
67- : builder.insertInto(table);
64+ ? insertInto(mapper.getKeyspace(), mapper.getTable())
65+ : insertInto(table);
6866 for (ColumnMapper<?> cm : columns)
6967 if (cm.kind != ColumnMapper.Kind.COMPUTED)
7068 insert.value(cm.getColumnName(), bindMarker());
@@ -78,7 +76,7 @@
7876 return insert.toString();
7977 }
8078 case GET: {
81- Select.Selection selection = builder.select();
79+ Select.Selection selection = select();
8280 for (ColumnMapper cm : mapper.allColumns()) {
8381 Select.SelectionOrAlias column = (cm.kind == ColumnMapper.Kind.COMPUTED)
8482 ? ((Select.SelectionOrAlias)selection).raw(cm.getColumnName())
@@ -106,8 +104,8 @@
106104 }
107105 case DEL: {
108106 Delete delete = table == null
109- ? builder.delete().all().from(mapper.getKeyspace(), mapper.getTable())
110- : builder.delete().all().from(table);
107+ ? delete().all().from(mapper.getKeyspace(), mapper.getTable())
108+ : delete().all().from(table);
111109 Delete.Where where = delete.where();
112110 for (int i = 0; i < mapper.primaryKeySize(); i++)
113111 where.and(eq(mapper.getPrimaryKeyColumn(i).getColumnName(), bindMarker()));
@@ -122,8 +120,8 @@
122120 case SLICE:
123121 case REVERSED_SLICE: {
124122 Select select = table == null
125- ? builder.select().all().from(mapper.getKeyspace(), mapper.getTable())
126- : builder.select().all().from(table);
123+ ? select().all().from(mapper.getKeyspace(), mapper.getTable())
124+ : select().all().from(table);
127125 Select.Where where = select.where();
128126 for (int i = 0; i < mapper.partitionKeys.size(); i++)
129127 where.and(eq(mapper.partitionKeys.get(i).getColumnName(), bindMarker()));
modified features/custom_codecs/README.md +2 −2
@@ -171,9 +171,9 @@
171171 Session session = ...
172172 MyPojo myPojo = ...
173173 // Using SimpleStatement
174-Statement stmt = session.newSimpleStatement("INSERT INTO t (id, json) VALUES (?, ?)", 42, myPojo));
174+Statement stmt = new SimpleStatement("INSERT INTO t (id, json) VALUES (?, ?)", 42, myPojo));
175175 // Using the Query Builder
176-BuiltStatement insertStmt = new QueryBuilder(cluster).insertInto("t")
176+BuiltStatement insertStmt = QueryBuilder.insertInto("t")
177177 .value("id", 42)
178178 .value("json", myPojo);
179179 // Using BoundStatements
modified features/custom_payloads/README.md +8 −8
@@ -71,7 +71,7 @@
7171 in both cases, the payload will be sent along with the `PREPARE` or `QUERY` request respectively:
7272
7373 ```java
74-Statement statement = session.newSimpleStatement("SELECT foo FROM bar WHERE qix = 1");
74+Statement statement = new SimpleStatement("SELECT foo FROM bar WHERE qix = 1");
7575 statement.setOutgoingPayload(myCustomPayload);
7676 session.execute(statement); // myCustomPayload will be sent with QUERY request
7777 session.prepare(statement); // myCustomPayload will be sent with PREPARE request
@@ -88,7 +88,7 @@
8888 `BatchStatement` itself, *not* to internal statements:
8989
9090 ```java
91-Statement statement = session.newSimpleStatement("INSERT INTO t1 (c1, c2) values ('foo', 'bar')")
91+Statement statement = new SimpleStatement("INSERT INTO t1 (c1, c2) values ('foo', 'bar')")
9292 // correct
9393 Statement batch = new BatchStatement().add(statement);
9494 batch.setOutgoingPayload(myCustomPayload);
@@ -104,7 +104,7 @@
104104 sent over and over for every new page request*.
105105
106106 ```java
107-Statement statement = session.newSimpleStatement("...");
107+Statement statement = new SimpleStatement("...");
108108 statement.setOutgoingPayload(myCustomPayload);
109109 ResultSet rows = session.execute(...); // myCustomPayload will be sent with first QUERY request
110110 for (Row row : rows) {
@@ -148,7 +148,7 @@
148148 1) From a `ResultSet`: use the `ExecutionInfo` class to retrieve the payload sent by the server.
149149
150150 ```java
151-Statement statement = session.newSimpleStatement("...");
151+Statement statement = new SimpleStatement("...");
152152 ResultSet rows = session.execute(...);
153153 // last payload sent by the server
154154 Map<String,ByteBuffer> serverPayload = rows.getExecutionInfo().getIncomingPayload();
@@ -160,7 +160,7 @@
160160 payloads for all `RESULT` responses, use the following method instead:
161161
162162 ```java
163-Statement statement = session.newSimpleStatement("...");
163+Statement statement = new SimpleStatement("...");
164164 ResultSet rows = session.execute(...);
165165 //all payloads sent by the server
166166 for (ExecutionInfo info : rows.getAllExecutionInfo()) {
@@ -183,7 +183,7 @@
183183 payload, if any, will become the default outgoing payload for the prepared statement.
184184
185185 ```java
186-Statement statement = session.newSimpleStatement("...");
186+Statement statement = new SimpleStatement("...");
187187 statement.setOutgoingPayload(myCustomPayload)
188188 PreparedStatement ps = session.prepare(...); // myCustomPayload will be sent with PREPARE request
189189 // AND become the default outgoing payload
@@ -194,7 +194,7 @@
194194 with the `PREPARE` request:
195195
196196 ```java
197-Statement statement = session.newSimpleStatement("...");
197+Statement statement = new SimpleStatement("...");
198198 PreparedStatement ps = session.prepare(...); // no payload sent with PREPARE request
199199 ps.setOutgoingPayload(myCustomPayload) // default outgoing payload is now myCustomPayload
200200 ```
@@ -218,7 +218,7 @@
218218 like in the example below:
219219
220220 ```java
221-Statement statement = session.newSimpleStatement("...");
221+Statement statement = new SimpleStatement("...");
222222 PreparedStatement ps = session.prepare(...); // no payload sent with PREPARE request
223223 BoundStatement bs = ps.bind(1); // no outgoing payload by default
224224 bs.setOutgoingPayload(myCustomPayload); // outgoing payload for this specific statement
modified features/paging/README.md +3 −3
@@ -25,7 +25,7 @@
2525 The fetch size can also be set on a statement:
2626
2727 ```java
28-Statement statement = session.newSimpleStatement("your query");
28+Statement statement = new SimpleStatement("your query");
2929 statement.setFetchSize(2000);
3030 ```
3131
@@ -130,7 +130,7 @@
130130
131131 ```java
132132 PagingState pagingState = PagingState.fromString(string);
133-Statement st = session.newSimpleStatement("your query");
133+Statement st = new SimpleStatement("your query");
134134 st.setPagingState(pagingState);
135135 ResultSet rs = session.execute(st);
136136 ```
@@ -147,7 +147,7 @@
147147 ```java
148148 final int RESULTS_PER_PAGE = 100;
149149
150-Statement st = session.newSimpleStatement("your query");
150+Statement st = new SimpleStatement("your query");
151151 st.setFetchSize(RESULTS_PER_PAGE);
152152
153153 String requestedPage = extractPagingStateStringFromURL();
modified features/query_timestamps/README.md +1 −1
@@ -36,7 +36,7 @@
3636 per-statement basis:
3737
3838 ```java
39-Statement statement = session.newSimpleStatement(
39+Statement statement = new SimpleStatement(
4040 "UPDATE users SET email = 'x@y.com' where id = 1");
4141 statement.setDefaultTimestamp(1234567890);
4242 session.execute(statement);
modified features/speculative_execution/README.md +1 −1
@@ -92,7 +92,7 @@
9292 You can override the value on each statement:
9393
9494 ```java
95-Statement s = session.newSimpleStatement("SELECT * FROM users WHERE id = 1");
95+Statement s = new SimpleStatement("SELECT * FROM users WHERE id = 1");
9696 s.setIdempotent(true);
9797 ```
9898
modified upgrade_guide/README.md +5 −12
@@ -42,19 +42,12 @@
4242 * `<V> T set(String name, V v, Class<V> targetClass)`
4343 * `<V> T set(String name, V v, TypeToken<V> targetType)`
4444 * `<V> T set(String name, V v, TypeCodec<V> codec)`
45- * `Session`. The following methods were added:
46- * `newSimpleStatement(String query)`
47- * `newSimpleStatement(String query, Object... values)`
45+ * `Statement`. The following public methods were modified:
46+ * `getRoutingKey(ProtocolVersion, CodecRegistry)`: both parameters added.
4847 * `RegularStatement`. The following public methods were modified:
49- * `getValues()`
50- * `hasValues()`
51- * `SimpleStatement`. Public constructors were removed; users are required to call either:
52- * `Session.newSimpleStatement(String query)` or
53- * `Session.newSimpleStatement(String query, Object... values)`
54- * `QueryBuilder`. This class now has a single, public constructor: `QueryBuilder(Cluster cluster)`.
55- Its fluent API has also changed; instead of e.g.: `QueryBuilder.select(...)`,
56- users should now use the following idiom: `new QueryBuilder(cluster).select(...)`
57- All methods that start a query are now instance methods instead of static ones.
48+ * `getValues(ProtocolVersion, CodecRegistry)`: second parameter added.
49+ * `getQueryString(CodecRegistry)` and `hasValues(CodecRegistry)`: parameter added. No-arg versions are still present
50+ and use the default codec registry; refer to the Javadocs for guidance on which version to use.
5851 * `PreparedStatement`. The following public method was added:
5952 * `CodecRegistry getCodecRegistry()`.
6053 * `TupleType`. The following public method was deleted: