Elffuss BraidHub

kikocis/java-driver public

Merge branch '2.2' into 3.0
Changeset1b2ecba88fe547b78b83aff53f2d3cdf1335a3abed700ca07b88ae5ae7752135
Authorolim7t <omichallat+github@gmail.com> · 2015-08-19 19:39 +02:00
Committerolim7t <omichallat+github@gmail.com> · 2015-08-19 19:39 +02:00
Parents1a13590453a2, 1663962b8185

Browse the files at this changeset

29 files changed

modified changelog/README.md +15 −0
@@ -15,6 +15,21 @@
1515 - [improvement] Disable frozen checks in mapper (JAVA-843)
1616 - [improvement] Allow user to register custom type codecs (JAVA-721)
1717 - [improvement] Support custom type codecs in mapper (JAVA-722)
18+- [bug] Propagate CodecRegistry to nested UDTs (JAVA-847)
19+- [improvement] Ability to store a default, shareable CodecRegistry
20+ instance (JAVA-848)
21+- [bug] Treat empty ByteBuffers as empty values in TupleCodec and
22+ UDTCodec (JAVA-880)
23+
24+
25+### 2.2.0-rc3
26+
27+- [bug] Propagate CodecRegistry to nested UDTs (JAVA-847)
28+- [improvement] Ability to store a default, shareable CodecRegistry
29+ instance (JAVA-848)
30+- [bug] Treat empty ByteBuffers as empty values in TupleCodec and
31+ UDTCodec (JAVA-880)
32+
1833
1934 ### 2.2.0-rc2
2035
modified driver-core/src/main/java/com/datastax/driver/core/ArrayBackedResultSet.java +1 −1
@@ -79,7 +79,7 @@
7979
8080 // if this is an internal call, it doesn't matter which codecRegistry will be used
8181 CodecRegistry codecRegistry = session == null ?
82- CodecRegistry.IMMUTABLE_INSTANCE :
82+ CodecRegistry.DEFAULT_INSTANCE :
8383 session.getCluster().getConfiguration().getCodecRegistry();
8484 columnDefs.setCodecRegistry(codecRegistry);
8585
modified driver-core/src/main/java/com/datastax/driver/core/Cluster.java +6 −1
@@ -925,8 +925,13 @@
925925 /**
926926 * Configures the {@link CodecRegistry} instance to use for the new cluster.
927927 * <p>
928- * If no codec registry is set through this method, a newly-created instance
928+ * If no codec registry is set through this method, {@link CodecRegistry#DEFAULT_INSTANCE}
929929 * will be used instead.
930+ * <p>Note that if two or more {@link Cluster} instances are configured to
931+ * use the default codec registry, they are going to share the same instance.
932+ * In this case, care should be taken when registering new codecs on it as any
933+ * codec registered by one cluster would be immediately available to others
934+ * sharing the same default instance.
930935 *
931936 * @param codecRegistry the codec registry to use.
932937 * @return this Builder.
modified driver-core/src/main/java/com/datastax/driver/core/CodecRegistry.java +141 −155
@@ -22,10 +22,7 @@
2222 import java.util.concurrent.ExecutionException;
2323
2424 import com.google.common.base.Objects;
25-import com.google.common.cache.CacheBuilder;
26-import com.google.common.cache.CacheLoader;
27-import com.google.common.cache.LoadingCache;
28-import com.google.common.collect.ImmutableList;
25+import com.google.common.cache.*;
2926 import com.google.common.collect.ImmutableSet;
3027 import com.google.common.reflect.TypeToken;
3128 import com.google.common.util.concurrent.UncheckedExecutionException;
@@ -48,18 +45,24 @@
4845 * <h3>Usage</h3>
4946 *
5047 * <p>
51- * To create a default {@link CodecRegistry} instance with all the default codecs used
52- * by the Java driver, simply use the following:
48+ * Most users won't need to manipulate {@link CodecRegistry} instances directly.
49+ * Only those willing to register user-defined codecs are required to do so.
50+ * By default, the driver uses {@link CodecRegistry#DEFAULT_INSTANCE}, a shareable
51+ * instance that initially contains all the built-in codecs required by the driver.
5352 *
54- * <pre>
55- * CodecRegistry myCodecRegistry = new CodecRegistry();
56- * </pre>
57- *
58- * Custom {@link TypeCodec}s can be added to a {@link CodecRegistry} via the {@code register} methods:
53+ * <p>
54+ * Users willing to customize their {@link CodecRegistry} can do so by {@code register registering}
55+ * new {@link TypeCodec}s either on {@link CodecRegistry#DEFAULT_INSTANCE},
56+ * or on a newly-crated one:
5957 *
6058 * <pre>
61- * CodecRegistry myCodecRegistry = new CodecRegistry()
62- * .register(myCodec1, myCodec2, myCodec3)
59+ * CodecRegistry myCodecRegistry;
60+ * // use the default instance
61+ * myCodecRegistry = CodecRegistry.DEFAULT_INSTANCE;
62+ * // or alternatively, create a new one
63+ * myCodecRegistry = new CodecRegistry();
64+ * // then
65+ * myCodecRegistry.register(myCodec1, myCodec2, myCodec3);
6366 * </pre>
6467 *
6568 * <p>
@@ -70,6 +73,7 @@
7073 * In order words, it is not possible to replace an existing codec,
7174 * specially the built-in ones; it is only possible to enrich the initial
7275 * set of codecs with new ones.
76+ *
7377 * <p>
7478 * To be used by the driver, {@link CodecRegistry} instances must then
7579 * be associated with a {@link Cluster} instance:
@@ -87,8 +91,7 @@
8791 * </pre>
8892 *
8993 * <p>
90- * For most users, a default {@link CodecRegistry} instance, containing
91- * all the default codecs, should be adequate.
94+ * By default, {@link Cluster} instances will use {@link CodecRegistry#DEFAULT_INSTANCE}.
9295 *
9396 * <h3>Example</h3>
9497 *
@@ -164,41 +167,20 @@
164167 );
165168
166169 /**
167- * The default set of codecs used by the Java driver.
168- * They contain codecs to handle native types, and collections thereof (lists, sets and maps).
169- *
170- * Note that the default set of codecs has no support for
171- * <a href="https://github.com/apache/cassandra/blob/trunk/src/java/org/apache/cassandra/db/marshal/AbstractType.java">Cassandra custom types</a>;
172- * to be able to deserialize values of such types, you need to manually register an appropriate codec.
173- */
174- static final ImmutableList<TypeCodec<?>> DEFAULT_CODECS;
175-
176- static {
177- ImmutableList.Builder<TypeCodec<?>> builder = new ImmutableList.Builder<TypeCodec<?>>();
178- builder.addAll(PRIMITIVE_CODECS);
179- for (TypeCodec<?> primitiveCodec1 : PRIMITIVE_CODECS) {
180- builder.add(new ListCodec(primitiveCodec1));
181- builder.add(new SetCodec(primitiveCodec1));
182- for (TypeCodec<?> primitiveCodec2 : PRIMITIVE_CODECS) {
183- builder.add(new MapCodec(primitiveCodec1, primitiveCodec2));
184- }
185- }
186- DEFAULT_CODECS = builder.build();
187- }
188-
189- /**
190- * An immutable instance of CodecRegistry.
191- * This is only meant to be used internally by the driver.
170+ * A default instance of CodecRegistry.
171+ * For most applications, sharing a single instance of CodecRegistry is fine.
172+ * But note that any codec registered with this instance will immediately
173+ * be available for all its clients.
192174 */
193- public static final CodecRegistry IMMUTABLE_INSTANCE = new CodecRegistry(true);
175+ public static final CodecRegistry DEFAULT_INSTANCE = new CodecRegistry();
194176
195177 private static final class CacheKey {
196178
197- private final TypeToken<?> javaType;
198-
199179 private final DataType cqlType;
200180
201- public CacheKey(TypeToken<?> javaType, DataType cqlType) {
181+ private final TypeToken<?> javaType;
182+
183+ public CacheKey(DataType cqlType, TypeToken<?> javaType) {
202184 this.javaType = javaType;
203185 this.cqlType = cqlType;
204186 }
@@ -210,7 +192,7 @@
210192 if (o == null || getClass() != o.getClass())
211193 return false;
212194 CacheKey cacheKey = (CacheKey)o;
213- return Objects.equal(javaType, cacheKey.javaType) && Objects.equal(cqlType, cacheKey.cqlType);
195+ return Objects.equal(cqlType, cacheKey.cqlType) && Objects.equal(javaType, cacheKey.javaType);
214196 }
215197
216198 @Override
@@ -219,7 +201,65 @@
219201 }
220202 }
221203
222- private final boolean immutable;
204+ /**
205+ * A complexity-based weigher.
206+ * Weights are computed mainly according to the CQL type:
207+ * <ol>
208+ * <li>Manually-registered codecs always weigh 0;
209+ * <li>Codecs for primtive types weigh 0;
210+ * <li>Codecs for collections weigh the total weight of their inner types + the weight of their level of deepness;
211+ * <li>Codecs for UDTs and tuples weigh the total weight of their inner types + the weight of their level of deepness, but cannot weigh less than 1;
212+ * <li>Codecs for custom (non-CQL) types weigh 1.
213+ * </ol>
214+ * A consequence of this algorithm is that codecs for primitive types and codecs for all "shallow" collections thereof
215+ * are never evicted.
216+ */
217+ private class TypeCodecWeigher implements Weigher<CacheKey, TypeCodec<?>> {
218+
219+ @Override
220+ public int weigh(CacheKey key, TypeCodec<?> value) {
221+ return codecs.contains(value) ? 0 : weigh(key.cqlType, 0);
222+ }
223+
224+ private int weigh(DataType cqlType, int level) {
225+ switch (cqlType.getName()) {
226+ case LIST:
227+ case SET:
228+ case MAP: {
229+ int weight = level;
230+ for (DataType eltType : cqlType.getTypeArguments()) {
231+ weight += weigh(eltType, level + 1);
232+ }
233+ return weight;
234+ }
235+ case UDT: {
236+ int weight = level;
237+ for (UserType.Field field : ((UserType)cqlType)) {
238+ weight += weigh(field.getType(), level + 1);
239+ }
240+ return weight == 0 ? 1 : weight;
241+ }
242+ case TUPLE: {
243+ int weight = level;
244+ for (DataType componentType : ((TupleType)cqlType).getComponentTypes()) {
245+ weight += weigh(componentType, level + 1);
246+ }
247+ return weight == 0 ? 1 : weight;
248+ }
249+ case CUSTOM:
250+ return 1;
251+ default:
252+ return 0;
253+ }
254+ }
255+ }
256+
257+ private class TypeCodecRemovalListener implements RemovalListener<CacheKey, TypeCodec<?>> {
258+ @Override
259+ public void onRemoval(RemovalNotification<CacheKey, TypeCodec<?>> notification) {
260+ logger.trace("Evicting codec from cache: {} (cause: {})", notification.getValue(), notification.getCause());
261+ }
262+ }
223263
224264 /**
225265 * The list of all known codecs.
@@ -234,14 +274,21 @@
234274 */
235275 private final LoadingCache<CacheKey, TypeCodec<?>> cache;
236276
277+ /**
278+ * Creates a default CodecRegistry instance with default cache options.
279+ */
237280 public CodecRegistry() {
238- this(false);
239- }
240-
241- private CodecRegistry(boolean immutable) {
242- this.immutable = immutable;
243- this.codecs = new CopyOnWriteArrayList<TypeCodec<?>>(DEFAULT_CODECS);
281+ this.codecs = new CopyOnWriteArrayList<TypeCodec<?>>(PRIMITIVE_CODECS);
244282 this.cache = CacheBuilder.newBuilder()
283+ // 19 primitive codecs + collections thereof = 19*3 + 19*19 = 418 codecs,
284+ // so let's start with roughly 1/4 of that
285+ .initialCapacity(100)
286+ .weigher(new TypeCodecWeigher())
287+ // a cache with all 418 "basic" codecs weighs 399 (19*2 + 19*19),
288+ // so let's cap at roughly 2.5x this size
289+ .maximumWeight(1000)
290+ .concurrencyLevel(Runtime.getRuntime().availableProcessors() * 4)
291+ .removalListener(new TypeCodecRemovalListener())
245292 .build(
246293 new CacheLoader<CacheKey, TypeCodec<?>>() {
247294 public TypeCodec<?> load(CacheKey cacheKey) {
@@ -257,25 +304,7 @@
257304 * @return this CodecRegistry (for method chaining).
258305 */
259306 public CodecRegistry register(TypeCodec<?> codec) {
260- return register(codec, false);
261- }
262-
263- /**
264- * Register the given codec with this registry.
265- *
266- * @param codec The codec to add to the registry.
267- * @param includeDerivedCollectionCodecs If {@code true}, register not only the given codec
268- * but also collection codecs whose element types are handled by the given codec, i.e.:
269- * <ul>
270- * <li>lists of the codec's type;</li>
271- * <li>sets of the codec's type;</li>
272- * <li>maps of a primitive type to the codec's type, or of the codec's type to a primitive
273- * type;</li>
274- * </ul>
275- * @return this CodecRegistry (for method chaining).
276- */
277- public CodecRegistry register(TypeCodec<?> codec, boolean includeDerivedCollectionCodecs) {
278- return register(Collections.singleton(codec), includeDerivedCollectionCodecs);
307+ return register(Collections.singleton(codec));
279308 }
280309
281310 /**
@@ -285,7 +314,7 @@
285314 * @return this Builder (for method chaining).
286315 */
287316 public CodecRegistry register(TypeCodec<?>... codecs) {
288- return register(Arrays.asList(codecs), false);
317+ return register(Arrays.asList(codecs));
289318 }
290319
291320 /**
@@ -295,42 +324,8 @@
295324 * @return this Builder (for method chaining).
296325 */
297326 public CodecRegistry register(Iterable<? extends TypeCodec<?>> codecs) {
298- return register(codecs, false);
299- }
300-
301- /**
302- * Register the given codecs with this registry.
303- *
304- * @param codecs The codecs to add to the registry.
305- * @param includeDerivedCollectionCodecs If {@code true}, register not only the given codecs
306- * but also collection codecs whose element types are handled by the given codecs, i.e. for
307- * each codec:
308- * <ul>
309- * <li>lists of the codec's type;</li>
310- * <li>sets of the codec's type;</li>
311- * <li>maps of a primitive type to the codec's type, or of the codec's type to a primitive
312- * type;</li>
313- * </ul>
314- * @return this Builder (for method chaining).
315- */
316- public CodecRegistry register(Iterable<? extends TypeCodec<?>> codecs, boolean includeDerivedCollectionCodecs) {
317- if(immutable)
318- throw new UnsupportedOperationException("This CodecRegistry instance is immutable");
319327 for (TypeCodec<?> codec : codecs) {
320- // add this codec to the beginning of the list so that it gets higher priority
321328 this.codecs.add(codec);
322- if(includeDerivedCollectionCodecs){
323- // list and set codecs of the given type
324- this.codecs.add(new ListCodec(codec));
325- this.codecs.add(new SetCodec(codec));
326- // a map which keys and values are of the same given type
327- this.codecs.add(new MapCodec(codec, codec));
328- // map codecs for combinations of the given type with all primitive types
329- for (TypeCodec<?> primitiveCodec : PRIMITIVE_CODECS) {
330- this.codecs.add(new MapCodec(primitiveCodec, codec));
331- this.codecs.add(new MapCodec(codec, primitiveCodec));
332- }
333- }
334329 }
335330 return this;
336331 }
@@ -353,7 +348,7 @@
353348 * <p>
354349 * Regular application code should avoid using this method.
355350 * <p>
356- * Codecs returned by this method are NOT cached.
351+ * Codecs returned by this method are <em>NOT</em> cached.
357352 *
358353 * @param value The value the codec should accept; must not be {@code null}.
359354 * @return A suitable codec.
@@ -381,7 +376,7 @@
381376 * @throws CodecNotFoundException if a suitable codec cannot be found.
382377 */
383378 public <T> TypeCodec<T> codecFor(DataType cqlType) throws CodecNotFoundException {
384- return lookupCache(cqlType, null);
379+ return lookupCodec(cqlType, null);
385380 }
386381
387382 /**
@@ -428,7 +423,7 @@
428423 public <T> TypeCodec<T> codecFor(DataType cqlType, TypeToken<T> javaType) throws CodecNotFoundException {
429424 checkNotNull(cqlType, "Parameter cqlType cannot be null");
430425 checkNotNull(javaType, "Parameter javaType cannot be null");
431- return lookupCache(cqlType, javaType);
426+ return lookupCodec(cqlType, javaType);
432427 }
433428
434429 /**
@@ -441,7 +436,7 @@
441436 * can be an expensive operation; besides, the resulting codec cannot be cached.
442437 * Therefore there might be a performance penalty when using this method.
443438 * <p>
444- * Codecs returned by this method <em>may</em> be cached.
439+ * Codecs returned by this method are <em>NOT</em> cached.
445440 *
446441 * @param cqlType The {@link DataType CQL type} the codec should accept; must not be {@code null}.
447442 * @param value The value the codec should accept; must not be {@code null}.
@@ -454,16 +449,18 @@
454449 return findCodec(cqlType, value);
455450 }
456451
457- private <T> TypeCodec<T> lookupCache(DataType cqlType, TypeToken<T> javaType) {
452+ private <T> TypeCodec<T> lookupCodec(DataType cqlType, TypeToken<T> javaType) {
458453 checkNotNull(cqlType, "Parameter cqlType cannot be null");
459- if(logger.isTraceEnabled())
460- logger.trace("Looking up codec for {} <-> {}", cqlType, javaType);
461- CacheKey cacheKey = new CacheKey(javaType, cqlType);
454+ logger.trace("Querying cache for codec [{} <-> {}]", cqlType, javaType);
455+ CacheKey cacheKey = new CacheKey(cqlType, javaType);
462456 try {
463- return (TypeCodec<T>)cache.get(cacheKey);
457+ TypeCodec<?> codec = cache.get(cacheKey);
458+ logger.trace("Returning cached codec [{} <-> {}]", cqlType, javaType);
459+ return (TypeCodec<T>)codec;
464460 } catch (UncheckedExecutionException e) {
465- if(e.getCause() instanceof CodecNotFoundException)
466- throw (CodecNotFoundException)e.getCause();
461+ if(e.getCause() instanceof CodecNotFoundException) {
462+ throw (CodecNotFoundException) e.getCause();
463+ }
467464 throw new CodecNotFoundException(e.getCause(), cqlType, javaType);
468465 } catch (ExecutionException e) {
469466 throw new CodecNotFoundException(e.getCause(), cqlType, javaType);
@@ -472,62 +469,53 @@
472469
473470 private <T> TypeCodec<T> findCodec(DataType cqlType, TypeToken<T> javaType) {
474471 checkNotNull(cqlType, "Parameter cqlType cannot be null");
475- if(logger.isTraceEnabled())
476- logger.trace("Looking for codec [{} <-> {}]", cqlType == null ? "ANY" : cqlType, javaType == null ? "ANY" : javaType);
472+ logger.trace("Looking for codec [{} <-> {}]",
473+ cqlType == null ? "ANY" : cqlType,
474+ javaType == null ? "ANY" : javaType);
477475 for (TypeCodec<?> codec : codecs) {
478476 if ((cqlType == null || codec.accepts(cqlType)) && (javaType == null || codec.accepts(javaType))) {
479- if(logger.isTraceEnabled())
480- logger.trace("Codec found: {}", codec);
477+ logger.trace("Codec found: {}", codec);
481478 return (TypeCodec<T>)codec;
482479 }
483480 }
484- // codec not found among the reservoir of known codecs, try to create an ad-hoc codec;
485- // this situation should happen mainly when dealing with enums, tuples and UDTs,
486- // and collections thereof.
487- TypeCodec<T> codec = maybeCreateCodec(cqlType, javaType);
488- if (codec == null)
489- throw logErrorAndThrow(cqlType, javaType);
490- // double-check that the created codec satisfies the initial request
491- if (!codec.accepts(cqlType) || (javaType != null && !codec.accepts(javaType)))
492- throw logErrorAndThrow(cqlType, javaType);
493-
494- if(logger.isTraceEnabled())
495- logger.trace("Codec found: {}", codec);
496- // add the codec for future use
497- codecs.addIfAbsent(codec);
498- return codec;
481+ return createCodec(cqlType, javaType);
499482 }
500483
501484 private <T> TypeCodec<T> findCodec(DataType cqlType, T value) {
502485 checkNotNull(value, "Parameter value cannot be null");
503- if(logger.isTraceEnabled())
504- logger.trace("Looking for codec [{} <-> {}]", cqlType == null ? "ANY" : cqlType, value.getClass());
486+ logger.trace("Looking for codec [{} <-> {}]", cqlType == null ? "ANY" : cqlType, value.getClass());
505487 for (TypeCodec<?> codec : codecs) {
506488 if ((cqlType == null || codec.accepts(cqlType)) && codec.accepts(value)) {
507- if(logger.isTraceEnabled())
508- logger.trace("Codec found: {}", codec);
489+ logger.trace("Codec found: {}", codec);
509490 return (TypeCodec<T>)codec;
510491 }
511492 }
512- // codec not found among the reservoir of known codecs, try to create an ad-hoc codec;
513- // this situation should happen mainly when dealing with enums, tuples and UDTs,
514- // and collections thereof.
493+ return createCodec(cqlType, value);
494+ }
495+
496+ private <T> TypeCodec<T> createCodec(DataType cqlType, TypeToken<T> javaType) {
497+ TypeCodec<T> codec = maybeCreateCodec(cqlType, javaType);
498+ if (codec == null)
499+ throw newException(cqlType, javaType);
500+ // double-check that the created codec satisfies the initial request
501+ if (!codec.accepts(cqlType) || (javaType != null && !codec.accepts(javaType)))
502+ throw newException(cqlType, javaType);
503+ logger.trace("Codec created: {}", codec);
504+ return codec;
505+ }
506+
507+ private <T> TypeCodec<T> createCodec(DataType cqlType, T value) {
515508 TypeCodec<T> codec = maybeCreateCodec(cqlType, value);
516509 if(codec == null)
517- throw logErrorAndThrow(cqlType, TypeToken.of(value.getClass()));
510+ throw newException(cqlType, TypeToken.of(value.getClass()));
518511 // double-check that the created codec satisfies the initial request
519512 if((cqlType != null && !codec.accepts(cqlType)) || !codec.accepts(value))
520- throw logErrorAndThrow(cqlType, TypeToken.of(value.getClass()));
521- if(logger.isTraceEnabled())
522- logger.trace("Codec found: {}", codec);
523- // add the codec for future use
524- codecs.addIfAbsent(codec);
513+ throw newException(cqlType, TypeToken.of(value.getClass()));
514+ logger.trace("Codec created: {}", codec);
525515 return codec;
526516 }
527517
528518 private <T> TypeCodec<T> maybeCreateCodec(DataType cqlType, TypeToken<T> javaType) {
529- if(immutable)
530- return null;
531519 checkNotNull(cqlType);
532520
533521 if ((cqlType.getName() == VARCHAR || cqlType.getName() == TEXT) && javaType != null && Enum.class.isAssignableFrom(javaType.getRawType())) {
@@ -579,9 +567,8 @@
579567 }
580568
581569 private <T> TypeCodec<T> maybeCreateCodec(DataType cqlType, T value) {
582- if(immutable)
583- return null;
584570 checkNotNull(value);
571+
585572 if ((cqlType == null || cqlType.getName() == VARCHAR || cqlType.getName() == TEXT) && value instanceof Enum) {
586573 return new EnumStringCodec(value.getClass());
587574 }
@@ -653,11 +640,10 @@
653640 return null;
654641 }
655642
656- private static CodecNotFoundException logErrorAndThrow(DataType cqlType, TypeToken<?> javaType) {
643+ private static CodecNotFoundException newException(DataType cqlType, TypeToken<?> javaType) {
657644 String msg = String.format("Codec not found for requested operation: [%s <-> %s]",
658645 cqlType == null ? "ANY" : cqlType,
659646 javaType == null ? "ANY" : javaType);
660- logger.error(msg);
661647 return new CodecNotFoundException(msg, cqlType, javaType);
662648 }
663649
modified driver-core/src/main/java/com/datastax/driver/core/CodecUtils.java +39 −3
@@ -64,6 +64,42 @@
6464 .where(new TypeParameter<V>(){}, valueType);
6565 }
6666
67+ /**
68+ * Propagate a CodecRegistry instance to a given type and its child types, if any.
69+ * <p>
70+ * By the time CQL types are decoded from response messages, the codec registry is not available;
71+ * This method manually sets a CodecRegistry on all CQL types that require it,
72+ * and thus should be called immediately after a response is decoded
73+ * into either a prepared statement or a result set.
74+ *
75+ * @param cqlType The decodec {@link DataType cqlType}.
76+ * @param codecRegistry The {@link CodecRegistry} instance to use.
77+ */
78+ static void setCodecRegistry(DataType cqlType, CodecRegistry codecRegistry) {
79+ // user types
80+ if(cqlType instanceof UserType) {
81+ UserType userType = (UserType)cqlType;
82+ userType.setCodecRegistry(codecRegistry);
83+ for (UserType.Field field : userType.byIdx) {
84+ setCodecRegistry(field.getType(), codecRegistry);
85+ }
86+ }
87+ // tuples
88+ else if(cqlType instanceof TupleType) {
89+ TupleType tupleType = (TupleType)cqlType;
90+ tupleType.setCodecRegistry(codecRegistry);
91+ for (DataType componentType : tupleType.getComponentTypes()) {
92+ setCodecRegistry(componentType, codecRegistry);
93+ }
94+ }
95+ // collections
96+ else if(cqlType.isCollection()) {
97+ for (DataType inner : cqlType.getTypeArguments()) {
98+ setCodecRegistry(inner, codecRegistry);
99+ }
100+ }
101+ }
102+
67103 /**
68104 * Utility method to serialize user-provided values.
69105 * <p>
@@ -166,9 +202,9 @@
166202 /**
167203 * Utility method that reads the collection size.
168204 * Mainly intended for collection codecs when deserializing CQL collections.
169- * @param input
170- * @param version
171- * @return
205+ * @param input A ByteBuffer containing a serialized CQL collection
206+ * @param version The protocol version to use.
207+ * @return The collection size
172208 */
173209 public static int readCollectionSize(ByteBuffer input, ProtocolVersion version) {
174210 switch (version) {
modified driver-core/src/main/java/com/datastax/driver/core/ColumnDefinitions.java +1 −18
@@ -286,28 +286,11 @@
286286
287287 void setCodecRegistry(CodecRegistry codecRegistry) {
288288 for (Definition definition : byIdx) {
289- setCodecRegistry(definition.type, codecRegistry);
289+ CodecUtils.setCodecRegistry(definition.type, codecRegistry);
290290 }
291291 this.codecRegistry = codecRegistry;
292292 }
293293
294- void setCodecRegistry(DataType cqlType, CodecRegistry codecRegistry) {
295- // by the time UDT and tuple values are decoded from response messages, the
296- // codec registry is not available, so set it now;
297- // this method should be called immediately after a response
298- // is decoded into either a prepared statement or a result set.
299- if(cqlType instanceof UserType) {
300- ((UserType)cqlType).setCodecRegistry(codecRegistry);
301- }
302- if(cqlType instanceof TupleType) {
303- ((TupleType)cqlType).setCodecRegistry(codecRegistry);
304- }
305- // propagate codec registry to inner types
306- for (DataType inner : cqlType.getTypeArguments()) {
307- setCodecRegistry(inner, codecRegistry);
308- }
309- }
310-
311294 /**
312295 * A column definition.
313296 */
modified driver-core/src/main/java/com/datastax/driver/core/Configuration.java +7 −1
@@ -142,6 +142,12 @@
142142
143143 /**
144144 * Returns the {@link CodecRegistry} instance for this configuration.
145+ * <p>
146+ * Note that this method could return {@link CodecRegistry#DEFAULT_INSTANCE}
147+ * if no specific codec registry has been set on the {@link Cluster}.
148+ * In this case, care should be taken when registering new codecs as they would be
149+ * immediately available to other {@link Cluster} instances sharing the same default instance.
150+ *
145151 * @return the {@link CodecRegistry} instance for this configuration.
146152 */
147153 public CodecRegistry getCodecRegistry() {
@@ -257,7 +263,7 @@
257263 metricsOptions != null ? metricsOptions : new MetricsOptions(),
258264 queryOptions != null ? queryOptions : new QueryOptions(),
259265 nettyOptions != null ? nettyOptions : NettyOptions.DEFAULT_INSTANCE,
260- codecRegistry != null ? codecRegistry : new CodecRegistry());
266+ codecRegistry != null ? codecRegistry : CodecRegistry.DEFAULT_INSTANCE);
261267 }
262268 }
263269 }
modified driver-core/src/main/java/com/datastax/driver/core/GettableByIndexData.java +6 −3
@@ -405,9 +405,12 @@
405405 /**
406406 * Returns the {@code i}th value as the Java type matching its CQL type.
407407 * <p>
408- * This method is not suitable to use with custom codecs: it will always
409- * use the default ones for the underlying CQL type. If you want to use
410- * non-default codecs, use {@link #get(int, Class)} or {@link #get(int, TypeToken)} instead.
408+ * This method uses the default codec for the underlying CQL type
409+ * to perform deserialization, and is safe to be used
410+ * <em>as long as only default codecs are in use</em>.
411+ * If a second, custom codec for the same CQL type is registered, which one will
412+ * be used is unspecified; in such cases, it is preferable to use
413+ * the more deterministic methods {@link #get(int, Class)} or {@link #get(int, TypeToken)} instead.
411414 *
412415 * @param i the index to retrieve.
413416 * @return the value of the {@code i}th value as the Java type matching its CQL type.
modified driver-core/src/main/java/com/datastax/driver/core/GettableByNameData.java +6 −3
@@ -404,9 +404,12 @@
404404 /**
405405 * Returns the value for {@code name} as the Java type matching its CQL type.
406406 * <p>
407- * This method is not suitable to use with custom codecs: it will always
408- * use the default ones for the underlying CQL type. If you want to use
409- * non-default codecs, use {@link #get(String, Class)} or {@link #get(String, TypeToken)} instead.
407+ * This method uses the default codec for the underlying CQL type
408+ * to perform deserialization, and is safe to be used
409+ * <em>as long as only default codecs are in use</em>.
410+ * If a second, custom codec for the same CQL type is registered, which one will
411+ * be used is unspecified; in such cases, it is preferable to use
412+ * the more deterministic methods {@link #get(String, Class)} or {@link #get(String, TypeToken)} instead.
410413 *
411414 * @param name the name to retrieve.
412415 * @return the value of the {@code i}th value as the Java type matching its CQL type.
modified driver-core/src/main/java/com/datastax/driver/core/Responses.java +1 −1
@@ -389,7 +389,7 @@
389389 String name = CBUtil.readString(body);
390390 // will set the appropriate CodecRegistry instance later
391391 // when the message will be decoded into either a PreparedStatement or a ResultSet
392- DataType type = DataType.decode(body, protocolVersion, null);
392+ DataType type = DataType.decode(body, protocolVersion, CodecRegistry.DEFAULT_INSTANCE);
393393 defs[i] = new ColumnDefinitions.Definition(ksName, cfName, name, type);
394394 }
395395
modified driver-core/src/main/java/com/datastax/driver/core/SettableByIndexData.java +38 −13
@@ -252,10 +252,14 @@
252252 * <p>
253253 * Note about performance: this method must perform a runtime inspection of the provided list,
254254 * in order to guess the best codec to serialize the list elements.
255- * The result of such inspection cannot be cached and thus must be performed for each invocation
256- * of this method, which may incur in a performance penalty.
257- * To circumvent this problem, consider using {@link #setList(int, List, Class)} or
258- * {@link #setList(int, List, TypeToken)}, which do not suffer from such symptoms.
255+ * <p>
256+ * Furthermore, if two or more codecs are available
257+ * for the underlying CQL type ({@code list}), <em>which one will be used will depend
258+ * on the actual object being serialized</em>.
259+ * <p>
260+ * For these reasons, it is generally preferable to use the more
261+ * deterministic methods {@link #setList(int, List, Class)} or
262+ * {@link #setList(int, List, TypeToken)}.
259263 *
260264 * @param i the index of the value to set.
261265 * @param v the value to set.
@@ -327,8 +331,14 @@
327331 * in order to guess the best codec to serialize the map entries.
328332 * The result of such inspection cannot be cached and thus must be performed for each invocation
329333 * of this method, which may incur in a performance penalty.
330- * To circumvent this problem, consider using {@link #setMap(int, Map, Class, Class)} or
331- * {@link #setMap(int, Map, TypeToken, TypeToken)}, which do not suffer from such symptoms.
334+ * <p>
335+ * Furthermore, if two or more codecs are available
336+ * for the underlying CQL type ({@code map}), <em>which one will be used will depend
337+ * on the actual object being serialized</em>.
338+ * <p>
339+ * For these reasons, it is generally preferable to use the more
340+ * deterministic methods {@link #setMap(int, Map, Class, Class)} or
341+ * {@link #setMap(int, Map, TypeToken, TypeToken)}.
332342 *
333343 * @param i the index of the value to set.
334344 * @param v the value to set.
@@ -398,12 +408,18 @@
398408 * <p>
399409 * Please note that {@code null} values are not supported inside collection by CQL.
400410 * <p>
401- * Note about performance: this method must perform a runtime inspection of the provided map,
402- * in order to guess the best codec to serialize the map entries.
411+ * Note about performance: this method must perform a runtime inspection of the provided set,
412+ * in order to guess the best codec to serialize the set elements.
403413 * The result of such inspection cannot be cached and thus must be performed for each invocation
404414 * of this method, which may incur in a performance penalty.
405- * To circumvent this problem, consider using {@link #setSet(int, Set, Class)} or
406- * {@link #setSet(int, Set, TypeToken)}, which do not suffer from such symptoms.
415+ * <p>
416+ * Furthermore, if two or more codecs are available
417+ * for the underlying CQL type ({@code set}), <em>which one will be used will depend
418+ * on the actual object being serialized</em>.
419+ * <p>
420+ * For these reasons, it is generally preferable to use the more
421+ * deterministic methods {@link #setSet(int, Set, Class)} or
422+ * {@link #setSet(int, Set, TypeToken)}.
407423 *
408424 * @param i the index of the value to set.
409425 * @param v the value to set.
@@ -506,9 +522,18 @@
506522 /**
507523 * Sets the {@code i}th value to the provided value.
508524 * <p>
509- * This method is not suitable to use with custom codecs: it will always
510- * use the default ones for the underlying CQL type. If you want to use
511- * non-default codecs, use {@link #set(int, V, Class)} or {@link #set(int, V, TypeToken)} instead.
525+ * Note about performance: this method must perform a runtime inspection of the provided object,
526+ * in order to guess the best codec to serialize it.
527+ * The result of such inspection cannot be cached and thus must be performed for each invocation
528+ * of this method, which may incur in a performance penalty.
529+ * <p>
530+ * Furthermore, if two or more codecs are available
531+ * for the underlying CQL type, <em>which one will be used will depend
532+ * on the actual object being serialized</em>.
533+ * <p>
534+ * For these reasons, it is generally preferable to use the more
535+ * deterministic methods {@link #set(int, V, Class)}
536+ * or {@link #set(int, V, TypeToken)} instead.
512537 *
513538 * @param i the index of the value to set.
514539 * @param v the value to set; may be {@code null}.
modified driver-core/src/main/java/com/datastax/driver/core/SettableByNameData.java +36 −10
@@ -298,8 +298,14 @@
298298 * in order to guess the best codec to serialize the list elements.
299299 * The result of such inspection cannot be cached and thus must be performed for each invocation
300300 * of this method, which may incur in a performance penalty.
301- * To circumvent this problem, consider using {@link #setList(String, List, Class)} or
302- * {@link #setList(String, List, TypeToken)}, which do not suffer from such symptoms.
301+ * <p>
302+ * Furthermore, if two or more codecs are available
303+ * for the underlying CQL type ({@code list}), <em>which one will be used will depend
304+ * on the actual object being serialized</em>.
305+ * <p>
306+ * For these reasons, it is generally preferable to use the more
307+ * deterministic methods {@link #setList(String, List, Class)} or
308+ * {@link #setList(String, List, TypeToken)}.
303309 *
304310 * @param name the name of the value to set; if {@code name} is present multiple
305311 * times, all its values are set.
@@ -373,8 +379,14 @@
373379 * in order to guess the best codec to serialize the map entries.
374380 * The result of such inspection cannot be cached and thus must be performed for each invocation
375381 * of this method, which may incur in a performance penalty.
376- * To circumvent this problem, consider using {@link #setMap(String, Map, Class, Class)} or
377- * {@link #setMap(String, Map, TypeToken, TypeToken)}, which do not suffer from such symptoms.
382+ * <p>
383+ * Furthermore, if two or more codecs are available
384+ * for the underlying CQL type ({@code map}), <em>which one will be used will depend
385+ * on the actual object being serialized</em>.
386+ * <p>
387+ * For these reasons, it is generally preferable to use the more
388+ * deterministic methods {@link #setMap(String, Map, Class, Class)} or
389+ * {@link #setMap(String, Map, TypeToken, TypeToken)}.
378390 *
379391 * @param name the name of the value to set; if {@code name} is present multiple
380392 * times, all its values are set.
@@ -449,11 +461,17 @@
449461 * Please note that {@code null} values are not supported inside collection by CQL.
450462 * <p>
451463 * Note about performance: this method must perform a runtime inspection of the provided map,
452- * in order to guess the best codec to serialize the map entries.
464+ * in order to guess the best codec to serialize the set elements.
453465 * The result of such inspection cannot be cached and thus must be performed for each invocation
454466 * of this method, which may incur in a performance penalty.
455- * To circumvent this problem, consider using {@link #setSet(String, Set, Class)} or
456- * {@link #setSet(String, Set, TypeToken)}, which do not suffer from such symptoms.
467+ * <p>
468+ * Furthermore, if two or more codecs are available
469+ * for the underlying CQL type ({@code set}), <em>which one will be used will depend
470+ * on the actual object being serialized</em>.
471+ * <p>
472+ * For these reasons, it is generally preferable to use the more
473+ * deterministic methods {@link #setSet(String, Set, Class)} or
474+ * {@link #setSet(String, Set, TypeToken)}.
457475 *
458476 * @param name the name of the value to set; if {@code name} is present multiple
459477 * times, all its values are set.
@@ -566,9 +584,17 @@
566584 /**
567585 * Sets the value for (all occurrences of) variable {@code name} to the provided value.
568586 * <p>
569- * This method is not suitable to use with custom codecs: it will always
570- * use the default ones for the underlying CQL type. If you want to use
571- * non-default codecs, use {@link #set(String, V, Class)} or {@link #set(String, V, TypeToken)} instead.
587+ * Note about performance: this method must perform a runtime inspection of the provided object,
588+ * in order to guess the best codec to serialize it.
589+ * The result of such inspection cannot be cached and thus must be performed for each invocation
590+ * of this method, which may incur in a performance penalty.
591+ * <p>
592+ * Furthermore, if two or more codecs are available
593+ * for the underlying CQL type, <em>which one will be used will depend
594+ * on the actual object being serialized</em>.
595+ * <p>
596+ * For these reasons, it is generally preferable to use the more
597+ * deterministic methods {@link #set(String, V, Class)} or {@link #set(String, V, TypeToken)} instead.
572598 *
573599 * @param name the name of the value to set; if {@code name} is present multiple
574600 * times, all its values are set.
modified driver-core/src/main/java/com/datastax/driver/core/SimpleStatement.java +3 −0
@@ -23,6 +23,9 @@
2323 /**
2424 * A simple {@code RegularStatement} implementation built directly from a query
2525 * string.
26+ * <p>
27+ * Use {@link Session#newSimpleStatement(String)} to create a new instance of this
28+ * class.
2629 */
2730 public class SimpleStatement extends RegularStatement {
2831
modified driver-core/src/main/java/com/datastax/driver/core/TupleType.java +21 −0
@@ -40,6 +40,27 @@
4040 this.codecRegistry = codecRegistry;
4141 }
4242
43+ /**
44+ * Creates a "disconnected" tuple type (<b>you should prefer
45+ * {@link Metadata#newTupleType(DataType...) cluster.getMetadata().newTupleType(...)}
46+ * whenever possible</b>).
47+ * <p>
48+ * This method is only exposed for situations where you don't have a {@code Cluster}
49+ * instance available. If you create a type with this method and use it with a
50+ * {@code Cluster} later, you won't be able to set tuple fields with custom codecs
51+ * registered against the cluster, or you might get errors if the protocol versions don't
52+ * match.
53+ *
54+ * @param protocolVersion the protocol version to use.
55+ * @param codecRegistry the codec registry to use.
56+ * @param types the types for the tuple type.
57+ *
58+ * @return the newly created tuple type.
59+ */
60+ public static TupleType of(ProtocolVersion protocolVersion, CodecRegistry codecRegistry, DataType... types) {
61+ return new TupleType(Arrays.asList(types), protocolVersion, codecRegistry);
62+ }
63+
4364 /**
4465 * The (immutable) list of types composing this tuple type.
4566 *
modified driver-core/src/main/java/com/datastax/driver/core/TypeCodec.java +8 −6
@@ -55,7 +55,7 @@
5555 * <ol>
5656 * <li>{@link #serialize(Object,ProtocolVersion)}: used to serialize from the codec's Java type to a
5757 * {@link ByteBuffer} instance corresponding to the codec's CQL type;</li>
58- * <li>{@link #deserialize(ByteBuffer,ProtocolVersion)}}: used to deserialize a {@link ByteBuffer} instance
58+ * <li>{@link #deserialize(ByteBuffer,ProtocolVersion)}: used to deserialize a {@link ByteBuffer} instance
5959 * corresponding to the codec's CQL type to the codec's Java type.</li>
6060 * </ol>
6161 *
@@ -73,9 +73,9 @@
7373 * Codecs also have the following inspection methods:
7474 *
7575 * <ol>
76- * <li>{@link #accepts(DataType)}}}: returns true if the codec can deserialize the given CQL type;</li>
77- * <li>{@link #accepts(TypeToken)}}: returns true if the codec can serialize the given Java type;</li>
78- * <li>{@link #accepts(Object)}}; returns true if the codec can serialize the given object.</li>
76+ * <li>{@link #accepts(DataType)}: returns true if the codec can deserialize the given CQL type;</li>
77+ * <li>{@link #accepts(TypeToken)}: returns true if the codec can serialize the given Java type;</li>
78+ * <li>{@link #accepts(Object)}; returns true if the codec can serialize the given object.</li>
7979 * </ol>
8080 *
8181 * <h3>Implementation notes</h3>
@@ -2009,8 +2009,9 @@
20092009
20102010 @Override
20112011 public UDTValue deserialize(ByteBuffer bytes, ProtocolVersion protocolVersion) {
2012- if (bytes == null || bytes.remaining() == 0)
2012+ if (bytes == null)
20132013 return null;
2014+ // empty byte buffers will result in empty UDTValues
20142015 ByteBuffer input = bytes.duplicate();
20152016 UDTValue value = definition.newValue();
20162017
@@ -2121,8 +2122,9 @@
21212122
21222123 @Override
21232124 public TupleValue deserialize(ByteBuffer bytes, ProtocolVersion protocolVersion) {
2124- if (bytes == null || bytes.remaining() == 0)
2125+ if (bytes == null)
21252126 return null;
2127+ // empty byte buffers will result in empty TupleValues
21262128 ByteBuffer input = bytes.duplicate();
21272129 TupleValue value = definition.newValue();
21282130
modified driver-core/src/main/java/com/datastax/driver/core/querybuilder/Batch.java +2 −2
@@ -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(Cluster cluster, RegularStatement[] statements, boolean logged) {
37- super((String)null, cluster);
36+ Batch(ProtocolVersion protocolVersion, CodecRegistry codecRegistry, RegularStatement[] statements, boolean logged) {
37+ super((String)null, protocolVersion, codecRegistry);
3838 this.statements = statements.length == 0
3939 ? new ArrayList<RegularStatement>()
4040 : new ArrayList<RegularStatement>(statements.length);
modified driver-core/src/main/java/com/datastax/driver/core/querybuilder/BuiltStatement.java +11 −14
@@ -37,7 +37,8 @@
3737 private final List<ColumnMetadata> partitionKey;
3838 private final List<Object> routingKeyValues;
3939 final String keyspace;
40- protected final Cluster cluster;
40+ private final ProtocolVersion protocolVersion;
41+ private final CodecRegistry codecRegistry;
4142
4243 private boolean dirty;
4344 private String cache;
@@ -50,18 +51,20 @@
5051 boolean hasBindMarkers;
5152 private boolean forceNoValues;
5253
53- BuiltStatement(String keyspace, Cluster cluster) {
54+ BuiltStatement(String keyspace, ProtocolVersion protocolVersion, CodecRegistry codecRegistry) {
5455 this.partitionKey = null;
5556 this.routingKeyValues = null;
5657 this.keyspace = keyspace;
57- this.cluster = cluster;
58+ this.protocolVersion = protocolVersion;
59+ this.codecRegistry = codecRegistry;
5860 }
5961
60- BuiltStatement(TableMetadata tableMetadata, Cluster cluster) {
62+ BuiltStatement(TableMetadata tableMetadata, ProtocolVersion protocolVersion, CodecRegistry codecRegistry) {
6163 this.partitionKey = tableMetadata.getPartitionKey();
6264 this.routingKeyValues = Arrays.asList(new Object[tableMetadata.getPartitionKey().size()]);
6365 this.keyspace = escapeId(tableMetadata.getKeyspace().getName());
64- this.cluster = cluster;
66+ this.protocolVersion = protocolVersion;
67+ this.codecRegistry = codecRegistry;
6568 }
6669
6770 // Same as Metadata.escapeId, but we don't have access to it here.
@@ -160,19 +163,13 @@
160163 }
161164
162165 CodecRegistry getCodecRegistry(){
163- return cluster.getConfiguration().getCodecRegistry();
166+ return codecRegistry;
164167 }
165168
166169 ProtocolVersion getProtocolVersion() {
167- cluster.init();
168- return cluster.getConfiguration().getProtocolOptions().getProtocolVersion();
170+ return protocolVersion;
169171 }
170172
171- /**
172- * {@inheritDoc}
173- * <p>
174- * Note: Calling this method may trigger the underlying {@link Cluster} initialization.
175- */
176173 @Override
177174 public ByteBuffer getRoutingKey() {
178175 if (routingKeyValues == null)
@@ -278,7 +275,7 @@
278275 T statement;
279276
280277 ForwardingStatement(T statement) {
281- super((String)null, statement.cluster);
278+ super((String)null, statement.getProtocolVersion(), statement.getCodecRegistry());
282279 this.statement = statement;
283280 }
284281
modified driver-core/src/main/java/com/datastax/driver/core/querybuilder/Delete.java +17 −13
@@ -20,6 +20,7 @@
2020
2121 import com.datastax.driver.core.Cluster;
2222 import com.datastax.driver.core.CodecRegistry;
23+import com.datastax.driver.core.ProtocolVersion;
2324 import com.datastax.driver.core.TableMetadata;
2425
2526 /**
@@ -34,8 +35,8 @@
3435 private final Conditions conditions;
3536 private boolean ifExists;
3637
37- Delete(Cluster cluster, String keyspace, String table, List<Selector> columns) {
38- super(keyspace, cluster);
38+ Delete(ProtocolVersion protocolVersion, CodecRegistry codecRegistry, String keyspace, String table, List<Selector> columns) {
39+ super(keyspace, protocolVersion, codecRegistry);
3940 this.table = table;
4041 this.columns = columns;
4142 this.where = new Where(this);
@@ -43,8 +44,8 @@
4344 this.conditions = new Conditions(this);
4445 }
4546
46- Delete(Cluster cluster, TableMetadata table, List<Selector> columns) {
47- super(table, cluster);
47+ Delete(ProtocolVersion protocolVersion, CodecRegistry codecRegistry, TableMetadata table, List<Selector> columns) {
48+ super(table, protocolVersion, codecRegistry);
4849 this.table = escapeId(table.getName());
4950 this.columns = columns;
5051 this.where = new Where(this);
@@ -277,16 +278,19 @@
277278 */
278279 public static class Builder {
279280
280- private final Cluster cluster;
281+ private final ProtocolVersion protocolVersion;
282+ private final CodecRegistry codecRegistry;
281283
282284 List<Selector> columns = new ArrayList<Selector>();
283285
284- Builder(Cluster cluster) {
285- this.cluster = cluster;
286+ Builder(ProtocolVersion protocolVersion, CodecRegistry codecRegistry) {
287+ this.protocolVersion = protocolVersion;
288+ this.codecRegistry = codecRegistry;
286289 }
287290
288- Builder(Cluster cluster, String... columnNames) {
289- this.cluster = cluster;
291+ Builder(ProtocolVersion protocolVersion, CodecRegistry codecRegistry, String... columnNames) {
292+ this.protocolVersion = protocolVersion;
293+ this.codecRegistry = codecRegistry;
290294 for (String columnName : columnNames) {
291295 this.columns.add(new Selector(columnName));
292296 }
@@ -310,7 +314,7 @@
310314 * @return a newly built DELETE statement that deletes from {@code keyspace.table}.
311315 */
312316 public Delete from(String keyspace, String table) {
313- return new Delete(cluster, keyspace, table, columns);
317+ return new Delete(protocolVersion, codecRegistry, keyspace, table, columns);
314318 }
315319
316320 /**
@@ -320,7 +324,7 @@
320324 * @return a newly built DELETE statement that deletes from {@code table}.
321325 */
322326 public Delete from(TableMetadata table) {
323- return new Delete(cluster, table, columns);
327+ return new Delete(protocolVersion, codecRegistry, table, columns);
324328 }
325329 }
326330
@@ -329,8 +333,8 @@
329333 */
330334 public static class Selection extends Builder {
331335
332- Selection(Cluster cluster) {
333- super(cluster);
336+ Selection(ProtocolVersion protocolVersion, CodecRegistry codecRegistry) {
337+ super(protocolVersion, codecRegistry);
334338 }
335339
336340 /**
modified driver-core/src/main/java/com/datastax/driver/core/querybuilder/Insert.java +5 −4
@@ -21,6 +21,7 @@
2121
2222 import com.datastax.driver.core.Cluster;
2323 import com.datastax.driver.core.CodecRegistry;
24+import com.datastax.driver.core.ProtocolVersion;
2425 import com.datastax.driver.core.TableMetadata;
2526
2627 /**
@@ -34,14 +35,14 @@
3435 private final Options usings;
3536 private boolean ifNotExists;
3637
37- Insert(Cluster cluster, String keyspace, String table) {
38- super(keyspace, cluster);
38+ Insert(ProtocolVersion protocolVersion, CodecRegistry codecRegistry, String keyspace, String table) {
39+ super(keyspace, protocolVersion, codecRegistry);
3940 this.table = table;
4041 this.usings = new Options(this);
4142 }
4243
43- Insert(Cluster cluster, TableMetadata table) {
44- super(table, cluster);
44+ Insert(ProtocolVersion protocolVersion, CodecRegistry codecRegistry, TableMetadata table) {
45+ super(table, protocolVersion, codecRegistry);
4546 this.table = escapeId(table.getName());
4647 this.usings = new Options(this);
4748 }
modified driver-core/src/main/java/com/datastax/driver/core/querybuilder/QueryBuilder.java +43 −22
@@ -17,9 +17,7 @@
1717
1818 import java.util.*;
1919
20-import com.datastax.driver.core.Cluster;
21-import com.datastax.driver.core.RegularStatement;
22-import com.datastax.driver.core.TableMetadata;
20+import com.datastax.driver.core.*;
2321 import com.datastax.driver.core.exceptions.InvalidQueryException;
2422
2523 /**
@@ -40,17 +38,40 @@
4038 */
4139 public final class QueryBuilder {
4240
43- private final Cluster cluster;
41+ private final ProtocolVersion protocolVersion;
42+ private final CodecRegistry codecRegistry;
4443
4544 /**
4645 * Create a new QueryBuilder instance and associate it with the given {@link Cluster}.
47- * Note: if the {@link Cluster} is not yet initialized, certain methods of the QueryBuilder API
48- * may trigger its initialization.
46+ * Note: if the {@link Cluster} is not yet initialized, this method
47+ * will trigger its initialization.
4948 *
5049 * @param cluster The {@link Cluster} instance this object should be attached to.
5150 */
5251 public QueryBuilder(Cluster cluster) {
53- this.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;
5475 }
5576
5677 /**
@@ -63,7 +84,7 @@
6384 * least a FROM clause to complete the query).
6485 */
6586 public Select.Builder select(String... columns) {
66- return new Select.Builder(cluster, Arrays.asList((Object[])columns));
87+ return new Select.Builder(protocolVersion, codecRegistry, Arrays.asList((Object[])columns));
6788 }
6889
6990 /**
@@ -74,7 +95,7 @@
7495 */
7596 public Select.Selection select() {
7697 // Note: the fact we return Select.Selection as return type is on purpose.
77- return new Select.SelectionOrAlias(cluster);
98+ return new Select.SelectionOrAlias(protocolVersion, codecRegistry);
7899 }
79100
80101 /**
@@ -84,7 +105,7 @@
84105 * @return an in-construction INSERT query.
85106 */
86107 public Insert insertInto(String table) {
87- return new Insert(cluster, null, table);
108+ return new Insert(protocolVersion, codecRegistry, null, table);
88109 }
89110
90111 /**
@@ -95,7 +116,7 @@
95116 * @return an in-construction INSERT query.
96117 */
97118 public Insert insertInto(String keyspace, String table) {
98- return new Insert(cluster, keyspace, table);
119+ return new Insert(protocolVersion, codecRegistry, keyspace, table);
99120 }
100121
101122 /**
@@ -105,7 +126,7 @@
105126 * @return an in-construction INSERT query.
106127 */
107128 public Insert insertInto(TableMetadata table) {
108- return new Insert(cluster, table);
129+ return new Insert(protocolVersion, codecRegistry, table);
109130 }
110131
111132 /**
@@ -116,7 +137,7 @@
116137 * clause needs to be provided to complete the query).
117138 */
118139 public Update update(String table) {
119- return new Update(cluster, null, table);
140+ return new Update(protocolVersion, codecRegistry, null, table);
120141 }
121142
122143 /**
@@ -128,7 +149,7 @@
128149 * clause needs to be provided to complete the query).
129150 */
130151 public Update update(String keyspace, String table) {
131- return new Update(cluster, keyspace, table);
152+ return new Update(protocolVersion, codecRegistry, keyspace, table);
132153 }
133154
134155 /**
@@ -139,7 +160,7 @@
139160 * clause needs to be provided to complete the query).
140161 */
141162 public Update update(TableMetadata table) {
142- return new Update(cluster, table);
163+ return new Update(protocolVersion, codecRegistry, table);
143164 }
144165
145166 /**
@@ -150,7 +171,7 @@
150171 * clause needs to be provided to complete the query).
151172 */
152173 public Delete.Builder delete(String... columns) {
153- return new Delete.Builder(cluster, columns);
174+ return new Delete.Builder(protocolVersion, codecRegistry, columns);
154175 }
155176
156177 /**
@@ -161,7 +182,7 @@
161182 * query).
162183 */
163184 public Delete.Selection delete() {
164- return new Delete.Selection(cluster);
185+ return new Delete.Selection(protocolVersion, codecRegistry);
165186 }
166187
167188 /**
@@ -178,7 +199,7 @@
178199 * @return a new {@code RegularStatement} that batch {@code statements}.
179200 */
180201 public Batch batch(RegularStatement... statements) {
181- return new Batch(cluster, statements, true);
202+ return new Batch(protocolVersion, codecRegistry, statements, true);
182203 }
183204
184205 /**
@@ -199,7 +220,7 @@
199220 * using the batch log.
200221 */
201222 public Batch unloggedBatch(RegularStatement... statements) {
202- return new Batch(cluster, statements, false);
223+ return new Batch(protocolVersion, codecRegistry, statements, false);
203224 }
204225
205226 /**
@@ -209,7 +230,7 @@
209230 * @return the truncation query.
210231 */
211232 public Truncate truncate(String table) {
212- return new Truncate(cluster, null, table);
233+ return new Truncate(protocolVersion, codecRegistry, null, table);
213234 }
214235
215236 /**
@@ -220,7 +241,7 @@
220241 * @return the truncation query.
221242 */
222243 public Truncate truncate(String keyspace, String table) {
223- return new Truncate(cluster, keyspace, table);
244+ return new Truncate(protocolVersion, codecRegistry, keyspace, table);
224245 }
225246
226247 /**
@@ -230,7 +251,7 @@
230251 * @return the truncation query.
231252 */
232253 public Truncate truncate(TableMetadata table) {
233- return new Truncate(cluster, table);
254+ return new Truncate(protocolVersion, codecRegistry, table);
234255 }
235256
236257 /**
modified driver-core/src/main/java/com/datastax/driver/core/querybuilder/Select.java +19 −15
@@ -22,6 +22,7 @@
2222
2323 import com.datastax.driver.core.Cluster;
2424 import com.datastax.driver.core.CodecRegistry;
25+import com.datastax.driver.core.ProtocolVersion;
2526 import com.datastax.driver.core.TableMetadata;
2627
2728 /**
@@ -39,16 +40,16 @@
3940 private Object limit;
4041 private boolean allowFiltering;
4142
42- Select(Cluster cluster, String keyspace, String table, List<Object> columnNames, boolean isDistinct) {
43- super(keyspace, cluster);
43+ Select(ProtocolVersion protocolVersion, CodecRegistry codecRegistry, String keyspace, String table, List<Object> columnNames, boolean isDistinct) {
44+ super(keyspace, protocolVersion, codecRegistry);
4445 this.table = table;
4546 this.isDistinct = isDistinct;
4647 this.columnNames = columnNames;
4748 this.where = new Where(this);
4849 }
4950
50- Select(Cluster cluster, TableMetadata table, List<Object> columnNames, boolean isDistinct) {
51- super(table, cluster);
51+ Select(ProtocolVersion protocolVersion, CodecRegistry codecRegistry, TableMetadata table, List<Object> columnNames, boolean isDistinct) {
52+ super(table, protocolVersion, codecRegistry);
5253 this.table = escapeId(table.getName());
5354 this.isDistinct = isDistinct;
5455 this.columnNames = columnNames;
@@ -257,16 +258,19 @@
257258 */
258259 public static class Builder {
259260
260- private final Cluster cluster;
261+ private final ProtocolVersion protocolVersion;
262+ private final CodecRegistry codecRegistry;
261263 List<Object> columnNames;
262264 boolean isDistinct;
263265
264- Builder(Cluster cluster) {
265- this.cluster = cluster;
266+ Builder(ProtocolVersion protocolVersion, CodecRegistry codecRegistry) {
267+ this.protocolVersion = protocolVersion;
268+ this.codecRegistry = codecRegistry;
266269 }
267270
268- Builder(Cluster cluster, List<Object> columnNames) {
269- this.cluster = cluster;
271+ Builder(ProtocolVersion protocolVersion, CodecRegistry codecRegistry, List<Object> columnNames) {
272+ this.protocolVersion = protocolVersion;
273+ this.codecRegistry = codecRegistry;
270274 this.columnNames = columnNames;
271275 }
272276
@@ -298,7 +302,7 @@
298302 * @return a newly built SELECT statement that selects from {@code keyspace.table}.
299303 */
300304 public Select from(String keyspace, String table) {
301- return new Select(cluster, keyspace, table, columnNames, isDistinct);
305+ return new Select(protocolVersion, codecRegistry, keyspace, table, columnNames, isDistinct);
302306 }
303307
304308 /**
@@ -308,7 +312,7 @@
308312 * @return a newly built SELECT statement that selects from {@code table}.
309313 */
310314 public Select from(TableMetadata table) {
311- return new Select(cluster, table, columnNames, isDistinct);
315+ return new Select(protocolVersion, codecRegistry, table, columnNames, isDistinct);
312316 }
313317 }
314318
@@ -317,8 +321,8 @@
317321 */
318322 public static abstract class Selection extends Builder {
319323
320- Selection(Cluster cluster) {
321- super(cluster);
324+ Selection(ProtocolVersion protocolVersion, CodecRegistry codecRegistry) {
325+ super(protocolVersion, codecRegistry);
322326 }
323327
324328 /**
@@ -405,8 +409,8 @@
405409
406410 private Object previousSelection;
407411
408- SelectionOrAlias(Cluster cluster) {
409- super(cluster);
412+ SelectionOrAlias(ProtocolVersion protocolVersion, CodecRegistry codecRegistry) {
413+ super(protocolVersion, codecRegistry);
410414 }
411415
412416 /**
modified driver-core/src/main/java/com/datastax/driver/core/querybuilder/Truncate.java +6 −4
@@ -18,6 +18,8 @@
1818 import java.util.List;
1919
2020 import com.datastax.driver.core.Cluster;
21+import com.datastax.driver.core.CodecRegistry;
22+import com.datastax.driver.core.ProtocolVersion;
2123 import com.datastax.driver.core.TableMetadata;
2224
2325 /**
@@ -27,13 +29,13 @@
2729
2830 private final String table;
2931
30- Truncate(Cluster cluster, String keyspace, String table) {
31- super(keyspace, cluster);
32+ Truncate(ProtocolVersion protocolVersion, CodecRegistry codecRegistry, String keyspace, String table) {
33+ super(keyspace, protocolVersion, codecRegistry);
3234 this.table = table;
3335 }
3436
35- Truncate(Cluster cluster, TableMetadata table) {
36- super(table, cluster);
37+ Truncate(ProtocolVersion protocolVersion, CodecRegistry codecRegistry, TableMetadata table) {
38+ super(table, protocolVersion, codecRegistry);
3739 this.table = escapeId(table.getName());
3840 }
3941
modified driver-core/src/main/java/com/datastax/driver/core/querybuilder/Update.java +5 −4
@@ -20,6 +20,7 @@
2020
2121 import com.datastax.driver.core.Cluster;
2222 import com.datastax.driver.core.CodecRegistry;
23+import com.datastax.driver.core.ProtocolVersion;
2324 import com.datastax.driver.core.TableMetadata;
2425 import com.datastax.driver.core.querybuilder.Assignment.CounterAssignment;
2526
@@ -34,8 +35,8 @@
3435 private final Options usings;
3536 private final Conditions conditions;
3637
37- Update(Cluster cluster, String keyspace, String table) {
38- super(keyspace, cluster);
38+ Update(ProtocolVersion protocolVersion, CodecRegistry codecRegistry, String keyspace, String table) {
39+ super(keyspace, protocolVersion, codecRegistry);
3940 this.table = table;
4041 this.assignments = new Assignments(this);
4142 this.where = new Where(this);
@@ -43,8 +44,8 @@
4344 this.conditions = new Conditions(this);
4445 }
4546
46- Update(Cluster cluster, TableMetadata table) {
47- super(table, cluster);
47+ Update(ProtocolVersion protocolVersion, CodecRegistry codecRegistry, TableMetadata table) {
48+ super(table, protocolVersion, codecRegistry);
4849 this.table = escapeId(table.getName());
4950 this.assignments = new Assignments(this);
5051 this.where = new Where(this);
modified driver-core/src/test/java/com/datastax/driver/core/TupleTest.java +19 −0
@@ -22,6 +22,7 @@
2222 import com.google.common.base.Joiner;
2323 import org.testng.annotations.Test;
2424
25+import static org.assertj.core.api.Assertions.assertThat;
2526 import static org.testng.Assert.assertEquals;
2627 import static org.testng.Assert.fail;
2728
@@ -388,6 +389,24 @@
388389 }
389390 }
390391
392+ /**
393+ * Validates that tuple values generated from an attached type (cluster-provided TupleType) and
394+ * a detached type (using TupleType.of) are the same.
395+ *
396+ * @since 2.2.0
397+ */
398+ @Test(groups = "short")
399+ public void detachedTupleTypeTest() {
400+ TupleType detachedType = TupleType.of(TestUtils.getDesiredProtocolVersion(), CodecRegistry.DEFAULT_INSTANCE,
401+ DataType.cint(), DataType.text(), DataType.cfloat());
402+ TupleValue detachedValue = detachedType.newValue(1, "hello", 2.0f);
403+
404+ TupleType attachedType = cluster.getMetadata().newTupleType(DataType.cint(), DataType.text(), DataType.cfloat());
405+ TupleValue attachedValue = attachedType.newValue(1, "hello", 2.0f);
406+
407+ assertThat(detachedValue).isEqualTo(attachedValue);
408+ }
409+
391410 /**
392411 * Helper method for creating nested tuple schema
393412 * @param depth
added driver-core/src/test/java/com/datastax/driver/core/TypeCodecNestedUDTAndTupleIntegrationTest.java +111 −0
@@ -0,0 +1,111 @@
1+/*
2+ * Copyright (C) 2012-2015 DataStax Inc.
3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ */
16+package com.datastax.driver.core;
17+
18+import java.util.*;
19+
20+import com.google.common.collect.Lists;
21+import com.google.common.collect.Sets;
22+import org.testng.annotations.Test;
23+
24+import static org.assertj.core.api.Assertions.assertThat;
25+
26+import com.datastax.driver.core.utils.CassandraVersion;
27+
28+/**
29+ * This tests that the CodecRegistry is able to create codecs on the fly
30+ * for nested UDTs and tuples received from a ResultSet, i.e. the first time
31+ * the registry encounters the UDT or tuple, it's coming from a ResultSet,
32+ * not from the Cluster's metadata.
33+ *
34+ * @jira_ticket JAVA-847
35+ */
36+@CassandraVersion(major = 2.1)
37+public class TypeCodecNestedUDTAndTupleIntegrationTest extends CCMBridge.PerClassSingleNodeCluster {
38+
39+ @Override
40+ protected Collection<String> getTableDefinitions() {
41+ return Lists.newArrayList(
42+ "CREATE TYPE IF NOT EXISTS \"udt3\" (f3 text)",
43+ "CREATE TYPE IF NOT EXISTS \"udt2\" (f2 frozen<udt3>)",
44+ "CREATE TYPE IF NOT EXISTS \"udt1\" (f1 frozen<udt2>)",
45+ "CREATE TABLE IF NOT EXISTS \"t1\" (pk int PRIMARY KEY, "
46+ + "c1 frozen<udt1>, "
47+ + "c2 frozen<tuple<tuple<tuple<text>>>>, "
48+ + "c3 frozen<tuple<tuple<tuple<udt1>>>>"
49+ + ")",
50+ // it's important to insert values using CQL literals
51+ // so that the CodecRegistry will not be required until
52+ // we receive a ResultSet
53+ "INSERT INTO t1 (pk, c1) VALUES (1, {f1:{f2:{f3:'foo'}}})",
54+ "INSERT INTO t1 (pk, c2) VALUES (2, ((('foo'))))",
55+ "INSERT INTO t1 (pk, c3) VALUES (3, ((({f1:{f2:{f3:'foo'}}}))))"
56+ );
57+ }
58+
59+ @Test(groups = "short")
60+ public void should_set_registry_on_nested_udts() {
61+ ResultSet rows = session.execute("SELECT c1 FROM t1 WHERE pk = 1");
62+ Row row = rows.one();
63+ // here the CodecRegistry will create a codec on-the-fly using the UserType received from the resultset metadata
64+ UDTValue udt1 = row.getUDTValue("c1");
65+ assertThat(udt1.getCodecRegistry()).isSameAs(cluster.getConfiguration().getCodecRegistry());
66+ UDTValue udt2 = udt1.getUDTValue("f1");
67+ assertThat(udt2.getCodecRegistry()).isSameAs(cluster.getConfiguration().getCodecRegistry());
68+ UDTValue udt3 = udt2.getUDTValue("f2");
69+ assertThat(udt3.getCodecRegistry()).isSameAs(cluster.getConfiguration().getCodecRegistry());
70+ String f3 = udt3.getString("f3");
71+ assertThat(f3).isEqualTo("foo");
72+ }
73+
74+ @Test(groups = "short")
75+ public void should_set_registry_on_nested_tuples() {
76+ ResultSet rows = session.execute("SELECT c2 FROM t1 WHERE pk = 2");
77+ Row row = rows.one();
78+ // here the CodecRegistry will create a codec on-the-fly using the TupleType received from the resultset metadata
79+ TupleValue tuple1 = row.getTupleValue("c2");
80+ assertThat(tuple1.getCodecRegistry()).isSameAs(cluster.getConfiguration().getCodecRegistry());
81+ TupleValue tuple2 = tuple1.getTupleValue(0);
82+ assertThat(tuple2.getCodecRegistry()).isSameAs(cluster.getConfiguration().getCodecRegistry());
83+ TupleValue tuple3 = tuple2.getTupleValue(0);
84+ assertThat(tuple3.getCodecRegistry()).isSameAs(cluster.getConfiguration().getCodecRegistry());
85+ String s = tuple3.getString(0);
86+ assertThat(s).isEqualTo("foo");
87+ }
88+
89+ @Test(groups = "short")
90+ public void should_set_registry_on_nested_tuples_and_udts() {
91+ ResultSet rows = session.execute("SELECT c3 FROM t1 WHERE pk = 3");
92+ Row row = rows.one();
93+ // here the CodecRegistry will create a codec on-the-fly using the TupleType received from the resultset metadata
94+ TupleValue tuple1 = row.getTupleValue("c3");
95+ assertThat(tuple1.getCodecRegistry()).isSameAs(cluster.getConfiguration().getCodecRegistry());
96+ TupleValue tuple2 = tuple1.getTupleValue(0);
97+ assertThat(tuple2.getCodecRegistry()).isSameAs(cluster.getConfiguration().getCodecRegistry());
98+ TupleValue tuple3 = tuple2.getTupleValue(0);
99+ assertThat(tuple3.getCodecRegistry()).isSameAs(cluster.getConfiguration().getCodecRegistry());
100+ UDTValue udt1 = tuple3.getUDTValue(0);
101+ assertThat(udt1.getCodecRegistry()).isSameAs(cluster.getConfiguration().getCodecRegistry());
102+ UDTValue udt2 = udt1.getUDTValue("f1");
103+ assertThat(udt2.getCodecRegistry()).isSameAs(cluster.getConfiguration().getCodecRegistry());
104+ UDTValue udt3 = udt2.getUDTValue("f2");
105+ assertThat(udt3.getCodecRegistry()).isSameAs(cluster.getConfiguration().getCodecRegistry());
106+ String f3 = udt3.getString("f3");
107+ assertThat(f3).isEqualTo("foo");
108+ }
109+
110+
111+}
modified driver-core/src/test/java/com/datastax/driver/core/TypeCodecOverlappingJavaTypeIntegrationTest.java +1 −1
@@ -52,7 +52,7 @@
5252 @Override
5353 protected Cluster.Builder configure(Cluster.Builder builder) {
5454 return builder.withCodecRegistry(
55- new CodecRegistry().register(new IntToStringCodec(), true)
55+ new CodecRegistry().register(new IntToStringCodec())
5656 );
5757 }
5858
modified driver-core/src/test/java/com/datastax/driver/core/TypeCodecTest.java +32 −1
@@ -31,6 +31,7 @@
3131 import static com.google.common.collect.Lists.newArrayList;
3232 import static org.testng.Assert.fail;
3333
34+import com.datastax.driver.core.TypeCodec.UDTCodec;
3435 import com.datastax.driver.core.UserType.Field;
3536 import com.datastax.driver.core.exceptions.CodecNotFoundException;
3637 import com.datastax.driver.core.exceptions.InvalidTypeException;
@@ -169,7 +170,7 @@
169170 UserType u2 = new UserType("ks", "table", newArrayList(new Field("f1", text()), new Field("f2", varchar())), V3, new CodecRegistry());
170171 UserType u3 = new UserType("ks", "table", newArrayList(new Field("f1", varchar()), new Field("f2", text())), V3, new CodecRegistry());
171172 UserType u4 = new UserType("ks", "table", newArrayList(new Field("f1", text()), new Field("f2", text())), V3, new CodecRegistry());
172- assertThat(new TypeCodec.UDTCodec(u1))
173+ assertThat(new UDTCodec(u1))
173174 .accepts(u2)
174175 .accepts(u3)
175176 .accepts(u4);
@@ -218,6 +219,36 @@
218219 }
219220
220221
222+ @Test(groups = "unit")
223+ public void should_deserialize_empty_buffer_as_tuple_with_null_values() {
224+ CodecRegistry codecRegistry = CodecRegistry.DEFAULT_INSTANCE;
225+ TupleType tupleType = new TupleType(newArrayList(DataType.cint(), DataType.varchar(), DataType.cfloat()), ProtocolVersion.NEWEST_SUPPORTED, codecRegistry);
226+ TupleValue expected = tupleType.newValue(null, null, null);
227+
228+ TupleValue actual = codecRegistry.codecFor(tupleType, TupleValue.class).deserialize(ByteBuffer.allocate(0), ProtocolVersion.NEWEST_SUPPORTED);
229+ assertThat(actual).isNotNull();
230+ assertThat(actual).isEqualTo(expected);
231+ }
232+
233+ @Test(groups = "unit")
234+ public void should_deserialize_empty_buffer_as_udt_with_null_values() {
235+ CodecRegistry codecRegistry = CodecRegistry.DEFAULT_INSTANCE;
236+ UserType udt = new UserType("ks", "t", Arrays.asList(
237+ new UserType.Field("t", DataType.text()),
238+ new UserType.Field("i", DataType.cint()),
239+ new UserType.Field("l", DataType.list(DataType.text()))
240+ ), ProtocolVersion.NEWEST_SUPPORTED, codecRegistry);
241+ UDTValue expected = udt.newValue();
242+ expected.setString("t", null);
243+ expected.setObject("i", null);
244+ expected.setList("l", null);
245+
246+ UDTValue actual = codecRegistry.codecFor(udt, UDTValue.class).deserialize(ByteBuffer.allocate(0), ProtocolVersion.NEWEST_SUPPORTED);
247+ assertThat(actual).isNotNull();
248+ assertThat(actual).isEqualTo(expected);
249+ }
250+
251+
221252 private class ListVarcharToListListInteger extends TypeCodec<List<List<Integer>>> {
222253
223254 private final ListCodec<String> codec = new ListCodec<String>(VarcharCodec.instance);
modified driver-core/src/test/java/com/datastax/driver/core/querybuilder/QueryBuilderTest.java +1 −14
@@ -42,20 +42,7 @@
4242
4343 public class QueryBuilderTest {
4444
45- private QueryBuilder builder;
46-
47- @BeforeMethod(groups = "unit")
48- public void setUpQueryBuilder() throws Exception {
49- CodecRegistry codecRegistry = new CodecRegistry();
50- Cluster cluster = mock(Cluster.class);
51- Configuration configuration = mock(Configuration.class);
52- ProtocolOptions protocolOptions = mock(ProtocolOptions.class);
53- when(cluster.getConfiguration()).thenReturn(configuration);
54- when(configuration.getCodecRegistry()).thenReturn(codecRegistry);
55- when(configuration.getProtocolOptions()).thenReturn(protocolOptions);
56- when(protocolOptions.getProtocolVersion()).thenReturn(TestUtils.getDesiredProtocolVersion());
57- builder = new QueryBuilder(cluster);
58- }
45+ private QueryBuilder builder = new QueryBuilder(TestUtils.getDesiredProtocolVersion(), CodecRegistry.DEFAULT_INSTANCE);
5946
6047 @Test(groups = "unit")
6148 public void selectTest() throws Exception {
modified features/custom_codecs/README.md +16 −8
@@ -108,25 +108,31 @@
108108 to only then parse the String into an object.
109109 More advanced solutions that read the underlying byte stream directly are possible.
110110
111-The second step is to register your codec:
111+The second step is to register your codec with a `CodecRegistry` instance:
112112
113113 ```java
114114 ObjectMapper objectMapper = ...
115115 JsonCodec<MyPojo> myJsonCodec = new JsonCodec<MyPojo>(MyPojo.class, objectMapper);
116-CodecRegistry myCodecRegistry = new CodecRegistry().register(myJsonCodec);
116+CodecRegistry myCodecRegistry = cluster.getConfiguration().getCodecRegistry();
117+myCodecRegistry.register(myJsonCodec);
117118 ```
118119
119-When you instantiate a `CodecRegistry`, it automatically registers all the default codecs used by the driver.
120-This ensures that the registry will not lack of an essential codec. *You cannot deregister default codecs, only
121-register new ones*.
120+As you can see, the easiest way to do so is to access the `Cluster`'s `CodecRegistry`.
121+By default, `Cluster` instances will use `CodecRegistry.DEFAULT_INSTANCE`,
122+which should be adequate for most users.
122123
123-The third step is to associate your `CodecRegistry` instance with your `Cluster` instance:
124+It is however possible to create a `Cluster` using a different `CodecRegistry`:
124125
125126 ```java
127+CodecRegistry myCodecRegistry = new CodecRegistry();
126128 Cluster cluster = new Cluster.builder().withCodecRegistry(myCodecRegistry).build();
127129 ```
128130
129-From now on, your codec is fully operational. It will be used every time the driver encounters
131+Note: when you instantiate a new `CodecRegistry`, it automatically registers all the default codecs used by the driver.
132+This ensures that the new registry will not lack of an essential codec. *You cannot deregister default codecs, only
133+register new ones*.
134+
135+From now on, your custom codec is fully operational. It will be used every time the driver encounters
130136 a `MyPojo` instance when executing queries, or when you ask it to retrieve a `MyPojo` instance from a `ResultSet`.
131137
132138 For example, here is how to save a `MyPojo` object:
@@ -262,9 +268,11 @@
262268
263269 Again, the driver provides a convenient base class: [MappingCodec].
264270
265-Now, create your `CodecRegistry` and `Cluster` instances the usual way:
271+Now (and only if you intend to use your own `CodecRegistry`),
272+create it and register it on your `Cluster` instance:
266273
267274 ```java
275+// only if you do not intend to use CodecRegistry.DEFAULT_INSTANCE
268276 CodecRegistry codecRegistry = new CodecRegistry();
269277 Cluster cluster = Cluster.builder()
270278 .addContactPoints(...)