Elffuss BraidHub

kikocis/java-driver public

Allow user to register custom type codecs (JAVA-721, JAVA-722).
Changesetf083a19ab3b5692cdc94b1913ea5127d2f8ca0cb57762e83f4b6e59836beb299
AuthorAlexandre Dutra <alexandre.dutra@datastax.com> · 2015-06-22 11:37 +02:00
CommitterAlexandre Dutra <alexandre.dutra@datastax.com> · 2015-07-28 10:30 +02:00
Parentsbcf9101430f7

Browse the files at this changeset

160 files changed

modified changelog/README.md +2 −0
@@ -9,6 +9,8 @@
99 - [improvement] Make ResultSet#fetchMoreResult return a
1010 ListenableFuture<ResultSet> (JAVA-836)
1111 - [improvement] Disable frozen checks in mapper (JAVA-843)
12+- [improvement] Allow user to register custom type codecs (JAVA-721)
13+- [improvement] Support custom type codecs in mapper (JAVA-722)
1214
1315 Merged from 2.1 branch:
1416
modified driver-core/pom.xml +14 −0
@@ -125,6 +125,20 @@
125125 <scope>test</scope>
126126 </dependency>
127127
128+ <dependency>
129+ <groupId>com.fasterxml.jackson.core</groupId>
130+ <artifactId>jackson-databind</artifactId>
131+ <version>2.5.3</version>
132+ <scope>test</scope>
133+ </dependency>
134+
135+ <dependency>
136+ <groupId>joda-time</groupId>
137+ <artifactId>joda-time</artifactId>
138+ <version>2.8.1</version>
139+ <scope>test</scope>
140+ </dependency>
141+
128142 </dependencies>
129143
130144 <build>
modified driver-core/src/main/java/com/datastax/driver/core/AbstractAddressableByIndexData.java +179 −122
@@ -21,7 +21,13 @@
2121 import java.nio.ByteBuffer;
2222 import java.util.*;
2323
24-import com.datastax.driver.core.exceptions.InvalidTypeException;
24+import com.google.common.base.Objects;
25+import com.google.common.reflect.TypeToken;
26+
27+import static com.datastax.driver.core.CodecUtils.listOf;
28+import static com.datastax.driver.core.CodecUtils.mapOf;
29+import static com.datastax.driver.core.CodecUtils.setOf;
30+import static com.datastax.driver.core.DataType.Name.*;
2531
2632 abstract class AbstractAddressableByIndexData<T extends SettableByIndexData<T>> extends AbstractGettableByIndexData implements SettableByIndexData<T> {
2733
@@ -43,75 +49,111 @@
4349 }
4450
4551 public T setBool(int i, boolean v) {
46- checkType(i, DataType.Name.BOOLEAN);
47- return setValue(i, TypeCodec.BooleanCodec.instance.serializeNoBoxing(v));
52+ checkType(i, BOOLEAN);
53+ TypeCodec<Boolean> codec = codecFor(i, Boolean.class);
54+ ByteBuffer bb;
55+ if(codec instanceof TypeCodec.PrimitiveBooleanCodec)
56+ bb = ((TypeCodec.PrimitiveBooleanCodec)codec).serializeNoBoxing(v, protocolVersion);
57+ else
58+ bb = codec.serialize(v, protocolVersion);
59+ return setValue(i, bb);
4860 }
4961
5062 public T setByte(int i, byte v) {
51- checkType(i, DataType.Name.TINYINT);
52- return setValue(i, TypeCodec.TinyIntCodec.instance.serializeNoBoxing(v));
63+ checkType(i, TINYINT);
64+ TypeCodec<Byte> codec = codecFor(i, Byte.class);
65+ ByteBuffer bb;
66+ if(codec instanceof TypeCodec.PrimitiveByteCodec)
67+ bb = ((TypeCodec.PrimitiveByteCodec)codec).serializeNoBoxing(v, protocolVersion);
68+ else
69+ bb = codec.serialize(v, protocolVersion);
70+ return setValue(i, bb);
5371 }
5472
5573 public T setShort(int i, short v) {
56- checkType(i, DataType.Name.SMALLINT);
57- return setValue(i, TypeCodec.SmallIntCodec.instance.serializeNoBoxing(v));
74+ checkType(i, SMALLINT);
75+ TypeCodec<Short> codec = codecFor(i, Short.class);
76+ ByteBuffer bb;
77+ if(codec instanceof TypeCodec.PrimitiveShortCodec)
78+ bb = ((TypeCodec.PrimitiveShortCodec)codec).serializeNoBoxing(v, protocolVersion);
79+ else
80+ bb = codec.serialize(v, protocolVersion);
81+ return setValue(i, bb);
5882 }
5983
6084 public T setInt(int i, int v) {
61- checkType(i, DataType.Name.INT);
62- return setValue(i, TypeCodec.IntCodec.instance.serializeNoBoxing(v));
85+ checkType(i, INT);
86+ TypeCodec<Integer> codec = codecFor(i, Integer.class);
87+ ByteBuffer bb;
88+ if(codec instanceof TypeCodec.PrimitiveIntCodec)
89+ bb = ((TypeCodec.PrimitiveIntCodec)codec).serializeNoBoxing(v, protocolVersion);
90+ else
91+ bb = codec.serialize(v, protocolVersion);
92+ return setValue(i, bb);
6393 }
6494
6595 public T setLong(int i, long v) {
66- checkType(i, DataType.Name.BIGINT, DataType.Name.COUNTER);
67- return setValue(i, TypeCodec.LongCodec.instance.serializeNoBoxing(v));
68- }
69-
70- public T setDate(int i, Date v) {
71- return setTimestamp(i, v);
96+ checkType(i, BIGINT, COUNTER);
97+ TypeCodec<Long> codec = codecFor(i, Long.class);
98+ ByteBuffer bb;
99+ if(codec instanceof TypeCodec.PrimitiveLongCodec)
100+ bb = ((TypeCodec.PrimitiveLongCodec)codec).serializeNoBoxing(v, protocolVersion);
101+ else
102+ bb = codec.serialize(v, protocolVersion);
103+ return setValue(i, bb);
72104 }
73105
74106 public T setTimestamp(int i, Date v) {
75- checkType(i, DataType.Name.TIMESTAMP);
76- return setValue(i, v == null ? null : TypeCodec.TimestampCodec.instance.serialize(v));
107+ checkType(i, TIMESTAMP);
108+ return setValue(i, codecFor(i, Date.class).serialize(v, protocolVersion));
77109 }
78110
79111 public T setDate(int i, LocalDate v) {
80- checkType(i, DataType.Name.DATE);
81- return setValue(i, TypeCodec.DateCodec.instance.serialize(v));
112+ checkType(i, DATE);
113+ return setValue(i, codecFor(i, LocalDate.class).serialize(v, protocolVersion));
82114 }
83115
84116 public T setTime(int i, long v) {
85- checkType(i, DataType.Name.TIME);
86- return setValue(i, TypeCodec.TimeCodec.instance.serializeNoBoxing(v));
117+ checkType(i, TIME);
118+ TypeCodec<Long> codec = codecFor(i, Long.class);
119+ ByteBuffer bb;
120+ if(codec instanceof TypeCodec.PrimitiveLongCodec)
121+ bb = ((TypeCodec.PrimitiveLongCodec)codec).serializeNoBoxing(v, protocolVersion);
122+ else
123+ bb = codec.serialize(v, protocolVersion);
124+ return setValue(i, bb);
87125 }
88126
89127 public T setFloat(int i, float v) {
90- checkType(i, DataType.Name.FLOAT);
91- return setValue(i, TypeCodec.FloatCodec.instance.serializeNoBoxing(v));
128+ checkType(i, FLOAT);
129+ TypeCodec<Float> codec = codecFor(i, Float.class);
130+ ByteBuffer bb;
131+ if(codec instanceof TypeCodec.PrimitiveFloatCodec)
132+ bb = ((TypeCodec.PrimitiveFloatCodec)codec).serializeNoBoxing(v, protocolVersion);
133+ else
134+ bb = codec.serialize(v, protocolVersion);
135+ return setValue(i, bb);
92136 }
93137
94138 public T setDouble(int i, double v) {
95- checkType(i, DataType.Name.DOUBLE);
96- return setValue(i, TypeCodec.DoubleCodec.instance.serializeNoBoxing(v));
139+ checkType(i, DOUBLE);
140+ TypeCodec<Double> codec = codecFor(i, Double.class);
141+ ByteBuffer bb;
142+ if(codec instanceof TypeCodec.PrimitiveDoubleCodec)
143+ bb = ((TypeCodec.PrimitiveDoubleCodec)codec).serializeNoBoxing(v, protocolVersion);
144+ else
145+ bb = codec.serialize(v, protocolVersion);
146+ return setValue(i, bb);
97147 }
98148
99149 public T setString(int i, String v) {
100- DataType.Name type = checkType(i, DataType.Name.VARCHAR, DataType.Name.TEXT, DataType.Name.ASCII);
101- switch (type) {
102- case ASCII:
103- return setValue(i, v == null ? null : TypeCodec.StringCodec.asciiInstance.serialize(v));
104- case TEXT:
105- case VARCHAR:
106- return setValue(i, v == null ? null : TypeCodec.StringCodec.utf8Instance.serialize(v));
107- default:
108- throw new AssertionError();
109- }
150+ checkType(i, VARCHAR, TEXT, ASCII);
151+ return setValue(i, codecFor(i, String.class).serialize(v, protocolVersion));
110152 }
111153
112154 public T setBytes(int i, ByteBuffer v) {
113- checkType(i, DataType.Name.BLOB);
114- return setBytesUnsafe(i, v);
155+ checkType(i, BLOB);
156+ return setValue(i, codecFor(i, ByteBuffer.class).serialize(v, protocolVersion));
115157 }
116158
117159 public T setBytesUnsafe(int i, ByteBuffer v) {
@@ -119,117 +161,130 @@
119161 }
120162
121163 public T setVarint(int i, BigInteger v) {
122- checkType(i, DataType.Name.VARINT);
123- return setValue(i, v == null ? null : TypeCodec.BigIntegerCodec.instance.serialize(v));
164+ checkType(i, VARINT);
165+ return setValue(i, codecFor(i, BigInteger.class).serialize(v, protocolVersion));
124166 }
125167
126168 public T setDecimal(int i, BigDecimal v) {
127- checkType(i, DataType.Name.DECIMAL);
128- return setValue(i, v == null ? null : TypeCodec.DecimalCodec.instance.serialize(v));
169+ checkType(i, DECIMAL);
170+ return setValue(i, codecFor(i, BigDecimal.class).serialize(v, protocolVersion));
129171 }
130172
131173 public T setUUID(int i, UUID v) {
132- DataType.Name type = checkType(i, DataType.Name.UUID, DataType.Name.TIMEUUID);
133-
134- if (v == null)
135- return setValue(i, null);
136-
137- if (type == DataType.Name.TIMEUUID && v.version() != 1)
138- throw new InvalidTypeException(String.format("%s is not a Type 1 (time-based) UUID", v));
139-
140- return type == DataType.Name.UUID
141- ? setValue(i, TypeCodec.UUIDCodec.instance.serialize(v))
142- : setValue(i, TypeCodec.TimeUUIDCodec.instance.serialize(v));
174+ checkType(i, UUID, TIMEUUID);
175+ return setValue(i, codecFor(i, UUID.class).serialize(v, protocolVersion));
143176 }
144177
145178 public T setInet(int i, InetAddress v) {
146- checkType(i, DataType.Name.INET);
147- return setValue(i, v == null ? null : TypeCodec.InetCodec.instance.serialize(v));
179+ checkType(i, INET);
180+ return setValue(i, codecFor(i, InetAddress.class).serialize(v, protocolVersion));
148181 }
149182
183+ @SuppressWarnings("unchecked")
150184 public <E> T setList(int i, List<E> v) {
151- DataType type = getType(i);
152- if (type.getName() != DataType.Name.LIST)
153- throw new InvalidTypeException(String.format("Column %s is of type %s, cannot set to a list", getName(i), type));
154-
155- if (v == null)
156- return setValue(i, null);
157-
158- // If the list is empty, it will never fail validation, but otherwise we should check the list given if of the right type
159- if (!v.isEmpty()) {
160- // Ugly? Yes
161- Class<?> providedClass = v.get(0).getClass();
162- Class<?> expectedClass = type.getTypeArguments().get(0).asJavaClass();
163-
164- if (!expectedClass.isAssignableFrom(providedClass))
165- throw new InvalidTypeException(String.format("Invalid value for column %s of CQL type %s, expecting list of %s but provided list of %s", getName(i), type, expectedClass, providedClass));
185+ checkType(i, LIST);
186+ if(v == null || v.isEmpty()) {
187+ // no runtime inspection possible, rely on the underlying metadata
188+ return setValue(i, codecFor(i).serialize(v, protocolVersion));
189+ } else {
190+ // inspect the first element and locate a codec that accepts both the underlying CQL type and the actual Java type
191+ DataType eltCqlType = getType(i).getTypeArguments().get(0);
192+ TypeToken<E> eltJavaType = getCodecRegistry().codecFor(eltCqlType, v.iterator().next()).getJavaType();
193+ return setValue(i, codecFor(i, listOf(eltJavaType)).serialize(v, protocolVersion));
166194 }
167- return setValue(i, type.codec(protocolVersion).serialize(v));
168195 }
169196
197+ @Override
198+ public <E> T setList(int i, List<E> v, Class<E> elementsClass) {
199+ return setValue(i, codecFor(i, listOf(elementsClass)).serialize(v, protocolVersion));
200+ }
201+
202+ @Override
203+ public <E> T setList(int i, List<E> v, TypeToken<E> elementsType) {
204+ return setValue(i, codecFor(i, listOf(elementsType)).serialize(v, protocolVersion));
205+ }
206+
207+ @SuppressWarnings("unchecked")
170208 public <K, V> T setMap(int i, Map<K, V> v) {
171- DataType type = getType(i);
172- if (type.getName() != DataType.Name.MAP)
173- throw new InvalidTypeException(String.format("Column %s is of type %s, cannot set to a map", getName(i), type));
174-
175- if (v == null)
176- return setValue(i, null);
177-
178- if (!v.isEmpty()) {
179- // Ugly? Yes
209+ checkType(i, MAP);
210+ if(v == null || v.isEmpty()) {
211+ // no runtime inspection possible, rely on the underlying metadata
212+ return setValue(i, codecFor(i).serialize(v, protocolVersion));
213+ } else {
214+ // inspect the first element and locate a codec that accepts both the underlying CQL type and the actual Java types for keys and values
215+ DataType keysCqlType = getType(i).getTypeArguments().get(0);
216+ DataType valuesCqlType = getType(i).getTypeArguments().get(1);
180217 Map.Entry<K, V> entry = v.entrySet().iterator().next();
181- Class<?> providedKeysClass = entry.getKey().getClass();
182- Class<?> providedValuesClass = entry.getValue().getClass();
183-
184- Class<?> expectedKeysClass = type.getTypeArguments().get(0).getName().javaType;
185- Class<?> expectedValuesClass = type.getTypeArguments().get(1).getName().javaType;
186- if (!expectedKeysClass.isAssignableFrom(providedKeysClass) || !expectedValuesClass.isAssignableFrom(providedValuesClass))
187- throw new InvalidTypeException(String.format("Invalid value for column %s of CQL type %s, expecting map of %s->%s but provided map of %s->%s", getName(i), type, expectedKeysClass, expectedValuesClass, providedKeysClass, providedValuesClass));
218+ TypeToken<K> keysType = getCodecRegistry().codecFor(keysCqlType, entry.getKey()).getJavaType();
219+ TypeToken<V> valuesType = getCodecRegistry().codecFor(valuesCqlType, entry.getValue()).getJavaType();
220+ return setValue(i, codecFor(i, mapOf(keysType, valuesType)).serialize(v, protocolVersion));
188221 }
189- return setValue(i, type.codec(protocolVersion).serialize(v));
190222 }
191223
224+ @Override
225+ public <K, V> T setMap(int i, Map<K, V> v, Class<K> keysClass, Class<V> valuesClass) {
226+ return setValue(i, codecFor(i, mapOf(keysClass, valuesClass)).serialize(v, protocolVersion));
227+ }
228+
229+ @Override
230+ public <K, V> T setMap(int i, Map<K, V> v, TypeToken<K> keysType, TypeToken<V> valuesType) {
231+ return setValue(i, codecFor(i, mapOf(keysType, valuesType)).serialize(v, protocolVersion));
232+ }
233+
234+ @SuppressWarnings("unchecked")
192235 public <E> T setSet(int i, Set<E> v) {
193- DataType type = getType(i);
194- if (type.getName() != DataType.Name.SET)
195- throw new InvalidTypeException(String.format("Column %s is of type %s, cannot set to a set", getName(i), type));
196-
197- if (v == null)
198- return setValue(i, null);
199-
200- if (!v.isEmpty()) {
201- // Ugly? Yes
202- Class<?> providedClass = v.iterator().next().getClass();
203- Class<?> expectedClass = type.getTypeArguments().get(0).getName().javaType;
204-
205- if (!expectedClass.isAssignableFrom(providedClass))
206- throw new InvalidTypeException(String.format("Invalid value for column %s of CQL type %s, expecting set of %s but provided set of %s", getName(i), type, expectedClass, providedClass));
236+ checkType(i, SET);
237+ if(v == null || v.isEmpty()) {
238+ // no runtime inspection possible, rely on the underlying metadata
239+ return setValue(i, codecFor(i).serialize(v, protocolVersion));
240+ } else {
241+ // inspect the first element and locate a codec that accepts both the underlying CQL type and the actual Java type
242+ DataType eltCqlType = getType(i).getTypeArguments().get(0);
243+ TypeToken<E> eltJavaType = getCodecRegistry().codecFor(eltCqlType, v.iterator().next()).getJavaType();
244+ return setValue(i, codecFor(i, setOf(eltJavaType)).serialize(v, protocolVersion));
207245 }
208- return setValue(i, type.codec(protocolVersion).serialize(v));
209246 }
210247
211- public T setUDTValue(int i, UDTValue v) {
212- DataType type = getType(i);
213- if (type.getName() != DataType.Name.UDT)
214- throw new InvalidTypeException(String.format("Column %s is of type %s, cannot set to a UDT", getName(i), type));
248+ @Override
249+ public <E> T setSet(int i, Set<E> v, Class<E> elementsClass) {
250+ return setValue(i, codecFor(i, setOf(elementsClass)).serialize(v, protocolVersion));
251+ }
215252
216- if (v == null)
217- return setValue(i, null);
253+ @Override
254+ public <E> T setSet(int i, Set<E> v, TypeToken<E> elementsType) {
255+ return setValue(i, codecFor(i, setOf(elementsType)).serialize(v, protocolVersion));
256+ }
218257
219- // UDT always use the V3 protocol version to encode values
220- return setValue(i, type.codec(ProtocolVersion.V3).serialize(v));
258+ public T setUDTValue(int i, UDTValue v) {
259+ checkType(i, UDT);
260+ return setValue(i, codecFor(i, UDTValue.class).serialize(v, protocolVersion));
221261 }
222262
223263 public T setTupleValue(int i, TupleValue v) {
224- DataType type = getType(i);
225- if (type.getName() != DataType.Name.TUPLE)
226- throw new InvalidTypeException(String.format("Column %s is of type %s, cannot set to a tuple", getName(i), type));
264+ checkType(i, TUPLE);
265+ return setValue(i, codecFor(i, TupleValue.class).serialize(v, protocolVersion));
266+ }
267+
268+ @Override
269+ public <V> T setObject(int i, V v) {
270+ TypeCodec<V> codec = v == null ? this.<V>codecFor(i) : codecFor(i, v);
271+ return set(i, v, codec);
272+ }
273+
274+ @Override
275+ public <V> T set(int i, V v, Class<V> targetClass) {
276+ return set(i, v, codecFor(i, targetClass));
277+ }
227278
228- if (v == null)
229- return setValue(i, null);
279+ @Override
280+ public <V> T set(int i, V v, TypeToken<V> targetType) {
281+ return set(i, v, codecFor(i, targetType));
282+ }
230283
231- // Tuples always user the V3 protocol version to encode values
232- return setValue(i, type.codec(ProtocolVersion.V3).serialize(v));
284+ @Override
285+ public <V> T set(int i, V v, TypeCodec<V> codec) {
286+ checkType(i, codec.getCqlType().getName());
287+ return setValue(i, codec.serialize(v, protocolVersion));
233288 }
234289
235290 public T setToNull(int i) {
@@ -245,6 +300,9 @@
245300 if (values.length != that.values.length)
246301 return false;
247302
303+ if(this.protocolVersion != that.protocolVersion)
304+ return false;
305+
248306 // Deserializing each value is slightly inefficient, but comparing
249307 // the bytes could in theory be wrong (for varint for instance, 2 values
250308 // can have different binary representation but be the same value due to
@@ -255,10 +313,9 @@
255313 if (!thisType.equals(thatType))
256314 return false;
257315
258- if ((values[i] == null) != (that.values[i] == null))
259- return false;
260-
261- if (values[i] != null && !(thisType.deserialize(values[i], protocolVersion).equals(thatType.deserialize(that.values[i], protocolVersion))))
316+ Object thisValue = this.codecFor(i).deserialize(this.values[i], this.protocolVersion);
317+ Object thatValue = that.codecFor(i).deserialize(that.values[i], that.protocolVersion);
318+ if (!Objects.equal(thisValue, thatValue))
262319 return false;
263320 }
264321 return true;
@@ -269,7 +326,7 @@
269326 // Same as equals
270327 int hash = 31;
271328 for (int i = 0; i < values.length; i++)
272- hash += values[i] == null ? 1 : getType(i).deserialize(values[i], protocolVersion).hashCode();
329+ hash += values[i] == null ? 1 : codecFor(i).deserialize(values[i], protocolVersion).hashCode();
273330 return hash;
274331 }
275332 }
modified driver-core/src/main/java/com/datastax/driver/core/AbstractData.java +319 −222
@@ -21,7 +21,13 @@
2121 import java.nio.ByteBuffer;
2222 import java.util.*;
2323
24-import com.datastax.driver.core.exceptions.InvalidTypeException;
24+import com.google.common.base.Objects;
25+import com.google.common.reflect.TypeToken;
26+
27+import static com.datastax.driver.core.CodecUtils.listOf;
28+import static com.datastax.driver.core.CodecUtils.mapOf;
29+import static com.datastax.driver.core.CodecUtils.setOf;
30+import static com.datastax.driver.core.DataType.Name.*;
2531
2632 // We don't want to expose this one: it's less useful externally and it's a bit ugly to expose anyway (but it's convenient).
2733 abstract class AbstractData<T extends SettableData<T>> extends AbstractGettableData implements SettableData<T> {
@@ -29,7 +35,7 @@
2935 final T wrapped;
3036 final ByteBuffer[] values;
3137
32- // Ugly, we coould probably clean that: it is currently needed however because we sometimes
38+ // Ugly, we could probably clean that: it is currently needed however because we sometimes
3339 // want wrapped to be 'this' (UDTValue), and sometimes some other object (in BoundStatement).
3440 @SuppressWarnings("unchecked")
3541 protected AbstractData(ProtocolVersion protocolVersion, int size) {
@@ -64,186 +70,193 @@
6470 }
6571
6672 public T setBool(int i, boolean v) {
67- checkType(i, DataType.Name.BOOLEAN);
68- return setValue(i, TypeCodec.BooleanCodec.instance.serializeNoBoxing(v));
73+ checkType(i, BOOLEAN);
74+ TypeCodec<Boolean> codec = codecFor(i, Boolean.class);
75+ ByteBuffer bb;
76+ if(codec instanceof TypeCodec.PrimitiveBooleanCodec)
77+ bb = ((TypeCodec.PrimitiveBooleanCodec)codec).serializeNoBoxing(v, protocolVersion);
78+ else
79+ bb = codec.serialize(v, protocolVersion);
80+ return setValue(i, bb);
6981 }
7082
7183 public T setBool(String name, boolean v) {
72- int[] indexes = getAllIndexesOf(name);
73- ByteBuffer value = TypeCodec.BooleanCodec.instance.serializeNoBoxing(v);
74- for (int i = 0; i < indexes.length; i++) {
75- checkType(indexes[i], DataType.Name.BOOLEAN);
76- setValue(indexes[i], value);
84+ for (int i : getAllIndexesOf(name)) {
85+ setBool(i, v);
7786 }
7887 return wrapped;
7988 }
8089
8190 public T setByte(int i, byte v) {
82- checkType(i, DataType.Name.TINYINT);
83- return setValue(i, TypeCodec.TinyIntCodec.instance.serializeNoBoxing(v));
91+ checkType(i, TINYINT);
92+ TypeCodec<Byte> codec = codecFor(i, Byte.class);
93+ ByteBuffer bb;
94+ if(codec instanceof TypeCodec.PrimitiveByteCodec)
95+ bb = ((TypeCodec.PrimitiveByteCodec)codec).serializeNoBoxing(v, protocolVersion);
96+ else
97+ bb = codec.serialize(v, protocolVersion);
98+ return setValue(i, bb);
8499 }
85100
86101 public T setByte(String name, byte v) {
87- int[] indexes = getAllIndexesOf(name);
88- ByteBuffer value = TypeCodec.TinyIntCodec.instance.serializeNoBoxing(v);
89- for (int i = 0; i < indexes.length; i++) {
90- checkType(indexes[i], DataType.Name.TINYINT);
91- setValue(indexes[i], value);
102+ for (int i : getAllIndexesOf(name)) {
103+ setByte(i, v);
92104 }
93105 return wrapped;
94106 }
95107
96108 public T setShort(int i, short v) {
97- checkType(i, DataType.Name.SMALLINT);
98- return setValue(i, TypeCodec.SmallIntCodec.instance.serializeNoBoxing(v));
109+ checkType(i, SMALLINT);
110+ TypeCodec<Short> codec = codecFor(i, Short.class);
111+ ByteBuffer bb;
112+ if(codec instanceof TypeCodec.PrimitiveShortCodec)
113+ bb = ((TypeCodec.PrimitiveShortCodec)codec).serializeNoBoxing(v, protocolVersion);
114+ else
115+ bb = codec.serialize(v, protocolVersion);
116+ return setValue(i, bb);
99117 }
100118
101119 public T setShort(String name, short v) {
102- int[] indexes = getAllIndexesOf(name);
103- ByteBuffer value = TypeCodec.SmallIntCodec.instance.serializeNoBoxing(v);
104- for (int i = 0; i < indexes.length; i++) {
105- checkType(indexes[i], DataType.Name.SMALLINT);
106- setValue(indexes[i], value);
120+ for (int i : getAllIndexesOf(name)) {
121+ setShort(i, v);
107122 }
108123 return wrapped;
109124 }
110125
111126 public T setInt(int i, int v) {
112- checkType(i, DataType.Name.INT);
113- return setValue(i, TypeCodec.IntCodec.instance.serializeNoBoxing(v));
127+ checkType(i, INT);
128+ TypeCodec<Integer> codec = codecFor(i, Integer.class);
129+ ByteBuffer bb;
130+ if(codec instanceof TypeCodec.PrimitiveIntCodec)
131+ bb = ((TypeCodec.PrimitiveIntCodec)codec).serializeNoBoxing(v, protocolVersion);
132+ else
133+ bb = codec.serialize(v, protocolVersion);
134+ return setValue(i, bb);
114135 }
115136
116137 public T setInt(String name, int v) {
117- int[] indexes = getAllIndexesOf(name);
118- ByteBuffer value = TypeCodec.IntCodec.instance.serializeNoBoxing(v);
119- for (int i = 0; i < indexes.length; i++) {
120- checkType(indexes[i], DataType.Name.INT);
121- setValue(indexes[i], value);
138+ for (int i : getAllIndexesOf(name)) {
139+ setInt(i, v);
122140 }
123141 return wrapped;
124142 }
125143
126144 public T setLong(int i, long v) {
127- checkType(i, DataType.Name.BIGINT, DataType.Name.COUNTER);
128- return setValue(i, TypeCodec.LongCodec.instance.serializeNoBoxing(v));
145+ checkType(i, BIGINT, COUNTER);
146+ TypeCodec<Long> codec = codecFor(i, Long.class);
147+ ByteBuffer bb;
148+ if(codec instanceof TypeCodec.PrimitiveLongCodec)
149+ bb = ((TypeCodec.PrimitiveLongCodec)codec).serializeNoBoxing(v, protocolVersion);
150+ else
151+ bb = codec.serialize(v, protocolVersion);
152+ return setValue(i, bb);
129153 }
130154
131155 public T setLong(String name, long v) {
132- int[] indexes = getAllIndexesOf(name);
133- ByteBuffer value = TypeCodec.LongCodec.instance.serializeNoBoxing(v);
134- for (int i = 0; i < indexes.length; i++) {
135- checkType(indexes[i], DataType.Name.BIGINT, DataType.Name.COUNTER);
136- setValue(indexes[i], value);
156+ for (int i : getAllIndexesOf(name)) {
157+ setLong(i, v);
137158 }
138159 return wrapped;
139160 }
140161
141162 public T setTimestamp(int i, Date v) {
142- checkType(i, DataType.Name.TIMESTAMP);
143- return setValue(i, v == null ? null : TypeCodec.TimestampCodec.instance.serialize(v));
163+ checkType(i, TIMESTAMP);
164+ return setValue(i, codecFor(i, Date.class).serialize(v, protocolVersion));
144165 }
145166
146167 public T setTimestamp(String name, Date v) {
147- int[] indexes = getAllIndexesOf(name);
148- ByteBuffer value = v == null ? null : TypeCodec.TimestampCodec.instance.serialize(v);
149- for (int i = 0; i < indexes.length; i++) {
150- checkType(indexes[i], DataType.Name.TIMESTAMP);
151- setValue(indexes[i], value);
168+ for (int i : getAllIndexesOf(name)) {
169+ setTimestamp(i, v);
152170 }
153171 return wrapped;
154172 }
155173
156174 public T setDate(int i, LocalDate v) {
157- checkType(i, DataType.Name.DATE);
158- return setValue(i, TypeCodec.DateCodec.instance.serialize(v));
175+ checkType(i, DATE);
176+ return setValue(i, codecFor(i, LocalDate.class).serialize(v, protocolVersion));
159177 }
160178
161179 public T setDate(String name, LocalDate v) {
162- int[] indexes = getAllIndexesOf(name);
163- ByteBuffer value = TypeCodec.DateCodec.instance.serialize(v);
164- for (int i = 0; i < indexes.length; i++) {
165- checkType(indexes[i], DataType.Name.DATE);
166- setValue(indexes[i], value);
180+ for (int i : getAllIndexesOf(name)) {
181+ setDate(i, v);
167182 }
168183 return wrapped;
169184 }
170185
171186 public T setTime(int i, long v) {
172- checkType(i, DataType.Name.TIME);
173- return setValue(i, TypeCodec.TimeCodec.instance.serializeNoBoxing(v));
187+ checkType(i, TIME);
188+ TypeCodec<Long> codec = codecFor(i, Long.class);
189+ ByteBuffer bb;
190+ if(codec instanceof TypeCodec.PrimitiveLongCodec)
191+ bb = ((TypeCodec.PrimitiveLongCodec)codec).serializeNoBoxing(v, protocolVersion);
192+ else
193+ bb = codec.serialize(v, protocolVersion);
194+ return setValue(i, bb);
174195 }
175196
176197 public T setTime(String name, long v) {
177- int[] indexes = getAllIndexesOf(name);
178- ByteBuffer value = TypeCodec.TimeCodec.instance.serializeNoBoxing(v);
179- for (int i = 0; i < indexes.length; i++) {
180- checkType(indexes[i], DataType.Name.TIME);
181- setValue(indexes[i], value);
198+ for (int i : getAllIndexesOf(name)) {
199+ setTime(i, v);
182200 }
183201 return wrapped;
184202 }
185203
186204 public T setFloat(int i, float v) {
187- checkType(i, DataType.Name.FLOAT);
188- return setValue(i, TypeCodec.FloatCodec.instance.serializeNoBoxing(v));
205+ checkType(i, FLOAT);
206+ TypeCodec<Float> codec = codecFor(i, Float.class);
207+ ByteBuffer bb;
208+ if(codec instanceof TypeCodec.PrimitiveFloatCodec)
209+ bb = ((TypeCodec.PrimitiveFloatCodec)codec).serializeNoBoxing(v, protocolVersion);
210+ else
211+ bb = codec.serialize(v, protocolVersion);
212+ return setValue(i, bb);
189213 }
190214
191215 public T setFloat(String name, float v) {
192- int[] indexes = getAllIndexesOf(name);
193- ByteBuffer value = TypeCodec.FloatCodec.instance.serializeNoBoxing(v);
194- for (int i = 0; i < indexes.length; i++) {
195- checkType(indexes[i], DataType.Name.FLOAT);
196- setValue(indexes[i], value);
216+ for (int i : getAllIndexesOf(name)) {
217+ setFloat(i, v);
197218 }
198219 return wrapped;
199220 }
200221
201222 public T setDouble(int i, double v) {
202- checkType(i, DataType.Name.DOUBLE);
203- return setValue(i, TypeCodec.DoubleCodec.instance.serializeNoBoxing(v));
223+ checkType(i, DOUBLE);
224+ TypeCodec<Double> codec = codecFor(i, Double.class);
225+ ByteBuffer bb;
226+ if(codec instanceof TypeCodec.PrimitiveDoubleCodec)
227+ bb = ((TypeCodec.PrimitiveDoubleCodec)codec).serializeNoBoxing(v, protocolVersion);
228+ else
229+ bb = codec.serialize(v, protocolVersion);
230+ return setValue(i, bb);
204231 }
205232
206233 public T setDouble(String name, double v) {
207- int[] indexes = getAllIndexesOf(name);
208- ByteBuffer value = TypeCodec.DoubleCodec.instance.serializeNoBoxing(v);
209- for (int i = 0; i < indexes.length; i++) {
210- checkType(indexes[i], DataType.Name.DOUBLE);
211- setValue(indexes[i], value);
234+ for (int i : getAllIndexesOf(name)) {
235+ setDouble(i, v);
212236 }
213237 return wrapped;
214238 }
215239
216240 public T setString(int i, String v) {
217- DataType.Name type = checkType(i, DataType.Name.VARCHAR, DataType.Name.TEXT, DataType.Name.ASCII);
218- switch (type) {
219- case ASCII:
220- return setValue(i, v == null ? null : TypeCodec.StringCodec.asciiInstance.serialize(v));
221- case TEXT:
222- case VARCHAR:
223- return setValue(i, v == null ? null : TypeCodec.StringCodec.utf8Instance.serialize(v));
224- default:
225- throw new AssertionError();
226- }
241+ checkType(i, VARCHAR, TEXT, ASCII);
242+ return setValue(i, codecFor(i, String.class).serialize(v, protocolVersion));
227243 }
228244
229245 public T setString(String name, String v) {
230- int[] indexes = getAllIndexesOf(name);
231- for (int i = 0; i < indexes.length; i++)
232- setString(indexes[i], v);
246+ for (int i : getAllIndexesOf(name)) {
247+ setString(i, v);
248+ }
233249 return wrapped;
234250 }
235251
236252 public T setBytes(int i, ByteBuffer v) {
237- checkType(i, DataType.Name.BLOB);
238- return setBytesUnsafe(i, v);
253+ checkType(i, BLOB);
254+ return setValue(i, codecFor(i, ByteBuffer.class).serialize(v, protocolVersion));
239255 }
240256
241257 public T setBytes(String name, ByteBuffer v) {
242- int[] indexes = getAllIndexesOf(name);
243- ByteBuffer value = v == null ? null : v.duplicate();
244- for (int i = 0; i < indexes.length; i++) {
245- checkType(indexes[i], DataType.Name.BLOB);
246- setValue(indexes[i], value);
258+ for (int i : getAllIndexesOf(name)) {
259+ setBytes(i, v);
247260 }
248261 return wrapped;
249262 }
@@ -253,80 +266,57 @@
253266 }
254267
255268 public T setBytesUnsafe(String name, ByteBuffer v) {
256- int[] indexes = getAllIndexesOf(name);
257269 ByteBuffer value = v == null ? null : v.duplicate();
258- for (int i = 0; i < indexes.length; i++)
259- setValue(indexes[i], value);
270+ for (int i : getAllIndexesOf(name)) {
271+ setValue(i, value);
272+ }
260273 return wrapped;
261274 }
262275
263276 public T setVarint(int i, BigInteger v) {
264- checkType(i, DataType.Name.VARINT);
265- return setValue(i, v == null ? null : TypeCodec.BigIntegerCodec.instance.serialize(v));
277+ checkType(i, VARINT);
278+ return setValue(i, codecFor(i, BigInteger.class).serialize(v, protocolVersion));
266279 }
267280
268281 public T setVarint(String name, BigInteger v) {
269- int[] indexes = getAllIndexesOf(name);
270- ByteBuffer value = v == null ? null : TypeCodec.BigIntegerCodec.instance.serialize(v);
271- for (int i = 0; i < indexes.length; i++) {
272- checkType(indexes[i], DataType.Name.VARINT);
273- setValue(indexes[i], value);
282+ for (int i : getAllIndexesOf(name)) {
283+ setVarint(i, v);
274284 }
275285 return wrapped;
276286 }
277287
278288 public T setDecimal(int i, BigDecimal v) {
279- checkType(i, DataType.Name.DECIMAL);
280- return setValue(i, v == null ? null : TypeCodec.DecimalCodec.instance.serialize(v));
289+ checkType(i, DECIMAL);
290+ return setValue(i, codecFor(i, BigDecimal.class).serialize(v, protocolVersion));
281291 }
282292
283293 public T setDecimal(String name, BigDecimal v) {
284- int[] indexes = getAllIndexesOf(name);
285- ByteBuffer value = v == null ? null : TypeCodec.DecimalCodec.instance.serialize(v);
286- for (int i = 0; i < indexes.length; i++) {
287- checkType(indexes[i], DataType.Name.DECIMAL);
288- setValue(indexes[i], value);
294+ for (int i : getAllIndexesOf(name)) {
295+ setDecimal(i, v);
289296 }
290297 return wrapped;
291298 }
292299
293300 public T setUUID(int i, UUID v) {
294- DataType.Name type = checkType(i, DataType.Name.UUID, DataType.Name.TIMEUUID);
295-
296- if (v == null)
297- return setValue(i, null);
298-
299- if (type == DataType.Name.TIMEUUID && v.version() != 1)
300- throw new InvalidTypeException(String.format("%s is not a Type 1 (time-based) UUID", v));
301-
302- return type == DataType.Name.UUID
303- ? setValue(i, TypeCodec.UUIDCodec.instance.serialize(v))
304- : setValue(i, TypeCodec.TimeUUIDCodec.instance.serialize(v));
301+ checkType(i, UUID, TIMEUUID);
302+ return setValue(i, codecFor(i, UUID.class).serialize(v, protocolVersion));
305303 }
306304
307305 public T setUUID(String name, UUID v) {
308- int[] indexes = getAllIndexesOf(name);
309- ByteBuffer value = v == null ? null : TypeCodec.UUIDCodec.instance.serialize(v);
310- for (int i = 0; i < indexes.length; i++) {
311- DataType.Name type = checkType(indexes[i], DataType.Name.UUID, DataType.Name.TIMEUUID);
312- if (v != null && type == DataType.Name.TIMEUUID && v.version() != 1)
313- throw new InvalidTypeException(String.format("%s is not a Type 1 (time-based) UUID", v));
314- setValue(indexes[i], value);
306+ for (int i : getAllIndexesOf(name)) {
307+ setUUID(i, v);
315308 }
316309 return wrapped;
317310 }
318311
319312 public T setInet(int i, InetAddress v) {
320- checkType(i, DataType.Name.INET);
321- return setValue(i, v == null ? null : TypeCodec.InetCodec.instance.serialize(v));
313+ checkType(i, INET);
314+ return setValue(i, codecFor(i, InetAddress.class).serialize(v, protocolVersion));
322315 }
323316
324317 public T setInet(String name, InetAddress v) {
325- int[] indexes = getAllIndexesOf(name);
326- ByteBuffer value = v == null ? null : TypeCodec.InetCodec.instance.serialize(v);
327- for (int i = 0; i < indexes.length; i++) {
328- checkType(indexes[i], DataType.Name.INET);
329- setValue(indexes[i], value);
318+ for (int i : getAllIndexesOf(name)) {
319+ setInet(i, v);
330320 }
331321 return wrapped;
332322 }
@@ -336,135 +326,240 @@
336326 if (v == null)
337327 throw new NullPointerException(String.format("Cannot set a null token for column %s", getName(i)));
338328 checkType(i, v.getType().getName());
339- return setValue(i, v.getType().codec(protocolVersion).serialize(v.getValue()));
329+ // Bypass CodecRegistry when serializing tokens
330+ return setValue(i, v.serialize(protocolVersion));
340331 }
341332
342333 T setToken(String name, Token v) {
343- int[] indexes = getAllIndexesOf(name);
344- for (int i = 0; i < indexes.length; i++)
345- setToken(indexes[i], v);
334+ for (int i : getAllIndexesOf(name)) {
335+ setToken(i, v);
336+ }
346337 return wrapped;
347338 }
348339
340+ @SuppressWarnings("unchecked")
349341 public <E> T setList(int i, List<E> v) {
350- DataType type = getType(i);
351- if (type.getName() != DataType.Name.LIST)
352- throw new InvalidTypeException(String.format("Column %s is of type %s, cannot set to a list", getName(i), type));
342+ checkType(i, LIST);
343+ if(v == null || v.isEmpty()) {
344+ // no runtime inspection possible, rely on the underlying metadata
345+ return setValue(i, codecFor(i).serialize(v, protocolVersion));
346+ } else {
347+ // inspect the first element and locate a codec that accepts both the underlying CQL type and the actual Java type
348+ DataType eltCqlType = getType(i).getTypeArguments().get(0);
349+ TypeToken<E> eltJavaType = getCodecRegistry().codecFor(eltCqlType, v.iterator().next()).getJavaType();
350+ return setValue(i, codecFor(i, listOf(eltJavaType)).serialize(v, protocolVersion));
351+ }
352+ }
353353
354- if (v == null)
355- return setValue(i, null);
354+ @Override
355+ public <E> T setList(int i, List<E> v, Class<E> elementsClass) {
356+ return setValue(i, codecFor(i, listOf(elementsClass)).serialize(v, protocolVersion));
357+ }
356358
357- // If the list is empty, it will never fail validation, but otherwise we should check the list given if of the right type
358- if (!v.isEmpty()) {
359- // Ugly? Yes
360- Class<?> providedClass = v.get(0).getClass();
361- Class<?> expectedClass = type.getTypeArguments().get(0).asJavaClass();
359+ @Override
360+ public <E> T setList(int i, List<E> v, TypeToken<E> elementsType) {
361+ return setValue(i, codecFor(i, listOf(elementsType)).serialize(v, protocolVersion));
362+ }
363+
364+ @Override
365+ public <E> T setList(String name, List<E> v) {
366+ for (int i : getAllIndexesOf(name)) {
367+ setList(i, v);
368+ }
369+ return wrapped;
370+ }
362371
363- if (!expectedClass.isAssignableFrom(providedClass))
364- throw new InvalidTypeException(String.format("Invalid value for column %s of CQL type %s, expecting list of %s but provided list of %s", getName(i), type, expectedClass, providedClass));
372+ @Override
373+ public <E> T setList(String name, List<E> v, Class<E> elementsClass) {
374+ for (int i : getAllIndexesOf(name)) {
375+ setList(i, v, elementsClass);
365376 }
366- return setValue(i, type.codec(protocolVersion).serialize(v));
377+ return wrapped;
367378 }
368379
369- public <E> T setList(String name, List<E> v) {
370- int[] indexes = getAllIndexesOf(name);
371- for (int i = 0; i < indexes.length; i++)
372- setList(indexes[i], v);
380+ @Override
381+ public <E> T setList(String name, List<E> v, TypeToken<E> elementsType) {
382+ for (int i : getAllIndexesOf(name)) {
383+ setList(i, v, elementsType);
384+ }
373385 return wrapped;
374386 }
375387
388+ @SuppressWarnings("unchecked")
389+ @Override
376390 public <K, V> T setMap(int i, Map<K, V> v) {
377- DataType type = getType(i);
378- if (type.getName() != DataType.Name.MAP)
379- throw new InvalidTypeException(String.format("Column %s is of type %s, cannot set to a map", getName(i), type));
391+ checkType(i, MAP);
392+ if(v == null || v.isEmpty()) {
393+ // no runtime inspection possible, rely on the underlying metadata
394+ return setValue(i, codecFor(i).serialize(v, protocolVersion));
395+ } else {
396+ // inspect the first element and locate a codec that accepts both the underlying CQL type and the actual Java types for keys and values
397+ DataType keysCqlType = getType(i).getTypeArguments().get(0);
398+ DataType valuesCqlType = getType(i).getTypeArguments().get(1);
399+ Map.Entry<K, V> entry = v.entrySet().iterator().next();
400+ TypeToken<K> keysType = getCodecRegistry().codecFor(keysCqlType, entry.getKey()).getJavaType();
401+ TypeToken<V> valuesType = getCodecRegistry().codecFor(valuesCqlType, entry.getValue()).getJavaType();
402+ return setValue(i, codecFor(i, mapOf(keysType, valuesType)).serialize(v, protocolVersion));
403+ }
404+ }
405+
406+ @Override
407+ public <K, V> T setMap(int i, Map<K, V> v, Class<K> keysClass, Class<V> valuesClass) {
408+ return setValue(i, codecFor(i, mapOf(keysClass, valuesClass)).serialize(v, protocolVersion));
409+ }
380410
381- if (v == null)
382- return setValue(i, null);
411+ @Override
412+ public <K, V> T setMap(int i, Map<K, V> v, TypeToken<K> keysType, TypeToken<V> valuesType) {
413+ return setValue(i, codecFor(i, mapOf(keysType, valuesType)).serialize(v, protocolVersion));
414+ }
383415
384- if (!v.isEmpty()) {
385- // Ugly? Yes
386- Map.Entry<K, V> entry = v.entrySet().iterator().next();
387- Class<?> providedKeysClass = entry.getKey().getClass();
388- Class<?> providedValuesClass = entry.getValue().getClass();
416+ @Override
417+ public <K, V> T setMap(String name, Map<K, V> v) {
418+ for (int i : getAllIndexesOf(name)) {
419+ setMap(i, v);
420+ }
421+ return wrapped;
422+ }
389423
390- Class<?> expectedKeysClass = type.getTypeArguments().get(0).getName().javaType;
391- Class<?> expectedValuesClass = type.getTypeArguments().get(1).getName().javaType;
392- if (!expectedKeysClass.isAssignableFrom(providedKeysClass) || !expectedValuesClass.isAssignableFrom(providedValuesClass))
393- throw new InvalidTypeException(String.format("Invalid value for column %s of CQL type %s, expecting map of %s->%s but provided map of %s->%s", getName(i), type, expectedKeysClass, expectedValuesClass, providedKeysClass, providedValuesClass));
424+ @Override
425+ public <K, V> T setMap(String name, Map<K, V> v, Class<K> keysClass, Class<V> valuesClass) {
426+ for (int i : getAllIndexesOf(name)) {
427+ setMap(i, v, keysClass, valuesClass);
394428 }
395- return setValue(i, type.codec(protocolVersion).serialize(v));
429+ return wrapped;
396430 }
397431
398- public <K, V> T setMap(String name, Map<K, V> v) {
399- int[] indexes = getAllIndexesOf(name);
400- for (int i = 0; i < indexes.length; i++)
401- setMap(indexes[i], v);
432+ @Override
433+ public <K, V> T setMap(String name, Map<K, V> v, TypeToken<K> keysType, TypeToken<V> valuesType) {
434+ for (int i : getAllIndexesOf(name)) {
435+ setMap(i, v, keysType, valuesType);
436+ }
402437 return wrapped;
403438 }
404439
440+ @SuppressWarnings("unchecked")
405441 public <E> T setSet(int i, Set<E> v) {
406- DataType type = getType(i);
407- if (type.getName() != DataType.Name.SET)
408- throw new InvalidTypeException(String.format("Column %s is of type %s, cannot set to a set", getName(i), type));
409-
410- if (v == null)
411- return setValue(i, null);
442+ checkType(i, SET);
443+ if(v == null || v.isEmpty()) {
444+ // no runtime inspection possible, rely on the underlying metadata
445+ return setValue(i, codecFor(i).serialize(v, protocolVersion));
446+ } else {
447+ // inspect the first element and locate a codec that accepts both the underlying CQL type and the actual Java type
448+ DataType eltCqlType = getType(i).getTypeArguments().get(0);
449+ TypeToken<E> eltJavaType = getCodecRegistry().codecFor(eltCqlType, v.iterator().next()).getJavaType();
450+ return setValue(i, codecFor(i, setOf(eltJavaType)).serialize(v, protocolVersion));
451+ }
452+ }
453+
454+ @Override
455+ public <E> T setSet(int i, Set<E> v, Class<E> elementsClass) {
456+ return setValue(i, codecFor(i, setOf(elementsClass)).serialize(v, protocolVersion));
457+ }
412458
413- if (!v.isEmpty()) {
414- // Ugly? Yes
415- Class<?> providedClass = v.iterator().next().getClass();
416- Class<?> expectedClass = type.getTypeArguments().get(0).getName().javaType;
459+ @Override
460+ public <E> T setSet(int i, Set<E> v, TypeToken<E> elementsType) {
461+ return setValue(i, codecFor(i, setOf(elementsType)).serialize(v, protocolVersion));
462+ }
417463
418- if (!expectedClass.isAssignableFrom(providedClass))
419- throw new InvalidTypeException(String.format("Invalid value for column %s of CQL type %s, expecting set of %s but provided set of %s", getName(i), type, expectedClass, providedClass));
464+ @Override
465+ public <E> T setSet(String name, Set<E> v) {
466+ for (int i : getAllIndexesOf(name)) {
467+ setSet(i, v);
420468 }
421- return setValue(i, type.codec(protocolVersion).serialize(v));
469+ return wrapped;
470+ }
471+
472+ @Override
473+ public <E> T setSet(String name, Set<E> v, Class<E> elementsClass) {
474+ for (int i : getAllIndexesOf(name)) {
475+ setSet(i, v, elementsClass);
476+ }
477+ return wrapped;
422478 }
423479
424- public <E> T setSet(String name, Set<E> v) {
425- int[] indexes = getAllIndexesOf(name);
426- for (int i = 0; i < indexes.length; i++)
427- setSet(indexes[i], v);
480+ @Override
481+ public <E> T setSet(String name, Set<E> v, TypeToken<E> elementsType) {
482+ for (int i : getAllIndexesOf(name)) {
483+ setSet(i, v, elementsType);
484+ }
428485 return wrapped;
429486 }
430487
431488 public T setUDTValue(int i, UDTValue v) {
432- DataType type = getType(i);
433- if (type.getName() != DataType.Name.UDT)
434- throw new InvalidTypeException(String.format("Column %s is of type %s, cannot set to a UDT", getName(i), type));
489+ checkType(i, UDT);
490+ return setValue(i, codecFor(i, UDTValue.class).serialize(v, protocolVersion));
491+ }
435492
436- if (v == null)
437- return setValue(i, null);
493+ public T setUDTValue(String name, UDTValue v) {
494+ for (int i : getAllIndexesOf(name)) {
495+ setUDTValue(i, v);
496+ }
497+ return wrapped;
498+ }
438499
439- // UDT always use the V3 protocol version to encode values
440- setValue(i, type.codec(ProtocolVersion.V3).serialize(v));
500+ public T setTupleValue(int i, TupleValue v) {
501+ checkType(i, TUPLE);
502+ return setValue(i, codecFor(i, TupleValue.class).serialize(v, protocolVersion));
503+ }
504+
505+ public T setTupleValue(String name, TupleValue v) {
506+ for (int i : getAllIndexesOf(name)) {
507+ setTupleValue(i, v);
508+ }
441509 return wrapped;
442510 }
443511
444- public T setUDTValue(String name, UDTValue v) {
445- int[] indexes = getAllIndexesOf(name);
446- for (int i = 0; i < indexes.length; i++)
447- setUDTValue(indexes[i], v);
512+ @Override
513+ public <V> T setObject(int i, V v) {
514+ TypeCodec<V> codec = v == null ? this.<V>codecFor(i) : codecFor(i, v);
515+ return set(i, v, codec);
516+ }
517+
518+ @Override
519+ public <V> T setObject(String name, V v) {
520+ for (int i : getAllIndexesOf(name)) {
521+ setObject(i, v);
522+ }
448523 return wrapped;
449524 }
450525
451- public T setTupleValue(int i, TupleValue v) {
452- DataType type = getType(i);
453- if (type.getName() != DataType.Name.TUPLE)
454- throw new InvalidTypeException(String.format("Column %s is of type %s, cannot set to a tuple", getName(i), type));
526+ @Override
527+ public <V> T set(int i, V v, Class<V> targetClass) {
528+ return set(i, v, codecFor(i, targetClass));
529+ }
455530
456- if (v == null)
457- return setValue(i, null);
531+ @Override
532+ public <V> T set(String name, V v, Class<V> targetClass) {
533+ for (int i : getAllIndexesOf(name)) {
534+ set(i, v, targetClass);
535+ }
536+ return wrapped;
537+ }
538+
539+ @Override
540+ public <V> T set(int i, V v, TypeToken<V> targetType) {
541+ return set(i, v, codecFor(i, targetType));
542+ }
458543
459- // Tuples always user the V3 protocol version to encode values
460- setValue(i, type.codec(ProtocolVersion.V3).serialize(v));
544+ @Override
545+ public <V> T set(String name, V v, TypeToken<V> targetType) {
546+ for (int i : getAllIndexesOf(name)) {
547+ set(i, v, targetType);
548+ }
461549 return wrapped;
462550 }
463551
464- public T setTupleValue(String name, TupleValue v) {
465- int[] indexes = getAllIndexesOf(name);
466- for (int i = 0; i < indexes.length; i++)
467- setTupleValue(indexes[i], v);
552+ @Override
553+ public <V> T set(int i, V v, TypeCodec<V> codec) {
554+ checkType(i, codec.getCqlType().getName());
555+ return setValue(i, codec.serialize(v, protocolVersion));
556+ }
557+
558+ @Override
559+ public <V> T set(String name, V v, TypeCodec<V> codec) {
560+ for (int i : getAllIndexesOf(name)) {
561+ set(i, v, codec);
562+ }
468563 return wrapped;
469564 }
470565
@@ -475,9 +570,9 @@
475570
476571 @Override
477572 public T setToNull(String name) {
478- int[] indexes = getAllIndexesOf(name);
479- for (int i = 0; i < indexes.length; i++)
480- setToNull(indexes[i]);
573+ for (int i : getAllIndexesOf(name)) {
574+ setToNull(i);
575+ }
481576 return wrapped;
482577 }
483578
@@ -490,6 +585,9 @@
490585 if (values.length != that.values.length)
491586 return false;
492587
588+ if(this.protocolVersion != that.protocolVersion)
589+ return false;
590+
493591 // Deserializing each value is slightly inefficient, but comparing
494592 // the bytes could in theory be wrong (for varint for instance, 2 values
495593 // can have different binary representation but be the same value due to
@@ -500,10 +598,9 @@
500598 if (!thisType.equals(thatType))
501599 return false;
502600
503- if ((values[i] == null) != (that.values[i] == null))
504- return false;
505-
506- if (values[i] != null && !(thisType.deserialize(values[i], protocolVersion).equals(thatType.deserialize(that.values[i], protocolVersion))))
601+ Object thisValue = this.codecFor(i).deserialize(this.values[i], this.protocolVersion);
602+ Object thatValue = that.codecFor(i).deserialize(that.values[i], that.protocolVersion);
603+ if (!Objects.equal(thisValue, thatValue))
507604 return false;
508605 }
509606 return true;
@@ -514,7 +611,7 @@
514611 // Same as equals
515612 int hash = 31;
516613 for (int i = 0; i < values.length; i++)
517- hash += values[i] == null ? 1 : getType(i).deserialize(values[i], protocolVersion).hashCode();
614+ hash += values[i] == null ? 1 : codecFor(i).deserialize(values[i], protocolVersion).hashCode();
518615 return hash;
519616 }
520617 }
modified driver-core/src/main/java/com/datastax/driver/core/AbstractGettableByIndexData.java +144 −228
@@ -19,7 +19,6 @@
1919 import java.math.BigInteger;
2020 import java.net.InetAddress;
2121 import java.nio.ByteBuffer;
22-import java.util.Collections;
2322 import java.util.Date;
2423 import java.util.List;
2524 import java.util.Map;
@@ -28,8 +27,16 @@
2827
2928 import com.google.common.reflect.TypeToken;
3029
30+import static com.google.common.collect.Sets.newHashSet;
31+import static com.google.common.collect.Sets.newLinkedHashSet;
32+
3133 import com.datastax.driver.core.exceptions.InvalidTypeException;
3234
35+import static com.datastax.driver.core.CodecUtils.listOf;
36+import static com.datastax.driver.core.CodecUtils.mapOf;
37+import static com.datastax.driver.core.CodecUtils.setOf;
38+import static com.datastax.driver.core.DataType.Name.*;
39+
3340 abstract class AbstractGettableByIndexData implements GettableByIndexData {
3441
3542 protected final ProtocolVersion protocolVersion;
@@ -68,27 +75,41 @@
6875 */
6976 protected abstract ByteBuffer getValue(int i);
7077
71- // Note: we avoid having a vararg method to avoid the array allocation that comes with it.
72- protected void checkType(int i, DataType.Name name) {
73- DataType defined = getType(i);
74- if (name != defined.getName())
75- throw new InvalidTypeException(String.format("Value %s is of type %s", getName(i), defined));
78+ protected abstract CodecRegistry getCodecRegistry();
79+
80+ protected <T> TypeCodec<T> codecFor(int i) {
81+ return getCodecRegistry().codecFor(getType(i));
82+ }
83+
84+ protected <T> TypeCodec<T> codecFor(int i, Class<T> javaClass){
85+ return getCodecRegistry().codecFor(getType(i), javaClass);
86+ }
87+
88+ protected <T> TypeCodec<T> codecFor(int i, TypeToken<T> javaType) {
89+ return getCodecRegistry().codecFor(getType(i), javaType);
7690 }
7791
78- protected DataType.Name checkType(int i, DataType.Name name1, DataType.Name name2) {
79- DataType defined = getType(i);
80- if (name1 != defined.getName() && name2 != defined.getName())
81- throw new InvalidTypeException(String.format("Value %s is of type %s", getName(i), defined));
92+ protected <T> TypeCodec<T> codecFor(int i, T value) {
93+ return getCodecRegistry().codecFor(getType(i), value);
94+ }
8295
83- return defined.getName();
96+ // Note: we avoid having a vararg method to avoid the array allocation that comes with it.
97+ protected void checkType(int i, DataType.Name actual) {
98+ DataType.Name expected = getType(i).getName();
99+ if (!actual.isCompatibleWith(expected))
100+ throw new InvalidTypeException(String.format("Value %s is of type %s, not %s", getName(i), expected, actual));
84101 }
85102
86- protected DataType.Name checkType(int i, DataType.Name name1, DataType.Name name2, DataType.Name name3) {
87- DataType defined = getType(i);
88- if (name1 != defined.getName() && name2 != defined.getName() && name3 != defined.getName())
89- throw new InvalidTypeException(String.format("Value %s is of type %s", getName(i), defined));
103+ protected void checkType(int i, DataType.Name actual1, DataType.Name actual2) {
104+ DataType.Name expected = getType(i).getName();
105+ if (!actual1.isCompatibleWith(expected) && !actual2.isCompatibleWith(expected))
106+ throw new InvalidTypeException(String.format("Value %s is of type %s, not any of [%s, %s]", getName(i), expected, actual1, actual2));
107+ }
90108
91- return defined.getName();
109+ protected void checkType(int i, DataType.Name actual1, DataType.Name actual2, DataType.Name actual3) {
110+ DataType.Name expected = getType(i).getName();
111+ if (!actual1.isCompatibleWith(expected) && !actual2.isCompatibleWith(expected) && !actual3.isCompatibleWith(expected))
112+ throw new InvalidTypeException(String.format("Value %s is of type %s, not any of [%s, %s, %s]", getName(i), expected, actual1, actual2, actual3));
92113 }
93114
94115 /**
@@ -104,13 +125,17 @@
104125 */
105126 @Override
106127 public boolean getBool(int i) {
107- checkType(i, DataType.Name.BOOLEAN);
128+ checkType(i, BOOLEAN);
108129
109130 ByteBuffer value = getValue(i);
110131 if (value == null || value.remaining() == 0)
111132 return false;
112133
113- return TypeCodec.BooleanCodec.instance.deserializeNoBoxing(value);
134+ TypeCodec<Boolean> codec = codecFor(i, Boolean.class);
135+ if(codec instanceof TypeCodec.PrimitiveBooleanCodec)
136+ return ((TypeCodec.PrimitiveBooleanCodec) codec).deserializeNoBoxing(value, protocolVersion);
137+ else
138+ return codec.deserialize(value, protocolVersion);
114139 }
115140
116141 /**
@@ -118,13 +143,13 @@
118143 */
119144 @Override
120145 public byte getByte(int i) {
121- checkType(i, DataType.Name.TINYINT);
122-
123- ByteBuffer value = getValue(i);
124- if (value == null || value.remaining() == 0)
125- return 0;
126-
127- return TypeCodec.TinyIntCodec.instance.deserializeNoBoxing(value);
146+ checkType(i, TINYINT);
147+ ByteBuffer value = getValue(i);
148+ TypeCodec<Byte> codec = codecFor(i, Byte.class);
149+ if(codec instanceof TypeCodec.PrimitiveByteCodec)
150+ return ((TypeCodec.PrimitiveByteCodec) codec).deserializeNoBoxing(value, protocolVersion);
151+ else
152+ return codec.deserialize(value, protocolVersion);
128153 }
129154
130155 /**
@@ -132,13 +157,13 @@
132157 */
133158 @Override
134159 public short getShort(int i) {
135- checkType(i, DataType.Name.SMALLINT);
136-
137- ByteBuffer value = getValue(i);
138- if (value == null || value.remaining() == 0)
139- return 0;
140-
141- return TypeCodec.SmallIntCodec.instance.deserializeNoBoxing(value);
160+ checkType(i, SMALLINT);
161+ ByteBuffer value = getValue(i);
162+ TypeCodec<Short> codec = codecFor(i, Short.class);
163+ if(codec instanceof TypeCodec.PrimitiveShortCodec)
164+ return ((TypeCodec.PrimitiveShortCodec) codec).deserializeNoBoxing(value, protocolVersion);
165+ else
166+ return codec.deserialize(value, protocolVersion);
142167 }
143168
144169 /**
@@ -146,13 +171,13 @@
146171 */
147172 @Override
148173 public int getInt(int i) {
149- checkType(i, DataType.Name.INT);
150-
151- ByteBuffer value = getValue(i);
152- if (value == null || value.remaining() == 0)
153- return 0;
154-
155- return TypeCodec.IntCodec.instance.deserializeNoBoxing(value);
174+ checkType(i, INT);
175+ ByteBuffer value = getValue(i);
176+ TypeCodec<Integer> codec = codecFor(i, Integer.class);
177+ if(codec instanceof TypeCodec.PrimitiveIntCodec)
178+ return ((TypeCodec.PrimitiveIntCodec) codec).deserializeNoBoxing(value, protocolVersion);
179+ else
180+ return codec.deserialize(value, protocolVersion);
156181 }
157182
158183 /**
@@ -160,28 +185,23 @@
160185 */
161186 @Override
162187 public long getLong(int i) {
163- checkType(i, DataType.Name.BIGINT, DataType.Name.COUNTER);
164-
165- ByteBuffer value = getValue(i);
166- if (value == null || value.remaining() == 0)
167- return 0L;
168-
169- return TypeCodec.LongCodec.instance.deserializeNoBoxing(value);
188+ checkType(i, BIGINT, COUNTER);
189+ ByteBuffer value = getValue(i);
190+ TypeCodec<Long> codec = codecFor(i, Long.class);
191+ if(codec instanceof TypeCodec.PrimitiveLongCodec)
192+ return ((TypeCodec.PrimitiveLongCodec) codec).deserializeNoBoxing(value, protocolVersion);
193+ else
194+ return codec.deserialize(value, protocolVersion);
170195 }
171196
172197 /**
173198 * {@inheritDoc}
174199 */
175200 @Override
176- public Date getTimestamp(int i)
177- {
178- checkType(i, DataType.Name.TIMESTAMP);
179-
201+ public Date getTimestamp(int i) {
202+ checkType(i, TIMESTAMP);
180203 ByteBuffer value = getValue(i);
181- if (value == null || value.remaining() == 0)
182- return null;
183-
184- return TypeCodec.TimestampCodec.instance.deserialize(value);
204+ return codecFor(i, Date.class).deserialize(value, protocolVersion);
185205 }
186206
187207 /**
@@ -189,13 +209,9 @@
189209 */
190210 @Override
191211 public LocalDate getDate(int i) {
192- checkType(i, DataType.Name.DATE);
193-
212+ checkType(i, DATE);
194213 ByteBuffer value = getValue(i);
195- if (value == null || value.remaining() == 0)
196- return null;
197-
198- return TypeCodec.DateCodec.instance.deserialize(value);
214+ return codecFor(i, LocalDate.class).deserialize(value, protocolVersion);
199215 }
200216
201217 /**
@@ -203,13 +219,13 @@
203219 */
204220 @Override
205221 public long getTime(int i) {
206- checkType(i, DataType.Name.TIME);
207-
208- ByteBuffer value = getValue(i);
209- if (value == null || value.remaining() == 0)
210- return 0L;
211-
212- return TypeCodec.TimeCodec.instance.deserializeNoBoxing(value);
222+ checkType(i, TIME);
223+ ByteBuffer value = getValue(i);
224+ TypeCodec<Long> codec = codecFor(i, Long.class);
225+ if(codec instanceof TypeCodec.PrimitiveLongCodec)
226+ return ((TypeCodec.PrimitiveLongCodec) codec).deserializeNoBoxing(value, protocolVersion);
227+ else
228+ return codec.deserialize(value, protocolVersion);
213229 }
214230
215231 /**
@@ -217,13 +233,13 @@
217233 */
218234 @Override
219235 public float getFloat(int i) {
220- checkType(i, DataType.Name.FLOAT);
221-
222- ByteBuffer value = getValue(i);
223- if (value == null || value.remaining() == 0)
224- return 0.0f;
225-
226- return TypeCodec.FloatCodec.instance.deserializeNoBoxing(value);
236+ checkType(i, FLOAT);
237+ ByteBuffer value = getValue(i);
238+ TypeCodec<Float> codec = codecFor(i, Float.class);
239+ if(codec instanceof TypeCodec.PrimitiveFloatCodec)
240+ return ((TypeCodec.PrimitiveFloatCodec) codec).deserializeNoBoxing(value, protocolVersion);
241+ else
242+ return codec.deserialize(value, protocolVersion);
227243 }
228244
229245 /**
@@ -231,13 +247,13 @@
231247 */
232248 @Override
233249 public double getDouble(int i) {
234- checkType(i, DataType.Name.DOUBLE);
235-
236- ByteBuffer value = getValue(i);
237- if (value == null || value.remaining() == 0)
238- return 0.0;
239-
240- return TypeCodec.DoubleCodec.instance.deserializeNoBoxing(value);
250+ checkType(i, DOUBLE);
251+ ByteBuffer value = getValue(i);
252+ TypeCodec<Double> codec = codecFor(i, Double.class);
253+ if(codec instanceof TypeCodec.PrimitiveDoubleCodec)
254+ return ((TypeCodec.PrimitiveDoubleCodec) codec).deserializeNoBoxing(value, protocolVersion);
255+ else
256+ return codec.deserialize(value, protocolVersion);
241257 }
242258
243259 /**
@@ -248,7 +264,6 @@
248264 ByteBuffer value = getValue(i);
249265 if (value == null)
250266 return null;
251-
252267 return value.duplicate();
253268 }
254269
@@ -257,8 +272,9 @@
257272 */
258273 @Override
259274 public ByteBuffer getBytes(int i) {
260- checkType(i, DataType.Name.BLOB);
261- return getBytesUnsafe(i);
275+ checkType(i, BLOB);
276+ ByteBuffer value = getValue(i);
277+ return codecFor(i, ByteBuffer.class).deserialize(value, protocolVersion);
262278 }
263279
264280 /**
@@ -266,17 +282,9 @@
266282 */
267283 @Override
268284 public String getString(int i) {
269- DataType.Name type = checkType(i, DataType.Name.VARCHAR,
270- DataType.Name.TEXT,
271- DataType.Name.ASCII);
272-
285+ checkType(i, VARCHAR, ASCII);
273286 ByteBuffer value = getValue(i);
274- if (value == null)
275- return null;
276-
277- return type == DataType.Name.ASCII
278- ? TypeCodec.StringCodec.asciiInstance.deserialize(value)
279- : TypeCodec.StringCodec.utf8Instance.deserialize(value);
287+ return codecFor(i, String.class).deserialize(value, protocolVersion);
280288 }
281289
282290 /**
@@ -284,13 +292,9 @@
284292 */
285293 @Override
286294 public BigInteger getVarint(int i) {
287- checkType(i, DataType.Name.VARINT);
288-
295+ checkType(i, VARINT);
289296 ByteBuffer value = getValue(i);
290- if (value == null || value.remaining() == 0)
291- return null;
292-
293- return TypeCodec.BigIntegerCodec.instance.deserialize(value);
297+ return codecFor(i, BigInteger.class).deserialize(value, protocolVersion);
294298 }
295299
296300 /**
@@ -298,13 +302,9 @@
298302 */
299303 @Override
300304 public BigDecimal getDecimal(int i) {
301- checkType(i, DataType.Name.DECIMAL);
302-
305+ checkType(i, DECIMAL);
303306 ByteBuffer value = getValue(i);
304- if (value == null || value.remaining() == 0)
305- return null;
306-
307- return TypeCodec.DecimalCodec.instance.deserialize(value);
307+ return codecFor(i, BigDecimal.class).deserialize(value, protocolVersion);
308308 }
309309
310310 /**
@@ -312,15 +312,9 @@
312312 */
313313 @Override
314314 public UUID getUUID(int i) {
315- DataType.Name type = checkType(i, DataType.Name.UUID, DataType.Name.TIMEUUID);
316-
315+ checkType(i, UUID, TIMEUUID);
317316 ByteBuffer value = getValue(i);
318- if (value == null || value.remaining() == 0)
319- return null;
320-
321- return type == DataType.Name.UUID
322- ? TypeCodec.UUIDCodec.instance.deserialize(value)
323- : TypeCodec.TimeUUIDCodec.instance.deserialize(value);
317+ return codecFor(i, UUID.class).deserialize(value, protocolVersion);
324318 }
325319
326320 /**
@@ -328,13 +322,9 @@
328322 */
329323 @Override
330324 public InetAddress getInet(int i) {
331- checkType(i, DataType.Name.INET);
332-
325+ checkType(i, INET);
333326 ByteBuffer value = getValue(i);
334- if (value == null || value.remaining() == 0)
335- return null;
336-
337- return TypeCodec.InetCodec.instance.deserialize(value);
327+ return codecFor(i, InetAddress.class).deserialize(value, protocolVersion);
338328 }
339329
340330 /**
@@ -343,19 +333,7 @@
343333 @Override
344334 @SuppressWarnings("unchecked")
345335 public <T> List<T> getList(int i, Class<T> elementsClass) {
346- DataType type = getType(i);
347- if (type.getName() != DataType.Name.LIST)
348- throw new InvalidTypeException(String.format("Column %s is not of list type", getName(i)));
349-
350- Class<?> expectedClass = type.getTypeArguments().get(0).getName().javaType;
351- if (!elementsClass.isAssignableFrom(expectedClass))
352- throw new InvalidTypeException(String.format("Column %s is a list of %s (CQL type %s), cannot be retrieved as a list of %s", getName(i), expectedClass, type, elementsClass));
353-
354- ByteBuffer value = getValue(i);
355- if (value == null)
356- return Collections.<T>emptyList();
357-
358- return Collections.unmodifiableList((List<T>)type.codec(protocolVersion).deserialize(value));
336+ return getList(i, TypeToken.of(elementsClass));
359337 }
360338
361339 /**
@@ -364,19 +342,10 @@
364342 @Override
365343 @SuppressWarnings("unchecked")
366344 public <T> List<T> getList(int i, TypeToken<T> elementsType) {
367- DataType type = getType(i);
368- if (type.getName() != DataType.Name.LIST)
369- throw new InvalidTypeException(String.format("Column %s is not of list type", getName(i)));
370-
371- DataType expectedType = type.getTypeArguments().get(0);
372- if (!expectedType.canBeDeserializedAs(elementsType))
373- throw new InvalidTypeException(String.format("Column %s has CQL type %s, cannot be retrieved as a list of %s", getName(i), type, elementsType));
374-
345+ checkType(i, LIST);
375346 ByteBuffer value = getValue(i);
376- if (value == null)
377- return Collections.<T>emptyList();
378-
379- return Collections.unmodifiableList((List<T>)type.codec(protocolVersion).deserialize(value));
347+ TypeToken<List<T>> javaType = listOf(elementsType);
348+ return codecFor(i, javaType).deserialize(value, protocolVersion);
380349 }
381350
382351 /**
@@ -385,19 +354,7 @@
385354 @Override
386355 @SuppressWarnings("unchecked")
387356 public <T> Set<T> getSet(int i, Class<T> elementsClass) {
388- DataType type = getType(i);
389- if (type.getName() != DataType.Name.SET)
390- throw new InvalidTypeException(String.format("Column %s is not of set type", getName(i)));
391-
392- Class<?> expectedClass = type.getTypeArguments().get(0).getName().javaType;
393- if (!elementsClass.isAssignableFrom(expectedClass))
394- throw new InvalidTypeException(String.format("Column %s is a set of %s (CQL type %s), cannot be retrieved as a set of %s", getName(i), expectedClass, type, elementsClass));
395-
396- ByteBuffer value = getValue(i);
397- if (value == null)
398- return Collections.<T>emptySet();
399-
400- return Collections.unmodifiableSet((Set<T>)type.codec(protocolVersion).deserialize(value));
357+ return getSet(i, TypeToken.of(elementsClass));
401358 }
402359
403360 /**
@@ -406,19 +363,10 @@
406363 @Override
407364 @SuppressWarnings("unchecked")
408365 public <T> Set<T> getSet(int i, TypeToken<T> elementsType) {
409- DataType type = getType(i);
410- if (type.getName() != DataType.Name.SET)
411- throw new InvalidTypeException(String.format("Column %s is not of set type", getName(i)));
412-
413- DataType expectedType = type.getTypeArguments().get(0);
414- if (!expectedType.canBeDeserializedAs(elementsType))
415- throw new InvalidTypeException(String.format("Column %s has CQL type %s, cannot be retrieved as a set of %s", getName(i), type, elementsType));
416-
366+ checkType(i, SET);
417367 ByteBuffer value = getValue(i);
418- if (value == null)
419- return Collections.<T>emptySet();
420-
421- return Collections.unmodifiableSet((Set<T>)type.codec(protocolVersion).deserialize(value));
368+ TypeToken<Set<T>> javaType = setOf(elementsType);
369+ return codecFor(i, javaType).deserialize(value, protocolVersion);
422370 }
423371
424372 /**
@@ -427,20 +375,7 @@
427375 @Override
428376 @SuppressWarnings("unchecked")
429377 public <K, V> Map<K, V> getMap(int i, Class<K> keysClass, Class<V> valuesClass) {
430- DataType type = getType(i);
431- if (type.getName() != DataType.Name.MAP)
432- throw new InvalidTypeException(String.format("Column %s is not of map type", getName(i)));
433-
434- Class<?> expectedKeysClass = type.getTypeArguments().get(0).getName().javaType;
435- Class<?> expectedValuesClass = type.getTypeArguments().get(1).getName().javaType;
436- if (!keysClass.isAssignableFrom(expectedKeysClass) || !valuesClass.isAssignableFrom(expectedValuesClass))
437- throw new InvalidTypeException(String.format("Column %s is a map of %s->%s (CQL type %s), cannot be retrieved as a map of %s->%s", getName(i), expectedKeysClass, expectedValuesClass, type, keysClass, valuesClass));
438-
439- ByteBuffer value = getValue(i);
440- if (value == null)
441- return Collections.<K, V>emptyMap();
442-
443- return Collections.unmodifiableMap((Map<K, V>)type.codec(protocolVersion).deserialize(value));
378+ return getMap(i, TypeToken.of(keysClass), TypeToken.of(valuesClass));
444379 }
445380
446381 /**
@@ -449,20 +384,10 @@
449384 @Override
450385 @SuppressWarnings("unchecked")
451386 public <K, V> Map<K, V> getMap(int i, TypeToken<K> keysType, TypeToken<V> valuesType) {
452- DataType type = getType(i);
453- if (type.getName() != DataType.Name.MAP)
454- throw new InvalidTypeException(String.format("Column %s is not of map type", getName(i)));
455-
456- DataType expectedKeysType = type.getTypeArguments().get(0);
457- DataType expectedValuesType = type.getTypeArguments().get(1);
458- if (!expectedKeysType.canBeDeserializedAs(keysType) || !expectedValuesType.canBeDeserializedAs(valuesType))
459- throw new InvalidTypeException(String.format("Column %s has CQL type %s, cannot be retrieved as a map of %s->%s", getName(i), type, keysType, valuesType));
460-
387+ checkType(i, MAP);
461388 ByteBuffer value = getValue(i);
462- if (value == null)
463- return Collections.<K, V>emptyMap();
464-
465- return Collections.unmodifiableMap((Map<K, V>)type.codec(protocolVersion).deserialize(value));
389+ TypeToken<Map<K, V>> javaType = mapOf(keysType, valuesType);
390+ return codecFor(i, javaType).deserialize(value, protocolVersion);
466391 }
467392
468393 /**
@@ -471,15 +396,9 @@
471396 @Override
472397 @SuppressWarnings("unchecked")
473398 public UDTValue getUDTValue(int i) {
474- DataType type = getType(i);
475- if (type.getName() != DataType.Name.UDT)
476- throw new InvalidTypeException(String.format("Column %s is not a UDT", getName(i)));
477-
399+ checkType(i, UDT);
478400 ByteBuffer value = getValue(i);
479- if (value == null || value.remaining() == 0)
480- return null;
481-
482- return (UDTValue)type.codec(protocolVersion).deserialize(value);
401+ return codecFor(i, UDTValue.class).deserialize(value, protocolVersion);
483402 }
484403
485404 /**
@@ -488,15 +407,9 @@
488407 @Override
489408 @SuppressWarnings("unchecked")
490409 public TupleValue getTupleValue(int i) {
491- DataType type = getType(i);
492- if (type.getName() != DataType.Name.TUPLE)
493- throw new InvalidTypeException(String.format("Column %s is not a tuple", getName(i)));
494-
410+ checkType(i, TUPLE);
495411 ByteBuffer value = getValue(i);
496- if (value == null || value.remaining() == 0)
497- return null;
498-
499- return (TupleValue)type.codec(protocolVersion).deserialize(value);
412+ return codecFor(i, TupleValue.class).deserialize(value, protocolVersion);
500413 }
501414
502415 /**
@@ -504,20 +417,23 @@
504417 */
505418 @Override
506419 public Object getObject(int i) {
507- ByteBuffer raw = getValue(i);
508- DataType type = getType(i);
509- if (raw == null)
510- switch (type.getName()) {
511- case LIST:
512- return Collections.emptyList();
513- case SET:
514- return Collections.emptySet();
515- case MAP:
516- return Collections.emptyMap();
517- default:
518- return null;
519- }
520- else
521- return type.deserialize(raw, protocolVersion);
420+ return get(i, codecFor(i));
421+ }
422+
423+ @Override
424+ public <T> T get(int i, Class<T> targetClass) {
425+ return get(i, codecFor(i, targetClass));
426+ }
427+
428+ @Override
429+ public <T> T get(int i, TypeToken<T> targetType) {
430+ return get(i, codecFor(i, targetType));
431+ }
432+
433+ @Override
434+ public <T> T get(int i, TypeCodec<T> codec) {
435+ checkType(i, codec.getCqlType().getName());
436+ ByteBuffer value = getValue(i);
437+ return codec.deserialize(value, protocolVersion);
522438 }
523439 }
modified driver-core/src/main/java/com/datastax/driver/core/AbstractGettableData.java +24 −0
@@ -264,4 +264,28 @@
264264 public Object getObject(String name) {
265265 return getObject(getIndexOf(name));
266266 }
267+
268+ /**
269+ * {@inheritDoc}
270+ */
271+ @Override
272+ public <T> T get(String name, Class<T> targetClass) {
273+ return get(getIndexOf(name), targetClass);
274+ }
275+
276+ /**
277+ * {@inheritDoc}
278+ */
279+ @Override
280+ public <T> T get(String name, TypeToken<T> targetType) {
281+ return get(getIndexOf(name), targetType);
282+ }
283+
284+ /**
285+ * {@inheritDoc}
286+ */
287+ @Override
288+ public <T> T get(String name, TypeCodec<T> codec) {
289+ return get(getIndexOf(name), codec);
290+ }
267291 }
modified driver-core/src/main/java/com/datastax/driver/core/AbstractSession.java +22 −5
@@ -36,7 +36,7 @@
3636 */
3737 @Override
3838 public ResultSet execute(String query) {
39- return execute(new SimpleStatement(query));
39+ return execute(newSimpleStatement(query));
4040 }
4141
4242 /**
@@ -44,7 +44,7 @@
4444 */
4545 @Override
4646 public ResultSet execute(String query, Object... values) {
47- return execute(new SimpleStatement(query, values));
47+ return execute(newSimpleStatement(query, values));
4848 }
4949
5050 /**
@@ -60,7 +60,7 @@
6060 */
6161 @Override
6262 public ResultSetFuture executeAsync(String query) {
63- return executeAsync(new SimpleStatement(query));
63+ return executeAsync(newSimpleStatement(query));
6464 }
6565
6666 /**
@@ -68,7 +68,23 @@
6868 */
6969 @Override
7070 public ResultSetFuture executeAsync(String query, Object... values) {
71- return executeAsync(new SimpleStatement(query, 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);
7288 }
7389
7490 /**
@@ -108,10 +124,11 @@
108124 */
109125 @Override
110126 public ListenableFuture<PreparedStatement> prepareAsync(final RegularStatement statement) {
127+
111128 if (statement.hasValues())
112129 throw new IllegalArgumentException("A statement to prepare should not have values");
113130
114- ListenableFuture<PreparedStatement> prepared = prepareAsync(statement.toString(), statement.getOutgoingPayload());
131+ ListenableFuture<PreparedStatement> prepared = prepareAsync(statement.getQueryString(), statement.getOutgoingPayload());
115132 return Futures.transform(prepared, new Function<PreparedStatement, PreparedStatement>() {
116133 @Override
117134 public PreparedStatement apply(PreparedStatement prepared) {
modified driver-core/src/main/java/com/datastax/driver/core/AggregateMetadata.java +15 −11
@@ -38,10 +38,11 @@
3838 private final String stateFuncSimpleName;
3939 private final String stateFuncFullName;
4040 private final DataType stateType;
41+ private final TypeCodec<Object> stateTypeCodec;
4142
4243 public AggregateMetadata(KeyspaceMetadata keyspace, String fullName, String simpleName, List<DataType> argumentTypes,
4344 String finalFuncSimpleName, String finalFuncFullName, Object initCond, DataType returnType,
44- String stateFuncSimpleName, String stateFuncFullName, DataType stateType) {
45+ String stateFuncSimpleName, String stateFuncFullName, DataType stateType, TypeCodec<Object> stateTypeCodec) {
4546 this.keyspace = keyspace;
4647 this.fullName = fullName;
4748 this.simpleName = simpleName;
@@ -53,6 +54,7 @@
5354 this.stateFuncSimpleName = stateFuncSimpleName;
5455 this.stateFuncFullName = stateFuncFullName;
5556 this.stateType = stateType;
57+ this.stateTypeCodec = stateTypeCodec;
5658 }
5759
5860 // CREATE TABLE system.schema_aggregates (
@@ -67,25 +69,25 @@
6769 // state_type text,
6870 // PRIMARY KEY (keyspace_name, aggregate_name, signature)
6971 // ) WITH CLUSTERING ORDER BY (aggregate_name ASC, signature ASC)
70- static AggregateMetadata build(KeyspaceMetadata ksm, Row row, ProtocolVersion protocolVersion) {
72+ static AggregateMetadata build(KeyspaceMetadata ksm, Row row, ProtocolVersion protocolVersion, CodecRegistry codecRegistry) {
7173 String simpleName = row.getString("aggregate_name");
7274 List<String> signature = row.getList("signature", String.class);
7375 String fullName = Metadata.fullFunctionName(simpleName, signature);
74- List<DataType> argumentTypes = parseTypes(row.getList("argument_types", String.class));
76+ List<DataType> argumentTypes = parseTypes(row.getList("argument_types", String.class), protocolVersion, codecRegistry);
7577 String finalFuncSimpleName = row.getString("final_func");
76- DataType returnType = CassandraTypeParser.parseOne(row.getString("return_type"));
78+ DataType returnType = CassandraTypeParser.parseOne(row.getString("return_type"), protocolVersion, codecRegistry);
7779 String stateFuncSimpleName = row.getString("state_func");
7880 String stateTypeName = row.getString("state_type");
79- DataType stateType = CassandraTypeParser.parseOne(stateTypeName);
81+ DataType stateType = CassandraTypeParser.parseOne(stateTypeName, protocolVersion, codecRegistry);
8082 ByteBuffer rawInitCond = row.getBytes("initcond");
81- Object initCond = rawInitCond == null ? null : stateType.deserialize(rawInitCond, protocolVersion);
83+ Object initCond = rawInitCond == null ? null : codecRegistry.codecFor(stateType).deserialize(rawInitCond, protocolVersion);
8284
8385 String finalFuncFullName = finalFuncSimpleName == null ? null : String.format("%s(%s)", finalFuncSimpleName, stateType);
8486 String stateFuncFullName = makeStateFuncFullName(stateFuncSimpleName, stateType.toString(), signature);
8587
8688 AggregateMetadata aggregate = new AggregateMetadata(ksm, fullName, simpleName, argumentTypes,
8789 finalFuncSimpleName, finalFuncFullName, initCond, returnType, stateFuncSimpleName,
88- stateFuncFullName, stateType);
90+ stateFuncFullName, stateType, codecRegistry.codecFor(stateType));
8991 ksm.add(aggregate);
9092 return aggregate;
9193 }
@@ -96,13 +98,15 @@
9698 return Metadata.fullFunctionName(stateFuncSimpleName, args);
9799 }
98100
99- private static List<DataType> parseTypes(List<String> names) {
101+ private static List<DataType> parseTypes(List<String> names, ProtocolVersion protocolVersion, CodecRegistry codecRegistry) {
100102 if (names.isEmpty())
101103 return Collections.emptyList();
102104
103105 ImmutableList.Builder<DataType> builder = ImmutableList.builder();
104- for (String name : names)
105- builder.add(CassandraTypeParser.parseOne(name));
106+ for (String name : names) {
107+ DataType type = CassandraTypeParser.parseOne(name, protocolVersion, codecRegistry);
108+ builder.add(type);
109+ }
106110 return builder.build();
107111 }
108112
@@ -170,7 +174,7 @@
170174 if (initCond != null)
171175 TableMetadata.spaceOrNewLine(sb, formatted)
172176 .append("INITCOND ")
173- .append(stateType.format(initCond));
177+ .append(stateTypeCodec.format(initCond));
174178
175179 sb.append(';');
176180
modified driver-core/src/main/java/com/datastax/driver/core/ArrayBackedResultSet.java +11 −5
@@ -29,7 +29,6 @@
2929 import org.slf4j.LoggerFactory;
3030
3131 import com.datastax.driver.core.exceptions.DriverInternalError;
32-import com.datastax.driver.core.utils.MoreFutures;
3332
3433 /**
3534 * Default implementation of a result set, backed by an ArrayDeque of ArrayList.
@@ -50,7 +49,7 @@
5049 this.metadata = metadata;
5150 this.protocolVersion = protocolVersion;
5251 this.tokenFactory = tokenFactory;
53- this.wasApplied = checkWasApplied(firstRow, metadata);
52+ this.wasApplied = checkWasApplied(firstRow, metadata, protocolVersion);
5453 }
5554
5655 static ArrayBackedResultSet fromMessage(Responses.Result msg, SessionManager session, ProtocolVersion protocolVersion, ExecutionInfo info, Statement statement) {
@@ -77,6 +76,13 @@
7776 // info can be null only for internal calls, but we don't page those. We assert
7877 // this explicitly because MultiPage implementation don't support info == null.
7978 assert r.metadata.pagingState == null || info != null;
79+
80+ // if this is an internal call, it doesn't matter which codecRegistry will be used
81+ CodecRegistry codecRegistry = session == null ?
82+ CodecRegistry.IMMUTABLE_INSTANCE :
83+ session.getCluster().getConfiguration().getCodecRegistry();
84+ columnDefs.setCodecRegistry(codecRegistry);
85+
8086 return r.metadata.pagingState == null
8187 ? new SinglePage(columnDefs, tokenFactory, protocolVersion, r.data, info)
8288 : new MultiPage(columnDefs, tokenFactory, protocolVersion, r.data, info, r.metadata.pagingState, session, statement);
@@ -419,7 +425,7 @@
419425
420426 // This method checks the value of the "[applied]" column manually, to avoid instantiating an ArrayBackedRow
421427 // object that we would throw away immediately.
422- private static boolean checkWasApplied(List<ByteBuffer> firstRow, ColumnDefinitions metadata) {
428+ private static boolean checkWasApplied(List<ByteBuffer> firstRow, ColumnDefinitions metadata, ProtocolVersion protocolVersion) {
423429 // If the column is not present or not a boolean, we assume the query
424430 // was not a conditional statement, and therefore return true.
425431 if (firstRow == null)
@@ -436,6 +442,6 @@
436442 if (value == null || value.remaining() == 0)
437443 return false;
438444
439- return TypeCodec.BooleanCodec.instance.deserializeNoBoxing(value);
445+ return TypeCodec.BooleanCodec.instance.deserializeNoBoxing(value, protocolVersion);
440446 }
441-}
No newline at the end of the file
447+}
modified driver-core/src/main/java/com/datastax/driver/core/ArrayBackedRow.java +10 −3
@@ -19,6 +19,8 @@
1919 import java.util.*;
2020 import java.util.regex.Pattern;
2121
22+import com.google.common.base.Joiner;
23+
2224 import com.datastax.driver.core.exceptions.DriverInternalError;
2325
2426 /**
@@ -71,6 +73,11 @@
7173 return data.get(i);
7274 }
7375
76+ @Override
77+ protected CodecRegistry getCodecRegistry() {
78+ return metadata.getCodecRegistry();
79+ }
80+
7481 @Override
7582 protected int getIndexOf(String name) {
7683 return metadata.getFirstIdx(name);
@@ -81,7 +88,7 @@
8188 if (tokenFactory == null)
8289 throw new DriverInternalError("Token factory not set. This should only happen at initialization time");
8390
84- metadata.checkType(i, tokenFactory.getTokenType().getName());
91+ checkType(i, tokenFactory.getTokenType().getName());
8592
8693 ByteBuffer value = data.get(i);
8794 if (value == null || value.remaining() == 0)
@@ -116,9 +123,9 @@
116123 if (bb == null)
117124 sb.append("NULL");
118125 else
119- sb.append(metadata.getType(i).codec(protocolVersion).deserialize(bb).toString());
126+ sb.append(getCodecRegistry().codecFor(metadata.getType(i)).deserialize(bb, protocolVersion).toString());
120127 }
121128 sb.append(']');
122129 return sb.toString();
123130 }
124-}
No newline at the end of the file
131+}
modified driver-core/src/main/java/com/datastax/driver/core/BatchStatement.java +10 −9
@@ -16,11 +16,7 @@
1616 package com.datastax.driver.core;
1717
1818 import java.nio.ByteBuffer;
19-import java.util.ArrayList;
20-import java.util.Arrays;
21-import java.util.Collection;
22-import java.util.Collections;
23-import java.util.List;
19+import java.util.*;
2420
2521 import com.google.common.collect.ImmutableList;
2622
@@ -85,13 +81,16 @@
8581 this.batchType = batchType;
8682 }
8783
88- IdAndValues getIdAndValues(ProtocolVersion protocolVersion) {
84+ IdAndValues getIdAndValues() {
8985 IdAndValues idAndVals = new IdAndValues(statements.size());
9086 for (Statement statement : statements) {
87+ if(statement instanceof StatementWrapper)
88+ statement = ((StatementWrapper) statement).getWrappedStatement();
9189 if (statement instanceof RegularStatement) {
9290 RegularStatement st = (RegularStatement)statement;
93- ByteBuffer[] vals = st.getValues(protocolVersion);
94- idAndVals.ids.add(st.getQueryString());
91+ ByteBuffer[] vals = st.getValues();
92+ String query = st.getQueryString();
93+ idAndVals.ids.add(query);
9594 idAndVals.values.add(vals == null ? Collections.<ByteBuffer>emptyList() : Arrays.asList(vals));
9695 } else {
9796 // We handle BatchStatement in add() so ...
@@ -133,7 +132,7 @@
133132 public BatchStatement add(Statement statement) {
134133
135134 // We handle BatchStatement here (rather than in getIdAndValues) as it make it slightly
136- // easier to avoid endless loop if the use mistakenly pass a batch that depends on this
135+ // easier to avoid endless loops if the user mistakenly passes a batch that depends on this
137136 // object (or this directly).
138137 if (statement instanceof BatchStatement) {
139138 for (Statement subStatements : ((BatchStatement)statement).statements) {
@@ -216,6 +215,8 @@
216215 @Override
217216 public ByteBuffer getRoutingKey() {
218217 for (Statement statement : statements) {
218+ if(statement instanceof StatementWrapper)
219+ statement = ((StatementWrapper) statement).getWrappedStatement();
219220 ByteBuffer rk = statement.getRoutingKey();
220221 if (rk != null)
221222 return rk;
modified driver-core/src/main/java/com/datastax/driver/core/BoundStatement.java +404 −618
@@ -52,6 +52,8 @@
5252 // we still want to avoid duplicating too much code so we wrap.
5353 final DataWrapper wrapper;
5454
55+ private final CodecRegistry codecRegistry;
56+
5557 private ByteBuffer routingKey;
5658
5759 /**
@@ -79,6 +81,7 @@
7981 else
8082 // propagate incoming payload as outgoing payload, if no outgoing payload has been explicitly set
8183 this.setOutgoingPayload(statement.getIncomingPayload());
84+ this.codecRegistry = statement.getCodecRegistry();
8285 }
8386
8487 /**
@@ -144,95 +147,22 @@
144147 if (values.length > statement.getVariables().size())
145148 throw new IllegalArgumentException(String.format("Prepared statement has only %d variables, %d values provided", statement.getVariables().size(), values.length));
146149
147- for (int i = 0; i < values.length; i++)
148- {
149- Object toSet = values[i];
150-
151- if (toSet == null) {
150+ for (int i = 0; i < values.length; i++) {
151+ Object value = values[i];
152+ if (value == null) {
152153 wrapper.values[i] = null;
153- continue;
154- }
155-
156- DataType columnType = statement.getVariables().getType(i);
157- switch (columnType.getName()) {
158- case LIST:
159- if (!(toSet instanceof List))
160- throw new InvalidTypeException(String.format("Invalid type for value %d, column is a list but %s provided", i, toSet.getClass()));
161-
162- List<?> l = (List<?>)toSet;
163- // If the list is empty, it will never fail validation, but otherwise we should check the list given if of the right type
164- if (!l.isEmpty()) {
165- // Ugly? Yes
166- Class<?> providedClass = l.get(0).getClass();
167- Class<?> expectedClass = columnType.getTypeArguments().get(0).asJavaClass();
168- if (!expectedClass.isAssignableFrom(providedClass))
169- throw new InvalidTypeException(String.format("Invalid type for value %d of CQL type %s, expecting list of %s but provided list of %s", i, columnType, expectedClass, providedClass));
170- }
171- break;
172- case SET:
173- if (!(toSet instanceof Set))
174- throw new InvalidTypeException(String.format("Invalid type for value %d, column is a set but %s provided", i, toSet.getClass()));
175-
176- Set<?> s = (Set<?>)toSet;
177- // If the list is empty, it will never fail validation, but otherwise we should check the list given if of the right type
178- if (!s.isEmpty()) {
179- // Ugly? Yes
180- Class<?> providedClass = s.iterator().next().getClass();
181- Class<?> expectedClass = columnType.getTypeArguments().get(0).getName().javaType;
182- if (!expectedClass.isAssignableFrom(providedClass))
183- throw new InvalidTypeException(String.format("Invalid type for value %d of CQL type %s, expecting set of %s but provided set of %s", i, columnType, expectedClass, providedClass));
184- }
185- break;
186- case MAP:
187- if (!(toSet instanceof Map))
188- throw new InvalidTypeException(String.format("Invalid type for value %d, column is a map but %s provided", i, toSet.getClass()));
189-
190- Map<?, ?> m = (Map<?, ?>)toSet;
191- // If the list is empty, it will never fail validation, but otherwise we should check the list given if of the right type
192- if (!m.isEmpty()) {
193- // Ugly? Yes
194- Map.Entry<?, ?> entry = m.entrySet().iterator().next();
195- Class<?> providedKeysClass = entry.getKey().getClass();
196- Class<?> providedValuesClass = entry.getValue().getClass();
197-
198- Class<?> expectedKeysClass = columnType.getTypeArguments().get(0).getName().javaType;
199- Class<?> expectedValuesClass = columnType.getTypeArguments().get(1).getName().javaType;
200- if (!expectedKeysClass.isAssignableFrom(providedKeysClass) || !expectedValuesClass.isAssignableFrom(providedValuesClass))
201- throw new InvalidTypeException(String.format("Invalid type for value %d of CQL type %s, expecting map of %s->%s but provided set of %s->%s", i, columnType, expectedKeysClass, expectedValuesClass, providedKeysClass, providedValuesClass));
202- }
203- break;
204- default:
205- if (toSet instanceof Token)
206- toSet = ((Token)toSet).getValue();
207-
208- Class<?> providedClass = toSet.getClass();
209- Class<?> expectedClass = columnType.getName().javaType;
210- if (!expectedClass.isAssignableFrom(providedClass))
211- throw new InvalidTypeException(String.format("Invalid type for value %d of CQL type %s, expecting %s but %s provided", i, columnType, expectedClass, providedClass));
212- break;
154+ } else {
155+ ProtocolVersion protocolVersion = statement.getPreparedId().protocolVersion;
156+ if (value instanceof Token)
157+ // bypass CodecRegistry for token values
158+ wrapper.values[i] = ((Token)value).serialize(protocolVersion);
159+ else
160+ wrapper.values[i] = wrapper.codecFor(i, value).serialize(value, protocolVersion);
213161 }
214- wrapper.values[i] = columnType.codec(statement.getPreparedId().protocolVersion).serialize(toSet);
215162 }
216163 return this;
217164 }
218165
219- /**
220- * Sets the routing key for this bound statement.
221- * <p>
222- * This is useful when the routing key can neither be set on the {@code PreparedStatement} this bound statement
223- * was built from, nor automatically computed from bound variables. In particular, this is the case if the
224- * partition key is composite and only some of its components are bound.
225- *
226- * @param routingKey the raw (binary) value to use as routing key.
227- * @return this {@code BoundStatement} object.
228- *
229- * @see BoundStatement#getRoutingKey
230- */
231- public BoundStatement setRoutingKey(ByteBuffer routingKey) {
232- this.routingKey = routingKey;
233- return this;
234- }
235-
236166 /**
237167 * The routing key for this bound query.
238168 * <p>
@@ -253,7 +183,6 @@
253183 *
254184 * @return the routing key for this statement or {@code null}.
255185 */
256- @Override
257186 public ByteBuffer getRoutingKey() {
258187 if (this.routingKey != null) {
259188 return this.routingKey;
@@ -275,24 +204,31 @@
275204 return null;
276205 components[i] = value;
277206 }
278- return SimpleStatement.compose(components);
207+ return CodecUtils.compose(components);
279208 }
280209 }
281210 return null;
282211 }
283212
284213 /**
285- * Returns the keyspace this query operates on.
214+ * Sets the routing key for this bound statement.
286215 * <p>
287- * This method will always return a non-{@code null} value (unless the statement
288- * has no variables, but you should avoid prepared statement in the first in that
289- * case). The keyspace returned will be the one corresponding to the first
290- * variable prepared in this statement (which in almost all case will be <i>the</i>
291- * keyspace for the operation, though it's possible in CQL to build a batch
292- * statement that acts on multiple keyspace).
216+ * This is useful when the routing key can neither be set on the {@code PreparedStatement} this bound statement
217+ * was built from, nor automatically computed from bound variables. In particular, this is the case if the
218+ * partition key is composite and only some of its components are bound.
219+ *
220+ * @param routingKey the raw (binary) value to use as routing key.
221+ * @return this {@code BoundStatement} object.
293222 *
294- * @return the keyspace for this statement (see above), or {@code null} if the
295- * statement has no variables.
223+ * @see BoundStatement#getRoutingKey
224+ */
225+ public BoundStatement setRoutingKey(ByteBuffer routingKey) {
226+ this.routingKey = routingKey;
227+ return this;
228+ }
229+
230+ /**
231+ * {@inheritDoc}
296232 */
297233 @Override
298234 public String getKeyspace() {
@@ -300,157 +236,81 @@
300236 }
301237
302238 /**
303- * Sets the {@code i}th value to the provided boolean.
304- *
305- * @param i the index of the variable to set.
306- * @param v the value to set.
307- * @return this BoundStatement.
308- *
309- * @throws IndexOutOfBoundsException if {@code i < 0 || i >= this.preparedStatement().variables().size()}.
310- * @throws InvalidTypeException if column {@code i} is not of type BOOLEAN.
239+ * {@inheritDoc}
311240 */
241+ @Override
312242 public BoundStatement setBool(int i, boolean v) {
313243 return wrapper.setBool(i, v);
314244 }
315245
316246 /**
317- * Sets the value for (all occurrences of) variable {@code name} to the
318- * provided boolean.
319- *
320- * @param name the name of the variable to set; if multiple variables
321- * {@code name} are prepared, all of them are set.
322- * @param v the value to set.
323- * @return this BoundStatement.
324- *
325- * @throws IllegalArgumentException if {@code name} is not a prepared
326- * variable, that is, if {@code !this.preparedStatement().variables().names().contains(name)}.
327- * @throws InvalidTypeException if (any one occurrence of) {@code name} is not of type BOOLEAN.
247+ * {@inheritDoc}
328248 */
249+ @Override
329250 public BoundStatement setBool(String name, boolean v) {
330251 return wrapper.setBool(name, v);
331252 }
332253
333254 /**
334- * Set the {@code i}th value to the provided byte.
335- *
336- * @param i the index of the variable to set.
337- * @param v the value to set.
338- * @return this BoundStatement.
339- *
340- * @throws IndexOutOfBoundsException if {@code i < 0 || i >= this.preparedStatement().variables().size()}.
341- * @throws InvalidTypeException if column {@code i} is not of type TINYINT.
255+ * {@inheritDoc}
342256 */
257+ @Override
343258 public BoundStatement setByte(int i, byte v) {
344259 return wrapper.setByte(i, v);
345260 }
346261
347262 /**
348- * Sets the value for (all occurrences of) variable {@code name} to the
349- * provided byte.
350- *
351- * @param name the name of the variable to set; if multiple variables
352- * {@code name} are prepared, all of them are set.
353- * @param v the value to set.
354- * @return this BoundStatement.
355- *
356- * @throws IllegalArgumentException if {@code name} is not a prepared
357- * variable, that is, if {@code !this.preparedStatement().variables().names().contains(name)}.
358- * @throws InvalidTypeException if (any one occurrence of) {@code name} is not of type TINYINT.
263+ * {@inheritDoc}
359264 */
265+ @Override
360266 public BoundStatement setByte(String name, byte v) {
361267 return wrapper.setByte(name, v);
362268 }
363269
364270 /**
365- * Set the {@code i}th value to the provided short.
366- *
367- * @param i the index of the variable to set.
368- * @param v the value to set.
369- * @return this BoundStatement.
370- *
371- * @throws IndexOutOfBoundsException if {@code i < 0 || i >= this.preparedStatement().variables().size()}.
372- * @throws InvalidTypeException if column {@code i} is not of type SMALLINT.
271+ * {@inheritDoc}
373272 */
273+ @Override
374274 public BoundStatement setShort(int i, short v) {
375275 return wrapper.setShort(i, v);
376276 }
377277
378278 /**
379- * Sets the value for (all occurrences of) variable {@code name} to the
380- * provided short.
381- *
382- * @param name the name of the variable to set; if multiple variables
383- * {@code name} are prepared, all of them are set.
384- * @param v the value to set.
385- * @return this BoundStatement.
386- *
387- * @throws IllegalArgumentException if {@code name} is not a prepared
388- * variable, that is, if {@code !this.preparedStatement().variables().names().contains(name)}.
389- * @throws InvalidTypeException if (any one occurrence of) {@code name} is not of type SMALLINT.
279+ * {@inheritDoc}
390280 */
281+ @Override
391282 public BoundStatement setShort(String name, short v) {
392283 return wrapper.setShort(name, v);
393284 }
394285
395286 /**
396- * Set the {@code i}th value to the provided integer.
397- *
398- * @param i the index of the variable to set.
399- * @param v the value to set.
400- * @return this BoundStatement.
401- *
402- * @throws IndexOutOfBoundsException if {@code i < 0 || i >= this.preparedStatement().variables().size()}.
403- * @throws InvalidTypeException if column {@code i} is not of type INT.
287+ * {@inheritDoc}
404288 */
289+ @Override
405290 public BoundStatement setInt(int i, int v) {
406291 return wrapper.setInt(i, v);
407292 }
408293
409294 /**
410- * Sets the value for (all occurrences of) variable {@code name} to the
411- * provided integer.
412- *
413- * @param name the name of the variable to set; if multiple variables
414- * {@code name} are prepared, all of them are set.
415- * @param v the value to set.
416- * @return this BoundStatement.
417- *
418- * @throws IllegalArgumentException if {@code name} is not a prepared
419- * variable, that is, if {@code !this.preparedStatement().variables().names().contains(name)}.
420- * @throws InvalidTypeException if (any one occurrence of) {@code name} is not of type INT.
295+ * {@inheritDoc}
421296 */
297+ @Override
422298 public BoundStatement setInt(String name, int v) {
423299 return wrapper.setInt(name, v);
424300 }
425301
426302 /**
427- * Sets the {@code i}th value to the provided long.
428- *
429- * @param i the index of the variable to set.
430- * @param v the value to set.
431- * @return this BoundStatement.
432- *
433- * @throws IndexOutOfBoundsException if {@code i < 0 || i >= this.preparedStatement().variables().size()}.
434- * @throws InvalidTypeException if column {@code i} is not of type BIGINT or COUNTER.
303+ * {@inheritDoc}
435304 */
305+ @Override
436306 public BoundStatement setLong(int i, long v) {
437307 return wrapper.setLong(i, v);
438308 }
439309
440310 /**
441- * Sets the value for (all occurrences of) variable {@code name} to the
442- * provided long.
443- *
444- * @param name the name of the variable to set; if multiple variables
445- * {@code name} are prepared, all of them are set.
446- * @param v the value to set.
447- * @return this BoundStatement.
448- *
449- * @throws IllegalArgumentException if {@code name} is not a prepared
450- * variable, that is, if {@code !this.preparedStatement().variables().names().contains(name)}.
451- * @throws InvalidTypeException if (any occurrence of) {@code name} is
452- * not of type BIGINT or COUNTER.
311+ * {@inheritDoc}
453312 */
313+ @Override
454314 public BoundStatement setLong(String name, long v) {
455315 return wrapper.setLong(name, v);
456316 }
@@ -492,401 +352,193 @@
492352 }
493353
494354 /**
495- * Set the {@code i}th value to the provided date.
496- *
497- * @param i the index of the variable to set.
498- * @param v the value to set.
499- * @return this BoundStatement.
500- *
501- * @throws IndexOutOfBoundsException if {@code i < 0 || i >= this.preparedStatement().variables().size()}.
502- * @throws InvalidTypeException if column {@code i} is not of type TIMESTAMP.
355+ * {@inheritDoc}
503356 */
357+ @Override
504358 public BoundStatement setTimestamp(int i, Date v) {
505359 return wrapper.setTimestamp(i, v);
506360 }
507361
508362 /**
509- * Sets the value for (all occurrences of) variable {@code name} to the
510- * provided date.
511- *
512- * @param name the name of the variable to set; if multiple variables
513- * {@code name} are prepared, all of them are set.
514- * @param v the value to set.
515- * @return this BoundStatement.
516- *
517- * @throws IllegalArgumentException if {@code name} is not a prepared
518- * variable, that is, if {@code !this.preparedStatement().variables().names().contains(name)}.
519- * @throws InvalidTypeException if (any occurrence of) {@code name} is
520- * not of type TIMESTAMP.
363+ * {@inheritDoc}
521364 */
365+ @Override
522366 public BoundStatement setTimestamp(String name, Date v) {
523367 return wrapper.setTimestamp(name, v);
524368 }
525369
526370 /**
527- * Set the {@code i}th value to the provided date.
528- *
529- * @param i the index of the value to set.
530- * @param v the value to set.
531- * @return this object.
532- *
533- * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
534- * @throws InvalidTypeException if value {@code i} is not of type DATE.
371+ * {@inheritDoc}
535372 */
373+ @Override
536374 public BoundStatement setDate(int i, LocalDate v) {
537375 return wrapper.setDate(i, v);
538376 }
539377
540378 /**
541- * Sets the value for (all occurrences of) variable {@code name} to the
542- * provided date.
543- *
544- * @param name the name of the value to set; if {@code name} is present multiple
545- * times, all its values are set.
546- * @param v the value to set.
547- * @return this object.
548- *
549- * @throws IllegalArgumentException if {@code name} is not a valid name for this object.
550- * @throws InvalidTypeException if (any occurrence of) {@code name} is
551- * not of type DATE.
379+ * {@inheritDoc}
552380 */
381+ @Override
553382 public BoundStatement setDate(String name, LocalDate v) {
554383 return wrapper.setDate(name, v);
555384 }
556385
557386 /**
558- * Set the {@code i}th value to the provided time as a long in nanoseconds since midnight.
559- *
560- * @param i the index of the value to set.
561- * @param v the value to set.
562- * @return this object.
563- *
564- * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
565- * @throws InvalidTypeException if value {@code i} is not of type TIME.
387+ * {@inheritDoc}
566388 */
389+ @Override
567390 public BoundStatement setTime(int i, long v) {
568391 return wrapper.setTime(i, v);
569392 }
570393
571394 /**
572- * Sets the value for (all occurrences of) variable {@code name} to the
573- * provided time as a long in nanoseconds since midnight.
574- *
575- * @param name the name of the value to set; if {@code name} is present multiple
576- * times, all its values are set.
577- * @param v the value to set.
578- * @return this object.
579- *
580- * @throws IllegalArgumentException if {@code name} is not a valid name for this object.
581- * @throws InvalidTypeException if (any occurrence of) {@code name} is
582- * not of type TIME.
395+ * {@inheritDoc}
583396 */
397+ @Override
584398 public BoundStatement setTime(String name, long v) {
585399 return wrapper.setTime(name, v);
586400 }
587401
588402 /**
589- * Sets the {@code i}th value to the provided float.
590- *
591- * @param i the index of the variable to set.
592- * @param v the value to set.
593- * @return this BoundStatement.
594- *
595- * @throws IndexOutOfBoundsException if {@code i < 0 || i >= this.preparedStatement().variables().size()}.
596- * @throws InvalidTypeException if column {@code i} is not of type FLOAT.
403+ * {@inheritDoc}
597404 */
405+ @Override
598406 public BoundStatement setFloat(int i, float v) {
599407 return wrapper.setFloat(i, v);
600408 }
601409
602410 /**
603- * Sets the value for (all occurrences of) variable {@code name} to the
604- * provided float.
605- *
606- * @param name the name of the variable to set; if multiple variables
607- * {@code name} are prepared, all of them are set.
608- * @param v the value to set.
609- * @return this BoundStatement.
610- *
611- * @throws IllegalArgumentException if {@code name} is not a prepared
612- * variable, that is, if {@code !this.preparedStatement().variables().names().contains(name)}.
613- * @throws InvalidTypeException if (any occurrence of) {@code name} is
614- * not of type FLOAT.
411+ * {@inheritDoc}
615412 */
413+ @Override
616414 public BoundStatement setFloat(String name, float v) {
617415 return wrapper.setFloat(name, v);
618416 }
619417
620418 /**
621- * Sets the {@code i}th value to the provided double.
622- *
623- * @param i the index of the variable to set.
624- * @param v the value to set.
625- * @return this BoundStatement.
626- *
627- * @throws IndexOutOfBoundsException if {@code i < 0 || i >= this.preparedStatement().variables().size()}.
628- * @throws InvalidTypeException if column {@code i} is not of type DOUBLE.
419+ * {@inheritDoc}
629420 */
421+ @Override
630422 public BoundStatement setDouble(int i, double v) {
631423 return wrapper.setDouble(i, v);
632424 }
633425
634426 /**
635- * Sets the value for (all occurrences of) variable {@code name} to the
636- * provided double.
637- *
638- * @param name the name of the variable to set; if multiple variables
639- * {@code name} are prepared, all of them are set.
640- * @param v the value to set.
641- * @return this BoundStatement.
642- *
643- * @throws IllegalArgumentException if {@code name} is not a prepared
644- * variable, that is, if {@code !this.preparedStatement().variables().names().contains(name)}.
645- * @throws InvalidTypeException if (any occurrence of) {@code name} is
646- * not of type DOUBLE.
427+ * {@inheritDoc}
647428 */
429+ @Override
648430 public BoundStatement setDouble(String name, double v) {
649431 return wrapper.setDouble(name, v);
650432 }
651433
652434 /**
653- * Sets the {@code i}th value to the provided string.
654- *
655- * @param i the index of the variable to set.
656- * @param v the value to set.
657- * @return this BoundStatement.
658- *
659- * @throws IndexOutOfBoundsException if {@code i < 0 || i >= this.preparedStatement().variables().size()}.
660- * @throws InvalidTypeException if column {@code i} is of neither of the
661- * following types: VARCHAR, TEXT or ASCII.
435+ * {@inheritDoc}
662436 */
437+ @Override
663438 public BoundStatement setString(int i, String v) {
664439 return wrapper.setString(i, v);
665440 }
666441
667442 /**
668- * Sets the value for (all occurrences of) variable {@code name} to the
669- * provided string.
670- *
671- * @param name the name of the variable to set; if multiple variables
672- * {@code name} are prepared, all of them are set.
673- * @param v the value to set.
674- * @return this BoundStatement.
675- *
676- * @throws IllegalArgumentException if {@code name} is not a prepared
677- * variable, that is, if {@code !this.preparedStatement().variables().names().contains(name)}.
678- * @throws InvalidTypeException if (any occurrence of) {@code name} is
679- * of neither of the following types: VARCHAR, TEXT or ASCII.
443+ * {@inheritDoc}
680444 */
445+ @Override
681446 public BoundStatement setString(String name, String v) {
682447 return wrapper.setString(name, v);
683448 }
684449
685450 /**
686- * Sets the {@code i}th value to the provided byte buffer.
687- *
688- * This method validate that the type of the column set is BLOB. If you
689- * want to insert manually serialized data into columns of another type,
690- * use {@link #setBytesUnsafe} instead.
691- *
692- * @param i the index of the variable to set.
693- * @param v the value to set.
694- * @return this BoundStatement.
695- *
696- * @throws IndexOutOfBoundsException if {@code i < 0 || i >= this.preparedStatement().variables().size()}.
697- * @throws InvalidTypeException if column {@code i} is not of type BLOB.
451+ * {@inheritDoc}
698452 */
453+ @Override
699454 public BoundStatement setBytes(int i, ByteBuffer v) {
700455 return wrapper.setBytes(i, v);
701456 }
702457
703458 /**
704- * Sets the value for (all occurrences of) variable {@code name} to the
705- * provided byte buffer.
706- *
707- * This method validate that the type of the column set is BLOB. If you
708- * want to insert manually serialized data into columns of another type,
709- * use {@link #setBytesUnsafe} instead.
710- *
711- * @param name the name of the variable to set; if multiple variables
712- * {@code name} are prepared, all of them are set.
713- * @param v the value to set.
714- * @return this BoundStatement.
715- *
716- * @throws IllegalArgumentException if {@code name} is not a prepared
717- * variable, that is if {@code !this.preparedStatement().variables().names().contains(name)}.
718- * @throws InvalidTypeException if (any occurrence of) {@code name} is not of type BLOB.
459+ * {@inheritDoc}
719460 */
461+ @Override
720462 public BoundStatement setBytes(String name, ByteBuffer v) {
721463 return wrapper.setBytes(name, v);
722464 }
723465
724466 /**
725- * Sets the {@code i}th value to the provided byte buffer.
726- *
727- * Contrary to {@link #setBytes}, this method does not check the
728- * type of the column set. If you insert data that is not compatible with
729- * the type of the column, you will get an {@code InvalidQueryException} at
730- * execute time.
731- *
732- * @param i the index of the variable to set.
733- * @param v the value to set.
734- * @return this BoundStatement.
735- *
736- * @throws IndexOutOfBoundsException if {@code i < 0 || i >= this.preparedStatement().variables().size()}.
467+ * {@inheritDoc}
737468 */
469+ @Override
738470 public BoundStatement setBytesUnsafe(int i, ByteBuffer v) {
739471 return wrapper.setBytesUnsafe(i, v);
740472 }
741473
742474 /**
743- * Sets the value for (all occurrences of) variable {@code name} to the
744- * provided byte buffer.
745- *
746- * Contrary to {@link #setBytes}, this method does not check the
747- * type of the column set. If you insert data that is not compatible with
748- * the type of the column, you will get an {@code InvalidQueryException} at
749- * execute time.
750- *
751- * @param name the name of the variable to set; if multiple variables
752- * {@code name} are prepared, all of them are set.
753- * @param v the value to set.
754- * @return this BoundStatement.
755- *
756- * @throws IllegalArgumentException if {@code name} is not a prepared
757- * variable, that is if {@code !this.preparedStatement().variables().names().contains(name)}.
475+ * {@inheritDoc}
758476 */
477+ @Override
759478 public BoundStatement setBytesUnsafe(String name, ByteBuffer v) {
760479 return wrapper.setBytesUnsafe(name, v);
761480 }
762481
763482 /**
764- * Sets the {@code i}th value to the provided big integer.
765- *
766- * @param i the index of the variable to set.
767- * @param v the value to set.
768- * @return this BoundStatement.
769- *
770- * @throws IndexOutOfBoundsException if {@code i < 0 || i >= this.preparedStatement().variables().size()}.
771- * @throws InvalidTypeException if column {@code i} is not of type VARINT.
483+ * {@inheritDoc}
772484 */
485+ @Override
773486 public BoundStatement setVarint(int i, BigInteger v) {
774487 return wrapper.setVarint(i, v);
775488 }
776489
777490 /**
778- * Sets the value for (all occurrences of) variable {@code name} to the
779- * provided big integer.
780- *
781- * @param name the name of the variable to set; if multiple variables
782- * {@code name} are prepared, all of them are set.
783- * @param v the value to set.
784- * @return this BoundStatement.
785- *
786- * @throws IllegalArgumentException if {@code name} is not a prepared
787- * variable, that is, if {@code !this.preparedStatement().variables().names().contains(name)}.
788- * @throws InvalidTypeException if (any occurrence of) {@code name} is
789- * not of type VARINT.
491+ * {@inheritDoc}
790492 */
493+ @Override
791494 public BoundStatement setVarint(String name, BigInteger v) {
792495 return wrapper.setVarint(name, v);
793496 }
794497
795498 /**
796- * Sets the {@code i}th value to the provided big decimal.
797- *
798- * @param i the index of the variable to set.
799- * @param v the value to set.
800- * @return this BoundStatement.
801- *
802- * @throws IndexOutOfBoundsException if {@code i < 0 || i >= this.preparedStatement().variables().size()}.
803- * @throws InvalidTypeException if column {@code i} is not of type DECIMAL.
499+ * {@inheritDoc}
804500 */
501+ @Override
805502 public BoundStatement setDecimal(int i, BigDecimal v) {
806503 return wrapper.setDecimal(i, v);
807504 }
808505
809506 /**
810- * Sets the value for (all occurrences of) variable {@code name} to the
811- * provided big decimal.
812- *
813- * @param name the name of the variable to set; if multiple variables
814- * {@code name} are prepared, all of them are set.
815- * @param v the value to set.
816- * @return this BoundStatement.
817- *
818- * @throws IllegalArgumentException if {@code name} is not a prepared
819- * variable, that is, if {@code !this.preparedStatement().variables().names().contains(name)}.
820- * @throws InvalidTypeException if (any occurrence of) {@code name} is
821- * not of type DECIMAL.
507+ * {@inheritDoc}
822508 */
509+ @Override
823510 public BoundStatement setDecimal(String name, BigDecimal v) {
824511 return wrapper.setDecimal(name, v);
825512 }
826513
827514 /**
828- * Sets the {@code i}th value to the provided UUID.
829- *
830- * @param i the index of the variable to set.
831- * @param v the value to set.
832- * @return this BoundStatement.
833- *
834- * @throws IndexOutOfBoundsException if {@code i < 0 || i >= this.preparedStatement().variables().size()}.
835- * @throws InvalidTypeException if column {@code i} is not of type UUID or
836- * TIMEUUID, or if column {@code i} is of type TIMEUUID but {@code v} is
837- * not a type 1 UUID.
515+ * {@inheritDoc}
838516 */
517+ @Override
839518 public BoundStatement setUUID(int i, UUID v) {
840519 return wrapper.setUUID(i, v);
841520 }
842521
843522 /**
844- * Sets the value for (all occurrences of) variable {@code name} to the
845- * provided UUID.
846- *
847- * @param name the name of the variable to set; if multiple variables
848- * {@code name} are prepared, all of them are set.
849- * @param v the value to set.
850- * @return this BoundStatement.
851- *
852- * @throws IllegalArgumentException if {@code name} is not a prepared
853- * variable, that is, if {@code !this.preparedStatement().variables().names().contains(name)}.
854- * @throws InvalidTypeException if (any occurrence of) {@code name} is
855- * not of type UUID or TIMEUUID, or if column {@code name} is of type
856- * TIMEUUID but {@code v} is not a type 1 UUID.
523+ * {@inheritDoc}
857524 */
525+ @Override
858526 public BoundStatement setUUID(String name, UUID v) {
859527 return wrapper.setUUID(name, v);
860528 }
861529
862530 /**
863- * Sets the {@code i}th value to the provided inet address.
864- *
865- * @param i the index of the variable to set.
866- * @param v the value to set.
867- * @return this BoundStatement.
868- *
869- * @throws IndexOutOfBoundsException if {@code i < 0 || i >= this.preparedStatement().variables().size()}.
870- * @throws InvalidTypeException if column {@code i} is not of type INET.
531+ * {@inheritDoc}
871532 */
533+ @Override
872534 public BoundStatement setInet(int i, InetAddress v) {
873535 return wrapper.setInet(i, v);
874536 }
875537
876538 /**
877- * Sets the value for (all occurrences of) variable {@code name} to the
878- * provided inet address.
879- *
880- * @param name the name of the variable to set; if multiple variables
881- * {@code name} are prepared, all of them are set.
882- * @param v the value to set.
883- * @return this BoundStatement.
884- *
885- * @throws IllegalArgumentException if {@code name} is not a prepared
886- * variable, that is, if {@code !this.preparedStatement().variables().names().contains(name)}.
887- * @throws InvalidTypeException if (any occurrence of) {@code name} is
888- * not of type INET.
539+ * {@inheritDoc}
889540 */
541+ @Override
890542 public BoundStatement setInet(String name, InetAddress v) {
891543 return wrapper.setInet(name, v);
892544 }
@@ -973,231 +625,257 @@
973625 }
974626
975627 /**
976- * Sets the {@code i}th value to the provided list.
977- * <p>
978- * Please note that {@code null} values are not supported inside collection by CQL.
979- *
980- * @param <T> the type of the elements of the list to set.
981- * @param i the index of the variable to set.
982- * @param v the value to set.
983- * @return this BoundStatement.
984- *
985- * @throws IndexOutOfBoundsException if {@code i < 0 || i >= this.preparedStatement().variables().size()}.
986- * @throws InvalidTypeException if column {@code i} is not a list type or
987- * if the elements of {@code v} are not of the type of the elements of
988- * column {@code i}.
989- * @throws NullPointerException if {@code v} contains null values. Nulls are not supported in collections
990- * by CQL.
628+ * {@inheritDoc}
991629 */
630+ @Override
992631 public <T> BoundStatement setList(int i, List<T> v) {
993632 return wrapper.setList(i, v);
994633 }
995634
996635 /**
997- * Sets the value for (all occurrences of) variable {@code name} to the
998- * provided list.
999- * <p>
1000- * Please note that {@code null} values are not supported inside collection by CQL.
1001- *
1002- * @param <T> the type of the elements of the list to set.
1003- * @param name the name of the variable to set; if multiple variables
1004- * {@code name} are prepared, all of them are set.
1005- * @param v the value to set.
1006- * @return this BoundStatement.
1007- *
1008- * @throws IllegalArgumentException if {@code name} is not a prepared
1009- * variable, that is, if {@code !this.preparedStatement().variables().names().contains(name)}.
1010- * @throws InvalidTypeException if (any occurrence of) {@code name} is
1011- * not a list type or if the elements of {@code v} are not of the type of
1012- * the elements of column {@code name}.
1013- * @throws NullPointerException if {@code v} contains null values. Nulls are not supported in collections
1014- * by CQL.
636+ * {@inheritDoc}
637+ */
638+ @Override
639+ public <E> BoundStatement setList(int i, List<E> v, Class<E> elementsClass) {
640+ return wrapper.setList(i, v, elementsClass);
641+ }
642+
643+ /**
644+ * {@inheritDoc}
1015645 */
646+ @Override
647+ public <E> BoundStatement setList(int i, List<E> v, TypeToken<E> elementsType) {
648+ return wrapper.setList(i, v, elementsType);
649+ }
650+
651+ /**
652+ * {@inheritDoc}
653+ */
654+ @Override
1016655 public <T> BoundStatement setList(String name, List<T> v) {
1017656 return wrapper.setList(name, v);
1018657 }
1019658
1020659 /**
1021- * Sets the {@code i}th value to the provided map.
1022- * <p>
1023- * Please note that {@code null} values are not supported inside collection by CQL.
1024- *
1025- * @param <K> the type of the keys for the map to set.
1026- * @param <V> the type of the values for the map to set.
1027- * @param i the index of the variable to set.
1028- * @param v the value to set.
1029- * @return this BoundStatement.
1030- *
1031- * @throws IndexOutOfBoundsException if {@code i < 0 || i >= this.preparedStatement().variables().size()}.
1032- * @throws InvalidTypeException if column {@code i} is not a map type or
1033- * if the elements (keys or values) of {@code v} are not of the type of the
1034- * elements of column {@code i}.
1035- * @throws NullPointerException if {@code v} contains null values. Nulls are not supported in collections
1036- * by CQL.
660+ * {@inheritDoc}
661+ */
662+ @Override
663+ public <E> BoundStatement setList(String name, List<E> v, Class<E> elementsClass) {
664+ return wrapper.setList(name, v, elementsClass);
665+ }
666+
667+ /**
668+ * {@inheritDoc}
669+ */
670+ @Override
671+ public <E> BoundStatement setList(String name, List<E> v, TypeToken<E> elementsType) {
672+ return wrapper.setList(name, v, elementsType);
673+ }
674+
675+ /**
676+ * {@inheritDoc}
677+ */
678+ @Override
679+ public <K, V> BoundStatement setMap(int i, Map<K, V> v) {
680+ return wrapper.setMap(i, v);
681+ }
682+
683+ /**
684+ * {@inheritDoc}
685+ */
686+ @Override
687+ public <K, V> BoundStatement setMap(int i, Map<K, V> v, Class<K> keysClass, Class<V> valuesClass) {
688+ return wrapper.setMap(i,v, keysClass, valuesClass);
689+ }
690+
691+ /**
692+ * {@inheritDoc}
693+ */
694+ @Override
695+ public <K, V> BoundStatement setMap(int i, Map<K, V> v, TypeToken<K> keysType, TypeToken<V> valuesType) {
696+ return wrapper.setMap(i, v, keysType, valuesType);
697+ }
698+
699+ /**
700+ * {@inheritDoc}
701+ */
702+ @Override
703+ public <K, V> BoundStatement setMap(String name, Map<K, V> v) {
704+ return wrapper.setMap(name, v);
705+ }
706+
707+ /**
708+ * {@inheritDoc}
709+ */
710+ @Override
711+ public <K, V> BoundStatement setMap(String name, Map<K, V> v, Class<K> keysClass, Class<V> valuesClass) {
712+ return wrapper.setMap(name, v, keysClass, valuesClass);
713+ }
714+
715+ /**
716+ * {@inheritDoc}
717+ */
718+ @Override
719+ public <K, V> BoundStatement setMap(String name, Map<K, V> v, TypeToken<K> keysType, TypeToken<V> valuesType) {
720+ return wrapper.setMap(name, v, keysType, valuesType);
721+ }
722+
723+ /**
724+ * {@inheritDoc}
1037725 */
1038- public <K, V> BoundStatement setMap(int i, Map<K, V> v) {
1039- return wrapper.setMap(i, v);
726+ @Override
727+ public <T> BoundStatement setSet(int i, Set<T> v) {
728+ return wrapper.setSet(i, v);
1040729 }
1041730
1042731 /**
1043- * Sets the value for (all occurrences of) variable {@code name} to the
1044- * provided map.
1045- * <p>
1046- * Please note that {@code null} values are not supported inside collection by CQL.
1047- *
1048- * @param <K> the type of the keys for the map to set.
1049- * @param <V> the type of the values for the map to set.
1050- * @param name the name of the variable to set; if multiple variables
1051- * {@code name} are prepared, all of them are set.
1052- * @param v the value to set.
1053- * @return this BoundStatement.
1054- *
1055- * @throws IllegalArgumentException if {@code name} is not a prepared
1056- * variable, that is, if {@code !this.preparedStatement().variables().names().contains(name)}.
1057- * @throws InvalidTypeException if (any occurrence of) {@code name} is
1058- * not a map type or if the elements (keys or values) of {@code v} are not of
1059- * the type of the elements of column {@code name}.
1060- * @throws NullPointerException if {@code v} contains null values. Nulls are not supported in collections
1061- * by CQL.
732+ * {@inheritDoc}
1062733 */
1063- public <K, V> BoundStatement setMap(String name, Map<K, V> v) {
1064- return wrapper.setMap(name, v);
734+ @Override
735+ public <E> BoundStatement setSet(int i, Set<E> v, Class<E> elementsClass) {
736+ return wrapper.setSet(i, v, elementsClass);
1065737 }
1066738
1067739 /**
1068- * Sets the {@code i}th value to the provided set.
1069- * <p>
1070- * Please note that {@code null} values are not supported inside collection by CQL.
1071- *
1072- * @param <T> the type of the elements of the set to set.
1073- * @param i the index of the variable to set.
1074- * @param v the value to set.
1075- * @return this BoundStatement.
1076- *
1077- * @throws IndexOutOfBoundsException if {@code i < 0 || i >= this.preparedStatement().variables().size()}.
1078- * @throws InvalidTypeException if column {@code i} is not a set type or
1079- * if the elements of {@code v} are not of the type of the elements of
1080- * column {@code i}.
1081- * @throws NullPointerException if {@code v} contains null values. Nulls are not supported in collections
1082- * by CQL.
740+ * {@inheritDoc}
1083741 */
1084- public <T> BoundStatement setSet(int i, Set<T> v) {
1085- return wrapper.setSet(i, v);
742+ @Override
743+ public <E> BoundStatement setSet(int i, Set<E> v, TypeToken<E> elementsType) {
744+ return wrapper.setSet(i, v, elementsType);
1086745 }
1087746
1088747 /**
1089- * Sets the value for (all occurrences of) variable {@code name} to the
1090- * provided set.
1091- * <p>
1092- * Please note that {@code null} values are not supported inside collection by CQL.
1093- *
1094- * @param <T> the type of the elements of the set to set.
1095- * @param name the name of the variable to set; if multiple variables
1096- * {@code name} are prepared, all of them are set.
1097- * @param v the value to set.
1098- * @return this BoundStatement.
1099- *
1100- * @throws IllegalArgumentException if {@code name} is not a prepared
1101- * variable, that is, if {@code !this.preparedStatement().variables().names().contains(name)}.
1102- * @throws InvalidTypeException if (any occurrence of) {@code name} is
1103- * not a map type or if the elements of {@code v} are not of the type of
1104- * the elements of column {@code name}.
1105- * @throws NullPointerException if {@code v} contains null values. Nulls are not supported in collections
1106- * by CQL.
748+ * {@inheritDoc}
1107749 */
750+ @Override
1108751 public <T> BoundStatement setSet(String name, Set<T> v) {
1109752 return wrapper.setSet(name, v);
1110753 }
1111754
1112755 /**
1113- * Sets the {@code i}th value to the provided UDT value.
1114- *
1115- * @param i the index of the value to set.
1116- * @param v the value to set.
1117- * @return this BoundStatement .
1118- *
1119- * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this BoundStatement.
1120- * @throws InvalidTypeException if value {@code i} is not a UDT value or if its definition
1121- * does not correspond to the one of {@code v}.
756+ * {@inheritDoc}
757+ */
758+ @Override
759+ public <E> BoundStatement setSet(String name, Set<E> v, Class<E> elementsClass) {
760+ return wrapper.setSet(name, v, elementsClass);
761+ }
762+
763+ /**
764+ * {@inheritDoc}
1122765 */
766+ @Override
767+ public <E> BoundStatement setSet(String name, Set<E> v, TypeToken<E> elementsType) {
768+ return wrapper.setSet(name, v, elementsType);
769+ }
770+
771+ /**
772+ * {@inheritDoc}
773+ */
774+ @Override
1123775 public BoundStatement setUDTValue(int i, UDTValue v) {
1124776 return wrapper.setUDTValue(i, v);
1125777 }
1126778
1127779 /**
1128- * Sets the value for (all occurrences of) variable {@code name} to the
1129- * provided UDT value.
1130- *
1131- * @param name the name of the value to set; if {@code name} is present multiple
1132- * times, all its values are set.
1133- * @param v the value to set.
1134- * @return this BoundStatement.
1135- *
1136- * @throws IllegalArgumentException if {@code name} is not a valid name for this BoundStatement.
1137- * @throws InvalidTypeException if (any occurrence of) {@code name} is
1138- * not a UDT value or if the definition of column {@code name} does not correspond to
1139- * the one of {@code v}.
780+ * {@inheritDoc}
1140781 */
782+ @Override
1141783 public BoundStatement setUDTValue(String name, UDTValue v) {
1142784 return wrapper.setUDTValue(name, v);
1143785 }
1144786
1145787 /**
1146- * Sets the {@code i}th value to the provided tuple value.
1147- *
1148- * @param i the index of the value to set.
1149- * @param v the value to set.
1150- * @return this BoundStatement.
1151- *
1152- * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this BoundStatement.
1153- * @throws InvalidTypeException if value {@code i} is not a tuple value or if its types
1154- * do not correspond to the ones of {@code v}.
788+ * {@inheritDoc}
1155789 */
790+ @Override
1156791 public BoundStatement setTupleValue(int i, TupleValue v) {
1157792 return wrapper.setTupleValue(i, v);
1158793 }
1159794
1160795 /**
1161- * Sets the value for (all occurrences of) variable {@code name} to the
1162- * provided tuple value.
1163- *
1164- * @param name the name of the value to set; if {@code name} is present multiple
1165- * times, all its values are set.
1166- * @param v the value to set.
1167- * @return this BoundStatement.
1168- *
1169- * @throws IllegalArgumentException if {@code name} is not a valid name for this BoundStatement.
1170- * @throws InvalidTypeException if (any occurrence of) {@code name} is
1171- * not a tuple value or if the types of column {@code name} do not correspond to
1172- * the ones of {@code v}.
796+ * {@inheritDoc}
1173797 */
798+ @Override
1174799 public BoundStatement setTupleValue(String name, TupleValue v) {
1175800 return wrapper.setTupleValue(name, v);
1176801 }
1177802
1178803 /**
1179- * Sets the {@code i}th value to {@code null}.
1180- * <p>
1181- * This is mainly intended for CQL types which map to native Java types.
1182- *
1183- * @param i the index of the value to set.
1184- * @return this object.
1185- * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
804+ * {@inheritDoc}
805+ */
806+ @Override
807+ public <V> BoundStatement setObject(int i, V v) {
808+ return wrapper.setObject(i, v);
809+ }
810+
811+ /**
812+ * {@inheritDoc}
813+ */
814+ @Override
815+ public <V> BoundStatement setObject(String name, V v) {
816+ return wrapper.setObject(name, v);
817+ }
818+
819+ /**
820+ * {@inheritDoc}
821+ */
822+ @Override
823+ public <V> BoundStatement set(int i, V v, Class<V> targetClass) {
824+ return wrapper.set(i, v, targetClass);
825+ }
826+
827+ /**
828+ * {@inheritDoc}
829+ */
830+ @Override
831+ public <V> BoundStatement set(String name, V v, Class<V> targetClass) {
832+ return wrapper.set(name, v, targetClass);
833+ }
834+
835+ /**
836+ * {@inheritDoc}
837+ */
838+ @Override
839+ public <V> BoundStatement set(int i, V v, TypeToken<V> targetType) {
840+ return wrapper.set(i, v, targetType);
841+ }
842+
843+ /**
844+ * {@inheritDoc}
845+ */
846+ @Override
847+ public <V> BoundStatement set(String name, V v, TypeToken<V> targetType) {
848+ return wrapper.set(name, v, targetType);
849+ }
850+
851+ /**
852+ * {@inheritDoc}
853+ */
854+ @Override
855+ public <V> BoundStatement set(int i, V v, TypeCodec<V> codec) {
856+ return wrapper.set(i, v, codec);
857+ }
858+
859+ /**
860+ * {@inheritDoc}
861+ */
862+ @Override
863+ public <V> BoundStatement set(String name, V v, TypeCodec<V> codec) {
864+ return wrapper.set(name, v, codec);
865+ }
866+
867+ /**
868+ * {@inheritDoc}
1186869 */
870+ @Override
1187871 public BoundStatement setToNull(int i) {
1188872 return wrapper.setToNull(i);
1189873 }
1190874
1191875 /**
1192- * Sets the value for (all occurrences of) variable {@code name} to {@code null}.
1193- * <p>
1194- * This is mainly intended for CQL types which map to native Java types.
1195- *
1196- * @param name the name of the value to set; if {@code name} is present multiple
1197- * times, all its values are set.
1198- * @return this object.
1199- * @throws IllegalArgumentException if {@code name} is not a valid name for this object.
876+ * {@inheritDoc}
1200877 */
878+ @Override
1201879 public BoundStatement setToNull(String name) {
1202880 return wrapper.setToNull(name);
1203881 }
@@ -1205,6 +883,7 @@
1205883 /**
1206884 * {@inheritDoc}
1207885 */
886+ @Override
1208887 public boolean isNull(int i) {
1209888 return wrapper.isNull(i);
1210889 }
@@ -1212,6 +891,7 @@
1212891 /**
1213892 * {@inheritDoc}
1214893 */
894+ @Override
1215895 public boolean isNull(String name) {
1216896 return wrapper.isNull(name);
1217897 }
@@ -1219,6 +899,7 @@
1219899 /**
1220900 * {@inheritDoc}
1221901 */
902+ @Override
1222903 public boolean getBool(int i) {
1223904 return wrapper.getBool(i);
1224905 }
@@ -1226,6 +907,7 @@
1226907 /**
1227908 * {@inheritDoc}
1228909 */
910+ @Override
1229911 public boolean getBool(String name) {
1230912 return wrapper.getBool(name);
1231913 }
@@ -1233,6 +915,7 @@
1233915 /**
1234916 * {@inheritDoc}
1235917 */
918+ @Override
1236919 public byte getByte(int i) {
1237920 return wrapper.getByte(i);
1238921 }
@@ -1240,6 +923,7 @@
1240923 /**
1241924 * {@inheritDoc}
1242925 */
926+ @Override
1243927 public byte getByte(String name) {
1244928 return wrapper.getByte(name);
1245929 }
@@ -1247,6 +931,7 @@
1247931 /**
1248932 * {@inheritDoc}
1249933 */
934+ @Override
1250935 public short getShort(int i) {
1251936 return wrapper.getShort(i);
1252937 }
@@ -1254,6 +939,7 @@
1254939 /**
1255940 * {@inheritDoc}
1256941 */
942+ @Override
1257943 public short getShort(String name) {
1258944 return wrapper.getShort(name);
1259945 }
@@ -1261,6 +947,7 @@
1261947 /**
1262948 * {@inheritDoc}
1263949 */
950+ @Override
1264951 public int getInt(int i) {
1265952 return wrapper.getInt(i);
1266953 }
@@ -1268,6 +955,7 @@
1268955 /**
1269956 * {@inheritDoc}
1270957 */
958+ @Override
1271959 public int getInt(String name) {
1272960 return wrapper.getInt(name);
1273961 }
@@ -1275,6 +963,7 @@
1275963 /**
1276964 * {@inheritDoc}
1277965 */
966+ @Override
1278967 public long getLong(int i) {
1279968 return wrapper.getLong(i);
1280969 }
@@ -1282,6 +971,7 @@
1282971 /**
1283972 * {@inheritDoc}
1284973 */
974+ @Override
1285975 public long getLong(String name) {
1286976 return wrapper.getLong(name);
1287977 }
@@ -1289,6 +979,7 @@
1289979 /**
1290980 * {@inheritDoc}
1291981 */
982+ @Override
1292983 public Date getTimestamp(int i) {
1293984 return wrapper.getTimestamp(i);
1294985 }
@@ -1296,6 +987,7 @@
1296987 /**
1297988 * {@inheritDoc}
1298989 */
990+ @Override
1299991 public Date getTimestamp(String name) {
1300992 return wrapper.getTimestamp(name);
1301993 }
@@ -1303,6 +995,7 @@
1303995 /**
1304996 * {@inheritDoc}
1305997 */
998+ @Override
1306999 public LocalDate getDate(int i) {
13071000 return wrapper.getDate(i);
13081001 }
@@ -1310,6 +1003,7 @@
13101003 /**
13111004 * {@inheritDoc}
13121005 */
1006+ @Override
13131007 public LocalDate getDate(String name) {
13141008 return wrapper.getDate(name);
13151009 }
@@ -1317,6 +1011,7 @@
13171011 /**
13181012 * {@inheritDoc}
13191013 */
1014+ @Override
13201015 public long getTime(int i) {
13211016 return wrapper.getTime(i);
13221017 }
@@ -1324,6 +1019,7 @@
13241019 /**
13251020 * {@inheritDoc}
13261021 */
1022+ @Override
13271023 public long getTime(String name) {
13281024 return wrapper.getTime(name);
13291025 }
@@ -1331,6 +1027,7 @@
13311027 /**
13321028 * {@inheritDoc}
13331029 */
1030+ @Override
13341031 public float getFloat(int i) {
13351032 return wrapper.getFloat(i);
13361033 }
@@ -1338,6 +1035,7 @@
13381035 /**
13391036 * {@inheritDoc}
13401037 */
1038+ @Override
13411039 public float getFloat(String name) {
13421040 return wrapper.getFloat(name);
13431041 }
@@ -1345,6 +1043,7 @@
13451043 /**
13461044 * {@inheritDoc}
13471045 */
1046+ @Override
13481047 public double getDouble(int i) {
13491048 return wrapper.getDouble(i);
13501049 }
@@ -1352,6 +1051,7 @@
13521051 /**
13531052 * {@inheritDoc}
13541053 */
1054+ @Override
13551055 public double getDouble(String name) {
13561056 return wrapper.getDouble(name);
13571057 }
@@ -1359,6 +1059,7 @@
13591059 /**
13601060 * {@inheritDoc}
13611061 */
1062+ @Override
13621063 public ByteBuffer getBytesUnsafe(int i) {
13631064 return wrapper.getBytesUnsafe(i);
13641065 }
@@ -1366,6 +1067,7 @@
13661067 /**
13671068 * {@inheritDoc}
13681069 */
1070+ @Override
13691071 public ByteBuffer getBytesUnsafe(String name) {
13701072 return wrapper.getBytesUnsafe(name);
13711073 }
@@ -1373,6 +1075,7 @@
13731075 /**
13741076 * {@inheritDoc}
13751077 */
1078+ @Override
13761079 public ByteBuffer getBytes(int i) {
13771080 return wrapper.getBytes(i);
13781081 }
@@ -1380,6 +1083,7 @@
13801083 /**
13811084 * {@inheritDoc}
13821085 */
1086+ @Override
13831087 public ByteBuffer getBytes(String name) {
13841088 return wrapper.getBytes(name);
13851089 }
@@ -1387,6 +1091,7 @@
13871091 /**
13881092 * {@inheritDoc}
13891093 */
1094+ @Override
13901095 public String getString(int i) {
13911096 return wrapper.getString(i);
13921097 }
@@ -1394,6 +1099,7 @@
13941099 /**
13951100 * {@inheritDoc}
13961101 */
1102+ @Override
13971103 public String getString(String name) {
13981104 return wrapper.getString(name);
13991105 }
@@ -1401,6 +1107,7 @@
14011107 /**
14021108 * {@inheritDoc}
14031109 */
1110+ @Override
14041111 public BigInteger getVarint(int i) {
14051112 return wrapper.getVarint(i);
14061113 }
@@ -1408,6 +1115,7 @@
14081115 /**
14091116 * {@inheritDoc}
14101117 */
1118+ @Override
14111119 public BigInteger getVarint(String name) {
14121120 return wrapper.getVarint(name);
14131121 }
@@ -1415,6 +1123,7 @@
14151123 /**
14161124 * {@inheritDoc}
14171125 */
1126+ @Override
14181127 public BigDecimal getDecimal(int i) {
14191128 return wrapper.getDecimal(i);
14201129 }
@@ -1422,6 +1131,7 @@
14221131 /**
14231132 * {@inheritDoc}
14241133 */
1134+ @Override
14251135 public BigDecimal getDecimal(String name) {
14261136 return wrapper.getDecimal(name);
14271137 }
@@ -1429,6 +1139,7 @@
14291139 /**
14301140 * {@inheritDoc}
14311141 */
1142+ @Override
14321143 public UUID getUUID(int i) {
14331144 return wrapper.getUUID(i);
14341145 }
@@ -1436,6 +1147,7 @@
14361147 /**
14371148 * {@inheritDoc}
14381149 */
1150+ @Override
14391151 public UUID getUUID(String name) {
14401152 return wrapper.getUUID(name);
14411153 }
@@ -1443,6 +1155,7 @@
14431155 /**
14441156 * {@inheritDoc}
14451157 */
1158+ @Override
14461159 public InetAddress getInet(int i) {
14471160 return wrapper.getInet(i);
14481161 }
@@ -1450,6 +1163,7 @@
14501163 /**
14511164 * {@inheritDoc}
14521165 */
1166+ @Override
14531167 public InetAddress getInet(String name) {
14541168 return wrapper.getInet(name);
14551169 }
@@ -1457,6 +1171,7 @@
14571171 /**
14581172 * {@inheritDoc}
14591173 */
1174+ @Override
14601175 public <T> List<T> getList(int i, Class<T> elementsClass) {
14611176 return wrapper.getList(i, elementsClass);
14621177 }
@@ -1464,6 +1179,7 @@
14641179 /**
14651180 * {@inheritDoc}
14661181 */
1182+ @Override
14671183 public <T> List<T> getList(int i, TypeToken<T> elementsType) {
14681184 return wrapper.getList(i, elementsType);
14691185 }
@@ -1471,6 +1187,7 @@
14711187 /**
14721188 * {@inheritDoc}
14731189 */
1190+ @Override
14741191 public <T> List<T> getList(String name, Class<T> elementsClass) {
14751192 return wrapper.getList(name, elementsClass);
14761193 }
@@ -1478,6 +1195,7 @@
14781195 /**
14791196 * {@inheritDoc}
14801197 */
1198+ @Override
14811199 public <T> List<T> getList(String name, TypeToken<T> elementsType) {
14821200 return wrapper.getList(name, elementsType);
14831201 }
@@ -1485,6 +1203,7 @@
14851203 /**
14861204 * {@inheritDoc}
14871205 */
1206+ @Override
14881207 public <T> Set<T> getSet(int i, Class<T> elementsClass) {
14891208 return wrapper.getSet(i, elementsClass);
14901209 }
@@ -1492,6 +1211,7 @@
14921211 /**
14931212 * {@inheritDoc}
14941213 */
1214+ @Override
14951215 public <T> Set<T> getSet(int i, TypeToken<T> elementsType) {
14961216 return wrapper.getSet(i, elementsType);
14971217 }
@@ -1499,6 +1219,7 @@
14991219 /**
15001220 * {@inheritDoc}
15011221 */
1222+ @Override
15021223 public <T> Set<T> getSet(String name, Class<T> elementsClass) {
15031224 return wrapper.getSet(name, elementsClass);
15041225 }
@@ -1506,6 +1227,7 @@
15061227 /**
15071228 * {@inheritDoc}
15081229 */
1230+ @Override
15091231 public <T> Set<T> getSet(String name, TypeToken<T> elementsType) {
15101232 return wrapper.getSet(name, elementsType);
15111233 }
@@ -1513,6 +1235,7 @@
15131235 /**
15141236 * {@inheritDoc}
15151237 */
1238+ @Override
15161239 public <K, V> Map<K, V> getMap(int i, Class<K> keysClass, Class<V> valuesClass) {
15171240 return wrapper.getMap(i, keysClass, valuesClass);
15181241 }
@@ -1520,6 +1243,7 @@
15201243 /**
15211244 * {@inheritDoc}
15221245 */
1246+ @Override
15231247 public <K, V> Map<K, V> getMap(int i, TypeToken<K> keysType, TypeToken<V> valuesType) {
15241248 return wrapper.getMap(i, keysType, valuesType);
15251249 }
@@ -1527,6 +1251,7 @@
15271251 /**
15281252 * {@inheritDoc}
15291253 */
1254+ @Override
15301255 public <K, V> Map<K, V> getMap(String name, Class<K> keysClass, Class<V> valuesClass) {
15311256 return wrapper.getMap(name, keysClass, valuesClass);
15321257 }
@@ -1534,6 +1259,7 @@
15341259 /**
15351260 * {@inheritDoc}
15361261 */
1262+ @Override
15371263 public <K, V> Map<K, V> getMap(String name, TypeToken<K> keysType, TypeToken<V> valuesType) {
15381264 return wrapper.getMap(name, keysType, valuesType);
15391265 }
@@ -1541,6 +1267,7 @@
15411267 /**
15421268 * {@inheritDoc}
15431269 */
1270+ @Override
15441271 public UDTValue getUDTValue(int i) {
15451272 return wrapper.getUDTValue(i);
15461273 }
@@ -1548,6 +1275,7 @@
15481275 /**
15491276 * {@inheritDoc}
15501277 */
1278+ @Override
15511279 public UDTValue getUDTValue(String name) {
15521280 return wrapper.getUDTValue(name);
15531281 }
@@ -1555,6 +1283,7 @@
15551283 /**
15561284 * {@inheritDoc}
15571285 */
1286+ @Override
15581287 public TupleValue getTupleValue(int i) {
15591288 return wrapper.getTupleValue(i);
15601289 }
@@ -1562,6 +1291,7 @@
15621291 /**
15631292 * {@inheritDoc}
15641293 */
1294+ @Override
15651295 public TupleValue getTupleValue(String name) {
15661296 return wrapper.getTupleValue(name);
15671297 }
@@ -1569,6 +1299,7 @@
15691299 /**
15701300 * {@inheritDoc}
15711301 */
1302+ @Override
15721303 public Object getObject(int i) {
15731304 return wrapper.getObject(i);
15741305 }
@@ -1576,10 +1307,70 @@
15761307 /**
15771308 * {@inheritDoc}
15781309 */
1310+ @Override
15791311 public Object getObject(String name) {
15801312 return wrapper.getObject(name);
15811313 }
15821314
1315+
1316+ /**
1317+ * {@inheritDoc}
1318+ */
1319+ @Override
1320+ public <T> T get(int i, Class<T> targetClass) {
1321+ return wrapper.get(i, targetClass);
1322+ }
1323+
1324+ /**
1325+ * {@inheritDoc}
1326+ */
1327+ @Override
1328+ public <T> T get(String name, Class<T> targetClass) {
1329+ return wrapper.get(name, targetClass);
1330+ }
1331+
1332+ /**
1333+ * {@inheritDoc}
1334+ */
1335+ @Override
1336+ public <T> T get(int i, TypeToken<T> targetType) {
1337+ return wrapper.get(i, targetType);
1338+ }
1339+
1340+ /**
1341+ * {@inheritDoc}
1342+ */
1343+ @Override
1344+ public <T> T get(String name, TypeToken<T> targetType) {
1345+ return wrapper.get(name, targetType);
1346+ }
1347+
1348+ /**
1349+ * {@inheritDoc}
1350+ */
1351+ @Override
1352+ public <T> T get(int i, TypeCodec<T> codec) {
1353+ return wrapper.get(i, codec);
1354+ }
1355+
1356+ /**
1357+ * {@inheritDoc}
1358+ */
1359+ @Override
1360+ public <T> T get(String name, TypeCodec<T> codec) {
1361+ return wrapper.get(name, codec);
1362+ }
1363+
1364+ void ensureAllSet() {
1365+ int index = 0;
1366+ for (ByteBuffer value : wrapper.values) {
1367+ if (value == BoundStatement.UNSET)
1368+ throw new IllegalStateException("Unset value at index " + index + ". "
1369+ + "If you want this value to be null, please set it to null explicitly.");
1370+ index += 1;
1371+ }
1372+ }
1373+
15831374 static class DataWrapper extends AbstractData<BoundStatement> {
15841375
15851376 DataWrapper(BoundStatement wrapped, int size) {
@@ -1597,15 +1388,10 @@
15971388 protected String getName(int i) {
15981389 return wrapped.statement.getVariables().getName(i);
15991390 }
1600- }
16011391
1602- void ensureAllSet() {
1603- int index = 0;
1604- for (ByteBuffer value : wrapper.values) {
1605- if (value == BoundStatement.UNSET)
1606- throw new IllegalStateException("Unset value at index " + index + ". "
1607- + "If you want this value to be null, please set it to null explicitly.");
1608- index += 1;
1392+ @Override
1393+ protected CodecRegistry getCodecRegistry() {
1394+ return wrapped.codecRegistry;
16091395 }
16101396 }
16111397 }
modified driver-core/src/main/java/com/datastax/driver/core/CassandraTypeParser.java +14 −14
@@ -72,7 +72,7 @@
7272 .put("org.apache.cassandra.db.marshal.ShortType", DataType.smallint())
7373 .build();
7474
75- static DataType parseOne(String className) {
75+ static DataType parseOne(String className, ProtocolVersion protocolVersion, CodecRegistry codecRegistry) {
7676 boolean frozen = false;
7777 if (isReversed(className)) {
7878 // Just skip the ReversedType part, we don't care
@@ -86,14 +86,14 @@
8686 String next = parser.parseNextName();
8787
8888 if (next.startsWith(LIST_TYPE))
89- return DataType.list(parseOne(parser.getTypeParameters().get(0)), frozen);
89+ return DataType.list(parseOne(parser.getTypeParameters().get(0), protocolVersion, codecRegistry), frozen);
9090
9191 if (next.startsWith(SET_TYPE))
92- return DataType.set(parseOne(parser.getTypeParameters().get(0)), frozen);
92+ return DataType.set(parseOne(parser.getTypeParameters().get(0), protocolVersion, codecRegistry), frozen);
9393
9494 if (next.startsWith(MAP_TYPE)) {
9595 List<String> params = parser.getTypeParameters();
96- return DataType.map(parseOne(params.get(0)), parseOne(params.get(1)), frozen);
96+ return DataType.map(parseOne(params.get(0), protocolVersion, codecRegistry), parseOne(params.get(1), protocolVersion, codecRegistry), frozen);
9797 }
9898
9999 if (frozen)
@@ -105,22 +105,22 @@
105105
106106 String keyspace = parser.readOne();
107107 parser.skipBlankAndComma();
108- String typeName = TypeCodec.StringCodec.utf8Instance.deserialize(Bytes.fromHexString("0x" + parser.readOne()));
108+ String typeName = TypeCodec.VarcharCodec.instance.deserialize(Bytes.fromHexString("0x" + parser.readOne()), protocolVersion);
109109 parser.skipBlankAndComma();
110110 Map<String, String> rawFields = parser.getNameAndTypeParameters();
111111 List<UserType.Field> fields = new ArrayList<UserType.Field>(rawFields.size());
112112 for (Map.Entry<String, String> entry : rawFields.entrySet())
113- fields.add(new UserType.Field(entry.getKey(), parseOne(entry.getValue())));
114- return new UserType(keyspace, typeName, fields);
113+ fields.add(new UserType.Field(entry.getKey(), parseOne(entry.getValue(), protocolVersion, codecRegistry)));
114+ return new UserType(keyspace, typeName, fields, protocolVersion, codecRegistry);
115115 }
116116
117117 if (isTupleType(next)) {
118118 List<String> rawTypes = parser.getTypeParameters();
119119 List<DataType> types = new ArrayList<DataType>(rawTypes.size());
120120 for (String rawType : rawTypes) {
121- types.add(parseOne(rawType));
121+ types.add(parseOne(rawType, protocolVersion, codecRegistry));
122122 }
123- return new TupleType(types);
123+ return new TupleType(types, protocolVersion, codecRegistry);
124124 }
125125
126126 DataType type = cassTypeToDataType.get(next);
@@ -161,12 +161,12 @@
161161 return className.startsWith(COLLECTION_TYPE);
162162 }
163163
164- static ParseResult parseWithComposite(String className) {
164+ static ParseResult parseWithComposite(String className, ProtocolVersion protocolVersion, CodecRegistry codecRegistry) {
165165 Parser parser = new Parser(className, 0);
166166
167167 String next = parser.parseNextName();
168168 if (!isComposite(next))
169- return new ParseResult(parseOne(className), isReversed(next));
169+ return new ParseResult(parseOne(className, protocolVersion, codecRegistry), isReversed(next));
170170
171171 List<String> subClassNames = parser.getTypeParameters();
172172 int count = subClassNames.size();
@@ -178,13 +178,13 @@
178178 collectionParser.parseNextName(); // skips columnToCollectionType
179179 Map<String, String> params = collectionParser.getCollectionsParameters();
180180 for (Map.Entry<String, String> entry : params.entrySet())
181- collections.put(entry.getKey(), parseOne(entry.getValue()));
181+ collections.put(entry.getKey(), parseOne(entry.getValue(), protocolVersion, codecRegistry));
182182 }
183183
184184 List<DataType> types = new ArrayList<DataType>(count);
185185 List<Boolean> reversed = new ArrayList<Boolean>(count);
186186 for (int i = 0; i < count; i++) {
187- types.add(parseOne(subClassNames.get(i)));
187+ types.add(parseOne(subClassNames.get(i), protocolVersion, codecRegistry));
188188 reversed.add(isReversed(subClassNames.get(i)));
189189 }
190190
@@ -319,7 +319,7 @@
319319 String bbHex = readNextIdentifier();
320320 String name = null;
321321 try {
322- name = TypeCodec.StringCodec.utf8Instance.deserialize(Bytes.fromHexString("0x" + bbHex));
322+ name = TypeCodec.VarcharCodec.instance.deserialize(Bytes.fromHexString("0x" + bbHex), ProtocolVersion.NEWEST_SUPPORTED);
323323 } catch (NumberFormatException e) {
324324 throwSyntaxError(e.getMessage());
325325 }
modified driver-core/src/main/java/com/datastax/driver/core/Cluster.java +35 −38
@@ -26,7 +26,6 @@
2626 import java.util.concurrent.atomic.AtomicReference;
2727
2828 import com.google.common.annotations.VisibleForTesting;
29-import com.google.common.base.Objects;
3029 import com.google.common.base.Predicates;
3130 import com.google.common.collect.*;
3231 import com.google.common.util.concurrent.*;
@@ -575,27 +574,16 @@
575574 private ProtocolVersion protocolVersion;
576575 private AuthProvider authProvider = AuthProvider.NONE;
577576
578- private LoadBalancingPolicy loadBalancingPolicy;
579- private ReconnectionPolicy reconnectionPolicy;
580- private RetryPolicy retryPolicy;
581- private AddressTranslator addressTranslator;
582- private TimestampGenerator timestampGenerator;
583- private SpeculativeExecutionPolicy speculativeExecutionPolicy;
577+ private final Policies.Builder policiesBuilder = Policies.builder();
578+ private final Configuration.Builder configurationBuilder = Configuration.builder();
584579
585580 private ProtocolOptions.Compression compression = ProtocolOptions.Compression.NONE;
586581 private SSLOptions sslOptions = null;
587582 private boolean metricsEnabled = true;
588583 private boolean jmxEnabled = true;
589584
590- private PoolingOptions poolingOptions;
591- private SocketOptions socketOptions;
592- private QueryOptions queryOptions;
593-
594- private NettyOptions nettyOptions = NettyOptions.DEFAULT_INSTANCE;
595-
596585 private Collection<Host.StateListener> listeners;
597586
598-
599587 @Override
600588 public String getClusterName() {
601589 return clusterName;
@@ -852,7 +840,7 @@
852840 * @return this Builder.
853841 */
854842 public Builder withLoadBalancingPolicy(LoadBalancingPolicy policy) {
855- this.loadBalancingPolicy = policy;
843+ policiesBuilder.withLoadBalancingPolicy(policy);
856844 return this;
857845 }
858846
@@ -866,7 +854,7 @@
866854 * @return this Builder.
867855 */
868856 public Builder withReconnectionPolicy(ReconnectionPolicy policy) {
869- this.reconnectionPolicy = policy;
857+ policiesBuilder.withReconnectionPolicy(policy);
870858 return this;
871859 }
872860
@@ -880,7 +868,7 @@
880868 * @return this Builder.
881869 */
882870 public Builder withRetryPolicy(RetryPolicy policy) {
883- this.retryPolicy = policy;
871+ policiesBuilder.withRetryPolicy(policy);
884872 return this;
885873 }
886874
@@ -895,7 +883,7 @@
895883 * @return this Builder.
896884 */
897885 public Builder withAddressTranslator(AddressTranslator translator) {
898- this.addressTranslator = translator;
886+ policiesBuilder.withAddressTranslator(translator);
899887 return this;
900888 }
901889
@@ -915,7 +903,7 @@
915903 * @return this Builder.
916904 */
917905 public Builder withTimestampGenerator(TimestampGenerator timestampGenerator) {
918- this.timestampGenerator = timestampGenerator;
906+ policiesBuilder.withTimestampGenerator(timestampGenerator);
919907 return this;
920908 }
921909
@@ -929,7 +917,22 @@
929917 * @return this Builder.
930918 */
931919 public Builder withSpeculativeExecutionPolicy(SpeculativeExecutionPolicy policy) {
932- this.speculativeExecutionPolicy = policy;
920+ policiesBuilder.withSpeculativeExecutionPolicy(policy);
921+ return this;
922+ }
923+
924+
925+ /**
926+ * Configures the {@link CodecRegistry} instance to use for the new cluster.
927+ * <p>
928+ * If no codec registry is set through this method, a newly-created instance
929+ * will be used instead.
930+ *
931+ * @param codecRegistry the codec registry to use.
932+ * @return this Builder.
933+ */
934+ public Builder withCodecRegistry(CodecRegistry codecRegistry) {
935+ configurationBuilder.withCodecRegistry(codecRegistry);
933936 return this;
934937 }
935938
@@ -1059,7 +1062,7 @@
10591062 * @return this builder.
10601063 */
10611064 public Builder withPoolingOptions(PoolingOptions options) {
1062- this.poolingOptions = options;
1065+ configurationBuilder.withPoolingOptions(options);
10631066 return this;
10641067 }
10651068
@@ -1073,7 +1076,7 @@
10731076 * @return this builder.
10741077 */
10751078 public Builder withSocketOptions(SocketOptions options) {
1076- this.socketOptions = options;
1079+ configurationBuilder.withSocketOptions(options);
10771080 return this;
10781081 }
10791082
@@ -1087,7 +1090,7 @@
10871090 * @return this builder.
10881091 */
10891092 public Builder withQueryOptions(QueryOptions options) {
1090- this.queryOptions = options;
1093+ configurationBuilder.withQueryOptions(options);
10911094 return this;
10921095 }
10931096
@@ -1101,7 +1104,7 @@
11011104 * @return this builder.
11021105 */
11031106 public Builder withNettyOptions(NettyOptions nettyOptions) {
1104- this.nettyOptions = nettyOptions;
1107+ configurationBuilder.withNettyOptions(nettyOptions);
11051108 return this;
11061109 }
11071110
@@ -1116,21 +1119,15 @@
11161119 */
11171120 @Override
11181121 public Configuration getConfiguration() {
1119- Policies policies = Policies.builder()
1120- .withLoadBalancingPolicy(loadBalancingPolicy)
1121- .withReconnectionPolicy(reconnectionPolicy)
1122- .withRetryPolicy(retryPolicy)
1123- .withAddressTranslator(addressTranslator)
1124- .withTimestampGenerator(timestampGenerator)
1125- .withSpeculativeExecutionPolicy(speculativeExecutionPolicy)
1122+ ProtocolOptions protocolOptions = new ProtocolOptions(port, protocolVersion, maxSchemaAgreementWaitSeconds, sslOptions, authProvider)
1123+ .setCompression(compression);
1124+ MetricsOptions metricsOptions = metricsEnabled ? new MetricsOptions(jmxEnabled) : null;
1125+
1126+ return configurationBuilder
1127+ .withProtocolOptions(protocolOptions)
1128+ .withMetricsOptions(metricsOptions)
1129+ .withPolicies(policiesBuilder.build())
11261130 .build();
1127- return new Configuration(policies,
1128- new ProtocolOptions(port, protocolVersion, maxSchemaAgreementWaitSeconds, sslOptions, authProvider).setCompression(compression),
1129- poolingOptions == null ? new PoolingOptions() : poolingOptions,
1130- socketOptions == null ? new SocketOptions() : socketOptions,
1131- metricsEnabled ? new MetricsOptions(jmxEnabled) : null,
1132- queryOptions == null ? new QueryOptions() : queryOptions,
1133- nettyOptions);
11341131 }
11351132
11361133 @Override
added driver-core/src/main/java/com/datastax/driver/core/CodecRegistry.java +664 −0
@@ -0,0 +1,664 @@
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.lang.reflect.ParameterizedType;
19+import java.lang.reflect.Type;
20+import java.util.*;
21+import java.util.concurrent.CopyOnWriteArrayList;
22+import java.util.concurrent.ExecutionException;
23+
24+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;
29+import com.google.common.collect.ImmutableSet;
30+import com.google.common.reflect.TypeToken;
31+import com.google.common.util.concurrent.UncheckedExecutionException;
32+import org.slf4j.Logger;
33+import org.slf4j.LoggerFactory;
34+
35+import static com.google.common.base.Preconditions.checkNotNull;
36+
37+import com.datastax.driver.core.TypeCodec.*;
38+import com.datastax.driver.core.exceptions.CodecNotFoundException;
39+
40+import static com.datastax.driver.core.DataType.Name.*;
41+
42+/**
43+ * A registry for {@link TypeCodec}s. When the driver
44+ * needs to serialize or deserialize an object,
45+ * it will lookup in the {@link CodecRegistry} for
46+ * a suitable codec.
47+ *
48+ * <h3>Usage</h3>
49+ *
50+ * <p>
51+ * To create a default {@link CodecRegistry} instance with all the default codecs used
52+ * by the Java driver, simply use the following:
53+ *
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:
59+ *
60+ * <pre>
61+ * CodecRegistry myCodecRegistry = new CodecRegistry()
62+ * .register(myCodec1, myCodec2, myCodec3)
63+ * </pre>
64+ *
65+ * <p>
66+ * Note that the order in which codecs are registered matters;
67+ * if a codec is registered while another codec already handles the same
68+ * CQL-to-Java mapping, that codec will never be used (unless
69+ * the user forces its usage through e.g. {@link GettableByIndexData#get(int, TypeCodec)}).
70+ * In order words, it is not possible to replace an existing codec,
71+ * specially the built-in ones; it is only possible to enrich the initial
72+ * set of codecs with new ones.
73+ * <p>
74+ * To be used by the driver, {@link CodecRegistry} instances must then
75+ * be associated with a {@link Cluster} instance:
76+ *
77+ * <pre>
78+ * CodecRegistry myCodecRegistry = ...
79+ * Cluster cluster = Cluster.builder().withCodecRegistry(myCodecRegistry).build();
80+ * </pre>
81+ *
82+ * To retrieve the {@link CodecRegistry} instance associated with a Cluster, do the
83+ * following:
84+ *
85+ * <pre>
86+ * CodecRegistry registry = cluster.getConfiguration().getCodecRegistry();
87+ * </pre>
88+ *
89+ * <p>
90+ * For most users, a default {@link CodecRegistry} instance, containing
91+ * all the default codecs, should be adequate.
92+ *
93+ * <h3>Example</h3>
94+ *
95+ * <p>
96+ * E.g. let's suppose you want to have all your CQL timestamps
97+ * deserialized as {@code java.time.DateTime} instances:
98+ *
99+ * <pre>
100+ * TypeCodec&lt;DateTime> timestampCodec = ...
101+ * CodecRegistry myCodecRegistry = new CodecRegistry().register(timestampCodec);
102+ * </pre>
103+ *
104+ * Read the
105+ * <a href="http://datastax.github.io/java-driver/features/custom_codecs">online documentation</a>
106+ * for more examples.
107+ *
108+ * <h3>Notes</h3>
109+ *
110+ * <p>
111+ * When a {@link CodecRegistry} cannot find a suitable codec among all registered codecs,
112+ * it will attempt to create a suitable codec.
113+ * <p>
114+ * If the creation succeeds, that codec is added to the list of known codecs and is returned;
115+ * otherwise, a {@link CodecNotFoundException} is thrown.
116+ * <p>
117+ * Note that {@link CodecRegistry} instances can only create codecs in very limited situations:
118+ * <ol>
119+ * <li>Codecs for Enums are created on the fly using {@link EnumStringCodec};</li>
120+ * <li>Codecs for {@link UserType user types} are created on the fly using {@link UDTCodec};</li>
121+ * <li>Codecs for {@link TupleType tuple types} are created on the fly using {@link TupleCodec};</li>
122+ * <li>Codecs for collections are created on the fly using {@link ListCodec}, {@link SetCodec} and
123+ * {@link MapCodec}, if their element types can be handled by existing codecs (or codecs that can
124+ * themselves be generated).</li>
125+ * </ol>
126+ * Other combinations of Java and CQL types cannot have their codecs created on the fly;
127+ * such codecs must be manually registered.
128+ * <p>
129+ * Note that the default set of codecs has no support for
130+ * <a href="https://github.com/apache/cassandra/blob/trunk/src/java/org/apache/cassandra/db/marshal/AbstractType.java">Cassandra custom types</a>;
131+ * to be able to deserialize values of such types, you need to manually register an appropriate codec.
132+ * <p>
133+ * {@link CodecRegistry} instances are not meant to be shared between two or more {@link Cluster} instances; doing so
134+ * could yield unexpected results.
135+ * <p>
136+ * {@link CodecRegistry} instances are thread-safe.
137+ *
138+ */
139+@SuppressWarnings("all")
140+public final class CodecRegistry {
141+
142+ private static final Logger logger = LoggerFactory.getLogger(CodecRegistry.class);
143+
144+ private static final ImmutableSet<TypeCodec<?>> PRIMITIVE_CODECS = ImmutableSet.of(
145+ BlobCodec.instance,
146+ BooleanCodec.instance,
147+ SmallIntCodec.instance,
148+ TinyIntCodec.instance,
149+ IntCodec.instance,
150+ BigintCodec.instance,
151+ CounterCodec.instance,
152+ DoubleCodec.instance,
153+ FloatCodec.instance,
154+ VarintCodec.instance,
155+ DecimalCodec.instance,
156+ VarcharCodec.instance, // must be declared before AsciiCodec so it gets chosen when CQL type not available
157+ AsciiCodec.instance,
158+ TimestampCodec.instance,
159+ DateCodec.instance,
160+ TimeCodec.instance,
161+ UUIDCodec.instance, // must be declared before TimeUUIDCodec so it gets chosen when CQL type not available
162+ TimeUUIDCodec.instance,
163+ InetCodec.instance
164+ );
165+
166+ /**
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.
192+ */
193+ public static final CodecRegistry IMMUTABLE_INSTANCE = new CodecRegistry(true);
194+
195+ private static final class CacheKey {
196+
197+ private final TypeToken<?> javaType;
198+
199+ private final DataType cqlType;
200+
201+ public CacheKey(TypeToken<?> javaType, DataType cqlType) {
202+ this.javaType = javaType;
203+ this.cqlType = cqlType;
204+ }
205+
206+ @Override
207+ public boolean equals(Object o) {
208+ if (this == o)
209+ return true;
210+ if (o == null || getClass() != o.getClass())
211+ return false;
212+ CacheKey cacheKey = (CacheKey)o;
213+ return Objects.equal(javaType, cacheKey.javaType) && Objects.equal(cqlType, cacheKey.cqlType);
214+ }
215+
216+ @Override
217+ public int hashCode() {
218+ return Objects.hashCode(javaType, cqlType);
219+ }
220+ }
221+
222+ private final boolean immutable;
223+
224+ /**
225+ * The list of all known codecs.
226+ * This list is initialized with the built-in codecs;
227+ * User-defined codecs are appended to the list.
228+ */
229+ private final CopyOnWriteArrayList<TypeCodec<?>> codecs;
230+
231+ /**
232+ * A LoadingCache to serve requests for codecs whenever possible.
233+ * The cache can be used as long as at least the CQL type is known.
234+ */
235+ private final LoadingCache<CacheKey, TypeCodec<?>> cache;
236+
237+ public CodecRegistry() {
238+ this(false);
239+ }
240+
241+ private CodecRegistry(boolean immutable) {
242+ this.immutable = immutable;
243+ this.codecs = new CopyOnWriteArrayList<TypeCodec<?>>(DEFAULT_CODECS);
244+ this.cache = CacheBuilder.newBuilder()
245+ .build(
246+ new CacheLoader<CacheKey, TypeCodec<?>>() {
247+ public TypeCodec<?> load(CacheKey cacheKey) {
248+ return findCodec(cacheKey.cqlType, cacheKey.javaType);
249+ }
250+ });
251+ }
252+
253+ /**
254+ * Register the given codec with this registry.
255+ *
256+ * @param codec The codec to add to the registry.
257+ * @return this CodecRegistry (for method chaining).
258+ */
259+ 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);
279+ }
280+
281+ /**
282+ * Register the given codecs with this registry.
283+ *
284+ * @param codecs The codecs to add to the registry.
285+ * @return this Builder (for method chaining).
286+ */
287+ public CodecRegistry register(TypeCodec<?>... codecs) {
288+ return register(Arrays.asList(codecs), false);
289+ }
290+
291+ /**
292+ * Register the given codecs with this registry.
293+ *
294+ * @param codecs The codecs to add to the registry.
295+ * @return this Builder (for method chaining).
296+ */
297+ 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");
319+ for (TypeCodec<?> codec : codecs) {
320+ // add this codec to the beginning of the list so that it gets higher priority
321+ 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+ }
334+ }
335+ return this;
336+ }
337+
338+ /**
339+ * Returns a {@link TypeCodec codec} that accepts the given value.
340+ * <p>
341+ * This method takes an actual Java object and tries to locate a suitable codec for it.
342+ * For this reason, codecs must perform a {@link TypeCodec#accepts(Object) "manual" inspection}
343+ * of the object to determine if they can accept it or not, which, depending on the implementations,
344+ * can be an expensive operation; besides, the resulting codec cannot be cached.
345+ * Therefore there might be a performance penalty when using this method.
346+ * <p>
347+ * Furthermore, this method would return the first matching codec, regardless of its accepted {@link DataType CQL type}.
348+ * For this reason, this method might not return the most accurate codec and should be
349+ * reserved for situations where the target CQL type is not available or unknown.
350+ * In the Java driver, this happens mainly when serializing a value in a {@link SimpleStatement}
351+ * or in the {@link com.datastax.driver.core.querybuilder.QueryBuilder}, where no CQL type information
352+ * is available.
353+ * <p>
354+ * Regular application code should avoid using this method.
355+ * <p>
356+ * Codecs returned by this method are NOT cached.
357+ *
358+ * @param value The value the codec should accept; must not be {@code null}.
359+ * @return A suitable codec.
360+ * @throws CodecNotFoundException if a suitable codec cannot be found.
361+ */
362+ public <T> TypeCodec<T> codecFor(T value) {
363+ checkNotNull(value, "Parameter value cannot be null");
364+ TypeCodec<T> codec = findCodec(null, value);
365+ return codec;
366+ }
367+
368+ /**
369+ * Returns a {@link TypeCodec codec} that accepts the given {@link DataType CQL type}.
370+ * <p>
371+ * This method would return the first matching codec, regardless of its accepted Java type.
372+ * For this reason, this method might not return the most accurate codec and should be
373+ * reserved for situations where the runtime type is not available or unknown.
374+ * In the Java driver, this happens mainly when deserializing a value using the
375+ * {@link AbstractGettableData#getObject(int)} method.
376+ * <p>
377+ * Codecs returned by this method are cached.
378+ *
379+ * @param cqlType The {@link DataType CQL type} the codec should accept; must not be {@code null}.
380+ * @return A suitable codec.
381+ * @throws CodecNotFoundException if a suitable codec cannot be found.
382+ */
383+ public <T> TypeCodec<T> codecFor(DataType cqlType) throws CodecNotFoundException {
384+ return lookupCache(cqlType, null);
385+ }
386+
387+ /**
388+ * Returns a {@link TypeCodec codec} that accepts the given {@link DataType CQL type}
389+ * and the given Java class.
390+ * <p>
391+ * This method can only handle raw (non-parameterized) Java types.
392+ * For parameterized types, use {@link #codecFor(DataType, TypeToken)} instead.
393+ * <p>
394+ * Note that type inheritance needs special care.
395+ * If a codec accepts a Java type that is assignable to the
396+ * given Java type, that codec may be returned if it is found first
397+ * in the registry, <em>even if another codec is a better match</em>.
398+ * <p>
399+ * Codecs returned by this method are cached.
400+ *
401+ * @param cqlType The {@link DataType CQL type} the codec should accept; must not be {@code null}.
402+ * @param javaType The Java type the codec should accept; must not be {@code null}.
403+ * @return A suitable codec.
404+ * @throws CodecNotFoundException if a suitable codec cannot be found.
405+ */
406+ public <T> TypeCodec<T> codecFor(DataType cqlType, Class<T> javaType) throws CodecNotFoundException {
407+ return codecFor(cqlType, TypeToken.of(javaType));
408+ }
409+
410+ /**
411+ * Returns a {@link TypeCodec codec} that accepts the given {@link DataType CQL type}
412+ * and the given Java type.
413+ * <p>
414+ * This method handles parameterized types thanks to Guava's {@link TypeToken} API.
415+ * <p>
416+ * Note that type inheritance needs special care.
417+ * If a codec accepts a Java type that is assignable to the
418+ * given Java type, that codec may be returned if it is found first
419+ * in the registry, <em>even if another codec is a better match</em>.
420+ * <p>
421+ * Codecs returned by this method are cached.
422+ *
423+ * @param cqlType The {@link DataType CQL type} the codec should accept; must not be {@code null}.
424+ * @param javaType The {@link TypeToken Java type} the codec should accept; must not be {@code null}.
425+ * @return A suitable codec.
426+ * @throws CodecNotFoundException if a suitable codec cannot be found.
427+ */
428+ public <T> TypeCodec<T> codecFor(DataType cqlType, TypeToken<T> javaType) throws CodecNotFoundException {
429+ checkNotNull(cqlType, "Parameter cqlType cannot be null");
430+ checkNotNull(javaType, "Parameter javaType cannot be null");
431+ return lookupCache(cqlType, javaType);
432+ }
433+
434+ /**
435+ * Returns a {@link TypeCodec codec} that accepts the given {@link DataType CQL type}
436+ * and the given value.
437+ * <p>
438+ * This method takes an actual Java object and tries to locate a suitable codec for it.
439+ * For this reason, codecs must perform a {@link TypeCodec#accepts(Object) "manual" inspection}
440+ * of the object to determine if they can accept it or not, which, depending on the implementations,
441+ * can be an expensive operation; besides, the resulting codec cannot be cached.
442+ * Therefore there might be a performance penalty when using this method.
443+ * <p>
444+ * Codecs returned by this method <em>may</em> be cached.
445+ *
446+ * @param cqlType The {@link DataType CQL type} the codec should accept; must not be {@code null}.
447+ * @param value The value the codec should accept; must not be {@code null}.
448+ * @return A suitable codec.
449+ * @throws CodecNotFoundException if a suitable codec cannot be found.
450+ */
451+ public <T> TypeCodec<T> codecFor(DataType cqlType, T value) {
452+ checkNotNull(cqlType, "Parameter cqlType cannot be null");
453+ checkNotNull(value, "Parameter value cannot be null");
454+ return findCodec(cqlType, value);
455+ }
456+
457+ private <T> TypeCodec<T> lookupCache(DataType cqlType, TypeToken<T> javaType) {
458+ 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);
462+ try {
463+ return (TypeCodec<T>)cache.get(cacheKey);
464+ } catch (UncheckedExecutionException e) {
465+ if(e.getCause() instanceof CodecNotFoundException)
466+ throw (CodecNotFoundException)e.getCause();
467+ throw new CodecNotFoundException(e.getCause(), cqlType, javaType);
468+ } catch (ExecutionException e) {
469+ throw new CodecNotFoundException(e.getCause(), cqlType, javaType);
470+ }
471+ }
472+
473+ private <T> TypeCodec<T> findCodec(DataType cqlType, TypeToken<T> javaType) {
474+ 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);
477+ for (TypeCodec<?> codec : codecs) {
478+ if ((cqlType == null || codec.accepts(cqlType)) && (javaType == null || codec.accepts(javaType))) {
479+ if(logger.isTraceEnabled())
480+ logger.trace("Codec found: {}", codec);
481+ return (TypeCodec<T>)codec;
482+ }
483+ }
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;
499+ }
500+
501+ private <T> TypeCodec<T> findCodec(DataType cqlType, T value) {
502+ checkNotNull(value, "Parameter value cannot be null");
503+ if(logger.isTraceEnabled())
504+ logger.trace("Looking for codec [{} <-> {}]", cqlType == null ? "ANY" : cqlType, value.getClass());
505+ for (TypeCodec<?> codec : codecs) {
506+ if ((cqlType == null || codec.accepts(cqlType)) && codec.accepts(value)) {
507+ if(logger.isTraceEnabled())
508+ logger.trace("Codec found: {}", codec);
509+ return (TypeCodec<T>)codec;
510+ }
511+ }
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.
515+ TypeCodec<T> codec = maybeCreateCodec(cqlType, value);
516+ if(codec == null)
517+ throw logErrorAndThrow(cqlType, TypeToken.of(value.getClass()));
518+ // double-check that the created codec satisfies the initial request
519+ 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);
525+ return codec;
526+ }
527+
528+ private <T> TypeCodec<T> maybeCreateCodec(DataType cqlType, TypeToken<T> javaType) {
529+ if(immutable)
530+ return null;
531+ checkNotNull(cqlType);
532+
533+ if ((cqlType.getName() == VARCHAR || cqlType.getName() == TEXT) && javaType != null && Enum.class.isAssignableFrom(javaType.getRawType())) {
534+ return new EnumStringCodec(javaType.getRawType());
535+ }
536+
537+ if (cqlType.getName() == LIST && (javaType == null || List.class.isAssignableFrom(javaType.getRawType()))) {
538+ TypeToken<?> elementType = null;
539+ if (javaType != null && javaType.getType() instanceof ParameterizedType) {
540+ Type[] typeArguments = ((ParameterizedType)javaType.getType()).getActualTypeArguments();
541+ elementType = TypeToken.of(typeArguments[0]);
542+ }
543+ TypeCodec<?> eltCodec = findCodec(cqlType.getTypeArguments().get(0), elementType);
544+ return new ListCodec(eltCodec);
545+ }
546+
547+ if (cqlType.getName() == SET && (javaType == null || Set.class.isAssignableFrom(javaType.getRawType()))) {
548+ TypeToken<?> elementType = null;
549+ if (javaType != null && javaType.getType() instanceof ParameterizedType) {
550+ Type[] typeArguments = ((ParameterizedType)javaType.getType()).getActualTypeArguments();
551+ elementType = TypeToken.of(typeArguments[0]);
552+ }
553+ TypeCodec<?> eltCodec = findCodec(cqlType.getTypeArguments().get(0), elementType);
554+ return new SetCodec(eltCodec);
555+ }
556+
557+ if (cqlType.getName() == MAP && (javaType == null || Map.class.isAssignableFrom(javaType.getRawType()))) {
558+ TypeToken<?> keyType = null;
559+ TypeToken<?> valueType = null;
560+ if (javaType != null && javaType.getType() instanceof ParameterizedType) {
561+ Type[] typeArguments = ((ParameterizedType)javaType.getType()).getActualTypeArguments();
562+ keyType = TypeToken.of(typeArguments[0]);
563+ valueType = TypeToken.of(typeArguments[1]);
564+ }
565+ TypeCodec<?> keyCodec = findCodec(cqlType.getTypeArguments().get(0), keyType);
566+ TypeCodec<?> valueCodec = findCodec(cqlType.getTypeArguments().get(1), valueType);
567+ return new MapCodec(keyCodec, valueCodec);
568+ }
569+
570+ if (cqlType instanceof TupleType && (javaType == null || TupleValue.class.isAssignableFrom(javaType.getRawType()))) {
571+ return (TypeCodec<T>)new TupleCodec((TupleType)cqlType);
572+ }
573+
574+ if (cqlType instanceof UserType && (javaType == null || UDTValue.class.isAssignableFrom(javaType.getRawType()))) {
575+ return (TypeCodec<T>)new UDTCodec((UserType)cqlType);
576+ }
577+
578+ return null;
579+ }
580+
581+ private <T> TypeCodec<T> maybeCreateCodec(DataType cqlType, T value) {
582+ if(immutable)
583+ return null;
584+ checkNotNull(value);
585+ if ((cqlType == null || cqlType.getName() == VARCHAR || cqlType.getName() == TEXT) && value instanceof Enum) {
586+ return new EnumStringCodec(value.getClass());
587+ }
588+
589+ if ((cqlType == null || cqlType.getName() == LIST) && value instanceof List) {
590+ List list = (List)value;
591+ if (list.isEmpty()) {
592+ DataType elementType = (cqlType == null || cqlType.getTypeArguments().isEmpty())
593+ ? DataType.blob()
594+ : cqlType.getTypeArguments().get(0);
595+ return new ListCodec(findCodec(elementType, (TypeToken)null));
596+ } else {
597+ DataType elementType = (cqlType == null || cqlType.getTypeArguments().isEmpty())
598+ ? null
599+ : cqlType.getTypeArguments().get(0);
600+ return new ListCodec(findCodec(elementType, list.iterator().next()));
601+ }
602+ }
603+
604+ if ((cqlType == null || cqlType.getName() == SET) && value instanceof Set) {
605+ Set set = (Set)value;
606+ if (set.isEmpty()) {
607+ DataType elementType = (cqlType == null || cqlType.getTypeArguments().isEmpty())
608+ ? DataType.blob()
609+ : cqlType.getTypeArguments().get(0);
610+ return new SetCodec(findCodec(elementType, (TypeToken)null));
611+ } else {
612+ DataType elementType = (cqlType == null || cqlType.getTypeArguments().isEmpty())
613+ ? null
614+ : cqlType.getTypeArguments().get(0);
615+ return new SetCodec(findCodec(elementType, set.iterator().next()));
616+ }
617+ }
618+
619+ if ((cqlType == null || cqlType.getName() == MAP) && value instanceof Map) {
620+ Map map = (Map)value;
621+ if (map.isEmpty()) {
622+ DataType keyType = (cqlType == null || cqlType.getTypeArguments().size() < 1)
623+ ? DataType.blob()
624+ : cqlType.getTypeArguments().get(0);
625+ DataType valueType = (cqlType == null || cqlType.getTypeArguments().size() < 2)
626+ ? DataType.blob() :
627+ cqlType.getTypeArguments().get(1);
628+ return new MapCodec(
629+ findCodec(keyType, (TypeToken)null),
630+ findCodec(valueType, (TypeToken)null));
631+ } else {
632+ DataType keyType = (cqlType == null || cqlType.getTypeArguments().size() < 1)
633+ ? null
634+ : cqlType.getTypeArguments().get(0);
635+ DataType valueType = (cqlType == null || cqlType.getTypeArguments().size() < 2)
636+ ? null
637+ : cqlType.getTypeArguments().get(1);
638+ Map.Entry entry = (Map.Entry)map.entrySet().iterator().next();
639+ return new MapCodec(
640+ findCodec(keyType, entry.getKey()),
641+ findCodec(valueType, entry.getValue()));
642+ }
643+ }
644+
645+ if ((cqlType == null || cqlType.getName() == DataType.Name.TUPLE) && value instanceof TupleValue) {
646+ return (TypeCodec<T>)new TupleCodec(cqlType == null ? ((TupleValue)value).getType() : (TupleType) cqlType);
647+ }
648+
649+ if ((cqlType == null || cqlType.getName() == DataType.Name.UDT) && value instanceof UDTValue) {
650+ return (TypeCodec<T>)new UDTCodec(cqlType == null ? ((UDTValue)value).getType() : (UserType) cqlType);
651+ }
652+
653+ return null;
654+ }
655+
656+ private static CodecNotFoundException logErrorAndThrow(DataType cqlType, TypeToken<?> javaType) {
657+ String msg = String.format("Codec not found for requested operation: [%s <-> %s]",
658+ cqlType == null ? "ANY" : cqlType,
659+ javaType == null ? "ANY" : javaType);
660+ logger.error(msg);
661+ return new CodecNotFoundException(msg, cqlType, javaType);
662+ }
663+
664+}
added driver-core/src/main/java/com/datastax/driver/core/CodecUtils.java +284 −0
@@ -0,0 +1,284 @@
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.nio.ByteBuffer;
19+import java.util.List;
20+import java.util.Map;
21+import java.util.Set;
22+
23+import com.google.common.reflect.TypeParameter;
24+import com.google.common.reflect.TypeToken;
25+
26+import com.datastax.driver.core.exceptions.InvalidTypeException;
27+
28+/**
29+ * A set of utility methods to deal with type conversion,
30+ * serialization, and to create {@link TypeToken} instances.
31+ * <p>
32+ * This class is public because it is accessed from {@link com.datastax.driver.core.querybuilder.BuiltStatement}
33+ * but its use by client code is not supported.
34+ */
35+public final class CodecUtils {
36+
37+ private CodecUtils(){}
38+
39+ public static <T> TypeToken<List<T>> listOf(Class<T> eltType) {
40+ return new TypeToken<List<T>>(){}.where(new TypeParameter<T>(){}, eltType);
41+ }
42+
43+ public static <T> TypeToken<List<T>> listOf(TypeToken<T> eltType) {
44+ return new TypeToken<List<T>>(){}.where(new TypeParameter<T>(){}, eltType);
45+ }
46+
47+ public static <T> TypeToken<Set<T>> setOf(Class<T> eltType) {
48+ return new TypeToken<Set<T>>(){}.where(new TypeParameter<T>(){}, eltType);
49+ }
50+
51+ public static <T> TypeToken<Set<T>> setOf(TypeToken<T> eltType) {
52+ return new TypeToken<Set<T>>(){}.where(new TypeParameter<T>(){}, eltType);
53+ }
54+
55+ public static <K, V> TypeToken<Map<K, V>> mapOf(Class<K> keyType, Class<V> valueType) {
56+ return new TypeToken<Map<K, V>>(){}
57+ .where(new TypeParameter<K>(){}, keyType)
58+ .where(new TypeParameter<V>(){}, valueType);
59+ }
60+
61+ public static <K, V> TypeToken<Map<K, V>> mapOf(TypeToken<K> keyType, TypeToken<V> valueType) {
62+ return new TypeToken<Map<K, V>>(){}
63+ .where(new TypeParameter<K>(){}, keyType)
64+ .where(new TypeParameter<V>(){}, valueType);
65+ }
66+
67+ /**
68+ * Utility method to serialize user-provided values.
69+ * <p>
70+ * This method is useful in situations where there is no metadata available and the underlying CQL
71+ * type for the values is not known.
72+ * <p>
73+ * This situation happens when a {@link SimpleStatement}
74+ * or a {@link com.datastax.driver.core.querybuilder.BuiltStatement} (Query Builder) contain values;
75+ * in these places, the driver has no way to determine the right CQL type to use.
76+ * <p>
77+ * This method performs a best-effort heuristic to guess which codec to use.
78+ * Note that this is not particularly efficient as the codec registry needs to iterate over
79+ * the registered codecs until it finds a suitable one.
80+ *
81+ * @param values The values to convert.
82+ * @param protocolVersion The protocol version to use.
83+ * @param codecRegistry The {@link CodecRegistry} to use.
84+ * @return The converted values.
85+ */
86+ public static ByteBuffer[] convert(Object[] values, ProtocolVersion protocolVersion, CodecRegistry codecRegistry) {
87+ ByteBuffer[] serializedValues = new ByteBuffer[values.length];
88+ for (int i = 0; i < values.length; i++) {
89+ Object value = values[i];
90+ if (value == null) {
91+ // impossible to locate the right codec when object is null,
92+ // so forcing the result to null
93+ serializedValues[i] = null;
94+ } else {
95+ if (value instanceof Token) {
96+ // bypass CodecRegistry for Token instances
97+ serializedValues[i] = ((Token)value).serialize(protocolVersion);
98+ } else {
99+ try {
100+ TypeCodec<Object> codec = codecRegistry.codecFor(value);
101+ serializedValues[i] = codec.serialize(value, protocolVersion);
102+ } catch (Exception e) {
103+ // Catch and rethrow to provide a more helpful error message (one that include which value is bad)
104+ throw new InvalidTypeException(String.format("Value %d of type %s does not correspond to any CQL3 type", i, value.getClass()), e);
105+ }
106+ }
107+ }
108+ }
109+ return serializedValues;
110+ }
111+
112+ /**
113+ * Utility method to assemble different routing key components into a single {@link ByteBuffer}.
114+ * Mainly intended for statements that need to generate a routing key out of their current values.
115+ *
116+ * @param buffers the components of the routing key.
117+ * @return A ByteBuffer containing the serialized routing key
118+ */
119+ public static ByteBuffer compose(ByteBuffer... buffers) {
120+ if (buffers.length == 1)
121+ return buffers[0];
122+
123+ int totalLength = 0;
124+ for (ByteBuffer bb : buffers)
125+ totalLength += 2 + bb.remaining() + 1;
126+
127+ ByteBuffer out = ByteBuffer.allocate(totalLength);
128+ for (ByteBuffer buffer : buffers) {
129+ ByteBuffer bb = buffer.duplicate();
130+ putShortLength(out, bb.remaining());
131+ out.put(bb);
132+ out.put((byte)0);
133+ }
134+ out.flip();
135+ return out;
136+ }
137+
138+ private static void putShortLength(ByteBuffer bb, int length) {
139+ bb.put((byte)((length >> 8) & 0xFF));
140+ bb.put((byte)(length & 0xFF));
141+ }
142+
143+ /**
144+ * Utility method that "packs" together a list of {@link ByteBuffer}s containing
145+ * serialized collection elements.
146+ * Mainly intended for use with collection codecs when serializing collections.
147+ *
148+ * @param buffers the collection elements
149+ * @param elements the total number of elements
150+ * @param version the protocol version to use
151+ * @return The serialized collection
152+ */
153+ public static ByteBuffer pack(List<ByteBuffer> buffers, int elements, ProtocolVersion version) {
154+ int size = 0;
155+ for (ByteBuffer bb : buffers) {
156+ int elemSize = sizeOfValue(bb, version);
157+ size += elemSize;
158+ }
159+ ByteBuffer result = ByteBuffer.allocate(sizeOfCollectionSize(version) + size);
160+ writeCollectionSize(result, elements, version);
161+ for (ByteBuffer bb : buffers)
162+ writeCollectionValue(result, bb, version);
163+ return (ByteBuffer)result.flip();
164+ }
165+
166+ /**
167+ * Utility method that reads the collection size.
168+ * Mainly intended for collection codecs when deserializing CQL collections.
169+ * @param input
170+ * @param version
171+ * @return
172+ */
173+ public static int readCollectionSize(ByteBuffer input, ProtocolVersion version) {
174+ switch (version) {
175+ case V1:
176+ case V2:
177+ return getUnsignedShort(input);
178+ case V3:
179+ case V4:
180+ return input.getInt();
181+ default:
182+ throw version.unsupported();
183+ }
184+ }
185+
186+ public static ByteBuffer readBytes(ByteBuffer bb, int length) {
187+ ByteBuffer copy = bb.duplicate();
188+ copy.limit(copy.position() + length);
189+ bb.position(bb.position() + length);
190+ return copy;
191+ }
192+
193+ public static ByteBuffer readCollectionValue(ByteBuffer input, ProtocolVersion version) {
194+ int size;
195+ switch (version) {
196+ case V1:
197+ case V2:
198+ size = getUnsignedShort(input);
199+ break;
200+ case V3:
201+ case V4:
202+ size = input.getInt();
203+ break;
204+ default:
205+ throw version.unsupported();
206+ }
207+ return size < 0 ? null : readBytes(input, size);
208+ }
209+
210+
211+ private static void writeCollectionSize(ByteBuffer output, int elements, ProtocolVersion version) {
212+ switch (version) {
213+ case V1:
214+ case V2:
215+ if (elements > 65535)
216+ throw new IllegalArgumentException(String.format("Native protocol version %d supports up to 65535 elements in any collection - but collection contains %d elements", version.toInt(), elements));
217+ output.putShort((short)elements);
218+ break;
219+ case V3:
220+ case V4:
221+ output.putInt(elements);
222+ break;
223+ default:
224+ throw version.unsupported();
225+ }
226+ }
227+
228+ private static int sizeOfCollectionSize(ProtocolVersion version) {
229+ switch (version) {
230+ case V1:
231+ case V2:
232+ return 2;
233+ case V3:
234+ case V4:
235+ return 4;
236+ default:
237+ throw version.unsupported();
238+ }
239+ }
240+
241+ private static void writeCollectionValue(ByteBuffer output, ByteBuffer value, ProtocolVersion version) {
242+ switch (version) {
243+ case V1:
244+ case V2:
245+ assert value != null;
246+ output.putShort((short)value.remaining());
247+ output.put(value.duplicate());
248+ break;
249+ case V3:
250+ case V4:
251+ if (value == null) {
252+ output.putInt(-1);
253+ } else {
254+ output.putInt(value.remaining());
255+ output.put(value.duplicate());
256+ }
257+ break;
258+ default:
259+ throw version.unsupported();
260+ }
261+ }
262+
263+ private static int sizeOfValue(ByteBuffer value, ProtocolVersion version) {
264+ switch (version) {
265+ case V1:
266+ case V2:
267+ int elemSize = value.remaining();
268+ if (elemSize > 65535)
269+ throw new IllegalArgumentException(String.format("Native protocol version %d supports only elements with size up to 65535 bytes - but element size is %d bytes", version.toInt(), elemSize));
270+ return 2 + elemSize;
271+ case V3:
272+ case V4:
273+ return value == null ? 4 : 4 + value.remaining();
274+ default:
275+ throw version.unsupported();
276+ }
277+ }
278+
279+ private static int getUnsignedShort(ByteBuffer bb) {
280+ int length = (bb.get() & 0xFF) << 8;
281+ return length | (bb.get() & 0xFF);
282+ }
283+
284+}
modified driver-core/src/main/java/com/datastax/driver/core/ColumnDefinitions.java +27 −26
@@ -17,8 +17,6 @@
1717
1818 import java.util.*;
1919
20-import com.datastax.driver.core.exceptions.InvalidTypeException;
21-
2220 /**
2321 * Metadata describing the columns returned in a {@link ResultSet} or a
2422 * {@link PreparedStatement}.
@@ -61,6 +59,7 @@
6159
6260 private final Definition[] byIdx;
6361 private final Map<String, int[]> byName;
62+ private volatile CodecRegistry codecRegistry;
6463
6564 ColumnDefinitions(Definition[] defs) {
6665
@@ -279,32 +278,34 @@
279278 return getAllIdx(name)[0];
280279 }
281280
282- void checkBounds(int i) {
283- if (i < 0 || i >= size())
284- throw new ArrayIndexOutOfBoundsException(i);
285- }
286-
287- // Note: we avoid having a vararg method to avoid the array allocation that comes with it.
288- void checkType(int i, DataType.Name name) {
289- DataType defined = getType(i);
290- if (name != defined.getName())
291- throw new InvalidTypeException(String.format("Column %s is of type %s", getName(i), defined));
292- }
293-
294- DataType.Name checkType(int i, DataType.Name name1, DataType.Name name2) {
295- DataType defined = getType(i);
296- if (name1 != defined.getName() && name2 != defined.getName())
297- throw new InvalidTypeException(String.format("Column %s is of type %s", getName(i), defined));
298-
299- return defined.getName();
281+ CodecRegistry getCodecRegistry() {
282+ // this method should only be called after this field is set
283+ assert codecRegistry != null;
284+ return codecRegistry;
300285 }
301286
302- DataType.Name checkType(int i, DataType.Name name1, DataType.Name name2, DataType.Name name3) {
303- DataType defined = getType(i);
304- if (name1 != defined.getName() && name2 != defined.getName() && name3 != defined.getName())
305- throw new InvalidTypeException(String.format("Column %s is of type %s", getName(i), defined));
306-
307- return defined.getName();
287+ void setCodecRegistry(CodecRegistry codecRegistry) {
288+ for (Definition definition : byIdx) {
289+ setCodecRegistry(definition.type, codecRegistry);
290+ }
291+ this.codecRegistry = codecRegistry;
292+ }
293+
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+ }
308309 }
309310
310311 /**
modified driver-core/src/main/java/com/datastax/driver/core/ColumnMetadata.java +4 −4
@@ -190,7 +190,7 @@
190190 */
191191 return !isKeys()
192192 && !isEntries()
193- && column.getType().isCollection()
193+ && column.getType() instanceof DataType.CollectionType
194194 && column.getType().isFrozen();
195195 }
196196
@@ -299,6 +299,7 @@
299299 // Temporary class that is used to make building the schema easier. Not meant to be
300300 // exposed publicly at all.
301301 static class Raw {
302+
302303 public enum Kind { PARTITION_KEY, CLUSTERING_KEY, REGULAR, COMPACT_VALUE, STATIC }
303304
304305 public final String name;
@@ -317,7 +318,7 @@
317318 this.isReversed = isReversed;
318319 }
319320
320- static Raw fromRow(Row row, VersionNumber version) {
321+ static Raw fromRow(Row row, VersionNumber version, ProtocolVersion protocolVersion, CodecRegistry codecRegistry) {
321322
322323 String name = row.getString(COLUMN_NAME);
323324 Kind kind = version.getMajor() < 2 || row.isNull(KIND)
@@ -326,8 +327,7 @@
326327 int componentIndex = row.isNull(COMPONENT_INDEX) ? 0 : row.getInt(COMPONENT_INDEX);
327328 String validatorStr = row.getString(VALIDATOR);
328329 boolean reversed = CassandraTypeParser.isReversed(validatorStr);
329- DataType dataType = CassandraTypeParser.parseOne(validatorStr);
330-
330+ DataType dataType = CassandraTypeParser.parseOne(validatorStr, protocolVersion, codecRegistry);
331331 Raw c = new Raw(name, kind, componentIndex, dataType, reversed);
332332
333333 for (String str : Arrays.asList(INDEX_TYPE, INDEX_NAME, INDEX_OPTIONS))
modified driver-core/src/main/java/com/datastax/driver/core/Configuration.java +135 −27
@@ -33,46 +33,32 @@
3333 */
3434 public class Configuration {
3535
36- private final Policies policies;
36+ /**
37+ * Returns a builder to create a new {@code Configuration} object.
38+ *
39+ * @return the builder.
40+ */
41+ public static Builder builder() {
42+ return new Builder();
43+ }
3744
45+ private final Policies policies;
3846 private final ProtocolOptions protocolOptions;
3947 private final PoolingOptions poolingOptions;
4048 private final SocketOptions socketOptions;
4149 private final MetricsOptions metricsOptions;
4250 private final QueryOptions queryOptions;
4351 private final NettyOptions nettyOptions;
52+ private final CodecRegistry codecRegistry;
4453
45- /*
46- * Creates a configuration object.
47- */
48- public Configuration() {
49- this(Policies.builder().build(),
50- new ProtocolOptions(),
51- new PoolingOptions(),
52- new SocketOptions(),
53- new MetricsOptions(),
54- new QueryOptions(),
55- NettyOptions.DEFAULT_INSTANCE);
56- }
57-
58- /**
59- * Creates a configuration with the specified parameters.
60- *
61- * @param policies the policies to use
62- * @param protocolOptions the protocol options to use
63- * @param poolingOptions the pooling options to use
64- * @param socketOptions the socket options to use
65- * @param metricsOptions the metrics options, or null to disable metrics.
66- * @param queryOptions defaults related to queries.
67- * @param nettyOptions the {@link NettyOptions} instance to use
68- */
69- public Configuration(Policies policies,
54+ private Configuration(Policies policies,
7055 ProtocolOptions protocolOptions,
7156 PoolingOptions poolingOptions,
7257 SocketOptions socketOptions,
7358 MetricsOptions metricsOptions,
7459 QueryOptions queryOptions,
75- NettyOptions nettyOptions) {
60+ NettyOptions nettyOptions,
61+ CodecRegistry codecRegistry) {
7662 this.policies = policies;
7763 this.protocolOptions = protocolOptions;
7864 this.poolingOptions = poolingOptions;
@@ -80,6 +66,7 @@
8066 this.metricsOptions = metricsOptions;
8167 this.queryOptions = queryOptions;
8268 this.nettyOptions = nettyOptions;
69+ this.codecRegistry = codecRegistry;
8370 }
8471
8572 void register(Cluster.Manager manager) {
@@ -152,4 +139,125 @@
152139 public NettyOptions getNettyOptions() {
153140 return nettyOptions;
154141 }
142+
143+ /**
144+ * Returns the {@link CodecRegistry} instance for this configuration.
145+ * @return the {@link CodecRegistry} instance for this configuration.
146+ */
147+ public CodecRegistry getCodecRegistry() {
148+ return codecRegistry;
149+ }
150+
151+ /**
152+ * A builder to create a new {@code Configuration} object.
153+ */
154+ public static class Builder {
155+ private Policies policies;
156+ private ProtocolOptions protocolOptions;
157+ private PoolingOptions poolingOptions;
158+ private SocketOptions socketOptions;
159+ private MetricsOptions metricsOptions;
160+ private QueryOptions queryOptions;
161+ private NettyOptions nettyOptions;
162+ private CodecRegistry codecRegistry;
163+
164+ /**
165+ * Sets the policies for this cluster.
166+ * @param policies the policies.
167+ * @return this builder.
168+ */
169+ public Builder withPolicies(Policies policies) {
170+ this.policies = policies;
171+ return this;
172+ }
173+
174+ /**
175+ * Sets the protocol options for this cluster.
176+ * @param protocolOptions the protocol options.
177+ * @return this builder.
178+ */
179+ public Builder withProtocolOptions(ProtocolOptions protocolOptions) {
180+ this.protocolOptions = protocolOptions;
181+ return this;
182+ }
183+
184+ /**
185+ * Sets the pooling options for this cluster.
186+ * @param poolingOptions the pooling options.
187+ * @return this builder.
188+ */
189+ public Builder withPoolingOptions(PoolingOptions poolingOptions) {
190+ this.poolingOptions = poolingOptions;
191+ return this;
192+ }
193+
194+ /**
195+ * Sets the socket options for this cluster.
196+ * @param socketOptions the socket options.
197+ * @return this builder.
198+ */
199+ public Builder withSocketOptions(SocketOptions socketOptions) {
200+ this.socketOptions = socketOptions;
201+ return this;
202+ }
203+
204+ /**
205+ * Sets the metrics options for this cluster.
206+ * @param metricsOptions the metrics options.
207+ * @return this builder.
208+ */
209+ public Builder withMetricsOptions(MetricsOptions metricsOptions) {
210+ this.metricsOptions = metricsOptions;
211+ return this;
212+ }
213+
214+ /**
215+ * Sets the query options for this cluster.
216+ * @param queryOptions the query options.
217+ * @return this builder.
218+ */
219+ public Builder withQueryOptions(QueryOptions queryOptions) {
220+ this.queryOptions = queryOptions;
221+ return this;
222+ }
223+
224+ /**
225+ * Sets the Netty options for this cluster.
226+ * @param nettyOptions the Netty options.
227+ * @return this builder.
228+ */
229+ public Builder withNettyOptions(NettyOptions nettyOptions) {
230+ this.nettyOptions = nettyOptions;
231+ return this;
232+ }
233+
234+ /**
235+ * Sets the codec registry for this cluster.
236+ * @param codecRegistry the codec registry.
237+ * @return this builder.
238+ */
239+ public Builder withCodecRegistry(CodecRegistry codecRegistry) {
240+ this.codecRegistry = codecRegistry;
241+ return this;
242+ }
243+
244+ /**
245+ * Builds the final object from this builder.
246+ * <p>
247+ * Any field that hasn't been set explicitly will get its default value.
248+ *
249+ * @return the object.
250+ */
251+ public Configuration build() {
252+ return new Configuration(
253+ policies != null ? policies : Policies.builder().build(),
254+ protocolOptions != null ? protocolOptions : new ProtocolOptions(),
255+ poolingOptions != null ? poolingOptions : new PoolingOptions(),
256+ socketOptions != null ? socketOptions : new SocketOptions(),
257+ metricsOptions != null ? metricsOptions : new MetricsOptions(),
258+ queryOptions != null ? queryOptions : new QueryOptions(),
259+ nettyOptions != null ? nettyOptions : NettyOptions.DEFAULT_INSTANCE,
260+ codecRegistry != null ? codecRegistry : new CodecRegistry());
261+ }
262+ }
155263 }
modified driver-core/src/main/java/com/datastax/driver/core/ControlConnection.java +4 −2
@@ -38,6 +38,8 @@
3838
3939 private static final Logger logger = LoggerFactory.getLogger(ControlConnection.class);
4040
41+ private static final TypeCodec.ListCodec<String> LIST_OF_TEXT_CODEC = new TypeCodec.ListCodec<String>(TypeCodec.VarcharCodec.instance);
42+
4143 private static final InetAddress bindAllAddress;
4244 static
4345 {
@@ -335,9 +337,9 @@
335337 else if (targetType == TYPE)
336338 whereClause += " AND type_name = '" + targetName + '\'';
337339 else if (targetType == FUNCTION)
338- whereClause += " AND function_name = '" + targetName + "' AND signature = " + DataType.LIST_OF_TEXT.format(targetSignature);
340+ whereClause += " AND function_name = '" + targetName + "' AND signature = " + LIST_OF_TEXT_CODEC.format(targetSignature);
339341 else if (targetType == AGGREGATE)
340- whereClause += " AND aggregate_name = '" + targetName + "' AND signature = " + DataType.LIST_OF_TEXT.format(targetSignature);
342+ whereClause += " AND aggregate_name = '" + targetName + "' AND signature = " + LIST_OF_TEXT_CODEC.format(targetSignature);
341343 }
342344
343345 boolean isSchemaOrKeyspace = (targetType == null || targetType == KEYSPACE);
modified driver-core/src/main/java/com/datastax/driver/core/DataType.java +116 −374
@@ -15,10 +15,6 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.math.BigDecimal;
19-import java.math.BigInteger;
20-import java.net.InetAddress;
21-import java.nio.ByteBuffer;
2218 import java.util.*;
2319
2420 import com.google.common.base.Objects;
@@ -26,11 +22,9 @@
2622 import com.google.common.collect.ImmutableList;
2723 import com.google.common.collect.ImmutableSet;
2824 import com.google.common.collect.Sets;
29-import com.google.common.reflect.TypeToken;
3025 import io.netty.buffer.ByteBuf;
3126
3227 import com.datastax.driver.core.exceptions.DriverInternalError;
33-import com.datastax.driver.core.exceptions.InvalidTypeException;
3428
3529 /**
3630 * Data types supported by cassandra.
@@ -42,35 +36,44 @@
4236 */
4337 public enum Name {
4438
45- ASCII (1, String.class),
46- BIGINT (2, Long.class),
47- BLOB (3, ByteBuffer.class),
48- BOOLEAN (4, Boolean.class),
49- COUNTER (5, Long.class),
50- DECIMAL (6, BigDecimal.class),
51- DOUBLE (7, Double.class),
52- FLOAT (8, Float.class),
53- INET (16, InetAddress.class),
54- INT (9, Integer.class),
55- TEXT (10, String.class),
56- TIMESTAMP (11, Date.class),
57- UUID (12, UUID.class),
58- VARCHAR (13, String.class),
59- VARINT (14, BigInteger.class),
60- TIMEUUID (15, UUID.class),
61- LIST (32, List.class),
62- SET (34, Set.class),
63- MAP (33, Map.class),
64- UDT (48, UDTValue.class, ProtocolVersion.V3),
65- TUPLE (49, TupleValue.class, ProtocolVersion.V3),
66- CUSTOM (0, ByteBuffer.class),
67- DATE (17, LocalDate.class, ProtocolVersion.V4),
68- TIME (18, Long.class, ProtocolVersion.V4),
69- SMALLINT (19, Short.class, ProtocolVersion.V4),
70- TINYINT (20, Byte.class, ProtocolVersion.V4);
39+ ASCII (1),
40+ BIGINT (2),
41+ BLOB (3),
42+ BOOLEAN (4),
43+ COUNTER (5),
44+ DECIMAL (6),
45+ DOUBLE (7),
46+ FLOAT (8),
47+ INET (16),
48+ INT (9),
49+ TEXT (10){
50+ public boolean isCompatibleWith(Name that) {
51+ return this == that || that == VARCHAR;
52+ }
53+ },
54+ TIMESTAMP (11),
55+ UUID (12),
56+ VARCHAR (13){
57+ public boolean isCompatibleWith(Name that) {
58+ return this == that || that == TEXT;
59+ }
60+ },
61+ VARINT (14),
62+ TIMEUUID (15),
63+ LIST (32),
64+ SET (34),
65+ MAP (33),
66+ CUSTOM (0),
67+ UDT (48, ProtocolVersion.V3),
68+ TUPLE (49, ProtocolVersion.V3),
69+ SMALLINT (19, ProtocolVersion.V4),
70+ TINYINT (20, ProtocolVersion.V4),
71+ DATE (17, ProtocolVersion.V4),
72+ TIME (18, ProtocolVersion.V4)
73+ ;
7174
7275 final int protocolId;
73- final Class<?> javaType;
76+
7477 final ProtocolVersion minProtocolVersion;
7578
7679 private static final Name[] nameToIds;
@@ -86,15 +89,12 @@
8689 }
8790 }
8891
89- private Name(int protocolId, Class<?> javaType) {
90- this.protocolId = protocolId;
91- this.javaType = javaType;
92- this.minProtocolVersion = ProtocolVersion.V1;
92+ private Name(int protocolId) {
93+ this(protocolId, ProtocolVersion.V1);
9394 }
9495
95- private Name(int protocolId, Class<?> javaType, ProtocolVersion minProtocolVersion) {
96+ private Name(int protocolId, ProtocolVersion minProtocolVersion) {
9697 this.protocolId = protocolId;
97- this.javaType = javaType;
9898 this.minProtocolVersion = minProtocolVersion;
9999 }
100100
@@ -106,59 +106,15 @@
106106 }
107107
108108 /**
109- * Returns whether this data type name represent the name of a collection type
110- * that is a list, set or map.
111- *
112- * @return whether this data type name represent the name of a collection type.
113- */
114- public boolean isCollection() {
115- switch (this) {
116- case LIST:
117- case SET:
118- case MAP:
119- return true;
120- default:
121- return false;
122- }
123- }
124-
125- /**
126- * Returns the Java Class corresponding to this CQL type name.
109+ * Return {@code true} if the provided Name is equal to this one,
110+ * or if they are aliases for each other, and {@code false} otherwise.
127111 *
128- * The correspondence between CQL types and java ones is as follow:
129- * <table>
130- * <caption>DataType to Java class correspondence</caption>
131- * <tr><th>DataType (CQL)</th><th>Java Class</th></tr>
132- * <tr><td>ASCII </td><td>String</td></tr>
133- * <tr><td>BIGINT </td><td>Long</td></tr>
134- * <tr><td>BLOB </td><td>ByteBuffer</td></tr>
135- * <tr><td>BOOLEAN </td><td>Boolean</td></tr>
136- * <tr><td>COUNTER </td><td>Long</td></tr>
137- * <tr><td>CUSTOM </td><td>ByteBuffer</td></tr>
138- * <tr><td>DECIMAL </td><td>BigDecimal</td></tr>
139- * <tr><td>DOUBLE </td><td>Double</td></tr>
140- * <tr><td>FLOAT </td><td>Float</td></tr>
141- * <tr><td>INET </td><td>InetAddress</td></tr>
142- * <tr><td>TINYINT </td><td>Byte</td></tr>
143- * <tr><td>SMALLINT </td><td>Short</td></tr>
144- * <tr><td>INT </td><td>Integer</td></tr>
145- * <tr><td>LIST </td><td>List</td></tr>
146- * <tr><td>MAP </td><td>Map</td></tr>
147- * <tr><td>SET </td><td>Set</td></tr>
148- * <tr><td>TEXT </td><td>String</td></tr>
149- * <tr><td>TIMESTAMP </td><td>Date</td></tr>
150- * <tr><td>UUID </td><td>UUID</td></tr>
151- * <tr><td>UDT </td><td>UDTValue</td></tr>
152- * <tr><td>TUPLE </td><td>TupleValue</td></tr>
153- * <tr><td>VARCHAR </td><td>String</td></tr>
154- * <tr><td>VARINT </td><td>BigInteger</td></tr>
155- * <tr><td>TIMEUUID </td><td>UUID</td></tr>
156- * </table>
157- *
158- * @return the java Class corresponding to this CQL type name.
112+ * @param that the Name to compare with the current one.
113+ * @return {@code true} if the provided Name is equal to this one,
114+ * or if they are aliases for each other, and {@code false} otherwise.
159115 */
160- public Class<?> asJavaClass() {
161- return javaType;
116+ public boolean isCompatibleWith(Name that) {
117+ return this == that;
162118 }
163119
164120 @Override
@@ -167,38 +123,53 @@
167123 }
168124 }
169125
170- protected final DataType.Name name;
171-
172126 private static final Map<Name, DataType> primitiveTypeMap = new EnumMap<Name, DataType>(Name.class);
173127 static {
174- for (Name name : Name.values()) {
175- if (!name.isCollection() && name != Name.CUSTOM && name != Name.UDT && name != Name.TUPLE)
176- primitiveTypeMap.put(name, new DataType.Native(name));
177- }
128+ primitiveTypeMap.put(Name.ASCII, new DataType.NativeType(Name.ASCII));
129+ primitiveTypeMap.put(Name.BIGINT, new DataType.NativeType(Name.BIGINT));
130+ primitiveTypeMap.put(Name.BLOB, new DataType.NativeType(Name.BLOB));
131+ primitiveTypeMap.put(Name.BOOLEAN, new DataType.NativeType(Name.BOOLEAN));
132+ primitiveTypeMap.put(Name.COUNTER, new DataType.NativeType(Name.COUNTER));
133+ primitiveTypeMap.put(Name.DECIMAL, new DataType.NativeType(Name.DECIMAL));
134+ primitiveTypeMap.put(Name.DOUBLE, new DataType.NativeType(Name.DOUBLE));
135+ primitiveTypeMap.put(Name.FLOAT, new DataType.NativeType(Name.FLOAT));
136+ primitiveTypeMap.put(Name.INET, new DataType.NativeType(Name.INET));
137+ primitiveTypeMap.put(Name.INT, new DataType.NativeType(Name.INT));
138+ primitiveTypeMap.put(Name.TEXT, new DataType.NativeType(Name.TEXT));
139+ primitiveTypeMap.put(Name.TIMESTAMP, new DataType.NativeType(Name.TIMESTAMP));
140+ primitiveTypeMap.put(Name.UUID, new DataType.NativeType(Name.UUID));
141+ primitiveTypeMap.put(Name.VARCHAR, new DataType.NativeType(Name.VARCHAR));
142+ primitiveTypeMap.put(Name.VARINT, new DataType.NativeType(Name.VARINT));
143+ primitiveTypeMap.put(Name.TIMEUUID, new DataType.NativeType(Name.TIMEUUID));
144+ primitiveTypeMap.put(Name.SMALLINT, new DataType.NativeType(Name.SMALLINT));
145+ primitiveTypeMap.put(Name.TINYINT, new DataType.NativeType(Name.TINYINT));
146+ primitiveTypeMap.put(Name.DATE, new DataType.NativeType(Name.DATE));
147+ primitiveTypeMap.put(Name.TIME, new DataType.NativeType(Name.TIME));
178148 }
149+
179150 private static final Set<DataType> primitiveTypeSet = ImmutableSet.copyOf(primitiveTypeMap.values());
180151
181- static final DataType LIST_OF_TEXT = DataType.list(DataType.text());
152+ protected final DataType.Name name;
182153
183154 protected DataType(DataType.Name name) {
184155 this.name = name;
185156 }
186157
187- static DataType decode(ByteBuf buffer) {
158+ static DataType decode(ByteBuf buffer, ProtocolVersion protocolVersion, CodecRegistry codecRegistry) {
188159 Name name = Name.fromProtocolId(buffer.readUnsignedShort());
189160 switch (name) {
190161 case CUSTOM:
191162 String className = CBUtil.readString(buffer);
192163 return CassandraTypeParser.isUserType(className) || CassandraTypeParser.isTupleType(className)
193- ? CassandraTypeParser.parseOne(className)
164+ ? CassandraTypeParser.parseOne(className, protocolVersion, codecRegistry)
194165 : custom(className);
195166 case LIST:
196- return list(decode(buffer));
167+ return list(decode(buffer, protocolVersion, codecRegistry));
197168 case SET:
198- return set(decode(buffer));
169+ return set(decode(buffer, protocolVersion, codecRegistry));
199170 case MAP:
200- DataType keys = decode(buffer);
201- DataType values = decode(buffer);
171+ DataType keys = decode(buffer, protocolVersion, codecRegistry);
172+ DataType values = decode(buffer, protocolVersion, codecRegistry);
202173 return map(keys, values);
203174 case UDT:
204175 String keyspace = CBUtil.readString(buffer);
@@ -207,24 +178,22 @@
207178 List<UserType.Field> fields = new ArrayList<UserType.Field>(nFields);
208179 for (int i = 0; i < nFields; i++) {
209180 String fieldName = CBUtil.readString(buffer);
210- DataType fieldType = decode(buffer);
181+ DataType fieldType = decode(buffer, protocolVersion, codecRegistry);
211182 fields.add(new UserType.Field(fieldName, fieldType));
212183 }
213- return new UserType(keyspace, type, fields);
184+ return new UserType(keyspace, type, fields, protocolVersion, codecRegistry);
214185 case TUPLE:
215186 nFields = buffer.readShort() & 0xffff;
216187 List<DataType> types = new ArrayList<DataType>(nFields);
217188 for (int i = 0; i < nFields; i++) {
218- types.add(decode(buffer));
189+ types.add(decode(buffer, protocolVersion, codecRegistry));
219190 }
220- return new TupleType(types);
191+ return new TupleType(types, protocolVersion, codecRegistry);
221192 default:
222193 return primitiveTypeMap.get(name);
223194 }
224195 }
225196
226- abstract TypeCodec<Object> codec(ProtocolVersion protocolVersion);
227-
228197 /**
229198 * Returns the ASCII type.
230199 *
@@ -412,8 +381,8 @@
412381 * @param frozen whether the list is frozen.
413382 * @return the type of lists of {@code elementType} elements.
414383 */
415- public static DataType list(DataType elementType, boolean frozen) {
416- return new DataType.Collection(Name.LIST, ImmutableList.of(elementType), frozen);
384+ public static CollectionType list(DataType elementType, boolean frozen) {
385+ return new DataType.CollectionType(Name.LIST, ImmutableList.of(elementType), frozen);
417386 }
418387
419388 /**
@@ -424,7 +393,7 @@
424393 * @param elementType the type of the list elements.
425394 * @return the type of "not frozen" lists of {@code elementType} elements.
426395 */
427- public static DataType list(DataType elementType) {
396+ public static CollectionType list(DataType elementType) {
428397 return list(elementType, false);
429398 }
430399
@@ -436,7 +405,7 @@
436405 * @param elementType the type of the list elements.
437406 * @return the type of frozen lists of {@code elementType} elements.
438407 */
439- public static DataType frozenList(DataType elementType) {
408+ public static CollectionType frozenList(DataType elementType) {
440409 return list(elementType, true);
441410 }
442411
@@ -447,8 +416,8 @@
447416 * @param frozen whether the set is frozen.
448417 * @return the type of sets of {@code elementType} elements.
449418 */
450- public static DataType set(DataType elementType, boolean frozen) {
451- return new DataType.Collection(Name.SET, ImmutableList.of(elementType), frozen);
419+ public static CollectionType set(DataType elementType, boolean frozen) {
420+ return new DataType.CollectionType(Name.SET, ImmutableList.of(elementType), frozen);
452421 }
453422
454423 /**
@@ -459,7 +428,7 @@
459428 * @param elementType the type of the set elements.
460429 * @return the type of "not frozen" sets of {@code elementType} elements.
461430 */
462- public static DataType set(DataType elementType) {
431+ public static CollectionType set(DataType elementType) {
463432 return set(elementType, false);
464433 }
465434
@@ -471,7 +440,7 @@
471440 * @param elementType the type of the set elements.
472441 * @return the type of frozen sets of {@code elementType} elements.
473442 */
474- public static DataType frozenSet(DataType elementType) {
443+ public static CollectionType frozenSet(DataType elementType) {
475444 return set(elementType, true);
476445 }
477446
@@ -483,8 +452,8 @@
483452 * @param frozen whether the map is frozen.
484453 * @return the type of maps of {@code keyType} to {@code valueType} elements.
485454 */
486- public static DataType map(DataType keyType, DataType valueType, boolean frozen) {
487- return new DataType.Collection(Name.MAP, ImmutableList.of(keyType, valueType), frozen);
455+ public static CollectionType map(DataType keyType, DataType valueType, boolean frozen) {
456+ return new DataType.CollectionType(Name.MAP, ImmutableList.of(keyType, valueType), frozen);
488457 }
489458
490459 /**
@@ -496,7 +465,7 @@
496465 * @param valueType the type of the map values.
497466 * @return the type of "not frozen" maps of {@code keyType} to {@code valueType} elements.
498467 */
499- public static DataType map(DataType keyType, DataType valueType) {
468+ public static CollectionType map(DataType keyType, DataType valueType) {
500469 return map(keyType, valueType, false);
501470 }
502471
@@ -509,7 +478,7 @@
509478 * @param valueType the type of the map values.
510479 * @return the type of frozen maps of {@code keyType} to {@code valueType} elements.
511480 */
512- public static DataType frozenMap(DataType keyType, DataType valueType) {
481+ public static CollectionType frozenMap(DataType keyType, DataType valueType) {
513482 return map(keyType, valueType, true);
514483 }
515484
@@ -518,9 +487,7 @@
518487 * <p>
519488 * A custom type is defined by the name of the class used on the Cassandra
520489 * side to implement it. Note that the support for custom type by the
521- * driver is limited: values of a custom type won't be interpreted by the
522- * driver in any way. They will thus have to be set (by {@link BoundStatement#setBytesUnsafe}
523- * and retrieved (by {@link Row#getBytesUnsafe}) as raw ByteBuffer.
490+ * driver is limited.
524491 * <p>
525492 * The use of custom types is rarely useful and is thus not encouraged.
526493 *
@@ -530,7 +497,7 @@
530497 public static DataType custom(String typeClassName) {
531498 if (typeClassName == null)
532499 throw new NullPointerException();
533- return new DataType.Custom(Name.CUSTOM, typeClassName);
500+ return new DataType.CustomType(Name.CUSTOM, typeClassName);
534501 }
535502
536503 /**
@@ -552,6 +519,16 @@
552519 */
553520 public abstract boolean isFrozen();
554521
522+ /**
523+ * Returns whether this data type represent a CQL {@link com.datastax.driver.core.DataType.CollectionType collection type},
524+ * that is, a list, set or map.
525+ *
526+ * @return whether this data type name represent the name of a collection type.
527+ */
528+ public boolean isCollection() {
529+ return this instanceof CollectionType;
530+ }
531+
555532 /**
556533 * Returns the type arguments of this type.
557534 * <p>
@@ -570,73 +547,7 @@
570547 * @return an immutable list containing the type arguments of this type.
571548 */
572549 public List<DataType> getTypeArguments() {
573- return Collections.<DataType>emptyList();
574- }
575-
576- abstract boolean canBeDeserializedAs(TypeToken typeToken);
577-
578- /**
579- * Returns the server-side class name for a custom type.
580- *
581- * @return the server-side fully qualified class name for a custom type or
582- * {@code null} for any other type.
583- */
584- public String getCustomTypeClassName() {
585- return null;
586- }
587-
588- /**
589- * Parses a string CQL value for the type this object represent, returning its
590- * value as a Java object.
591- *
592- * @param value the value to parse.
593- * @return a java object representing {@code value}. If {@code value == null}, then
594- * {@code null} is returned.
595- *
596- * @throws InvalidTypeException if {@code value} is not a valid CQL string
597- * representation for this type. Please note that values for custom types
598- * can never be parsed and will always return this exception.
599- */
600- public Object parse(String value) {
601- // We don't care about the protocol version for parsing
602- return value == null ? null : codec(ProtocolVersion.NEWEST_SUPPORTED).parse(value);
603- }
604-
605- /**
606- * Format a Java object as an equivalent CQL value.
607- *
608- * @param value the value to format.
609- * @return a string corresponding to the CQL representation of {@code value}.
610- *
611- * @throws InvalidTypeException if {@code value} does not correspond to
612- * a CQL value (known by the driver). Please note that for custom types this
613- * method will always return this exception.
614- */
615- public String format(Object value) {
616- // We don't care about the protocol version for formatting
617- return value == null ? null : codec(ProtocolVersion.NEWEST_SUPPORTED).format(value);
618- }
619-
620- /**
621- * Returns whether this type is a collection one, i.e. a list, set or map type.
622- *
623- * @return whether this type is a collection one.
624- */
625- public boolean isCollection() {
626- return name.isCollection();
627- }
628-
629- /**
630- * Returns the Java Class corresponding to this type.
631- *
632- * This is a shortcut for {@code getName().asJavaClass()}.
633- *
634- * @return the java Class corresponding to this type.
635- *
636- * @see Name#asJavaClass
637- */
638- public Class<?> asJavaClass() {
639- return getName().asJavaClass();
550+ return Collections.emptyList();
640551 }
641552
642553 /**
@@ -670,114 +581,9 @@
670581 });
671582 }
672583
673- /**
674- * Serialize a value of this type to bytes, with the given protocol version.
675- * <p>
676- * The actual format of the resulting bytes will correspond to the
677- * Cassandra encoding for this type (for the requested protocol version).
678- *
679- * @param value the value to serialize.
680- * @param protocolVersion the protocol version to use when serializing
681- * {@code bytes}. In most cases, the proper value to provide for this argument
682- * is the value returned by {@link ProtocolOptions#getProtocolVersion} (which
683- * is the protocol version in use by the driver).
684- * @return the value serialized, or {@code null} if {@code value} is null.
685- *
686- * @throws InvalidTypeException if {@code value} is not a valid object
687- * for this {@code DataType}.
688- */
689- public ByteBuffer serialize(Object value, ProtocolVersion protocolVersion) {
690- Class<?> providedClass = value.getClass();
691- Class<?> expectedClass = asJavaClass();
692- if (!expectedClass.isAssignableFrom(providedClass))
693- throw new InvalidTypeException(String.format("Invalid value for CQL type %s, expecting %s but %s provided", toString(), expectedClass, providedClass));
694-
695- try {
696- return codec(protocolVersion).serialize(value);
697- } catch (ClassCastException e) {
698- // With collections, the element type has not been checked, so it can throw
699- throw new InvalidTypeException("Invalid type for collection element: " + e.getMessage());
700- }
701- }
702-
703- /**
704- * Deserialize a value of this type from the provided bytes using the given protocol version.
705- *
706- * @param bytes bytes holding the value to deserialize.
707- * @param protocolVersion the protocol version to use when deserializing
708- * {@code bytes}. In most cases, the proper value to provide for this argument
709- * is the value returned by {@link ProtocolOptions#getProtocolVersion} (which
710- * is the protocol version in use by the driver).
711- * @return the deserialized value (of class {@code this.asJavaClass()}).
712- * Will return {@code null} if either {@code bytes} is {@code null} or if
713- * {@code bytes.remaining() == 0} and this type has no value corresponding
714- * to an empty byte buffer (the latter somewhat strange behavior is due to
715- * the fact that for historical/technical reason, Cassandra types always
716- * accept empty byte buffer as valid value of those type, and so we avoid
717- * throwing an exception in that case. It is however highly discouraged to
718- * store empty byte buffers for types for which it doesn't make sense, so
719- * this detail can generally be ignored).
720- *
721- * @throws InvalidTypeException if {@code bytes} is not a valid
722- * encoding of an object of this {@code DataType}.
723- */
724- public Object deserialize(ByteBuffer bytes, ProtocolVersion protocolVersion) {
725- return codec(protocolVersion).deserialize(bytes);
726- }
727-
728- /**
729- * Deserialize a value of this type from the provided bytes using the given numeric protocol version.
730- *
731- * @throws IllegalArgumentException if {@code protocolVersion} does not correspond to any known version.
732- *
733- * @deprecated This method is provided for backward compatibility. Use
734- * {@link #deserialize(ByteBuffer,ProtocolVersion)} instead.
735- */
736- public Object deserialize(ByteBuffer bytes, int protocolVersion) {
737- return deserialize(bytes, ProtocolVersion.fromInt(protocolVersion));
738- }
739-
740- /**
741- * Serialize an object based on its java class.
742- * <p>
743- * This is equivalent to {@link #serialize} but with the difference that
744- * the actual {@code DataType} of the resulting value is inferred from the
745- * java class of {@code value}. The correspondence between CQL {@code DataType}
746- * and java class used is the one induced by the method {@link Name#asJavaClass}.
747- * Note that if you know the {@code DataType} of {@code value}, you should use
748- * the {@link #serialize} method instead as it is going to be faster.
749- *
750- * @param value the value to serialize.
751- * @param protocolVersion the protocol version to use when deserializing
752- * {@code bytes}. In most cases, the proper value to provide for this argument
753- * is the value returned by {@link ProtocolOptions#getProtocolVersion} (which
754- * is the protocol version in use by the driver).
755- * @return the value serialized, or {@code null} if {@code value} is null.
756- *
757- * @throws IllegalArgumentException if {@code value} is not of a type
758- * corresponding to a CQL3 type, i.e. is not a Class that could be returned
759- * by {@link DataType#asJavaClass}.
760- */
761- public static ByteBuffer serializeValue(Object value, ProtocolVersion protocolVersion) {
762- if (value == null)
763- return null;
764-
765- DataType dt = TypeCodec.getDataTypeFor(value);
766- if (dt == null)
767- throw new IllegalArgumentException(String.format("Value of type %s does not correspond to any CQL3 type", value.getClass()));
768-
769- try {
770- return dt.serialize(value, protocolVersion);
771- } catch (InvalidTypeException e) {
772- // In theory we couldn't get that if getDataTypeFor does his job correctly,
773- // but there is no point in sending an exception that the user won't expect if we're
774- // wrong on that.
775- throw new IllegalArgumentException(e.getMessage());
776- }
777- }
584+ public static class NativeType extends DataType {
778585
779- private static class Native extends DataType {
780- private Native(DataType.Name name) {
586+ private NativeType(DataType.Name name) {
781587 super(name);
782588 }
783589
@@ -786,16 +592,6 @@
786592 return false;
787593 }
788594
789- @Override
790- boolean canBeDeserializedAs(TypeToken typeToken) {
791- return typeToken.isAssignableFrom(getName().javaType);
792- }
793-
794- @Override
795- TypeCodec<Object> codec(ProtocolVersion protocolVersion) {
796- return TypeCodec.createFor(name);
797- }
798-
799595 @Override
800596 public final int hashCode() {
801597 return (name == Name.TEXT)
@@ -805,13 +601,11 @@
805601
806602 @Override
807603 public final boolean equals(Object o) {
808- if(!(o instanceof DataType.Native))
604+ if(!(o instanceof DataType.NativeType))
809605 return false;
810606
811- Native that = (DataType.Native)o;
812- return name == that.name ||
813- name == Name.VARCHAR && that.name == Name.TEXT ||
814- name == Name.TEXT && that.name == Name.VARCHAR;
607+ NativeType that = (DataType.NativeType)o;
608+ return this.name.isCompatibleWith(that.name);
815609 }
816610
817611 @Override
@@ -820,12 +614,12 @@
820614 }
821615 }
822616
823- private static class Collection extends DataType {
617+ public static class CollectionType extends DataType {
824618
825619 private final List<DataType> typeArguments;
826620 private boolean frozen;
827621
828- private Collection(DataType.Name name, List<DataType> typeArguments, boolean frozen) {
622+ private CollectionType(DataType.Name name, List<DataType> typeArguments, boolean frozen) {
829623 super(name);
830624 this.typeArguments = typeArguments;
831625 this.frozen = frozen;
@@ -836,36 +630,6 @@
836630 return frozen;
837631 }
838632
839- @Override
840- @SuppressWarnings("unchecked")
841- boolean canBeDeserializedAs(TypeToken typeToken) {
842- switch (name) {
843- case LIST:
844- return typeToken.getRawType().isAssignableFrom(List.class) &&
845- typeArguments.get(0).canBeDeserializedAs(typeToken.resolveType(typeToken.getRawType().getTypeParameters()[0]));
846- case SET:
847- return typeToken.getRawType().isAssignableFrom(Set.class) &&
848- typeArguments.get(0).canBeDeserializedAs(typeToken.resolveType(typeToken.getRawType().getTypeParameters()[0]));
849- case MAP:
850- return typeToken.getRawType().isAssignableFrom(Map.class) &&
851- typeArguments.get(0).canBeDeserializedAs(typeToken.resolveType(typeToken.getRawType().getTypeParameters()[0])) &&
852- typeArguments.get(1).canBeDeserializedAs(typeToken.resolveType(typeToken.getRawType().getTypeParameters()[1]));
853- }
854- throw new AssertionError();
855- }
856-
857- @SuppressWarnings("unchecked")
858- @Override
859- TypeCodec<Object> codec(ProtocolVersion protocolVersion) {
860- switch (name)
861- {
862- case LIST: return (TypeCodec)TypeCodec.listOf(typeArguments.get(0), protocolVersion);
863- case SET: return (TypeCodec)TypeCodec.setOf(typeArguments.get(0), protocolVersion);
864- case MAP: return (TypeCodec)TypeCodec.mapOf(typeArguments.get(0), typeArguments.get(1), protocolVersion);
865- }
866- throw new AssertionError();
867- }
868-
869633 @Override
870634 public List<DataType> getTypeArguments() {
871635 return typeArguments;
@@ -878,10 +642,10 @@
878642
879643 @Override
880644 public final boolean equals(Object o) {
881- if(!(o instanceof DataType.Collection))
645+ if(!(o instanceof DataType.CollectionType))
882646 return false;
883647
884- DataType.Collection d = (DataType.Collection)o;
648+ DataType.CollectionType d = (DataType.CollectionType)o;
885649 return name == d.name && typeArguments.equals(d.typeArguments);
886650 }
887651
@@ -898,11 +662,11 @@
898662 }
899663 }
900664
901- private static class Custom extends DataType {
665+ public static class CustomType extends DataType {
902666
903667 private final String customClassName;
904668
905- private Custom(DataType.Name name, String className) {
669+ private CustomType(DataType.Name name, String className) {
906670 super(name);
907671 this.customClassName = className;
908672 }
@@ -912,32 +676,10 @@
912676 return false;
913677 }
914678
915- @Override
916- boolean canBeDeserializedAs(TypeToken typeToken) {
917- return typeToken.getRawType().getName().equals(customClassName);
918- }
919-
920- @SuppressWarnings("unchecked")
921- @Override
922- TypeCodec<Object> codec(ProtocolVersion protocolVersion) {
923- return (TypeCodec)TypeCodec.BytesCodec.instance;
924- }
925-
926- @Override
927679 public String getCustomTypeClassName() {
928680 return customClassName;
929681 }
930682
931- @Override
932- public Object parse(String value) {
933- throw new InvalidTypeException("Cannot parse values of custom types");
934- }
935-
936- @Override
937- public String format(Object value) {
938- throw new InvalidTypeException("Cannot format values of custom types");
939- }
940-
941683 @Override
942684 public final int hashCode() {
943685 return Arrays.hashCode(new Object[]{ name, customClassName });
@@ -945,10 +687,10 @@
945687
946688 @Override
947689 public final boolean equals(Object o) {
948- if(!(o instanceof DataType.Custom))
690+ if(!(o instanceof DataType.CustomType))
949691 return false;
950692
951- DataType.Custom d = (DataType.Custom)o;
693+ DataType.CustomType d = (DataType.CustomType)o;
952694 return name == d.name && Objects.equal(customClassName, d.customClassName);
953695 }
954696
modified driver-core/src/main/java/com/datastax/driver/core/DefaultPreparedStatement.java +19 −7
@@ -32,6 +32,7 @@
3232 final String query;
3333 final String queryKeyspace;
3434 final Map<String, ByteBuffer> incomingPayload;
35+ final Cluster cluster;
3536
3637 volatile ByteBuffer routingKey;
3738
@@ -41,28 +42,34 @@
4142 volatile RetryPolicy retryPolicy;
4243 volatile ImmutableMap<String, ByteBuffer> outgoingPayload;
4344
44- private DefaultPreparedStatement(PreparedId id, String query, String queryKeyspace, Map<String, ByteBuffer> incomingPayload) {
45+ private DefaultPreparedStatement(PreparedId id, String query, String queryKeyspace, Map<String, ByteBuffer> incomingPayload, Cluster cluster) {
4546 this.preparedId = id;
4647 this.query = query;
4748 this.queryKeyspace = queryKeyspace;
4849 this.incomingPayload = incomingPayload;
50+ this.cluster = cluster;
4951 }
5052
51- static DefaultPreparedStatement fromMessage(Responses.Result.Prepared msg, Metadata clusterMetadata, ProtocolVersion protocolVersion, String query, String queryKeyspace) {
53+ static DefaultPreparedStatement fromMessage(Responses.Result.Prepared msg, Cluster cluster, String query, String queryKeyspace) {
5254 assert msg.metadata.columns != null;
5355
5456 ColumnDefinitions defs = msg.metadata.columns;
5557
56- if (defs.size() == 0)
57- return new DefaultPreparedStatement(new PreparedId(msg.statementId, defs, msg.resultMetadata.columns, null, protocolVersion), query, queryKeyspace, msg.getCustomPayload());
58+ defs.setCodecRegistry(cluster.getConfiguration().getCodecRegistry());
59+
60+ ProtocolVersion protocolVersion = cluster.getConfiguration().getProtocolOptions().getProtocolVersion();
61+
62+ if (defs.size() == 0) {
63+ return new DefaultPreparedStatement(new PreparedId(msg.statementId, defs, msg.resultMetadata.columns, null, protocolVersion), query, queryKeyspace, msg.getCustomPayload(), cluster);
64+ }
5865
5966 int[] pkIndices = (protocolVersion.compareTo(V4) >= 0)
6067 ? msg.metadata.pkIndices
61- : computePkIndices(clusterMetadata, defs);
68+ : computePkIndices(cluster.getMetadata(), defs);
6269
6370 PreparedId prepId = new PreparedId(msg.statementId, defs, msg.resultMetadata.columns, pkIndices, protocolVersion);
6471
65- return new DefaultPreparedStatement(prepId, query, queryKeyspace, msg.getCustomPayload());
72+ return new DefaultPreparedStatement(prepId, query, queryKeyspace, msg.getCustomPayload(), cluster);
6673 }
6774
6875 private static int[] computePkIndices(Metadata clusterMetadata, ColumnDefinitions boundColumns) {
@@ -129,7 +136,7 @@
129136 }
130137
131138 public PreparedStatement setRoutingKey(ByteBuffer... routingKeyComponents) {
132- this.routingKey = SimpleStatement.compose(routingKeyComponents);
139+ this.routingKey = CodecUtils.compose(routingKeyComponents);
133140 return this;
134141 }
135142
@@ -207,4 +214,9 @@
207214 this.outgoingPayload = payload == null ? null : ImmutableMap.copyOf(payload);
208215 return this;
209216 }
217+
218+ @Override
219+ public CodecRegistry getCodecRegistry() {
220+ return cluster.getConfiguration().getCodecRegistry();
221+ }
210222 }
modified driver-core/src/main/java/com/datastax/driver/core/FunctionMetadata.java +5 −6
@@ -20,7 +20,6 @@
2020 import java.util.List;
2121 import java.util.Map;
2222
23-import com.google.common.base.Joiner;
2423 import com.google.common.collect.ImmutableMap;
2524 import org.slf4j.Logger;
2625 import org.slf4j.LoggerFactory;
@@ -70,7 +69,7 @@
7069 // return_type text,
7170 // PRIMARY KEY (keyspace_name, function_name, signature)
7271 // ) WITH CLUSTERING ORDER BY (function_name ASC, signature ASC)
73- static FunctionMetadata build(KeyspaceMetadata ksm, Row row) {
72+ static FunctionMetadata build(KeyspaceMetadata ksm, Row row, ProtocolVersion protocolVersion, CodecRegistry codecRegistry) {
7473 String simpleName = row.getString("function_name");
7574 List<String> signature = row.getList("signature", String.class);
7675 String fullName = Metadata.fullFunctionName(simpleName, signature);
@@ -83,12 +82,12 @@
8382 ksm.getName(), fullName));
8483 return null;
8584 }
86- Map<String, DataType> arguments = buildArguments(argumentNames, argumentTypes);
85+ Map<String, DataType> arguments = buildArguments(argumentNames, argumentTypes, protocolVersion, codecRegistry);
8786
8887 String body = row.getString("body");
8988 boolean calledOnNullInput = row.getBool("called_on_null_input");
9089 String language = row.getString("language");
91- DataType returnType = CassandraTypeParser.parseOne(row.getString("return_type"));
90+ DataType returnType = CassandraTypeParser.parseOne(row.getString("return_type"), protocolVersion, codecRegistry);
9291
9392 FunctionMetadata function = new FunctionMetadata(ksm, fullName, simpleName, arguments, body,
9493 calledOnNullInput, language, returnType);
@@ -97,14 +96,14 @@
9796 }
9897
9998 // Note: the caller ensures that names and types have the same size
100- private static Map<String, DataType> buildArguments(List<String> names, List<String> types) {
99+ private static Map<String, DataType> buildArguments(List<String> names, List<String> types, ProtocolVersion protocolVersion, CodecRegistry codecRegistry) {
101100 if (names.isEmpty())
102101 return Collections.emptyMap();
103102
104103 ImmutableMap.Builder<String, DataType> builder = ImmutableMap.builder();
105104 Iterator<String> iterTypes = types.iterator();
106105 for (String name : names) {
107- DataType type = CassandraTypeParser.parseOne(iterTypes.next());
106+ DataType type = CassandraTypeParser.parseOne(iterTypes.next(), protocolVersion, codecRegistry);
108107 builder.put(name, type);
109108 }
110109 return builder.build();
modified driver-core/src/main/java/com/datastax/driver/core/GettableByIndexData.java +68 −0
@@ -404,6 +404,10 @@
404404
405405 /**
406406 * Returns the {@code i}th value as the Java type matching its CQL type.
407+ * <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.
407411 *
408412 * @param i the index to retrieve.
409413 * @return the value of the {@code i}th value as the Java type matching its CQL type.
@@ -413,4 +417,68 @@
413417 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
414418 */
415419 public Object getObject(int i);
420+
421+ /**
422+ * Returns the {@code i}th value converted to the given Java type.
423+ * <p>
424+ * A suitable {@link TypeCodec} instance for the underlying CQL type and {@code targetClass} must
425+ * have been previously registered with the {@link CodecRegistry} currently in use.
426+ * <p>
427+ * This method should be used instead of {@link #getObject(int)} in cases
428+ * where more than one codec is registered for the same CQL type; specifying the Java class
429+ * allows the {@link CodecRegistry} to narrow down the search and return only an exactly-matching codec (if any),
430+ * thus avoiding any risk of ambiguity.
431+ *
432+ * @param i the index to retrieve.
433+ * @param targetClass The Java type the value should be converted to.
434+ * @return the value of the {@code i}th value converted to the given Java type.
435+ * If the CQL value is {@code NULL}, this method will return {@code null}
436+ * for a simple type, UDT or tuple, and an empty (immutable) collection for collection types.
437+ * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
438+ * @throws com.datastax.driver.core.exceptions.CodecNotFoundException
439+ * if no {@link TypeCodec} instance for {@code targetClass} could be found
440+ * by the {@link CodecRegistry} currently in use.
441+ */
442+ <T> T get(int i, Class<T> targetClass);
443+
444+ /**
445+ * Returns the {@code i}th value converted to the given Java type.
446+ * <p>
447+ * A suitable {@link TypeCodec} instance for the underlying CQL type and {@code targetType} must
448+ * have been previously registered with the {@link CodecRegistry} currently in use.
449+ * <p>
450+ * This method should be used instead of {@link #getObject(int)} in cases
451+ * where more than one codec is registered for the same CQL type; specifying the Java class
452+ * allows the {@link CodecRegistry} to narrow down the search and return only an exactly-matching codec (if any),
453+ * thus avoiding any risk of ambiguity.
454+ *
455+ * @param i the index to retrieve.
456+ * @param targetType The Java type the value should be converted to.
457+ * @return the value of the {@code i}th value converted to the given Java type.
458+ * If the CQL value is {@code NULL}, the default set of codecs will return {@code null}
459+ * for a simple type, UDT or tuple, and an empty (immutable) collection for collection types.
460+ * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
461+ * @throws com.datastax.driver.core.exceptions.CodecNotFoundException
462+ * if no {@link TypeCodec} instance for {@code targetType} could be found
463+ * by the {@link CodecRegistry} currently in use.
464+ */
465+ <T> T get(int i, TypeToken<T> targetType);
466+
467+ /**
468+ * Returns the {@code i}th value converted using the given {@link TypeCodec}.
469+ * <p>
470+ * Note that this method allows to entirely bypass the {@link CodecRegistry} currently in use
471+ * and forces the driver to use the given codec instead.
472+ * <p>
473+ * It is the caller's responsibility to ensure that the given codec {@link TypeCodec#accepts(DataType) accepts}
474+ * the underlying CQL type; failing to do so may result in {@link InvalidTypeException}s being thrown.
475+ *
476+ * @param i the index to retrieve.
477+ * @param codec The {@link TypeCodec} to use to deserialize the value; may not be {@code null}.
478+ * @return the value of the {@code i}th value converted using the given {@link TypeCodec}.
479+ * @throws InvalidTypeException if the given codec does not {@link TypeCodec#accepts(DataType) accept} the underlying CQL type.
480+ * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
481+ */
482+ <T> T get(int i, TypeCodec<T> codec);
483+
416484 }
modified driver-core/src/main/java/com/datastax/driver/core/GettableByNameData.java +66 −0
@@ -403,6 +403,10 @@
403403
404404 /**
405405 * Returns the value for {@code name} as the Java type matching its CQL type.
406+ * <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.
406410 *
407411 * @param name the name to retrieve.
408412 * @return the value of the {@code i}th value as the Java type matching its CQL type.
@@ -412,4 +416,66 @@
412416 * @throws IllegalArgumentException if {@code name} is not a valid name for this object.
413417 */
414418 Object getObject(String name);
419+
420+ /**
421+ * Returns the value for {@code name} converted to the given Java type.
422+ * <p>
423+ * A suitable {@link TypeCodec} instance for for the underlying CQL type and {@code targetClass} must
424+ * have been previously registered with the {@link CodecRegistry} currently in use.
425+ * <p>
426+ * This method should be used instead of {@link #getObject(String)} in cases
427+ * where more than one codec is registered for the same CQL type; specifying the Java class
428+ * allows the {@link CodecRegistry} to narrow down the search and return only an exactly-matching codec (if any),
429+ * thus avoiding any risk of ambiguity.
430+ *
431+ * @param name the name to retrieve.
432+ * @param targetClass The Java type the value should be converted to.
433+ * @return the value for {@code name} value converted to the given Java type.
434+ * If the CQL value is {@code NULL}, then {@code null} is returned.
435+ * @throws IllegalArgumentException if {@code name} is not a valid name for this object.
436+ * @throws com.datastax.driver.core.exceptions.CodecNotFoundException
437+ * if no {@link TypeCodec} instance for {@code targetClass} could be found
438+ * by the {@link CodecRegistry} currently in use.
439+ */
440+ <T> T get(String name, Class<T> targetClass);
441+
442+ /**
443+ * Returns the value for {@code name} converted to the given Java type.
444+ * <p>
445+ * A suitable {@link TypeCodec} instance for for the underlying CQL type and {@code targetType} must
446+ * have been previously registered with the {@link CodecRegistry} currently in use.
447+ * <p>
448+ * This method should be used instead of {@link #getObject(String)} in cases
449+ * where more than one codec is registered for the same CQL type; specifying the Java class
450+ * allows the {@link CodecRegistry} to narrow down the search and return only an exactly-matching codec (if any),
451+ * thus avoiding any risk of ambiguity.
452+ *
453+ * @param name the name to retrieve.
454+ * @param targetType The Java type the value should be converted to.
455+ * @return the value for {@code name} value converted to the given Java type.
456+ * If the CQL value is {@code NULL}, then {@code null} is returned.
457+ * @throws IllegalArgumentException if {@code name} is not a valid name for this object.
458+ * @throws com.datastax.driver.core.exceptions.CodecNotFoundException
459+ * if no {@link TypeCodec} instance for {@code targetType} could be found
460+ * by the {@link CodecRegistry} currently in use.
461+ */
462+ <T> T get(String name, TypeToken<T> targetType);
463+
464+ /**
465+ * Returns the value for {@code name} converted using the given {@link TypeCodec}.
466+ * <p>
467+ * Note that this method allows to entirely bypass the {@link CodecRegistry} currently in use
468+ * and forces the driver to use the given codec instead.
469+ * <p>
470+ * It is the caller's responsibility to ensure that the given codec {@link TypeCodec#accepts(DataType) accepts}
471+ * the underlying CQL type; failing to do so may result in {@link InvalidTypeException}s being thrown.
472+ *
473+ * @param name the name to retrieve.
474+ * @param codec The {@link TypeCodec} to use to deserialize the value; may not be {@code null}.
475+ * @return the value of the {@code i}th value converted using the given {@link TypeCodec}.
476+ * @throws InvalidTypeException if the given codec does not {@link TypeCodec#accepts(DataType) accept} the underlying CQL type.
477+ * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
478+ */
479+ <T> T get(String name, TypeCodec<T> codec);
480+
415481 }
modified driver-core/src/main/java/com/datastax/driver/core/Host.java +0 −1
@@ -22,7 +22,6 @@
2222 import java.util.concurrent.locks.ReentrantLock;
2323
2424 import com.google.common.collect.ImmutableList;
25-import com.google.common.util.concurrent.Futures;
2625 import com.google.common.util.concurrent.ListenableFuture;
2726 import org.slf4j.Logger;
2827 import org.slf4j.LoggerFactory;
modified driver-core/src/main/java/com/datastax/driver/core/KeyspaceMetadata.java +4 −4
@@ -50,7 +50,7 @@
5050 this.strategy = ReplicationStrategy.create(replication);
5151 }
5252
53- static KeyspaceMetadata build(Row row, List<Row> udtRows) {
53+ static KeyspaceMetadata build(Row row, List<Row> udtRows, ProtocolVersion protocolVersion, CodecRegistry codecRegistry) {
5454
5555 String name = row.getString(KS_NAME);
5656 boolean durableWrites = row.getBool(DURABLE_WRITES);
@@ -64,7 +64,7 @@
6464 if (udtRows == null)
6565 return ksm;
6666
67- ksm.addUserTypes(udtRows);
67+ ksm.addUserTypes(udtRows, protocolVersion, codecRegistry);
6868
6969 return ksm;
7070 }
@@ -143,9 +143,9 @@
143143 return Collections.unmodifiableCollection(userTypes.values());
144144 }
145145
146- void addUserTypes(List<Row> udtRows) {
146+ void addUserTypes(List<Row> udtRows, ProtocolVersion protocolVersion, CodecRegistry codecRegistry) {
147147 for (Row r : udtRows) {
148- UserType def = UserType.build(r);
148+ UserType def = UserType.build(r, protocolVersion, codecRegistry);
149149 userTypes.put(def.getTypeName(), def);
150150 }
151151 }
modified driver-core/src/main/java/com/datastax/driver/core/Metadata.java +22 −12
@@ -82,7 +82,7 @@
8282 l = new HashMap<String, ColumnMetadata.Raw>();
8383 colsByCf.put(cfName, l);
8484 }
85- ColumnMetadata.Raw c = ColumnMetadata.Raw.fromRow(row, cassandraVersion);
85+ ColumnMetadata.Raw c = ColumnMetadata.Raw.fromRow(row, cassandraVersion, cluster.protocolVersion(), cluster.configuration.getCodecRegistry());
8686 l.put(c.name, c);
8787 }
8888 }
@@ -92,16 +92,16 @@
9292 Set<String> addedKs = new HashSet<String>();
9393 for (Row ksRow : ks) {
9494 String ksName = ksRow.getString(KeyspaceMetadata.KS_NAME);
95- KeyspaceMetadata ksm = KeyspaceMetadata.build(ksRow, udtDefs.get(ksName));
95+ KeyspaceMetadata ksm = KeyspaceMetadata.build(ksRow, udtDefs.get(ksName), cluster.protocolVersion(), cluster.configuration.getCodecRegistry());
9696
9797 if (cfDefs.containsKey(ksName)) {
9898 buildTableMetadata(ksm, cfDefs.get(ksName), colsDefs.get(ksName), cassandraVersion);
9999 }
100100 if (functionDefs.containsKey(ksName)) {
101- buildFunctionMetadata(ksm, functionDefs.get(ksName));
101+ buildFunctionMetadata(ksm, functionDefs.get(ksName), cluster.protocolVersion(), cluster.configuration.getCodecRegistry());
102102 }
103103 if (aggregateDefs.containsKey(ksName)) {
104- buildAggregateMetadata(ksm, aggregateDefs.get(ksName), cluster.protocolVersion());
104+ buildAggregateMetadata(ksm, aggregateDefs.get(ksName), cluster.protocolVersion(), cluster.configuration.getCodecRegistry());
105105 }
106106 addedKs.add(ksName);
107107 keyspaces.put(ksName, ksm);
@@ -135,15 +135,15 @@
135135 break;
136136 case TYPE:
137137 if (udtDefs.containsKey(targetKeyspace))
138- ksm.addUserTypes(udtDefs.get(targetKeyspace));
138+ ksm.addUserTypes(udtDefs.get(targetKeyspace), cluster.protocolVersion(), cluster.configuration.getCodecRegistry());
139139 break;
140140 case FUNCTION:
141141 if (functionDefs.containsKey(targetKeyspace))
142- buildFunctionMetadata(ksm, functionDefs.get(targetKeyspace));
142+ buildFunctionMetadata(ksm, functionDefs.get(targetKeyspace), cluster.protocolVersion(), cluster.configuration.getCodecRegistry());
143143 break;
144144 case AGGREGATE:
145145 if (functionDefs.containsKey(targetKeyspace))
146- buildAggregateMetadata(ksm, aggregateDefs.get(targetKeyspace), cluster.protocolVersion());
146+ buildAggregateMetadata(ksm, aggregateDefs.get(targetKeyspace), cluster.protocolVersion(), cluster.configuration.getCodecRegistry());
147147 break;
148148 default:
149149 logger.warn("Unexpected element type to rebuild: {}", targetType);
@@ -192,7 +192,7 @@
192192 cols = Collections.<String, ColumnMetadata.Raw>emptyMap();
193193 }
194194 }
195- TableMetadata.build(ksm, cfRow, cols, cassandraVersion);
195+ TableMetadata.build(ksm, cfRow, cols, cassandraVersion, cluster.protocolVersion(), cluster.configuration.getCodecRegistry());
196196 } catch (RuntimeException e) {
197197 // See ControlConnection#refreshSchema for why we'd rather not probably this further
198198 logger.error(String.format("Error parsing schema for table %s.%s: "
@@ -202,14 +202,14 @@
202202 }
203203 }
204204
205- private void buildFunctionMetadata(KeyspaceMetadata ksm, List<Row> rows) {
205+ private void buildFunctionMetadata(KeyspaceMetadata ksm, List<Row> rows, ProtocolVersion protocolVersion, CodecRegistry codecRegistry) {
206206 for (Row row : rows)
207- FunctionMetadata.build(ksm, row);
207+ FunctionMetadata.build(ksm, row, protocolVersion, codecRegistry);
208208 }
209209
210- private void buildAggregateMetadata(KeyspaceMetadata ksm, List<Row> rows, ProtocolVersion protocolVersion) {
210+ private void buildAggregateMetadata(KeyspaceMetadata ksm, List<Row> rows, ProtocolVersion protocolVersion, CodecRegistry codecRegistry) {
211211 for (Row row : rows)
212- AggregateMetadata.build(ksm, row, protocolVersion);
212+ AggregateMetadata.build(ksm, row, protocolVersion, codecRegistry);
213213 }
214214
215215
@@ -485,6 +485,16 @@
485485 return sb.toString();
486486 }
487487
488+ /**
489+ * Creates a tuple type given a list of types.
490+ *
491+ * @param types the types for the tuple type.
492+ * @return the newly created tuple type.
493+ */
494+ public TupleType newTupleType(DataType... types) {
495+ return new TupleType(Arrays.asList(types), cluster.protocolVersion(), cluster.configuration.getCodecRegistry());
496+ }
497+
488498 /**
489499 * Builds a new {@link Token} from its string representation, according to the partitioner
490500 * reported by the Cassandra nodes.
modified driver-core/src/main/java/com/datastax/driver/core/PagingState.java +7 −7
@@ -37,13 +37,13 @@
3737 */
3838 public class PagingState {
3939
40- private byte[] pagingState;
41- private byte[] hash;
42- private ProtocolVersion protocolVersion;
40+ private final byte[] pagingState;
41+ private final byte[] hash;
42+ private final ProtocolVersion protocolVersion;
4343
4444 PagingState(ByteBuffer pagingState, Statement statement, ProtocolVersion protocolVersion) {
4545 this.pagingState = Bytes.getArray(pagingState);
46- this.hash = hash(statement, protocolVersion);
46+ this.hash = hash(statement);
4747 this.protocolVersion = protocolVersion;
4848 }
4949
@@ -70,7 +70,7 @@
7070 : ProtocolVersion.V2;
7171 }
7272
73- private byte[] hash(Statement statement, ProtocolVersion protocolVersion) {
73+ private byte[] hash(Statement statement) {
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(protocolVersion);
88+ values = rs.getValues();
8989 }
9090 if (values != null) {
9191 for (ByteBuffer value : values) {
@@ -102,7 +102,7 @@
102102 }
103103
104104 boolean matches(Statement statement) {
105- byte[] toTest = hash(statement, protocolVersion);
105+ byte[] toTest = hash(statement);
106106 return Arrays.equals(toTest, this.hash);
107107 }
108108
modified driver-core/src/main/java/com/datastax/driver/core/PreparedStatement.java +11 −1
@@ -337,4 +337,14 @@
337337 */
338338 public PreparedStatement setOutgoingPayload(Map<String, ByteBuffer> payload);
339339
340-}
No newline at the end of the file
340+ /**
341+ * Return the {@link CodecRegistry} instance associated with this prepared statement.
342+ * Implementations should never return {@code null}; instead, they should always return
343+ * the {@link CodecRegistry} instance registered with the {@link Cluster} instance
344+ * this prepared statement belongs to.
345+ *
346+ * @return the {@link CodecRegistry} instance associated with this prepared statement.
347+ */
348+ public CodecRegistry getCodecRegistry();
349+
350+}
modified driver-core/src/main/java/com/datastax/driver/core/ProtocolVersion.java +1 −1
@@ -36,7 +36,7 @@
3636 /**
3737 * The most recent protocol version supported by the driver.
3838 */
39- public static ProtocolVersion NEWEST_SUPPORTED = V4;
39+ public static final ProtocolVersion NEWEST_SUPPORTED = V4;
4040
4141 private final VersionNumber minCassandraVersion;
4242 private final int asInt;
modified driver-core/src/main/java/com/datastax/driver/core/QueryLogger.java +11 −7
@@ -206,7 +206,7 @@
206206 protected volatile int maxLoggedParameters;
207207
208208 /**
209- * Private constructor. Instances of QueryLogger should be obtained via the {@link #builder(Cluster)} method.
209+ * Private constructor. Instances of QueryLogger should be obtained via the {@link #builder()} method.
210210 */
211211 private QueryLogger(int maxQueryStringLength, int maxParameterValueLength, int maxLoggedParameters) {
212212 this.maxQueryStringLength = maxQueryStringLength;
@@ -725,6 +725,8 @@
725725 valueStr = "NULL";
726726 } else {
727727 DataType type = definition.getType();
728+ CodecRegistry codecRegistry = cluster.getConfiguration().getCodecRegistry();
729+ TypeCodec<Object> codec = codecRegistry.codecFor(type);
728730 int maxParameterValueLength = this.maxParameterValueLength;
729731 if (type.equals(DataType.blob()) && maxParameterValueLength != -1) {
730732 // prevent large blobs from being converted to strings
@@ -733,14 +735,14 @@
733735 if (bufferTooLarge) {
734736 raw = (ByteBuffer)raw.duplicate().limit(maxBufferLength);
735737 }
736- Object value = type.deserialize(raw, protocolVersion());
737- valueStr = type.format(value);
738+ Object value = codec.deserialize(raw, protocolVersion());
739+ valueStr = codec.format(value);
738740 if (bufferTooLarge) {
739741 valueStr = valueStr + TRUNCATED_OUTPUT;
740742 }
741743 } else {
742- Object value = type.deserialize(raw, protocolVersion());
743- valueStr = type.format(value);
744+ Object value = codec.deserialize(raw, protocolVersion());
745+ valueStr = codec.format(value);
744746 if (maxParameterValueLength != -1 && valueStr.length() > maxParameterValueLength) {
745747 valueStr = valueStr.substring(0, maxParameterValueLength) + TRUNCATED_OUTPUT;
746748 }
@@ -766,7 +768,9 @@
766768 statement = ((StatementWrapper)statement).getWrappedStatement();
767769
768770 if (statement instanceof RegularStatement) {
769- remaining = append(((RegularStatement)statement).getQueryString().trim(), buffer, remaining);
771+ RegularStatement rs = (RegularStatement)statement;
772+ String query = rs.getQueryString();
773+ remaining = append(query.trim(), buffer, remaining);
770774 } else if (statement instanceof BoundStatement) {
771775 remaining = append(((BoundStatement)statement).preparedStatement().getQueryString().trim(), buffer, remaining);
772776 } else if (statement instanceof BatchStatement) {
@@ -813,4 +817,4 @@
813817 return remaining;
814818 }
815819
816-}
No newline at the end of the file
820+}
modified driver-core/src/main/java/com/datastax/driver/core/RegularStatement.java +6 −7
@@ -17,6 +17,8 @@
1717
1818 import java.nio.ByteBuffer;
1919
20+import com.datastax.driver.core.exceptions.InvalidTypeException;
21+
2022 /**
2123 * A regular (non-prepared and non batched) CQL statement.
2224 * <p>
@@ -49,14 +51,11 @@
4951 * 1 through {@link Cluster.Builder#withProtocolVersion} or you use
5052 * Cassandra 1.2).
5153 *
52- * @param protocolVersion the protocol version in which the returned values
53- * must be serialized for.
54- * @return the values to use for this statement or {@code null} if there is
55- * no such values.
56- *
57- * @see SimpleStatement#SimpleStatement(String, Object...)
54+ * @throws InvalidTypeException if one of the values is not of a type
55+ * that can be serialized to a CQL3 type
56+ * @see SimpleStatement#SimpleStatement(String, Cluster, Object...)
5857 */
59- public abstract ByteBuffer[] getValues(ProtocolVersion protocolVersion);
58+ public abstract ByteBuffer[] getValues();
6059
6160 /**
6261 * Whether or not this statement has values, that is if {@code getValues}
modified driver-core/src/main/java/com/datastax/driver/core/Responses.java +14 −12
@@ -19,7 +19,6 @@
1919 import java.nio.ByteBuffer;
2020 import java.util.*;
2121
22-import com.google.common.collect.ImmutableList;
2322 import io.netty.buffer.ByteBuf;
2423
2524 import com.datastax.driver.core.Responses.Result.Rows.Metadata;
@@ -348,11 +347,11 @@
348347 this.pkIndices = pkIndices;
349348 }
350349
351- public static Metadata decode(ByteBuf body) {
352- return decode(body, false);
350+ public static Metadata decode(ByteBuf body, ProtocolVersion protocolVersion) {
351+ return decode(body, false, protocolVersion);
353352 }
354353
355- public static Metadata decode(ByteBuf body, boolean withPkIndices) {
354+ public static Metadata decode(ByteBuf body, boolean withPkIndices, ProtocolVersion protocolVersion) {
356355
357356 // flags & column count
358357 EnumSet<Flag> flags = Flag.deserialize(body.readInt());
@@ -388,7 +387,9 @@
388387 String ksName = globalTablesSpec ? globalKsName : CBUtil.readString(body);
389388 String cfName = globalTablesSpec ? globalCfName : CBUtil.readString(body);
390389 String name = CBUtil.readString(body);
391- DataType type = DataType.decode(body);
390+ // will set the appropriate CodecRegistry instance later
391+ // when the message will be decoded into either a PreparedStatement or a ResultSet
392+ DataType type = DataType.decode(body, protocolVersion, null);
392393 defs[i] = new ColumnDefinitions.Definition(ksName, cfName, name, type);
393394 }
394395
@@ -416,7 +417,7 @@
416417 public static final Message.Decoder<Result> subcodec = new Message.Decoder<Result>() {
417418 public Result decode(ByteBuf body, ProtocolVersion version) {
418419
419- Metadata metadata = Metadata.decode(body);
420+ Metadata metadata = Metadata.decode(body, version);
420421
421422 int rowCount = body.readInt();
422423 int columnCount = metadata.columnCount;
@@ -455,11 +456,12 @@
455456 sb.append(" | null");
456457 } else {
457458 sb.append(" | ");
458- if (metadata.columns == null) {
459- sb.append(Bytes.toHexString(v));
460- } else {
461- sb.append(metadata.columns.getType(i).deserialize(v, version));
459+ if (metadata.columns != null) {
460+ sb.append(metadata.columns.getType(i));
461+ sb.append(" ");
462462 }
463+ // cannot deserialize without the right CodecRegistry instance
464+ sb.append(Bytes.toHexString(v));
463465 }
464466 }
465467 sb.append('\n');
@@ -475,7 +477,7 @@
475477 public Result decode(ByteBuf body, ProtocolVersion version) {
476478 MD5Digest id = MD5Digest.wrap(CBUtil.readBytes(body));
477479 boolean withPkIndices = version.compareTo(V4) >= 0;
478- Rows.Metadata metadata = Rows.Metadata.decode(body, withPkIndices);
480+ Rows.Metadata metadata = Rows.Metadata.decode(body, withPkIndices, version);
479481 Rows.Metadata resultMetadata = decodeResultMetadata(body, version);
480482 return new Prepared(id, metadata, resultMetadata);
481483 }
@@ -487,7 +489,7 @@
487489 case V2:
488490 case V3:
489491 case V4:
490- return Rows.Metadata.decode(body);
492+ return Rows.Metadata.decode(body, version);
491493 default:
492494 throw version.unsupported();
493495 }
modified driver-core/src/main/java/com/datastax/driver/core/Session.java +64 −2
@@ -110,7 +110,7 @@
110110 *
111111 * @param query the CQL query to execute.
112112 * @param values values required for the execution of {@code query}. See
113- * {@link SimpleStatement#SimpleStatement(String, Object...)} for more detail.
113+ * {@link #newSimpleStatement(String, Object...)} for more detail.
114114 * @return the result of the query. That result will never be null but can
115115 * be empty (and will be for any non SELECT query).
116116 *
@@ -172,7 +172,7 @@
172172 *
173173 * @param query the CQL query to execute.
174174 * @param values values required for the execution of {@code query}. See
175- * {@link SimpleStatement#SimpleStatement(String, Object...)} for more detail.
175+ * {@link #newSimpleStatement(String, Object...)} for more detail.
176176 * @return a future on the result of the query.
177177 *
178178 * @throws UnsupportedFeatureException if version 1 of the protocol
@@ -181,6 +181,68 @@
181181 */
182182 public ResultSetFuture executeAsync(String query, Object... values);
183183
184+ /**
185+ * Builds, but does not execute, a simple statement containing the provided query.
186+ *
187+ * Use this method when you want to customize certain aspects of the statement before
188+ * executing it (fetch size, tracing...); you can then pass the statement to
189+ * {@link #execute(Statement)}.
190+ *
191+ * @param query the CQL query to execute.
192+ * @return the simple statement.
193+ */
194+ public SimpleStatement newSimpleStatement(String query);
195+
196+ /**
197+ * Builds, but does not execute, a simple statement containing the provided query with
198+ * the provided parameters.
199+ *
200+ * Use this method when you want to customize certain aspects of the statement before
201+ * executing it (fetch size, tracing...); you can then pass the statement to
202+ * {@link #execute(Statement)}.
203+ * <p>
204+ * Parameterized simple statements are useful when you want to execute a
205+ * query only once (and thus do not want to resort to prepared statements), but
206+ * do not want to convert all column values to string (typically, if you have blob
207+ * values, encoding them to a hexadecimal string is not very efficient). In
208+ * that case, you can provide a query string with bind marker to this method,
209+ * along with the values for those bind variables. When executed, the server will
210+ * prepare the provided query, bind the provided values to that prepare statement and
211+ * execute the resulting statement. Thus,
212+ * <pre>
213+ * session.execute(session.newSimpleStatement(query, value1, value2, value3));
214+ * </pre>
215+ * is functionally equivalent to
216+ * <pre>
217+ * PreparedStatement ps = session.prepare(query);
218+ * session.execute(ps.bind(value1, value2, value3));
219+ * </pre>
220+ * except that the former version:
221+ * <ul>
222+ * <li>Requires only one round-trip to a Cassandra node.</li>
223+ * <li>Does not leave any prepared statement stored in memory (neither client or
224+ * server side) once it has been executed.</li>
225+ * </ul>
226+ * <p>
227+ * Note that the type of the {@code values} provided to this method will
228+ * not be validated by the driver as is done by {@link BoundStatement#bind} since
229+ * {@code query} is not parsed (and hence the driver cannot know what those value
230+ * should be). The codec to serialize each value will be chosen in the codec registry
231+ * associated with this session's cluster, based on the value's Java type
232+ * (this is the equivalent to calling {@link CodecRegistry#codecFor(Object)}).
233+ * If too many or too few values are provided, or if a value is not a valid one for
234+ * the variable it is bound to, an
235+ * {@link com.datastax.driver.core.exceptions.InvalidQueryException} will be thrown
236+ * by Cassandra at execution time. A {@code CodecNotFoundException} may be
237+ * thrown by this constructor however, if the codec registry does not know how to
238+ * handle one of the values.
239+ *
240+ * @param query the CQL query to execute.
241+ * @param values values required for the execution of {@code query}.
242+ * @return the simple statement.
243+ */
244+ public SimpleStatement newSimpleStatement(String query, Object... values);
245+
184246 /**
185247 * Executes the provided query asynchronously.
186248 *
modified driver-core/src/main/java/com/datastax/driver/core/SessionManager.java +6 −3
@@ -147,7 +147,7 @@
147147 switch (rm.kind) {
148148 case PREPARED:
149149 Responses.Result.Prepared pmsg = (Responses.Result.Prepared)rm;
150- PreparedStatement stmt = DefaultPreparedStatement.fromMessage(pmsg, cluster.getMetadata(), cluster.getConfiguration().getProtocolOptions().getProtocolVersion(), query, poolsState.keyspace);
150+ PreparedStatement stmt = DefaultPreparedStatement.fromMessage(pmsg, cluster, query, poolsState.keyspace);
151151 stmt = cluster.manager.addPrepared(stmt);
152152 try {
153153 // All Sessions are connected to the same nodes so it's enough to prepare only the nodes of this session.
@@ -499,6 +499,7 @@
499499 statement = ((StatementWrapper)statement).getWrappedStatement();
500500
501501 Message.Request request;
502+
502503 if (statement instanceof RegularStatement) {
503504 RegularStatement rs = (RegularStatement)statement;
504505
@@ -508,13 +509,15 @@
508509 if (version == ProtocolVersion.V1 && rs instanceof com.datastax.driver.core.querybuilder.BuiltStatement)
509510 ((com.datastax.driver.core.querybuilder.BuiltStatement)rs).setForceNoValues(true);
510511
511- ByteBuffer[] rawValues = rs.getValues(version);
512+ ByteBuffer[] rawValues = rs.getValues();
512513
513514 if (version == ProtocolVersion.V1 && rawValues != null)
514515 throw new UnsupportedFeatureException(version, "Binary values are not supported");
515516
516517 List<ByteBuffer> values = rawValues == null ? Collections.<ByteBuffer>emptyList() : Arrays.asList(rawValues);
518+
517519 String qString = rs.getQueryString();
520+
518521 Requests.QueryProtocolOptions options = new Requests.QueryProtocolOptions(consistency, values, false,
519522 fetchSize, usedPagingState, serialConsistency, defaultTimestamp);
520523 request = new Requests.Query(qString, options, statement.isTracing());
@@ -540,7 +543,7 @@
540543 BatchStatement bs = (BatchStatement)statement;
541544 if (version.compareTo(ProtocolVersion.V4) < 0)
542545 bs.ensureAllSet();
543- BatchStatement.IdAndValues idAndVals = bs.getIdAndValues(version);
546+ BatchStatement.IdAndValues idAndVals = bs.getIdAndValues();
544547 Requests.BatchProtocolOptions options = new Requests.BatchProtocolOptions(consistency, serialConsistency, defaultTimestamp);
545548 request = new Requests.Batch(bs.batchType, idAndVals.ids, idAndVals.values, options, statement.isTracing());
546549 }
modified driver-core/src/main/java/com/datastax/driver/core/SettableByIndexData.java +241 −1
@@ -21,6 +21,8 @@
2121 import java.nio.ByteBuffer;
2222 import java.util.*;
2323
24+import com.google.common.reflect.TypeToken;
25+
2426 import com.datastax.driver.core.exceptions.InvalidTypeException;
2527
2628 /**
@@ -246,7 +248,14 @@
246248 /**
247249 * Sets the {@code i}th value to the provided list.
248250 * <p>
249- * Please note that {@code null} values are not supported inside collection by CQL.
251+ * Please note that {@code null} values inside collections are not supported by CQL.
252+ * <p>
253+ * Note about performance: this method must perform a runtime inspection of the provided list,
254+ * 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.
250259 *
251260 * @param i the index of the value to set.
252261 * @param v the value to set.
@@ -261,10 +270,65 @@
261270 */
262271 public <E> T setList(int i, List<E> v);
263272
273+ /**
274+ * Sets the {@code i}th value to the provided list, whose elements are of the provided
275+ * Java class.
276+ * <p>
277+ * Please note that {@code null} values inside collections are not supported by CQL.
278+ * <p>
279+ * Note about performance: this method is able to cache codecs used to serialize the list elements,
280+ * and thus should be used instead of {@link #setList(int, List)}
281+ * whenever possible, because it performs significantly better.
282+ *
283+ * @param i the index of the value to set.
284+ * @param v the value to set.
285+ * @param elementsClass the class for the elements of the list.
286+ * @return this object.
287+ *
288+ * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
289+ * @throws InvalidTypeException if value {@code i} is not a list type or
290+ * if the elements of {@code v} are not of the type of the elements of
291+ * column {@code i}.
292+ * @throws NullPointerException if {@code v} contains null values. Nulls are not supported in collections
293+ * by CQL.
294+ */
295+ public <E> T setList(int i, List<E> v, Class<E> elementsClass);
296+
297+ /**
298+ * Sets the {@code i}th value to the provided list, whose elements are of the provided
299+ * Java type.
300+ * <p>
301+ * Please note that {@code null} values inside collections are not supported by CQL.
302+ * <p>
303+ * Note about performance: this method is able to cache codecs used to serialize the list elements,
304+ * and thus should be used instead of {@link #setList(int, List)}
305+ * whenever possible, because it performs significantly better.
306+ *
307+ * @param i the index of the value to set.
308+ * @param v the value to set.
309+ * @param elementsType the type for the elements of the list.
310+ * @return this object.
311+ *
312+ * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
313+ * @throws InvalidTypeException if value {@code i} is not a list type or
314+ * if the elements of {@code v} are not of the type of the elements of
315+ * column {@code i}.
316+ * @throws NullPointerException if {@code v} contains null values. Nulls are not supported in collections
317+ * by CQL.
318+ */
319+ public <E> T setList(int i, List<E> v, TypeToken<E> elementsType);
320+
264321 /**
265322 * Sets the {@code i}th value to the provided map.
266323 * <p>
267324 * Please note that {@code null} values are not supported inside collection by CQL.
325+ * <p>
326+ * Note about performance: this method must perform a runtime inspection of the provided map,
327+ * in order to guess the best codec to serialize the map entries.
328+ * The result of such inspection cannot be cached and thus must be performed for each invocation
329+ * 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.
268332 *
269333 * @param i the index of the value to set.
270334 * @param v the value to set.
@@ -279,10 +343,67 @@
279343 */
280344 public <K, V> T setMap(int i, Map<K, V> v);
281345
346+ /**
347+ * Sets the {@code i}th value to the provided map, whose keys and values are of the provided
348+ * Java classes.
349+ * <p>
350+ * Please note that {@code null} values inside collections are not supported by CQL.
351+ * <p>
352+ * Note about performance: this method is able to cache codecs used to serialize the map entries,
353+ * and thus should be used instead of {@link #setMap(int, Map)}
354+ * whenever possible, because it performs significantly better.
355+ *
356+ * @param i the index of the value to set.
357+ * @param v the value to set.
358+ * @param keysClass the class for the keys of the map.
359+ * @param valuesClass the class for the values of the map.
360+ * @return this object.
361+ *
362+ * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
363+ * @throws InvalidTypeException if value {@code i} is not a map type or
364+ * if the elements of {@code v} are not of the type of the elements of
365+ * column {@code i}.
366+ * @throws NullPointerException if {@code v} contains null values. Nulls are not supported in collections
367+ * by CQL.
368+ */
369+ public <K, V> T setMap(int i, Map<K, V> v, Class<K> keysClass, Class<V> valuesClass);
370+
371+ /**
372+ * Sets the {@code i}th value to the provided map, whose keys and values are of the provided
373+ * Java types.
374+ * <p>
375+ * Please note that {@code null} values inside collections are not supported by CQL.
376+ * <p>
377+ * Note about performance: this method is able to cache codecs used to serialize the map entries,
378+ * and thus should be used instead of {@link #setMap(int, Map)}
379+ * whenever possible, because it performs significantly better.
380+ *
381+ * @param i the index of the value to set.
382+ * @param v the value to set.
383+ * @param keysType the type for the keys of the map.
384+ * @param valuesType the type for the values of the map.
385+ * @return this object.
386+ *
387+ * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
388+ * @throws InvalidTypeException if value {@code i} is not a map type or
389+ * if the elements of {@code v} are not of the type of the elements of
390+ * column {@code i}.
391+ * @throws NullPointerException if {@code v} contains null values. Nulls are not supported in collections
392+ * by CQL.
393+ */
394+ public <K, V> T setMap(int i, Map<K, V> v, TypeToken<K> keysType, TypeToken<V> valuesType);
395+
282396 /**
283397 * Sets the {@code i}th value to the provided set.
284398 * <p>
285399 * Please note that {@code null} values are not supported inside collection by CQL.
400+ * <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.
403+ * The result of such inspection cannot be cached and thus must be performed for each invocation
404+ * 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.
286407 *
287408 * @param i the index of the value to set.
288409 * @param v the value to set.
@@ -297,6 +418,54 @@
297418 */
298419 public <E> T setSet(int i, Set<E> v);
299420
421+ /**
422+ * Sets the {@code i}th value to the provided set, whose elements are of the provided
423+ * Java class.
424+ * <p>
425+ * Please note that {@code null} values inside collections are not supported by CQL.
426+ * <p>
427+ * Note about performance: this method is able to cache codecs used to serialize the set elements,
428+ * and thus should be used instead of {@link #setSet(int, Set)}
429+ * whenever possible, because it performs significantly better.
430+ *
431+ * @param i the index of the value to set.
432+ * @param v the value to set.
433+ * @param elementsClass the class for the elements of the set.
434+ * @return this object.
435+ *
436+ * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
437+ * @throws InvalidTypeException if value {@code i} is not a set type or
438+ * if the elements of {@code v} are not of the type of the elements of
439+ * column {@code i}.
440+ * @throws NullPointerException if {@code v} contains null values. Nulls are not supported in collections
441+ * by CQL.
442+ */
443+ public <E> T setSet(int i, Set<E> v, Class<E> elementsClass);
444+
445+ /**
446+ * Sets the {@code i}th value to the provided set, whose elements are of the provided
447+ * Java type.
448+ * <p>
449+ * Please note that {@code null} values inside collections are not supported by CQL.
450+ * <p>
451+ * Note about performance: this method is able to cache codecs used to serialize the set elements,
452+ * and thus should be used instead of {@link #setSet(int, Set)}
453+ * whenever possible, because it performs significantly better.
454+ *
455+ * @param i the index of the value to set.
456+ * @param v the value to set.
457+ * @param elementsType the type for the elements of the set.
458+ * @return this object.
459+ *
460+ * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
461+ * @throws InvalidTypeException if value {@code i} is not a set type or
462+ * if the elements of {@code v} are not of the type of the elements of
463+ * column {@code i}.
464+ * @throws NullPointerException if {@code v} contains null values. Nulls are not supported in collections
465+ * by CQL.
466+ */
467+ public <E> T setSet(int i, Set<E> v, TypeToken<E> elementsType);
468+
300469 /**
301470 * Sets the {@code i}th value to the provided UDT value.
302471 *
@@ -333,4 +502,75 @@
333502 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
334503 */
335504 public T setToNull(int i);
505+
506+ /**
507+ * Sets the {@code i}th value to the provided value.
508+ * <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.
512+ *
513+ * @param i the index of the value to set.
514+ * @param v the value to set; may be {@code null}.
515+ * @return this object.
516+ * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
517+ */
518+ <V> T setObject(int i, V v);
519+
520+ /**
521+ * Sets the {@code i}th value to the provided value of the provided Java class.
522+ * <p>
523+ * A suitable {@link TypeCodec} instance for the underlying CQL type and the provided class must
524+ * have been previously registered with the {@link CodecRegistry} currently in use.
525+ * <p>
526+ * This method should be used instead of {@link #setObject(int, Object)} in cases
527+ * where more than one codec is registered for the same CQL type; specifying the Java class
528+ * allows the {@link CodecRegistry} to narrow down the search and return only an exactly-matching codec (if any),
529+ * thus avoiding any risk of ambiguity.
530+ *
531+ * @param i the index of the value to set.
532+ * @param v the value to set; may be {@code null}.
533+ * @param targetClass The Java class to convert to; must not be {@code null};
534+ * @return this object.
535+ * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
536+ */
537+ <V> T set(int i, V v, Class<V> targetClass);
538+
539+ /**
540+ * Sets the {@code i}th value to the provided value of the provided Java type.
541+ * <p>
542+ * A suitable {@link TypeCodec} instance for the underlying CQL type and the provided class must
543+ * have been previously registered with the {@link CodecRegistry} currently in use.
544+ * <p>
545+ * This method should be used instead of {@link #setObject(int, Object)} in cases
546+ * where more than one codec is registered for the same CQL type; specifying the Java class
547+ * allows the {@link CodecRegistry} to narrow down the search and return only an exactly-matching codec (if any),
548+ * thus avoiding any risk of ambiguity.
549+ *
550+ * @param i the index of the value to set.
551+ * @param v the value to set; may be {@code null}.
552+ * @param targetType The Java type to convert to; must not be {@code null};
553+ * @return this object.
554+ * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
555+ */
556+ <V> T set(int i, V v, TypeToken<V> targetType);
557+
558+ /**
559+ * Sets the {@code i}th value to the provided value, converted using the given {@link TypeCodec}.
560+ * <p>
561+ * Note that this method allows to entirely bypass the {@link CodecRegistry} currently in use
562+ * and forces the driver to use the given codec instead.
563+ * <p>
564+ * It is the caller's responsibility to ensure that the given codec {@link TypeCodec#accepts(DataType) accepts}
565+ * the underlying CQL type; failing to do so may result in {@link InvalidTypeException}s being thrown.
566+ *
567+ * @param i the index of the value to set.
568+ * @param v the value to set; may be {@code null}.
569+ * @param codec The {@link TypeCodec} to use to serialize the value; may not be {@code null}.
570+ * @return this object.
571+ * @throws InvalidTypeException if the given codec does not {@link TypeCodec#accepts(DataType) accept} the underlying CQL type.
572+ * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
573+ */
574+ <V> T set(int i, V v, TypeCodec<V> codec);
575+
336576 }
modified driver-core/src/main/java/com/datastax/driver/core/SettableByNameData.java +249 −1
@@ -21,6 +21,8 @@
2121 import java.nio.ByteBuffer;
2222 import java.util.*;
2323
24+import com.google.common.reflect.TypeToken;
25+
2426 import com.datastax.driver.core.exceptions.InvalidTypeException;
2527
2628 /**
@@ -290,7 +292,14 @@
290292 * Sets the value for (all occurrences of) variable {@code name} to the
291293 * provided list.
292294 * <p>
293- * Please note that {@code null} values are not supported inside collection by CQL.
295+ * Please note that {@code null} values inside collections are not supported by CQL.
296+ * <p>
297+ * Note about performance: this method must perform a runtime inspection of the provided list,
298+ * in order to guess the best codec to serialize the list elements.
299+ * The result of such inspection cannot be cached and thus must be performed for each invocation
300+ * 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.
294303 *
295304 * @param name the name of the value to set; if {@code name} is present multiple
296305 * times, all its values are set.
@@ -306,11 +315,66 @@
306315 */
307316 public <E> T setList(String name, List<E> v);
308317
318+ /**
319+ * Sets the value for (all occurrences of) variable {@code name} to the provided list,
320+ * whose elements are of the provided Java class.
321+ * <p>
322+ * Please note that {@code null} values inside collections are not supported by CQL.
323+ * <p>
324+ * Note about performance: this method is able to cache codecs used to serialize the list elements,
325+ * and thus should be used instead of {@link #setList(String, List)}
326+ * whenever possible, because it performs significantly better.
327+ *
328+ * @param name the name of the value to set; if {@code name} is present multiple
329+ * @param v the value to set.
330+ * @param elementsClass the class for the elements of the list.
331+ * @return this object.
332+ *
333+ * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
334+ * @throws InvalidTypeException if value {@code i} is not a list type or
335+ * if the elements of {@code v} are not of the type of the elements of
336+ * column {@code i}.
337+ * @throws NullPointerException if {@code v} contains null values. Nulls are not supported in collections
338+ * by CQL.
339+ */
340+ public <E> T setList(String name, List<E> v, Class<E> elementsClass);
341+
342+ /**
343+ * Sets the value for (all occurrences of) variable {@code name} to the provided list,
344+ * whose elements are of the provided Java type.
345+ * <p>
346+ * Please note that {@code null} values inside collections are not supported by CQL.
347+ * <p>
348+ * Note about performance: this method is able to cache codecs used to serialize the list elements,
349+ * and thus should be used instead of {@link #setList(String, List)}
350+ * whenever possible, because it performs significantly better.
351+ *
352+ * @param name the name of the value to set; if {@code name} is present multiple
353+ * @param v the value to set.
354+ * @param elementsType the type for the elements of the list.
355+ * @return this object.
356+ *
357+ * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
358+ * @throws InvalidTypeException if value {@code i} is not a list type or
359+ * if the elements of {@code v} are not of the type of the elements of
360+ * column {@code i}.
361+ * @throws NullPointerException if {@code v} contains null values. Nulls are not supported in collections
362+ * by CQL.
363+ */
364+ public <E> T setList(String name, List<E> v, TypeToken<E> elementsType);
365+
309366 /**
310367 * Sets the value for (all occurrences of) variable {@code name} to the
311368 * provided map.
312369 * <p>
313370 * Please note that {@code null} values are not supported inside collection by CQL.
371+ * <p>
372+ * Note about performance: this method must perform a runtime inspection of the provided map,
373+ * in order to guess the best codec to serialize the map entries.
374+ * The result of such inspection cannot be cached and thus must be performed for each invocation
375+ * 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.
314378 *
315379 * @param name the name of the value to set; if {@code name} is present multiple
316380 * times, all its values are set.
@@ -326,11 +390,70 @@
326390 */
327391 public <K, V> T setMap(String name, Map<K, V> v);
328392
393+ /**
394+ * Sets the value for (all occurrences of) variable {@code name} to the provided map,
395+ * whose keys and values are of the provided Java classes.
396+ * <p>
397+ * Please note that {@code null} values inside collections are not supported by CQL.
398+ * <p>
399+ * Note about performance: this method is able to cache codecs used to serialize the map entries,
400+ * and thus should be used instead of {@link #setMap(String, Map)}
401+ * whenever possible, because it performs significantly better.
402+ *
403+ * @param name the name of the value to set; if {@code name} is present multiple
404+ * times, all its values are set.
405+ * @param v the value to set.
406+ * @param keysClass the class for the keys of the map.
407+ * @param valuesClass the class for the values of the map.
408+ * @return this object.
409+ *
410+ * @throws IllegalArgumentException if {@code name} is not a valid name for this object.
411+ * @throws InvalidTypeException if (any occurrence of) {@code name} is
412+ * not a map type or if the elements (keys or values) of {@code v} are not of
413+ * the type of the elements of column {@code name}.
414+ * @throws NullPointerException if {@code v} contains null values. Nulls are not supported in collections
415+ * by CQL.
416+ */
417+ public <K, V> T setMap(String name, Map<K, V> v, Class<K> keysClass, Class<V> valuesClass);
418+
419+ /**
420+ * Sets the value for (all occurrences of) variable {@code name} to the provided map,
421+ * whose keys and values are of the provided Java types.
422+ * <p>
423+ * Please note that {@code null} values inside collections are not supported by CQL.
424+ * <p>
425+ * Note about performance: this method is able to cache codecs used to serialize the map entries,
426+ * and thus should be used instead of {@link #setMap(String, Map)}
427+ * whenever possible, because it performs significantly better.
428+ *
429+ * @param name the name of the value to set; if {@code name} is present multiple
430+ * times, all its values are set.
431+ * @param v the value to set.
432+ * @param keysType the type for the keys of the map.
433+ * @param valuesType the type for the values of the map.
434+ * @return this object.
435+ *
436+ * @throws IllegalArgumentException if {@code name} is not a valid name for this object.
437+ * @throws InvalidTypeException if (any occurrence of) {@code name} is
438+ * not a map type or if the elements (keys or values) of {@code v} are not of
439+ * the type of the elements of column {@code name}.
440+ * @throws NullPointerException if {@code v} contains null values. Nulls are not supported in collections
441+ * by CQL.
442+ */
443+ public <K, V> T setMap(String name, Map<K, V> v, TypeToken<K> keysType, TypeToken<V> valuesType);
444+
329445 /**
330446 * Sets the value for (all occurrences of) variable {@code name} to the
331447 * provided set.
332448 * <p>
333449 * Please note that {@code null} values are not supported inside collection by CQL.
450+ * <p>
451+ * 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.
453+ * The result of such inspection cannot be cached and thus must be performed for each invocation
454+ * 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.
334457 *
335458 * @param name the name of the value to set; if {@code name} is present multiple
336459 * times, all its values are set.
@@ -346,6 +469,54 @@
346469 */
347470 public <E> T setSet(String name, Set<E> v);
348471
472+ /**
473+ * Sets the value for (all occurrences of) variable {@code name} to the provided set,
474+ * whose elements are of the provided Java class.
475+ * <p>
476+ * Please note that {@code null} values inside collections are not supported by CQL.
477+ * <p>
478+ * Note about performance: this method is able to cache codecs used to serialize the set elements,
479+ * and thus should be used instead of {@link #setSet(String, Set)}
480+ * whenever possible, because it performs significantly better.
481+ *
482+ * @param name the name of the value to set; if {@code name} is present multiple
483+ * @param v the value to set.
484+ * @param elementsClass the class for the elements of the set.
485+ * @return this object.
486+ *
487+ * @throws IllegalArgumentException if {@code name} is not a valid name for this object.
488+ * @throws InvalidTypeException if (any occurrence of) {@code name} is
489+ * not a map type or if the elements (keys or values) of {@code v} are not of
490+ * the type of the elements of column {@code name}.
491+ * @throws NullPointerException if {@code v} contains null values. Nulls are not supported in collections
492+ * by CQL.
493+ */
494+ public <E> T setSet(String name, Set<E> v, Class<E> elementsClass);
495+
496+ /**
497+ * Sets the value for (all occurrences of) variable {@code name} to the provided set,
498+ * whose elements are of the provided Java type.
499+ * <p>
500+ * Please note that {@code null} values inside collections are not supported by CQL.
501+ * <p>
502+ * Note about performance: this method is able to cache codecs used to serialize the set elements,
503+ * and thus should be used instead of {@link #setSet(String, Set)}
504+ * whenever possible, because it performs significantly better.
505+ *
506+ * @param name the name of the value to set; if {@code name} is present multiple
507+ * @param v the value to set.
508+ * @param elementsType the type for the elements of the set.
509+ * @return this object.
510+ *
511+ * @throws IllegalArgumentException if {@code name} is not a valid name for this object.
512+ * @throws InvalidTypeException if (any occurrence of) {@code name} is
513+ * not a map type or if the elements (keys or values) of {@code v} are not of
514+ * the type of the elements of column {@code name}.
515+ * @throws NullPointerException if {@code v} contains null values. Nulls are not supported in collections
516+ * by CQL.
517+ */
518+ public <E> T setSet(String name, Set<E> v, TypeToken<E> elementsType);
519+
349520 /**
350521 * Sets the value for (all occurrences of) variable {@code name} to the
351522 * provided UDT value.
@@ -391,4 +562,81 @@
391562 * @throws IllegalArgumentException if {@code name} is not a valid name for this object.
392563 */
393564 public T setToNull(String name);
565+
566+ /**
567+ * Sets the value for (all occurrences of) variable {@code name} to the provided value.
568+ * <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.
572+ *
573+ * @param name the name of the value to set; if {@code name} is present multiple
574+ * times, all its values are set.
575+ * @param v the value to set; may be {@code null}.
576+ * @return this object.
577+ * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
578+ */
579+ <V> T setObject(String name, V v);
580+
581+ /**
582+ * Sets the value for (all occurrences of) variable {@code name} to the provided value of the provided Java class.
583+ * <p>
584+ * A suitable {@link TypeCodec} instance for the underlying CQL type and the provided class must
585+ * have been previously registered with the {@link CodecRegistry} currently in use.
586+ * <p>
587+ * This method should be used instead of {@link #setObject(String, Object)} in cases
588+ * where more than one codec is registered for the same CQL type; specifying the Java class
589+ * allows the {@link CodecRegistry} to narrow down the search and return only an exactly-matching codec (if any),
590+ * thus avoiding any risk of ambiguity.
591+ *
592+ * @param name the name of the value to set; if {@code name} is present multiple
593+ * times, all its values are set.
594+ * @param v the value to set; may be {@code null}.
595+ * @param targetClass The Java class to convert to; must not be {@code null};
596+ * @return this object.
597+ * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
598+ */
599+ <V> T set(String name, V v, Class<V> targetClass);
600+
601+ /**
602+ * Sets the value for (all occurrences of) variable {@code name} to the provided value of the provided Java type.
603+ * <p>
604+ * A suitable {@link TypeCodec} instance for the underlying CQL type and the provided class must
605+ * have been previously registered with the {@link CodecRegistry} currently in use.
606+ * <p>
607+ * This method should be used instead of {@link #setObject(String, Object)} in cases
608+ * where more than one codec is registered for the same CQL type; specifying the Java class
609+ * allows the {@link CodecRegistry} to narrow down the search and return only an exactly-matching codec (if any),
610+ * thus avoiding any risk of ambiguity.
611+ *
612+ * @param name the name of the value to set; if {@code name} is present multiple
613+ * times, all its values are set.
614+ * @param v the value to set; may be {@code null}.
615+ * @param targetType The Java type to convert to; must not be {@code null};
616+ * @return this object.
617+ * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
618+ */
619+ <V> T set(String name, V v, TypeToken<V> targetType);
620+
621+ /**
622+ * Sets the value for (all occurrences of) variable {@code name} to the provided value,
623+ * converted using the given {@link TypeCodec}.
624+ * <p>
625+ * Note that this method allows to entirely bypass the {@link CodecRegistry} currently in use
626+ * and forces the driver to use the given codec instead.
627+ * <p>
628+ * It is the caller's responsibility to ensure that the given codec {@link TypeCodec#accepts(DataType) accepts}
629+ * the underlying CQL type; failing to do so may result in {@link InvalidTypeException}s being thrown.
630+ *
631+ * @param name the name of the value to set; if {@code name} is present multiple
632+ * times, all its values are set.
633+ * @param v the value to set; may be {@code null}.
634+ * @param codec The {@link TypeCodec} to use to serialize the value; may not be {@code null}.
635+ * @return this object.
636+ * @throws InvalidTypeException if the given codec does not {@link TypeCodec#accepts(DataType) accept} the underlying CQL type.
637+ * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
638+ */
639+ <V> T set(String name, V v, TypeCodec<V> codec);
640+
641+
394642 }
modified driver-core/src/main/java/com/datastax/driver/core/SimpleStatement.java +24 −100
@@ -17,6 +17,9 @@
1717
1818 import java.nio.ByteBuffer;
1919
20+import static com.datastax.driver.core.CodecUtils.compose;
21+import static com.datastax.driver.core.CodecUtils.convert;
22+
2023 /**
2124 * A simple {@code RegularStatement} implementation built directly from a query
2225 * string.
@@ -25,99 +28,42 @@
2528
2629 private final String query;
2730 private final Object[] values;
31+ private final Cluster cluster;
2832
2933 private volatile ByteBuffer routingKey;
3034 private volatile String keyspace;
31-
32- /**
33- * Creates a new {@code SimpleStatement} with the provided query string (and no values).
34- *
35- * @param query the query string.
36- */
37- public SimpleStatement(String query) {
38- this.query = query;
39- this.values = null;
35+
36+ protected SimpleStatement(String query, Cluster cluster) {
37+ this(query, cluster, (Object[]) null);
4038 }
4139
42- /**
43- * Creates a new {@code SimpleStatement} with the provided query string and values.
44- * <p>
45- * This version of SimpleStatement is useful when you do not want to execute a
46- * query only once (and thus do not want to resort to prepared statement), but
47- * do not want to convert all column values to string (typically, if you have blob
48- * values, encoding them to a hexadecimal string is not very efficient). In
49- * that case, you can provide a query string with bind marker to this constructor
50- * along with the values for those bind variables. When executed, the server will
51- * prepare the provided, bind the provided values to that prepare statement and
52- * execute the resulting statement. Thus,
53- * <pre>
54- * session.execute(new SimpleStatement(query, value1, value2, value3));
55- * </pre>
56- * is functionally equivalent to
57- * <pre>
58- * PreparedStatement ps = session.prepare(query);
59- * session.execute(ps.bind(value1, value2, value3));
60- * </pre>
61- * except that the former version:
62- * <ul>
63- * <li>Requires only one round-trip to a Cassandra node.</li>
64- * <li>Does not left any prepared statement stored in memory (neither client or
65- * server side) once it has been executed.</li>
66- * </ul>
67- * <p>
68- * Note that the type of the {@code values} provided to this method will
69- * not be validated by the driver as is done by {@link BoundStatement#bind} since
70- * {@code query} is not parsed (and hence the driver cannot know what those value
71- * should be). If too much or too little values are provided or if a value is not
72- * a valid one for the variable it is bound to, an
73- * {@link com.datastax.driver.core.exceptions.InvalidQueryException} will be thrown
74- * by Cassandra at execution time. An {@code IllegalArgumentException} may be
75- * thrown by this constructor however if one of the value does not correspond to
76- * any CQL3 type (for instance, if it is a custom class).
77- *
78- * @param query the query string.
79- * @param values values required for the execution of {@code query}.
80- *
81- * @throws IllegalArgumentException if one of {@code values} is not of a type
82- * corresponding to a CQL3 type, i.e. is not a Class that could be returned
83- * by {@link DataType#asJavaClass}.
84- */
85- public SimpleStatement(String query, Object... values) {
86- if (values.length > 65535)
40+ protected SimpleStatement(String query, Cluster cluster, Object... values) {
41+ if (values != null && values.length > 65535)
8742 throw new IllegalArgumentException("Too many values, the maximum allowed is 65535");
8843 this.query = query;
8944 this.values = values;
45+ this.cluster = cluster;
9046 }
9147
92- private static ByteBuffer[] convert(Object[] values, ProtocolVersion protocolVersion) {
93- ByteBuffer[] serializedValues = new ByteBuffer[values.length];
94- for (int i = 0; i < values.length; i++) {
95- Object value = values[i];
96- try {
97- if (value instanceof Token)
98- value = ((Token)value).getValue();
99- serializedValues[i] = DataType.serializeValue(value, protocolVersion);
100- } catch (IllegalArgumentException e) {
101- // Catch and rethrow to provide a more helpful error message (one that include which value is bad)
102- throw new IllegalArgumentException(String.format("Value %d of type %s does not correspond to any CQL3 type", i, value.getClass()));
103- }
104- }
105- return serializedValues;
106- }
107-
108- /**
109- * Returns the query string.
110- *
111- * @return the query string;
112- */
11348 @Override
11449 public String getQueryString() {
11550 return query;
11651 }
11752
53+ /**
54+ * {@inheritDoc}
55+ * <p>
56+ * Note: Calling this method may trigger the underlying {@link Cluster} initialization.
57+ */
11858 @Override
119- public ByteBuffer[] getValues(ProtocolVersion protocolVersion) {
120- return values == null ? null : convert(values, protocolVersion);
59+ public ByteBuffer[] getValues() {
60+ if(values == null)
61+ return null;
62+ cluster.init();
63+ Configuration configuration = cluster.getConfiguration();
64+ ProtocolVersion protocolVersion = configuration.getProtocolOptions().getProtocolVersion();
65+ CodecRegistry codecRegistry = configuration.getCodecRegistry();
66+ return convert(values, protocolVersion, codecRegistry);
12167 }
12268
12369 /**
@@ -229,26 +175,4 @@
229175 return this;
230176 }
231177
232- // TODO: we could find that a better place (but it's not expose so it doesn't matter too much)
233- static ByteBuffer compose(ByteBuffer... buffers) {
234- int totalLength = 0;
235- for (ByteBuffer bb : buffers)
236- totalLength += 2 + bb.remaining() + 1;
237-
238- ByteBuffer out = ByteBuffer.allocate(totalLength);
239- for (ByteBuffer buffer : buffers)
240- {
241- ByteBuffer bb = buffer.duplicate();
242- putShortLength(out, bb.remaining());
243- out.put(bb);
244- out.put((byte) 0);
245- }
246- out.flip();
247- return out;
248- }
249-
250- private static void putShortLength(ByteBuffer bb, int length) {
251- bb.put((byte) ((length >> 8) & 0xFF));
252- bb.put((byte) (length & 0xFF));
253- }
254-}
No newline at the end of the file
178+}
modified driver-core/src/main/java/com/datastax/driver/core/Statement.java +1 −1
@@ -484,4 +484,4 @@
484484 this.outgoingPayload = payload == null ? null : ImmutableMap.copyOf(payload);
485485 return this;
486486 }
487-}
No newline at the end of the file
487+}
modified driver-core/src/main/java/com/datastax/driver/core/TableMetadata.java +4 −4
@@ -98,15 +98,15 @@
9898 this.cassandraVersion = cassandraVersion;
9999 }
100100
101- static TableMetadata build(KeyspaceMetadata ksm, Row row, Map<String, ColumnMetadata.Raw> rawCols, VersionNumber cassandraVersion) {
101+ static TableMetadata build(KeyspaceMetadata ksm, Row row, Map<String, ColumnMetadata.Raw> rawCols, VersionNumber cassandraVersion, ProtocolVersion protocolVersion, CodecRegistry codecRegistry) {
102102
103103 String name = row.getString(CF_NAME);
104104 UUID id = (cassandraVersion.getMajor() > 2 || (cassandraVersion.getMajor() == 2 && cassandraVersion.getMinor() >= 1))
105105 ? row.getUUID(CF_ID)
106106 : null;
107107
108- CassandraTypeParser.ParseResult keyValidator = CassandraTypeParser.parseWithComposite(row.getString(KEY_VALIDATOR));
109- CassandraTypeParser.ParseResult comparator = CassandraTypeParser.parseWithComposite(row.getString(COMPARATOR));
108+ CassandraTypeParser.ParseResult keyValidator = CassandraTypeParser.parseWithComposite(row.getString(KEY_VALIDATOR), protocolVersion, codecRegistry);
109+ CassandraTypeParser.ParseResult comparator = CassandraTypeParser.parseWithComposite(row.getString(COMPARATOR), protocolVersion, codecRegistry);
110110 List<String> columnAliases = cassandraVersion.getMajor() >= 2 || row.getString(COLUMN_ALIASES) == null
111111 ? Collections.<String>emptyList()
112112 : SimpleJSONParser.parseStringList(row.getString(COLUMN_ALIASES));
@@ -159,7 +159,7 @@
159159 // We have a value alias if we're dense
160160 if (isDense) {
161161 String alias = row.isNull(VALUE_ALIAS) ? DEFAULT_VALUE_ALIAS : row.getString(VALUE_ALIAS);
162- DataType type = CassandraTypeParser.parseOne(row.getString(VALIDATOR));
162+ DataType type = CassandraTypeParser.parseOne(row.getString(VALIDATOR), protocolVersion, codecRegistry);
163163 otherColumns.add(ColumnMetadata.forAlias(tm, alias, type));
164164 }
165165 }
modified driver-core/src/main/java/com/datastax/driver/core/Token.java +28 −3
@@ -19,7 +19,6 @@
1919 import java.nio.ByteBuffer;
2020 import java.security.MessageDigest;
2121 import java.security.NoSuchAlgorithmException;
22-import java.util.Arrays;
2322 import java.util.List;
2423
2524 import com.google.common.annotations.VisibleForTesting;
@@ -47,6 +46,17 @@
4746 */
4847 public abstract Object getValue();
4948
49+ /**
50+ * Returns the serialized form of the current token,
51+ * using the appropriate codec depending on the
52+ * partitioner in use and the CQL datatype for
53+ * the token.
54+ *
55+ * @param protocolVersion the protocol version in use.
56+ * @return the serialized form of the current token
57+ */
58+ public abstract ByteBuffer serialize(ProtocolVersion protocolVersion);
59+
5060 static Token.Factory getFactory(String partitionerName) {
5161 if (partitionerName.endsWith("Murmur3Partitioner"))
5262 return M3PToken.FACTORY;
@@ -213,7 +223,7 @@
213223
214224 @Override
215225 Token deserialize(ByteBuffer buffer, ProtocolVersion protocolVersion) {
216- return new M3PToken((Long) getTokenType().deserialize(buffer, protocolVersion));
226+ return new M3PToken(TypeCodec.BigintCodec.instance.deserialize(buffer, protocolVersion));
217227 }
218228
219229 @Override
@@ -264,6 +274,11 @@
264274 return value;
265275 }
266276
277+ @Override
278+ public ByteBuffer serialize(ProtocolVersion protocolVersion) {
279+ return TypeCodec.BigintCodec.instance.serialize(value, protocolVersion);
280+ }
281+
267282 @Override
268283 public int compareTo(Token other) {
269284 assert other instanceof M3PToken;
@@ -466,6 +481,11 @@
466481 return value;
467482 }
468483
484+ @Override
485+ public ByteBuffer serialize(ProtocolVersion protocolVersion) {
486+ return TypeCodec.BlobCodec.instance.serialize(value, protocolVersion);
487+ }
488+
469489 @Override
470490 public int compareTo(Token other) {
471491 assert other instanceof OPPToken;
@@ -532,7 +552,7 @@
532552
533553 @Override
534554 Token deserialize(ByteBuffer buffer, ProtocolVersion protocolVersion) {
535- return new RPToken((BigInteger)getTokenType().deserialize(buffer, protocolVersion));
555+ return new RPToken(TypeCodec.VarintCodec.instance.deserialize(buffer, protocolVersion));
536556 }
537557
538558 @Override
@@ -582,6 +602,11 @@
582602 return value;
583603 }
584604
605+ @Override
606+ public ByteBuffer serialize(ProtocolVersion protocolVersion) {
607+ return TypeCodec.VarintCodec.instance.serialize(value, protocolVersion);
608+ }
609+
585610 @Override
586611 public int compareTo(Token other) {
587612 assert other instanceof RPToken;
modified driver-core/src/main/java/com/datastax/driver/core/TupleType.java +63 −24
@@ -15,10 +15,10 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.util.*;
18+import java.util.Arrays;
19+import java.util.List;
1920
2021 import com.google.common.collect.ImmutableList;
21-import com.google.common.reflect.TypeToken;
2222
2323 import com.datastax.driver.core.exceptions.InvalidTypeException;
2424
@@ -30,26 +30,14 @@
3030 public class TupleType extends DataType {
3131
3232 private final List<DataType> types;
33+ private final ProtocolVersion protocolVersion;
34+ private volatile CodecRegistry codecRegistry;
3335
34- TupleType(List<DataType> types) {
36+ TupleType(List<DataType> types, ProtocolVersion protocolVersion, CodecRegistry codecRegistry) {
3537 super(DataType.Name.TUPLE);
3638 this.types = ImmutableList.copyOf(types);
37- }
38-
39- @SuppressWarnings("unchecked")
40- @Override
41- TypeCodec<Object> codec(ProtocolVersion protocolVersion) {
42- return (TypeCodec)TypeCodec.tupleOf(this, protocolVersion);
43- }
44-
45- /**
46- * Creates a tuple type given a list of types.
47- *
48- * @param types the types for the tuple type.
49- * @return the newly created tuple type.
50- */
51- public static TupleType of(DataType... types) {
52- return new TupleType(Arrays.asList(types));
39+ this.protocolVersion = protocolVersion;
40+ this.codecRegistry = codecRegistry;
5341 }
5442
5543 /**
@@ -95,8 +83,13 @@
9583 throw new IllegalArgumentException(String.format("Invalid number of values. Expecting %d but got %d", types.size(), values.length));
9684
9785 TupleValue t = newValue();
98- for (int i = 0; i < values.length; i++)
99- t.setValue(i, values[i] == null ? null : types.get(i).serialize(values[i], ProtocolVersion.V3));
86+ for (int i = 0; i < values.length; i++) {
87+ DataType dataType = types.get(i);
88+ if(values[i] == null)
89+ t.setValue(i, null);
90+ else
91+ t.setValue(i, codecRegistry.codecFor(dataType, values[i]).serialize(values[i], protocolVersion));
92+ }
10093 return t;
10194 }
10295
@@ -105,11 +98,30 @@
10598 return true;
10699 }
107100
108- @Override
109- boolean canBeDeserializedAs(TypeToken typeToken) {
110- return typeToken.isAssignableFrom(getName().javaType);
101+ /**
102+ * Return the protocol version that has been used to deserialize
103+ * this tuple type, or that will be used to serialize it.
104+ * In most cases this should be the version
105+ * currently in use by the cluster instance
106+ * that this tuple type belongs to, as reported by
107+ * {@link ProtocolOptions#getProtocolVersion()}.
108+ *
109+ * @return the protocol version that has been used to deserialize
110+ * this tuple type, or that will be used to serialize it.
111+ */
112+ ProtocolVersion getProtocolVersion() {
113+ return protocolVersion;
111114 }
112115
116+ CodecRegistry getCodecRegistry() {
117+ return codecRegistry;
118+ }
119+
120+ void setCodecRegistry(CodecRegistry codecRegistry) {
121+ this.codecRegistry = codecRegistry;
122+ }
123+
124+
113125 @Override
114126 public int hashCode() {
115127 return Arrays.hashCode(new Object[]{ name, types });
@@ -124,6 +136,32 @@
124136 return name == d.name && types.equals(d.types);
125137 }
126138
139+ /**
140+ * Return {@code true} if this tuple type contains the given tuple type,
141+ * and {@code false} otherwise.
142+ * <p>
143+ * A tuple type is said to contain another one
144+ * if the latter has fewer components than the former,
145+ * but all of them are of the same type.
146+ * E.g. the type {@code tuple<int, text>}
147+ * is contained by the type {@code tuple<int, text, double>}.
148+ * <p>
149+ * A contained type can be seen as a "partial" view
150+ * of a containing type, where the missing components
151+ * are supposed to be {@code null}.
152+ *
153+ * @param other the tuple type to compare against the current one
154+ * @return {@code true} if this tuple type contains the given tuple type,
155+ * and {@code false} otherwise.
156+ */
157+ public boolean contains(TupleType other) {
158+ if(this.equals(other))
159+ return true;
160+ if(other.types.size() > this.types.size())
161+ return false;
162+ return types.subList(0, other.types.size()).equals(other.types);
163+ }
164+
127165 @Override
128166 public String toString() {
129167 StringBuilder sb = new StringBuilder();
@@ -133,4 +171,5 @@
133171 }
134172 return sb.append(">>").toString();
135173 }
174+
136175 }
modified driver-core/src/main/java/com/datastax/driver/core/TupleValue.java +14 −8
@@ -15,9 +15,6 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.util.Arrays;
19-import java.util.List;
20-
2118 /**
2219 * A value for a Tuple.
2320 */
@@ -28,11 +25,10 @@
2825 /**
2926 * Builds a new value for a tuple.
3027 *
31- * @param types the types of the tuple's components.
28+ * @param type the {@link TupleType} instance defining this tuple's components.
3229 */
3330 TupleValue(TupleType type) {
34- // All things in a tuple are encoded with the protocol v3
35- super(ProtocolVersion.V3, type.getComponentTypes().size());
31+ super(type.getProtocolVersion(), type.getComponentTypes().size());
3632 this.type = type;
3733 }
3834
@@ -46,6 +42,11 @@
4642 return "component " + i;
4743 }
4844
45+ @Override
46+ protected CodecRegistry getCodecRegistry() {
47+ return type.getCodecRegistry();
48+ }
49+
4950 /**
5051 * The tuple type this is a value of.
5152 *
@@ -80,8 +81,13 @@
8081 if (i > 0)
8182 sb.append(", ");
8283
83- DataType dt = getType(i);
84- sb.append(values[i] == null ? "null" : dt.format(dt.deserialize(values[i], ProtocolVersion.V3)));
84+ if(values[i] == null)
85+ sb.append("null");
86+ else {
87+ DataType dt = getType(i);
88+ TypeCodec<Object> codec = getCodecRegistry().codecFor(dt);
89+ sb.append(codec.format(codec.deserialize(values[i], protocolVersion)));
90+ }
8591 }
8692 sb.append(")");
8793 return sb.toString();
modified driver-core/src/main/java/com/datastax/driver/core/TypeCodec.java +1290 −597
@@ -29,366 +29,401 @@
2929 import java.util.concurrent.TimeUnit;
3030 import java.util.regex.Pattern;
3131
32+import com.google.common.base.Objects;
33+import com.google.common.collect.ImmutableMap;
34+import com.google.common.reflect.TypeToken;
35+
36+import static com.google.common.base.Preconditions.checkArgument;
37+import static com.google.common.base.Preconditions.checkNotNull;
38+
3239 import com.datastax.driver.core.exceptions.InvalidTypeException;
3340 import com.datastax.driver.core.utils.Bytes;
3441
35-abstract class TypeCodec<T> {
36-
37- // Somehow those don't seem to get properly initialized if they're not here. The reason
38- // escape me right now so let's just leave it here for now
39- public static final StringCodec utf8Instance = new StringCodec(Charset.forName("UTF-8"));
40- public static final StringCodec asciiInstance = new StringCodec(Charset.forName("US-ASCII"));
41-
42- private static final Map<DataType.Name, TypeCodec<?>> primitiveCodecs = new EnumMap<DataType.Name, TypeCodec<?>>(DataType.Name.class);
43- static {
44- primitiveCodecs.put(DataType.Name.ASCII, StringCodec.asciiInstance);
45- primitiveCodecs.put(DataType.Name.BIGINT, LongCodec.instance);
46- primitiveCodecs.put(DataType.Name.BLOB, BytesCodec.instance);
47- primitiveCodecs.put(DataType.Name.BOOLEAN, BooleanCodec.instance);
48- primitiveCodecs.put(DataType.Name.COUNTER, LongCodec.instance);
49- primitiveCodecs.put(DataType.Name.DECIMAL, DecimalCodec.instance);
50- primitiveCodecs.put(DataType.Name.DOUBLE, DoubleCodec.instance);
51- primitiveCodecs.put(DataType.Name.FLOAT, FloatCodec.instance);
52- primitiveCodecs.put(DataType.Name.INET, InetCodec.instance);
53- primitiveCodecs.put(DataType.Name.TINYINT, TinyIntCodec.instance);
54- primitiveCodecs.put(DataType.Name.SMALLINT, SmallIntCodec.instance);
55- primitiveCodecs.put(DataType.Name.INT, IntCodec.instance);
56- primitiveCodecs.put(DataType.Name.TEXT, StringCodec.utf8Instance);
57- primitiveCodecs.put(DataType.Name.TIMESTAMP, TimestampCodec.instance);
58- primitiveCodecs.put(DataType.Name.DATE, DateCodec.instance);
59- primitiveCodecs.put(DataType.Name.TIME, TimeCodec.instance);
60- primitiveCodecs.put(DataType.Name.UUID, UUIDCodec.instance);
61- primitiveCodecs.put(DataType.Name.VARCHAR, StringCodec.utf8Instance);
62- primitiveCodecs.put(DataType.Name.VARINT, BigIntegerCodec.instance);
63- primitiveCodecs.put(DataType.Name.TIMEUUID, TimeUUIDCodec.instance);
64- primitiveCodecs.put(DataType.Name.CUSTOM, BytesCodec.instance);
65- }
66-
67- private static class PrimitiveCollectionCodecs
68- {
69- public final Map<DataType.Name, TypeCodec<List<?>>> primitiveListsCodecs = new EnumMap<DataType.Name, TypeCodec<List<?>>>(DataType.Name.class);
70- public final Map<DataType.Name, TypeCodec<Set<?>>> primitiveSetsCodecs = new EnumMap<DataType.Name, TypeCodec<Set<?>>>(DataType.Name.class);
71- public final Map<DataType.Name, Map<DataType.Name, TypeCodec<Map<?, ?>>>> primitiveMapsCodecs = new EnumMap<DataType.Name, Map<DataType.Name, TypeCodec<Map<?, ?>>>>(DataType.Name.class);
72-
73- @SuppressWarnings({"unchecked", "rawtypes"})
74- public PrimitiveCollectionCodecs(ProtocolVersion protocolVersion)
75- {
76- for (Map.Entry<DataType.Name, TypeCodec<?>> entry : primitiveCodecs.entrySet()) {
77- DataType.Name type = entry.getKey();
78- TypeCodec<?> codec = entry.getValue();
79- primitiveListsCodecs.put(type, new ListCodec(codec, protocolVersion));
80- primitiveSetsCodecs.put(type, new SetCodec(codec, protocolVersion));
81- Map<DataType.Name, TypeCodec<Map<?, ?>>> valueMap = new EnumMap<DataType.Name, TypeCodec<Map<?, ?>>>(DataType.Name.class);
82- for (Map.Entry<DataType.Name, TypeCodec<?>> valueEntry : primitiveCodecs.entrySet())
83- valueMap.put(valueEntry.getKey(), new MapCodec(codec, valueEntry.getValue(), protocolVersion));
84- primitiveMapsCodecs.put(type, valueMap);
85- }
86- }
87-
88- private static final PrimitiveCollectionCodecs primitiveCollectionCodecsV2 = new PrimitiveCollectionCodecs(ProtocolVersion.V2);
89- private static final PrimitiveCollectionCodecs primitiveCollectionCodecsV3 = new PrimitiveCollectionCodecs(ProtocolVersion.V3);
90- private static final PrimitiveCollectionCodecs primitiveCollectionCodecsV4 = new PrimitiveCollectionCodecs(ProtocolVersion.V4);
91-
92- static PrimitiveCollectionCodecs forVersion(ProtocolVersion version) {
93- // This happens during protocol negociation, when the version is not known yet.
94- // Use the smallest supported version, which is enough for what we need to do at this stage.
95- if (version == null)
96- version = ProtocolVersion.V1;
97-
98- switch (version) {
99- case V1:
100- case V2:
101- return primitiveCollectionCodecsV2;
102- case V3:
103- return primitiveCollectionCodecsV3;
104- case V4:
105- return primitiveCollectionCodecsV4;
106- default:
107- throw version.unsupported();
108- }
109- }
110- }
111-
112-
113- private TypeCodec() {}
114-
115- public abstract T parse(String value);
116- public abstract String format(T value);
117-
118- public abstract ByteBuffer serialize(T value);
119- public abstract T deserialize(ByteBuffer bytes);
120-
121- @SuppressWarnings("unchecked")
122- static <T> TypeCodec<T> createFor(DataType.Name name) {
123- assert !name.isCollection();
124- return (TypeCodec<T>)primitiveCodecs.get(name);
125- }
126-
127- @SuppressWarnings("unchecked")
128- static <T> TypeCodec<List<T>> listOf(DataType arg, ProtocolVersion protocolVersion) {
129- PrimitiveCollectionCodecs codecs = PrimitiveCollectionCodecs.forVersion(protocolVersion);
130- TypeCodec<List<?>> codec = codecs.primitiveListsCodecs.get(arg.getName());
131- return codec != null ? (TypeCodec)codec : new ListCodec<Object>(arg.codec(protocolVersion), protocolVersion);
132- }
42+import static com.datastax.driver.core.CodecUtils.listOf;
43+import static com.datastax.driver.core.CodecUtils.mapOf;
44+import static com.datastax.driver.core.CodecUtils.setOf;
45+import static com.datastax.driver.core.DataType.*;
46+
47+/**
48+ * A Codec that can serialize and deserialize to and from a given
49+ * {@link #getCqlType() CQL type} and a given {@link #getJavaType() Java Type}.
50+ *
51+ * <h3>Serializing and deserializing</h3>
52+ *
53+ * Two methods handle the serialization and deserialization of Java types into
54+ * CQL types according to the native protocol specifications:
55+ * <ol>
56+ * <li>{@link #serialize(Object,ProtocolVersion)}: used to serialize from the codec's Java type to a
57+ * {@link ByteBuffer} instance corresponding to the codec's CQL type;</li>
58+ * <li>{@link #deserialize(ByteBuffer,ProtocolVersion)}}: used to deserialize a {@link ByteBuffer} instance
59+ * corresponding to the codec's CQL type to the codec's Java type.</li>
60+ * </ol>
61+ *
62+ * <h3>Formatting and parsing</h3>
63+ *
64+ * Two methods handle the formatting and parsing of Java types into
65+ * CQL strings:
66+ * <ol>
67+ * <li>{@link #format(Object)}: formats the Java type handled by the codec as a CQL string;</li>
68+ * <li>{@link #parse(String)}; parses a CQL string into the Java type handled by the codec.</li>
69+ * </ol>
70+ *
71+ * <h3>Inspection</h3>
72+ *
73+ * Codecs also have the following inspection methods:
74+ *
75+ * <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>
79+ * </ol>
80+ *
81+ * <h3>Implementation notes</h3>
82+ *
83+ * <ol>
84+ * <li>TypeCodec implementations <em>must</em> be thread-safe.</li>
85+ * <li>TypeCodec implementations <em>must</em> perform fast and never block.</li>
86+ * <li>TypeCodec implementations <em>must</em> support all native protocol versions; it is not possible
87+ * to use different codecs for the same types but under different protocol versions.</li>
88+ * <li>TypeCodec implementations must comply with the native protocol specifications; failing
89+ * to do so will result in unexpected results and could cause the driver to crash.</li>
90+ * <li>TypeCodec implementations <em>should</em> be stateless and immutable.</li>
91+ * <li>TypeCodec implementations <em>should</em> interpret {@code null} values and empty ByteBuffers
92+ * (i.e. <code>{@link ByteBuffer#remaining()} == 0</code>) in a <em>reasonable</em> way;
93+ * usually, {@code NULL} CQL values should map to {@code null} references, but exceptions exist;
94+ * e.g. for varchar types, a {@code NULL} CQL value maps to a {@code null} reference,
95+ * whereas an empty buffer maps to an empty String. For collection types, it is also admitted that
96+ * {@code NULL} CQL values map to empty Java collections instead of {@code null} references.
97+ * In any case, the codec's behavior in respect to {@code null} values and empty ByteBuffers
98+ * should be clearly documented.</li>
99+ * <li>TypeCodec implementations that wish to handle Java primitive types <em>must</em> be instantiated with
100+ * the wrapper Java class instead, and implement the appropriate interface (see {@link BooleanCodec}
101+ * for an example).</li>
102+ * </ol>
103+ *
104+ * @param <T> The codec's Java type
105+ */
106+@SuppressWarnings("all")
107+public abstract class TypeCodec<T> {
108+
109+ private static final Map<TypeToken<?>, TypeToken<?>> primitiveToWrapperMap = ImmutableMap.<TypeToken<?>, TypeToken<?>>builder()
110+ .put(TypeToken.of(Boolean.TYPE) , TypeToken.of(Boolean.class))
111+ .put(TypeToken.of(Byte.TYPE) , TypeToken.of(Byte.class))
112+ .put(TypeToken.of(Character.TYPE), TypeToken.of(Character.class))
113+ .put(TypeToken.of(Short.TYPE) , TypeToken.of(Short.class))
114+ .put(TypeToken.of(Integer.TYPE) , TypeToken.of(Integer.class))
115+ .put(TypeToken.of(Long.TYPE) , TypeToken.of(Long.class))
116+ .put(TypeToken.of(Double.TYPE) , TypeToken.of(Double.class))
117+ .put(TypeToken.of(Float.TYPE) , TypeToken.of(Float.class))
118+ .build();
119+
120+ /**
121+ * The CQL keyword {@code NULL}.
122+ */
123+ private static final String NULL = "NULL";
124+
125+ protected final TypeToken<T> javaType;
126+
127+ protected final DataType cqlType;
133128
134- @SuppressWarnings("unchecked")
135- static <T> TypeCodec<Set<T>> setOf(DataType arg, ProtocolVersion protocolVersion) {
136- PrimitiveCollectionCodecs codecs = PrimitiveCollectionCodecs.forVersion(protocolVersion);
137- TypeCodec<Set<?>> codec = codecs.primitiveSetsCodecs.get(arg.getName());
138- return codec != null ? (TypeCodec)codec : new SetCodec<Object>(arg.codec(protocolVersion), protocolVersion);
129+ /**
130+ * This constructor can only be used for non parameterized types.
131+ * For parameterized ones, please use {@link #TypeCodec(DataType, TypeToken)} instead.
132+ *
133+ * @param javaClass The Java class this codec serializes from and deserializes to.
134+ */
135+ protected TypeCodec(DataType cqlType, Class<T> javaClass) {
136+ this(cqlType, TypeToken.of(javaClass));
139137 }
140138
141- @SuppressWarnings("unchecked")
142- static <K, V> TypeCodec<Map<K, V>> mapOf(DataType keys, DataType values, ProtocolVersion protocolVersion) {
143- PrimitiveCollectionCodecs codecs = PrimitiveCollectionCodecs.forVersion(protocolVersion);
144- Map<DataType.Name, TypeCodec<Map<?, ?>>> valueCodecs = codecs.primitiveMapsCodecs.get(keys.getName());
145- TypeCodec<Map<?, ?>> codec = valueCodecs == null ? null : valueCodecs.get(values.getName());
146- return codec != null ? (TypeCodec)codec : new MapCodec<Object, Object>(keys.codec(protocolVersion), values.codec(protocolVersion), protocolVersion);
139+ protected TypeCodec(DataType cqlType, TypeToken<T> javaType) {
140+ checkNotNull(cqlType, "cqlType cannot be null");
141+ checkNotNull(javaType, "javaType cannot be null");
142+ checkArgument(!javaType.isPrimitive(), "Cannot create a codec for a primitive Java type (%s), please use the wrapper type instead", javaType);
143+ this.cqlType = cqlType;
144+ this.javaType = javaType;
147145 }
148146
149- static UDTCodec udtOf(UserType definition, ProtocolVersion protocolVersion) {
150- return new UDTCodec(definition, protocolVersion);
147+ /**
148+ * Return the Java type that this codec deserializes to and serializes from.
149+ * @return The Java type this codec deserializes to and serializes from.
150+ */
151+ public TypeToken<T> getJavaType() {
152+ return javaType;
151153 }
152154
153- static TupleCodec tupleOf(TupleType type, ProtocolVersion protocolVersion) {
154- return new TupleCodec(type, protocolVersion);
155+ /**
156+ * Return the CQL type that this codec deserializes from and serializes to.
157+ * @return The Java type this codec deserializes from and serializes to.
158+ */
159+ public DataType getCqlType() {
160+ return cqlType;
155161 }
156162
157- /* This is ugly, but not sure how we can do much better/faster
158- * Returns null if it's doesn't correspond to a known type.
163+ /**
164+ * Serialize the given value according to the CQL type
165+ * handled by this codec.
166+ * <p>
167+ * Implementation notes:
168+ * <ol>
169+ * <li>Null values should be gracefully handled and no exception should be raised;
170+ * these should be considered as the equivalent of a NULL CQL value;</li>
171+ * <li>Codecs for CQL collection types should not permit null elements;</li>
172+ * <li>Codecs for CQL collection types should treat a {@code null} input as
173+ * the equivalent of an empty collection.</li>
174+ * </ol>
159175 *
160- * Also, note that this only a dataType that is fit for the value,
161- * but for instance, for a UUID, this will return DataType.uuid() but
162- * never DataType.timeuuid(). Also, provided an empty list, this will return
163- * DataType.list(DataType.blob()), which is semi-random. This is ok if all
164- * we want is serialize the value, but that's probably all we should do with
165- * the return of this method.
166- */
167- static DataType getDataTypeFor(Object value) {
168- // Starts with ByteBuffer, so that if already serialized value are provided, we don't have the
169- // cost of testing a bunch of other types first
170- if (value instanceof ByteBuffer)
171- return DataType.blob();
172-
173- if (value instanceof Number) {
174- if (value instanceof Byte)
175- return DataType.tinyint();
176- if (value instanceof Short)
177- return DataType.smallint();
178- if (value instanceof Integer)
179- return DataType.cint();
180- if (value instanceof Long)
181- return DataType.bigint();
182- if (value instanceof Float)
183- return DataType.cfloat();
184- if (value instanceof Double)
185- return DataType.cdouble();
186- if (value instanceof BigDecimal)
187- return DataType.decimal();
188- if (value instanceof BigInteger)
189- return DataType.varint();
190- return null;
191- }
192-
193- if (value instanceof String)
194- return DataType.text();
195-
196- if (value instanceof Boolean)
197- return DataType.cboolean();
198-
199- if (value instanceof InetAddress)
200- return DataType.inet();
201-
202- if (value instanceof Date)
203- return DataType.timestamp();
204-
205- if (value instanceof LocalDate)
206- return DataType.date();
207-
208- if (value instanceof UUID)
209- return DataType.uuid();
210-
211- if (value instanceof List) {
212- List<?> l = (List<?>)value;
213- if (l.isEmpty())
214- return DataType.list(DataType.blob());
215- DataType eltType = getDataTypeFor(l.get(0));
216- return eltType == null ? null : DataType.list(eltType);
217- }
218-
219- if (value instanceof Set) {
220- Set<?> s = (Set<?>)value;
221- if (s.isEmpty())
222- return DataType.set(DataType.blob());
223- DataType eltType = getDataTypeFor(s.iterator().next());
224- return eltType == null ? null : DataType.set(eltType);
225- }
226-
227- if (value instanceof Map) {
228- Map<?, ?> m = (Map<?, ?>)value;
229- if (m.isEmpty())
230- return DataType.map(DataType.blob(), DataType.blob());
231- Map.Entry<?, ?> e = m.entrySet().iterator().next();
232- DataType keyType = getDataTypeFor(e.getKey());
233- DataType valueType = getDataTypeFor(e.getValue());
234- return keyType == null || valueType == null
235- ? null
236- : DataType.map(keyType, valueType);
237- }
238-
239- if (value instanceof UDTValue) {
240- return ((UDTValue) value).getType();
241- }
242-
243- if (value instanceof TupleValue) {
244- return ((TupleValue) value).getType();
245- }
246-
247- return null;
248- }
249-
250- private static ByteBuffer pack(List<ByteBuffer> buffers, int elements, ProtocolVersion version) {
251- int size = 0;
252- for (ByteBuffer bb : buffers) {
253- int elemSize = sizeOfValue(bb, version);
254- size += elemSize;
255- }
256-
257- ByteBuffer result = ByteBuffer.allocate(sizeOfCollectionSize(elements, version) + size);
258- writeCollectionSize(result, elements, version);
259- for (ByteBuffer bb : buffers)
260- writeCollectionValue(result, bb, version);
261- return (ByteBuffer)result.flip();
262- }
263-
264- private static void writeCollectionSize(ByteBuffer output, int elements, ProtocolVersion version) {
265- switch (version) {
266- case V1:
267- case V2:
268- if (elements > 65535)
269- throw new IllegalArgumentException("Native protocol version 2 supports up to 65535 elements in any collection - but collection contains " + elements + " elements");
270- output.putShort((short)elements);
271- break;
272- case V3:
273- case V4:
274- output.putInt(elements);
275- break;
276- default:
277- throw version.unsupported();
278- }
279- }
280-
281- private static int getUnsignedShort(ByteBuffer bb) {
282- int length = (bb.get() & 0xFF) << 8;
283- return length | (bb.get() & 0xFF);
284- }
285-
286- private static int readCollectionSize(ByteBuffer input, ProtocolVersion version) {
287- switch (version) {
288- case V1:
289- case V2:
290- return getUnsignedShort(input);
291- case V3:
292- case V4:
293- return input.getInt();
294- default:
295- throw version.unsupported();
296- }
297- }
298-
299- private static int sizeOfCollectionSize(int elements, ProtocolVersion version) {
300- switch (version) {
301- case V1:
302- case V2:
303- return 2;
304- case V3:
305- case V4:
306- return 4;
307- default:
308- throw version.unsupported();
309- }
310- }
311-
312- private static void writeCollectionValue(ByteBuffer output, ByteBuffer value, ProtocolVersion version) {
313- switch (version) {
314- case V1:
315- case V2:
316- assert value != null;
317- output.putShort((short)value.remaining());
318- output.put(value.duplicate());
319- break;
320- case V3:
321- case V4:
322- if (value == null) {
323- output.putInt(-1);
324- } else {
325- output.putInt(value.remaining());
326- output.put(value.duplicate());
327- }
328- break;
329- default:
330- throw version.unsupported();
331- }
176+ * @param value An instance of T; may be {@code null}.
177+ * @param protocolVersion the protocol version to use when serializing
178+ * {@code bytes}. In most cases, the proper value to provide for this argument
179+ * is the value returned by {@link ProtocolOptions#getProtocolVersion} (which
180+ * is the protocol version in use by the driver).
181+ * @return A {@link ByteBuffer} instance containing the serialized form of T
182+ * @throws InvalidTypeException if the given value does not have the expected type
183+ */
184+ public abstract ByteBuffer serialize(T value, ProtocolVersion protocolVersion) throws InvalidTypeException;
185+
186+ /**
187+ * Deserialize the given {@link ByteBuffer} instance according to the CQL type
188+ * handled by this codec.
189+ * <p>
190+ * Implementation notes:
191+ * <ol>
192+ * <li>Null or empty buffers should be gracefully handled and no exception should be raised;
193+ * these should be considered as the equivalent of a NULL CQL value and, in most cases, should
194+ * map to {@code null} or a default value for the corresponding Java type, if applicable;</li>
195+ * <li>Codecs for CQL collection types should return unmodifiable collections;</li>
196+ * <li>Codecs for CQL collection types should avoid returning {@code null};
197+ * they should return empty collections instead.</li>
198+ * </ol>
199+ *
200+ * @param bytes A {@link ByteBuffer} instance containing the serialized form of T;
201+ * may be {@code null} or empty.
202+ * @param protocolVersion the protocol version to use when serializing
203+ * {@code bytes}. In most cases, the proper value to provide for this argument
204+ * is the value returned by {@link ProtocolOptions#getProtocolVersion} (which
205+ * is the protocol version in use by the driver).
206+ * @return An instance of T
207+ * @throws InvalidTypeException if the given {@link ByteBuffer} instance cannot be deserialized
208+ */
209+ public abstract T deserialize(ByteBuffer bytes, ProtocolVersion protocolVersion) throws InvalidTypeException;
210+
211+ /**
212+ * Parse the given CQL literal into an instance of the Java type
213+ * handled by this codec.
214+ * Implementors should take care of unquoting and unescaping the given CQL string
215+ * where applicable.
216+ * Null values and empty Strings should be accepted, as weel as the string {@code "NULL"};
217+ * in most cases, implementations should interpret these inputs has equivalent to a {@code null}
218+ * reference.
219+ *
220+ * @param value The CQL string to parse, may be {@code null} or empty.
221+ * @return An instance of T; may be {@code null} on a {@code null input}.
222+ * @throws InvalidTypeException if the given value cannot be parsed into the expected type
223+ */
224+ public abstract T parse(String value) throws InvalidTypeException;
225+
226+ /**
227+ * Format the given value as a valid CQL literal according
228+ * to the CQL type handled by this codec.
229+ * Implementors should take care of quoting and escaping the resulting CQL literal
230+ * where applicable.
231+ * Null values should be accepted; in most cases, implementations should
232+ * return the CQL keyword {@code "NULL"} for {@code null} inputs.
233+ *
234+ * @param value An instance of T; may be {@code null}.
235+ * @return CQL string
236+ * @throws InvalidTypeException if the given value does not have the expected type
237+ */
238+ public abstract String format(T value) throws InvalidTypeException;
239+
240+ /**
241+ * Return {@code true} if this codec is capable of serializing
242+ * the given {@code javaType}.
243+ *
244+ * @param javaType The Java type this codec should serialize from and deserialize to; cannot be {@code null}.
245+ * @return {@code true} if the codec is capable of serializing
246+ * the given {@code javaType}, and {@code false} otherwise.
247+ * @throws NullPointerException if {@code javaType} is {@code null}.
248+ */
249+ public boolean accepts(TypeToken javaType) {
250+ checkNotNull(javaType);
251+ if(javaType.isPrimitive()) {
252+ javaType = primitiveToWrapperMap.get(javaType);
253+ }
254+ // TODO accept generics type covariance, i.e. a codec for List<Number> should accept List<Integer>
255+ return this.javaType.isAssignableFrom(javaType);
332256 }
333257
334- private static ByteBuffer readBytes(ByteBuffer bb, int length) {
335- ByteBuffer copy = bb.duplicate();
336- copy.limit(copy.position() + length);
337- bb.position(bb.position() + length);
338- return copy;
258+ /**
259+ * Return {@code true} if this codec is capable of deserializing
260+ * the given {@code cqlType}.
261+ *
262+ * @param cqlType The CQL type this codec should deserialize from and serialize to; cannot be {@code null}.
263+ * @return {@code true} if the codec is capable of deserializing
264+ * the given {@code cqlType}, and {@code false} otherwise.
265+ * @throws NullPointerException if {@code cqlType} is {@code null}.
266+ */
267+ public boolean accepts(DataType cqlType) {
268+ checkNotNull(cqlType);
269+ return this.cqlType.equals(cqlType);
339270 }
340271
341- private static ByteBuffer readCollectionValue(ByteBuffer input, ProtocolVersion version) {
342- int size;
343- switch (version) {
344- case V1:
345- case V2:
346- size = getUnsignedShort(input);
347- break;
348- case V3:
349- case V4:
350- size = input.getInt();
351- break;
352- default:
353- throw version.unsupported();
354- }
355- return size < 0 ? null : readBytes(input, size);
272+ /**
273+ * Return {@code true} if this codec is capable of serializing
274+ * the given object. Note that the object's Java type is inferred
275+ * from the object' runtime (raw) type, contrary
276+ * to {@link #accepts(TypeToken)} which is capable of
277+ * handling generic types.
278+ * <p>
279+ * This method is intended mostly to be used by the QueryBuilder
280+ * when no type information is available when the codec is used.
281+ * <p>
282+ * Implementation notes:
283+ * <ol>
284+ * <li>The base implementation provided here can only handle non-parameterized types;
285+ * codecs handling parameterized types, such as collection types, must override
286+ * this method and perform some sort of "manual"
287+ * inspection of the actual type parameters.</li>
288+ * <li>Similarly, codecs that only accept a partial subset of all possible values,
289+ * such as {@link TimeUUIDCodec} or {@link AsciiCodec}, must override
290+ * this method and manually inspect the object to check if it
291+ * complies or not with the codec's limitations.</li>
292+ * </ol>
293+ *
294+ * @param value The Java type this codec should serialize from and deserialize to; cannot be {@code null}.
295+ * @return {@code true} if the codec is capable of serializing
296+ * the given {@code javaType}, and {@code false} otherwise.
297+ * @throws NullPointerException if {@code value} is {@code null}.
298+ */
299+ public boolean accepts(Object value) {
300+ checkNotNull(value);
301+ return accepts(TypeToken.of(value.getClass()));
356302 }
357303
358- private static int sizeOfValue(ByteBuffer value, ProtocolVersion version) {
359- switch (version) {
360- case V1:
361- case V2:
362- int elemSize = value.remaining();
363- if (elemSize > 65535)
364- throw new IllegalArgumentException("Native protocol version 2 supports only elements with size up to 65535 bytes - but element size is " + elemSize + " bytes");
365- return 2 + elemSize;
366- case V3:
367- case V4:
368- return value == null ? 4 : 4 + value.remaining();
369- default:
370- throw version.unsupported();
371- }
304+ @Override
305+ public boolean equals(Object o) {
306+ if (this == o)
307+ return true;
308+ if (!(o instanceof TypeCodec))
309+ return false;
310+ TypeCodec<?> typeCodec = (TypeCodec<?>)o;
311+ return Objects.equal(javaType, typeCodec.javaType) && Objects.equal(cqlType, typeCodec.cqlType);
312+ }
313+
314+ @Override
315+ public int hashCode() {
316+ return Objects.hashCode(javaType, cqlType);
317+ }
318+
319+ @Override
320+ public String toString() {
321+ return String.format("%s [%s <-> %s]", this.getClass().getSimpleName(), cqlType, javaType);
322+ }
323+
324+ /**
325+ * An interface for codecs that are capable of handling primitive booleans,
326+ * thus avoiding the overhead of boxing and unboxing such primitives.
327+ */
328+ public interface PrimitiveBooleanCodec {
329+
330+ ByteBuffer serializeNoBoxing(boolean v, ProtocolVersion protocolVersion);
331+ boolean deserializeNoBoxing(ByteBuffer v, ProtocolVersion protocolVersion);
332+
333+ }
334+
335+ /**
336+ * An interface for codecs that are capable of handling primitive bytes,
337+ * thus avoiding the overhead of boxing and unboxing such primitives.
338+ */
339+ public interface PrimitiveByteCodec {
340+
341+ ByteBuffer serializeNoBoxing(byte v, ProtocolVersion protocolVersion);
342+ byte deserializeNoBoxing(ByteBuffer v, ProtocolVersion protocolVersion);
343+
344+ }
345+
346+ /**
347+ * An interface for codecs that are capable of handling primitive shorts,
348+ * thus avoiding the overhead of boxing and unboxing such primitives.
349+ */
350+ public interface PrimitiveShortCodec {
351+
352+ ByteBuffer serializeNoBoxing(short v, ProtocolVersion protocolVersion);
353+ short deserializeNoBoxing(ByteBuffer v, ProtocolVersion protocolVersion);
354+
355+ }
356+
357+ /**
358+ * An interface for codecs that are capable of handling primitive ints,
359+ * thus avoiding the overhead of boxing and unboxing such primitives.
360+ */
361+ public interface PrimitiveIntCodec {
362+
363+ ByteBuffer serializeNoBoxing(int v, ProtocolVersion protocolVersion);
364+ int deserializeNoBoxing(ByteBuffer v, ProtocolVersion protocolVersion);
365+
366+ }
367+
368+ /**
369+ * An interface for codecs that are capable of handling primitive longs,
370+ * thus avoiding the overhead of boxing and unboxing such primitives.
371+ */
372+ public interface PrimitiveLongCodec {
373+
374+ ByteBuffer serializeNoBoxing(long v, ProtocolVersion protocolVersion);
375+ long deserializeNoBoxing(ByteBuffer v, ProtocolVersion protocolVersion);
376+
377+ }
378+
379+ /**
380+ * An interface for codecs that are capable of handling primitive floats,
381+ * thus avoiding the overhead of boxing and unboxing such primitives.
382+ */
383+ public interface PrimitiveFloatCodec {
384+
385+ ByteBuffer serializeNoBoxing(float v, ProtocolVersion protocolVersion);
386+ float deserializeNoBoxing(ByteBuffer v, ProtocolVersion protocolVersion);
387+
388+ }
389+
390+ /**
391+ * An interface for codecs that are capable of handling primitive doubles,
392+ * thus avoiding the overhead of boxing and unboxing such primitives.
393+ */
394+ public interface PrimitiveDoubleCodec {
395+
396+ ByteBuffer serializeNoBoxing(double v, ProtocolVersion protocolVersion);
397+ double deserializeNoBoxing(ByteBuffer v, ProtocolVersion protocolVersion);
398+
372399 }
373400
374- static class StringCodec extends TypeCodec<String> {
401+ /**
402+ * Base class for codecs handling CQL string types such as {@link DataType#varchar()},
403+ * {@link DataType#text()} or {@link DataType#ascii()}.
404+ */
405+ public static abstract class StringCodec extends TypeCodec<String> {
375406
376407 private final Charset charset;
377408
378- private StringCodec(Charset charset) {
409+ public StringCodec(DataType cqlType, Charset charset) {
410+ super(cqlType, String.class);
379411 this.charset = charset;
380412 }
381413
382414 @Override
383415 public String parse(String value) {
416+ if (value == null || value.isEmpty() || value.equals(NULL)) return null;
384417 if (value.charAt(0) != '\'' || value.charAt(value.length() - 1) != '\'')
385- throw new InvalidTypeException("text values must enclosed by a single quotes");
418+ throw new InvalidTypeException("text or varchar values must be enclosed by single quotes");
386419
387420 return value.substring(1, value.length() - 1).replace("''", "'");
388421 }
389422
390423 @Override
391424 public String format(String value) {
425+ if (value == null)
426+ return NULL;
392427 return '\'' + replace(value, '\'', "''") + '\'';
393428 }
394429
@@ -401,7 +436,7 @@
401436 int nbMatch = 0;
402437 int start = -1;
403438 do {
404- start = text.indexOf(search, start+1);
439+ start = text.indexOf(search, start + 1);
405440 if (start != -1)
406441 ++nbMatch;
407442 } while (start != -1);
@@ -425,26 +460,78 @@
425460 }
426461
427462 @Override
428- public ByteBuffer serialize(String value) {
429- return ByteBuffer.wrap(value.getBytes(charset));
463+ public ByteBuffer serialize(String value, ProtocolVersion protocolVersion) {
464+ return value == null ? null : ByteBuffer.wrap(value.getBytes(charset));
430465 }
431466
467+ /**
468+ * {@inheritDoc}
469+ *
470+ * Implementation note: this method treats {@code null}s and empty buffers differently:
471+ * the formers are mapped to {@code null}s while the latters are mappend to empty strings.
472+ */
432473 @Override
433- public String deserialize(ByteBuffer bytes) {
474+ public String deserialize(ByteBuffer bytes, ProtocolVersion protocolVersion) {
475+ if (bytes == null)
476+ return null;
477+ if(bytes.remaining() == 0)
478+ return "";
434479 return new String(Bytes.getArray(bytes), charset);
435480 }
436481 }
437482
438- static class LongCodec extends TypeCodec<Long> {
483+ /**
484+ * This codec maps a CQL {@link DataType#varchar()} to a Java {@link String}.
485+ * Note that this codec also handles {@link DataType#text()}, which is merely
486+ * an alias for {@link DataType#varchar()}.
487+ */
488+ public static class VarcharCodec extends StringCodec {
489+
490+ public static final VarcharCodec instance = new VarcharCodec();
491+
492+ private VarcharCodec() {
493+ super(varchar(), Charset.forName("UTF-8"));
494+ }
495+
496+ }
497+
498+ /**
499+ * This codec maps a CQL {@link DataType#ascii()} to a Java {@link String}.
500+ */
501+ public static class AsciiCodec extends StringCodec {
502+
503+ public static final AsciiCodec instance = new AsciiCodec();
504+
505+ private static final Pattern ASCII_PATTERN = Pattern.compile("^\\p{ASCII}*$");
506+
507+ private AsciiCodec() {
508+ super(ascii(), Charset.forName("US-ASCII"));
509+ }
510+
511+ @Override
512+ public boolean accepts(Object value) {
513+ if (value instanceof String) {
514+ return ASCII_PATTERN.matcher((String)value).matches();
515+ }
516+ return false;
517+ }
518+
519+ }
439520
440- public static final LongCodec instance = new LongCodec();
521+ /**
522+ * Base class for codecs handling CQL 8-byte integer types such as {@link DataType#bigint()},
523+ * {@link DataType#counter()} or {@link DataType#time()}.
524+ */
525+ public abstract static class LongCodec extends TypeCodec<Long> implements PrimitiveLongCodec {
441526
442- private LongCodec() {}
527+ public LongCodec(DataType cqlType) {
528+ super(cqlType, Long.class);
529+ }
443530
444531 @Override
445532 public Long parse(String value) {
446533 try {
447- return Long.parseLong(value);
534+ return value == null || value.isEmpty() || value.equals(NULL) ? null : Long.parseLong(value);
448535 } catch (NumberFormatException e) {
449536 throw new InvalidTypeException(String.format("Cannot parse 64-bits long value from \"%s\"", value));
450537 }
@@ -452,26 +539,32 @@
452539
453540 @Override
454541 public String format(Long value) {
542+ if (value == null)
543+ return NULL;
455544 return Long.toString(value);
456545 }
457546
458547 @Override
459- public ByteBuffer serialize(Long value) {
460- return serializeNoBoxing(value);
548+ public ByteBuffer serialize(Long value, ProtocolVersion protocolVersion) {
549+ return value == null ? null : serializeNoBoxing(value, protocolVersion);
461550 }
462551
463- public ByteBuffer serializeNoBoxing(long value) {
552+ @Override
553+ public ByteBuffer serializeNoBoxing(long value, ProtocolVersion protocolVersion) {
464554 ByteBuffer bb = ByteBuffer.allocate(8);
465555 bb.putLong(0, value);
466556 return bb;
467557 }
468558
469559 @Override
470- public Long deserialize(ByteBuffer bytes) {
471- return deserializeNoBoxing(bytes);
560+ public Long deserialize(ByteBuffer bytes, ProtocolVersion protocolVersion) {
561+ return bytes == null || bytes.remaining() == 0 ? null : deserializeNoBoxing(bytes, protocolVersion);
472562 }
473563
474- public long deserializeNoBoxing(ByteBuffer bytes) {
564+ @Override
565+ public long deserializeNoBoxing(ByteBuffer bytes, ProtocolVersion protocolVersion) {
566+ if (bytes == null || bytes.remaining() == 0)
567+ return 0;
475568 if (bytes.remaining() != 8)
476569 throw new InvalidTypeException("Invalid 64-bits long value, expecting 8 bytes but got " + bytes.remaining());
477570
@@ -479,43 +572,119 @@
479572 }
480573 }
481574
482- static class BytesCodec extends TypeCodec<ByteBuffer> {
575+ /**
576+ * This codec maps a CQL {@link DataType#bigint()} to a Java {@link Long}.
577+ */
578+ public static class BigintCodec extends LongCodec {
579+
580+ public static final BigintCodec instance = new BigintCodec();
581+
582+ private BigintCodec() {
583+ super(bigint());
584+ }
585+
586+ }
587+
588+ /**
589+ * This codec maps a CQL {@link DataType#counter()} to a Java {@link Long}.
590+ */
591+ public static class CounterCodec extends LongCodec {
592+
593+ public static final CounterCodec instance = new CounterCodec();
594+
595+ private CounterCodec() {
596+ super(counter());
597+ }
598+
599+ }
600+
601+ /**
602+ * This codec maps a CQL {@link DataType#blob()} to a Java {@link ByteBuffer}.
603+ */
604+ public static class BlobCodec extends TypeCodec<ByteBuffer> {
605+
606+ public static final BlobCodec instance = new BlobCodec();
607+
608+ private BlobCodec() {
609+ super(blob(), ByteBuffer.class);
610+ }
611+
612+ @Override
613+ public ByteBuffer parse(String value) {
614+ return value == null || value.isEmpty() || value.equals(NULL) ? null : Bytes.fromHexString(value);
615+ }
616+
617+ @Override
618+ public String format(ByteBuffer value) {
619+ if (value == null)
620+ return NULL;
621+ return Bytes.toHexString(value);
622+ }
623+
624+ @Override
625+ public ByteBuffer serialize(ByteBuffer value, ProtocolVersion protocolVersion) {
626+ return value == null ? null : value.duplicate();
627+ }
628+
629+ @Override
630+ public ByteBuffer deserialize(ByteBuffer bytes, ProtocolVersion protocolVersion) {
631+ return bytes == null ? null : bytes.duplicate();
632+ }
633+ }
483634
484- public static final BytesCodec instance = new BytesCodec();
635+ /**
636+ * This codec maps a CQL {@link DataType#custom(String)} to a Java {@link ByteBuffer}.
637+ * Note that no instance of this codec is part of the default set of codecs used by the Java driver;
638+ * instances of this codec must be manually registered.
639+ */
640+ public static class CustomCodec extends TypeCodec<ByteBuffer> {
485641
486- private BytesCodec() {}
642+ public CustomCodec(DataType custom) {
643+ super(custom, ByteBuffer.class);
644+ assert custom.getName() == Name.CUSTOM;
645+ }
487646
488647 @Override
489648 public ByteBuffer parse(String value) {
490- return Bytes.fromHexString(value);
649+ return value == null || value.isEmpty() || value.equals(NULL) ? null : Bytes.fromHexString(value);
491650 }
492651
493652 @Override
494653 public String format(ByteBuffer value) {
654+ if (value == null)
655+ return NULL;
495656 return Bytes.toHexString(value);
496657 }
497658
498659 @Override
499- public ByteBuffer serialize(ByteBuffer value) {
500- return value.duplicate();
660+ public ByteBuffer serialize(ByteBuffer value, ProtocolVersion protocolVersion) {
661+ return value == null ? null : value.duplicate();
501662 }
502663
503664 @Override
504- public ByteBuffer deserialize(ByteBuffer bytes) {
505- return bytes.duplicate();
665+ public ByteBuffer deserialize(ByteBuffer bytes, ProtocolVersion protocolVersion) {
666+ return bytes == null ? null : bytes.duplicate();
506667 }
507668 }
508669
509- static class BooleanCodec extends TypeCodec<Boolean> {
510- private static final ByteBuffer TRUE = ByteBuffer.wrap(new byte[]{1});
511- private static final ByteBuffer FALSE = ByteBuffer.wrap(new byte[]{0});
670+ /**
671+ * This codec maps a CQL {@link DataType#cboolean()} to a Java {@link Boolean}.
672+ */
673+ public static class BooleanCodec extends TypeCodec<Boolean> implements PrimitiveBooleanCodec {
674+
675+ private static final ByteBuffer TRUE = ByteBuffer.wrap(new byte[]{ 1 });
676+ private static final ByteBuffer FALSE = ByteBuffer.wrap(new byte[]{ 0 });
512677
513678 public static final BooleanCodec instance = new BooleanCodec();
514679
515- private BooleanCodec() {}
680+ private BooleanCodec() {
681+ super(cboolean(), Boolean.class);
682+ }
516683
517684 @Override
518685 public Boolean parse(String value) {
686+ if (value == null || value.isEmpty() || value.equals(NULL))
687+ return null;
519688 if (value.equalsIgnoreCase(Boolean.FALSE.toString()))
520689 return false;
521690 if (value.equalsIgnoreCase(Boolean.TRUE.toString()))
@@ -526,24 +695,30 @@
526695
527696 @Override
528697 public String format(Boolean value) {
698+ if (value == null)
699+ return NULL;
529700 return value ? "true" : "false";
530701 }
531702
532703 @Override
533- public ByteBuffer serialize(Boolean value) {
534- return serializeNoBoxing(value);
704+ public ByteBuffer serialize(Boolean value, ProtocolVersion protocolVersion) {
705+ return value == null ? null : serializeNoBoxing(value, protocolVersion);
535706 }
536707
537- public ByteBuffer serializeNoBoxing(boolean value) {
708+ @Override
709+ public ByteBuffer serializeNoBoxing(boolean value, ProtocolVersion protocolVersion) {
538710 return value ? TRUE.duplicate() : FALSE.duplicate();
539711 }
540712
541713 @Override
542- public Boolean deserialize(ByteBuffer bytes) {
543- return deserializeNoBoxing(bytes);
714+ public Boolean deserialize(ByteBuffer bytes, ProtocolVersion protocolVersion) {
715+ return bytes == null || bytes.remaining() == 0 ? null : deserializeNoBoxing(bytes, protocolVersion);
544716 }
545717
546- public boolean deserializeNoBoxing(ByteBuffer bytes) {
718+ @Override
719+ public boolean deserializeNoBoxing(ByteBuffer bytes, ProtocolVersion protocolVersion) {
720+ if (bytes == null || bytes.remaining() == 0)
721+ return false;
547722 if (bytes.remaining() != 1)
548723 throw new InvalidTypeException("Invalid boolean value, expecting 1 byte but got " + bytes.remaining());
549724
@@ -551,16 +726,21 @@
551726 }
552727 }
553728
554- static class DecimalCodec extends TypeCodec<BigDecimal> {
729+ /**
730+ * This codec maps a CQL {@link DataType#decimal()} to a Java {@link BigDecimal}.
731+ */
732+ public static class DecimalCodec extends TypeCodec<BigDecimal> {
555733
556734 public static final DecimalCodec instance = new DecimalCodec();
557735
558- private DecimalCodec() {}
736+ private DecimalCodec() {
737+ super(decimal(), BigDecimal.class);
738+ }
559739
560740 @Override
561741 public BigDecimal parse(String value) {
562742 try {
563- return new BigDecimal(value);
743+ return value == null || value.isEmpty() || value.equals(NULL) ? null : new BigDecimal(value);
564744 } catch (NumberFormatException e) {
565745 throw new InvalidTypeException(String.format("Cannot parse decimal value from \"%s\"", value));
566746 }
@@ -568,11 +748,15 @@
568748
569749 @Override
570750 public String format(BigDecimal value) {
751+ if (value == null)
752+ return NULL;
571753 return value.toString();
572754 }
573755
574756 @Override
575- public ByteBuffer serialize(BigDecimal value) {
757+ public ByteBuffer serialize(BigDecimal value, ProtocolVersion protocolVersion) {
758+ if (value == null)
759+ return null;
576760 BigInteger bi = value.unscaledValue();
577761 int scale = value.scale();
578762 byte[] bibytes = bi.toByteArray();
@@ -585,7 +769,9 @@
585769 }
586770
587771 @Override
588- public BigDecimal deserialize(ByteBuffer bytes) {
772+ public BigDecimal deserialize(ByteBuffer bytes, ProtocolVersion protocolVersion) {
773+ if (bytes == null || bytes.remaining() == 0)
774+ return null;
589775 if (bytes.remaining() < 4)
590776 throw new InvalidTypeException("Invalid decimal value, expecting at least 4 bytes but got " + bytes.remaining());
591777
@@ -599,16 +785,21 @@
599785 }
600786 }
601787
602- static class DoubleCodec extends TypeCodec<Double> {
788+ /**
789+ * This codec maps a CQL {@link DataType#cdouble()} to a Java {@link Double}.
790+ */
791+ public static class DoubleCodec extends TypeCodec<Double> implements PrimitiveDoubleCodec {
603792
604793 public static final DoubleCodec instance = new DoubleCodec();
605794
606- private DoubleCodec() {}
795+ private DoubleCodec() {
796+ super(cdouble(), Double.class);
797+ }
607798
608799 @Override
609800 public Double parse(String value) {
610801 try {
611- return Double.parseDouble(value);
802+ return value == null || value.isEmpty() || value.equals(NULL) ? null : Double.parseDouble(value);
612803 } catch (NumberFormatException e) {
613804 throw new InvalidTypeException(String.format("Cannot parse 64-bits double value from \"%s\"", value));
614805 }
@@ -616,26 +807,32 @@
616807
617808 @Override
618809 public String format(Double value) {
810+ if (value == null)
811+ return NULL;
619812 return Double.toString(value);
620813 }
621814
622815 @Override
623- public ByteBuffer serialize(Double value) {
624- return serializeNoBoxing(value);
816+ public ByteBuffer serialize(Double value, ProtocolVersion protocolVersion) {
817+ return value == null ? null : serializeNoBoxing(value, protocolVersion);
625818 }
626819
627- public ByteBuffer serializeNoBoxing(double value) {
820+ @Override
821+ public ByteBuffer serializeNoBoxing(double value, ProtocolVersion protocolVersion) {
628822 ByteBuffer bb = ByteBuffer.allocate(8);
629823 bb.putDouble(0, value);
630824 return bb;
631825 }
632826
633827 @Override
634- public Double deserialize(ByteBuffer bytes) {
635- return deserializeNoBoxing(bytes);
828+ public Double deserialize(ByteBuffer bytes, ProtocolVersion protocolVersion) {
829+ return bytes == null || bytes.remaining() == 0 ? null : deserializeNoBoxing(bytes, protocolVersion);
636830 }
637831
638- public double deserializeNoBoxing(ByteBuffer bytes) {
832+ @Override
833+ public double deserializeNoBoxing(ByteBuffer bytes, ProtocolVersion protocolVersion) {
834+ if (bytes == null || bytes.remaining() == 0)
835+ return 0;
639836 if (bytes.remaining() != 8)
640837 throw new InvalidTypeException("Invalid 64-bits double value, expecting 8 bytes but got " + bytes.remaining());
641838
@@ -643,16 +840,21 @@
643840 }
644841 }
645842
646- static class FloatCodec extends TypeCodec<Float> {
843+ /**
844+ * This codec maps a CQL {@link DataType#cfloat()} to a Java {@link Float}.
845+ */
846+ public static class FloatCodec extends TypeCodec<Float> implements PrimitiveFloatCodec {
647847
648848 public static final FloatCodec instance = new FloatCodec();
649849
650- private FloatCodec() {}
850+ private FloatCodec() {
851+ super(cfloat(), Float.class);
852+ }
651853
652854 @Override
653855 public Float parse(String value) {
654856 try {
655- return Float.parseFloat(value);
857+ return value == null || value.isEmpty() || value.equals(NULL) ? null : Float.parseFloat(value);
656858 } catch (NumberFormatException e) {
657859 throw new InvalidTypeException(String.format("Cannot parse 32-bits float value from \"%s\"", value));
658860 }
@@ -660,26 +862,32 @@
660862
661863 @Override
662864 public String format(Float value) {
865+ if (value == null)
866+ return NULL;
663867 return Float.toString(value);
664868 }
665869
666870 @Override
667- public ByteBuffer serialize(Float value) {
668- return serializeNoBoxing(value);
871+ public ByteBuffer serialize(Float value, ProtocolVersion protocolVersion) {
872+ return value == null ? null : serializeNoBoxing(value, protocolVersion);
669873 }
670874
671- public ByteBuffer serializeNoBoxing(float value) {
875+ @Override
876+ public ByteBuffer serializeNoBoxing(float value, ProtocolVersion protocolVersion) {
672877 ByteBuffer bb = ByteBuffer.allocate(4);
673878 bb.putFloat(0, value);
674879 return bb;
675880 }
676881
677882 @Override
678- public Float deserialize(ByteBuffer bytes) {
679- return deserializeNoBoxing(bytes);
883+ public Float deserialize(ByteBuffer bytes, ProtocolVersion protocolVersion) {
884+ return bytes == null || bytes.remaining() == 0 ? null : deserializeNoBoxing(bytes, protocolVersion);
680885 }
681886
682- public float deserializeNoBoxing(ByteBuffer bytes) {
887+ @Override
888+ public float deserializeNoBoxing(ByteBuffer bytes, ProtocolVersion protocolVersion) {
889+ if (bytes == null || bytes.remaining() == 0)
890+ return 0;
683891 if (bytes.remaining() != 4)
684892 throw new InvalidTypeException("Invalid 32-bits float value, expecting 4 bytes but got " + bytes.remaining());
685893
@@ -687,14 +895,22 @@
687895 }
688896 }
689897
690- static class InetCodec extends TypeCodec<InetAddress> {
898+ /**
899+ * This codec maps a CQL {@link DataType#inet()} to a Java {@link InetAddress}.
900+ */
901+ public static class InetCodec extends TypeCodec<InetAddress> {
691902
692903 public static final InetCodec instance = new InetCodec();
693904
694- private InetCodec() {}
905+ private InetCodec() {
906+ super(inet(), InetAddress.class);
907+ }
695908
696909 @Override
697910 public InetAddress parse(String value) {
911+ if (value == null || value.isEmpty() || value.equals(NULL))
912+ return null;
913+
698914 value = value.trim();
699915 if (value.charAt(0) != '\'' || value.charAt(value.length() - 1) != '\'')
700916 throw new InvalidTypeException(String.format("inet values must be enclosed in single quotes (\"%s\")", value));
@@ -707,16 +923,20 @@
707923
708924 @Override
709925 public String format(InetAddress value) {
926+ if (value == null)
927+ return NULL;
710928 return "'" + value.getHostAddress() + "'";
711929 }
712930
713931 @Override
714- public ByteBuffer serialize(InetAddress value) {
715- return ByteBuffer.wrap(value.getAddress());
932+ public ByteBuffer serialize(InetAddress value, ProtocolVersion protocolVersion) {
933+ return value == null ? null : ByteBuffer.wrap(value.getAddress());
716934 }
717935
718936 @Override
719- public InetAddress deserialize(ByteBuffer bytes) {
937+ public InetAddress deserialize(ByteBuffer bytes, ProtocolVersion protocolVersion) {
938+ if (bytes == null || bytes.remaining() == 0)
939+ return null;
720940 try {
721941 return InetAddress.getByAddress(Bytes.getArray(bytes));
722942 } catch (UnknownHostException e) {
@@ -725,16 +945,21 @@
725945 }
726946 }
727947
728- static class TinyIntCodec extends TypeCodec<Byte> {
948+ /**
949+ * This codec maps a CQL {@link DataType#tinyint()} to a Java {@link Byte}.
950+ */
951+ public static class TinyIntCodec extends TypeCodec<Byte> implements PrimitiveByteCodec {
729952
730953 public static final TinyIntCodec instance = new TinyIntCodec();
731954
732- private TinyIntCodec() {}
955+ private TinyIntCodec() {
956+ super(tinyint(), Byte.class);
957+ }
733958
734959 @Override
735960 public Byte parse(String value) {
736961 try {
737- return Byte.parseByte(value);
962+ return value == null || value.isEmpty() || value.equals(NULL) ? null : Byte.parseByte(value);
738963 } catch (NumberFormatException e) {
739964 throw new InvalidTypeException(String.format("Cannot parse 8-bits int value from \"%s\"", value));
740965 }
@@ -742,26 +967,32 @@
742967
743968 @Override
744969 public String format(Byte value) {
970+ if (value == null)
971+ return NULL;
745972 return Byte.toString(value);
746973 }
747974
748975 @Override
749- public ByteBuffer serialize(Byte value) {
750- return serializeNoBoxing(value);
976+ public ByteBuffer serialize(Byte value, ProtocolVersion protocolVersion) {
977+ return value == null ? null : serializeNoBoxing(value, protocolVersion);
751978 }
752979
753- public ByteBuffer serializeNoBoxing(byte value) {
980+ @Override
981+ public ByteBuffer serializeNoBoxing(byte value, ProtocolVersion protocolVersion) {
754982 ByteBuffer bb = ByteBuffer.allocate(1);
755983 bb.put(0, value);
756984 return bb;
757985 }
758986
759987 @Override
760- public Byte deserialize(ByteBuffer bytes) {
761- return deserializeNoBoxing(bytes);
988+ public Byte deserialize(ByteBuffer bytes, ProtocolVersion protocolVersion) {
989+ return bytes == null || bytes.remaining() == 0 ? null : deserializeNoBoxing(bytes, protocolVersion);
762990 }
763991
764- public byte deserializeNoBoxing(ByteBuffer bytes) {
992+ @Override
993+ public byte deserializeNoBoxing(ByteBuffer bytes, ProtocolVersion protocolVersion) {
994+ if (bytes == null || bytes.remaining() == 0)
995+ return 0;
765996 if (bytes.remaining() != 1)
766997 throw new InvalidTypeException("Invalid 8-bits integer value, expecting 1 byte but got " + bytes.remaining());
767998
@@ -769,16 +1000,21 @@
7691000 }
7701001 }
7711002
772- static class SmallIntCodec extends TypeCodec<Short> {
1003+ /**
1004+ * This codec maps a CQL {@link DataType#smallint()} to a Java {@link Short}.
1005+ */
1006+ public static class SmallIntCodec extends TypeCodec<Short> implements PrimitiveShortCodec {
7731007
7741008 public static final SmallIntCodec instance = new SmallIntCodec();
7751009
776- private SmallIntCodec() {}
1010+ private SmallIntCodec() {
1011+ super(smallint(), Short.class);
1012+ }
7771013
7781014 @Override
7791015 public Short parse(String value) {
7801016 try {
781- return Short.parseShort(value);
1017+ return value == null || value.isEmpty() || value.equals(NULL) ? null : Short.parseShort(value);
7821018 } catch (NumberFormatException e) {
7831019 throw new InvalidTypeException(String.format("Cannot parse 16-bits int value from \"%s\"", value));
7841020 }
@@ -786,26 +1022,32 @@
7861022
7871023 @Override
7881024 public String format(Short value) {
1025+ if (value == null)
1026+ return NULL;
7891027 return Short.toString(value);
7901028 }
7911029
7921030 @Override
793- public ByteBuffer serialize(Short value) {
794- return serializeNoBoxing(value);
1031+ public ByteBuffer serialize(Short value, ProtocolVersion protocolVersion) {
1032+ return value == null ? null : serializeNoBoxing(value, protocolVersion);
7951033 }
7961034
797- public ByteBuffer serializeNoBoxing(short value) {
1035+ @Override
1036+ public ByteBuffer serializeNoBoxing(short value, ProtocolVersion protocolVersion) {
7981037 ByteBuffer bb = ByteBuffer.allocate(2);
7991038 bb.putShort(0, value);
8001039 return bb;
8011040 }
8021041
8031042 @Override
804- public Short deserialize(ByteBuffer bytes) {
805- return deserializeNoBoxing(bytes);
1043+ public Short deserialize(ByteBuffer bytes, ProtocolVersion protocolVersion) {
1044+ return bytes == null || bytes.remaining() == 0 ? null : deserializeNoBoxing(bytes, protocolVersion);
8061045 }
8071046
808- public Short deserializeNoBoxing(ByteBuffer bytes) {
1047+ @Override
1048+ public short deserializeNoBoxing(ByteBuffer bytes, ProtocolVersion protocolVersion) {
1049+ if (bytes == null || bytes.remaining() == 0)
1050+ return 0;
8091051 if (bytes.remaining() != 2)
8101052 throw new InvalidTypeException("Invalid 16-bits integer value, expecting 2 bytes but got " + bytes.remaining());
8111053
@@ -813,16 +1055,21 @@
8131055 }
8141056 }
8151057
816- static class IntCodec extends TypeCodec<Integer> {
1058+ /**
1059+ * This codec maps a CQL {@link DataType#cint()} to a Java {@link Integer}.
1060+ */
1061+ public static class IntCodec extends TypeCodec<Integer> implements PrimitiveIntCodec {
8171062
8181063 public static final IntCodec instance = new IntCodec();
8191064
820- private IntCodec() {}
1065+ private IntCodec() {
1066+ super(cint(), Integer.class);
1067+ }
8211068
8221069 @Override
8231070 public Integer parse(String value) {
8241071 try {
825- return Integer.parseInt(value);
1072+ return value == null || value.isEmpty() || value.equals(NULL) ? null : Integer.parseInt(value);
8261073 } catch (NumberFormatException e) {
8271074 throw new InvalidTypeException(String.format("Cannot parse 32-bits int value from \"%s\"", value));
8281075 }
@@ -830,26 +1077,32 @@
8301077
8311078 @Override
8321079 public String format(Integer value) {
1080+ if (value == null)
1081+ return NULL;
8331082 return Integer.toString(value);
8341083 }
8351084
8361085 @Override
837- public ByteBuffer serialize(Integer value) {
838- return serializeNoBoxing(value);
1086+ public ByteBuffer serialize(Integer value, ProtocolVersion protocolVersion) {
1087+ return value == null ? null : serializeNoBoxing(value, protocolVersion);
8391088 }
8401089
841- public ByteBuffer serializeNoBoxing(int value) {
1090+ @Override
1091+ public ByteBuffer serializeNoBoxing(int value, ProtocolVersion protocolVersion) {
8421092 ByteBuffer bb = ByteBuffer.allocate(4);
8431093 bb.putInt(0, value);
8441094 return bb;
8451095 }
8461096
8471097 @Override
848- public Integer deserialize(ByteBuffer bytes) {
849- return deserializeNoBoxing(bytes);
1098+ public Integer deserialize(ByteBuffer bytes, ProtocolVersion protocolVersion) {
1099+ return bytes == null || bytes.remaining() == 0 ? null : deserializeNoBoxing(bytes, protocolVersion);
8501100 }
8511101
852- public int deserializeNoBoxing(ByteBuffer bytes) {
1102+ @Override
1103+ public int deserializeNoBoxing(ByteBuffer bytes, ProtocolVersion protocolVersion) {
1104+ if (bytes == null || bytes.remaining() == 0)
1105+ return 0;
8531106 if (bytes.remaining() != 4)
8541107 throw new InvalidTypeException("Invalid 32-bits integer value, expecting 4 bytes but got " + bytes.remaining());
8551108
@@ -857,9 +1110,12 @@
8571110 }
8581111 }
8591112
860- static class TimestampCodec extends TypeCodec<Date> {
1113+ /**
1114+ * This codec maps a CQL {@link DataType#timestamp()} to a Java {@link Date}.
1115+ */
1116+ public static class TimestampCodec extends TypeCodec<Date> {
8611117
862- private static final String[] iso8601Patterns = new String[] {
1118+ private static final String[] iso8601Patterns = new String[]{
8631119 "yyyy-MM-dd HH:mm",
8641120 "yyyy-MM-dd HH:mm:ss",
8651121 "yyyy-MM-dd HH:mmZ",
@@ -877,9 +1133,12 @@
8771133 };
8781134
8791135 public static final TimestampCodec instance = new TimestampCodec();
1136+
8801137 private static final Pattern IS_LONG_PATTERN = Pattern.compile("^-?\\d+$");
8811138
882- private TimestampCodec() {}
1139+ private TimestampCodec() {
1140+ super(timestamp(), Date.class);
1141+ }
8831142
8841143 /*
8851144 * Copied and adapted from apache commons DateUtils.parseStrictly method (that is used Cassandra side
@@ -908,8 +1167,10 @@
9081167
9091168 @Override
9101169 public Date parse(String value) {
1170+ if (value == null || value.isEmpty() || value.equals(NULL))
1171+ return null;
1172+
9111173 // strip enclosing single quotes, if any
912- // enclosing quotes are optional for long literals, mandatory for date patterns
9131174 if (value.charAt(0) == '\'' && value.charAt(value.length() - 1) == '\'')
9141175 value = value.substring(1, value.length() - 1);
9151176
@@ -930,33 +1191,42 @@
9301191
9311192 @Override
9321193 public String format(Date value) {
1194+ if (value == null)
1195+ return NULL;
9331196 return Long.toString(value.getTime());
9341197 }
9351198
9361199 @Override
937- public ByteBuffer serialize(Date value) {
938- return LongCodec.instance.serializeNoBoxing(value.getTime());
1200+ public ByteBuffer serialize(Date value, ProtocolVersion protocolVersion) {
1201+ return value == null ? null : BigintCodec.instance.serializeNoBoxing(value.getTime(), protocolVersion);
9391202 }
9401203
9411204 @Override
942- public Date deserialize(ByteBuffer bytes) {
943- return new Date(LongCodec.instance.deserializeNoBoxing(bytes));
1205+ public Date deserialize(ByteBuffer bytes, ProtocolVersion protocolVersion) {
1206+ return bytes == null || bytes.remaining() == 0 ? null : new Date(BigintCodec.instance.deserializeNoBoxing(bytes, protocolVersion));
9441207 }
9451208 }
9461209
947- static class DateCodec extends TypeCodec<LocalDate> {
1210+ /**
1211+ * This codec maps a CQL {@link DataType#date()} to the custom {@link LocalDate} class.
1212+ */
1213+ public static class DateCodec extends TypeCodec<LocalDate> {
9481214
9491215 public static final DateCodec instance = new DateCodec();
1216+
9501217 private static final Pattern IS_LONG_PATTERN = Pattern.compile("^-?\\d+$");
9511218 private static final String pattern = "yyyy-MM-dd";
9521219 private static final long MAX_LONG_VALUE = (1L << 32) - 1;
9531220 private static final long EPOCH_AS_CQL_LONG = (1L << 31);
9541221
9551222 private DateCodec() {
1223+ super(date(), LocalDate.class);
9561224 }
9571225
9581226 @Override
9591227 public LocalDate parse(String value) {
1228+ if (value == null || value.isEmpty() || value.equals(NULL))
1229+ return null;
9601230
9611231 // strip enclosing single quotes, if any
9621232 // single quotes are optional for long literals, mandatory for date patterns
@@ -981,6 +1251,7 @@
9811251 return LocalDate.fromDaysSinceEpoch(days);
9821252 }
9831253
1254+
9841255 SimpleDateFormat parser = new SimpleDateFormat(pattern);
9851256 parser.setLenient(false);
9861257 parser.setTimeZone(TimeZone.getTimeZone("UTC"));
@@ -996,17 +1267,19 @@
9961267
9971268 @Override
9981269 public String format(LocalDate value) {
1270+ if (value == null)
1271+ return NULL;
9991272 return "'" + value.toString() + "'";
10001273 }
10011274
10021275 @Override
1003- public ByteBuffer serialize(LocalDate value) {
1004- return IntCodec.instance.serializeNoBoxing(javaToProtocol(value.getDaysSinceEpoch()));
1276+ public ByteBuffer serialize(LocalDate value, ProtocolVersion protocolVersion) {
1277+ return value == null ? null : IntCodec.instance.serializeNoBoxing(javaToProtocol(value.getDaysSinceEpoch()), protocolVersion);
10051278 }
10061279
10071280 @Override
1008- public LocalDate deserialize(ByteBuffer bytes) {
1009- return LocalDate.fromDaysSinceEpoch(protocolToJava(IntCodec.instance.deserializeNoBoxing(bytes)));
1281+ public LocalDate deserialize(ByteBuffer bytes, ProtocolVersion protocolVersion) {
1282+ return bytes == null || bytes.remaining() == 0 ? null : LocalDate.fromDaysSinceEpoch(protocolToJava(IntCodec.instance.deserializeNoBoxing(bytes, protocolVersion)));
10101283 }
10111284
10121285 // The protocol encodes DATE as an _unsigned_ int with the epoch in the middle of the range (2^31).
@@ -1021,13 +1294,17 @@
10211294 }
10221295 }
10231296
1024- static class TimeCodec extends LongCodec {
1297+ /**
1298+ * This codec maps a CQL {@link DataType#time()} to a Java {@link Long}.
1299+ */
1300+ public static class TimeCodec extends LongCodec {
10251301
10261302 private static final Pattern IS_LONG_PATTERN = Pattern.compile("^-?\\d+$");
10271303
10281304 public static final TimeCodec instance = new TimeCodec();
10291305
10301306 private TimeCodec() {
1307+ super(time());
10311308 }
10321309
10331310 // Time specific parsing loosely based on java.sql.Timestamp
@@ -1093,6 +1370,9 @@
10931370
10941371 @Override
10951372 public Long parse(String value) {
1373+ if (value == null || value.isEmpty() || value.equals(NULL))
1374+ return null;
1375+
10961376 // enclosing single quotes required, even for long literals
10971377 if (value.charAt(0) != '\'' || value.charAt(value.length() - 1) != '\'')
10981378 throw new InvalidTypeException("time values must be enclosed by single quotes");
@@ -1116,7 +1396,7 @@
11161396 @Override
11171397 public String format(Long value) {
11181398 if (value == null)
1119- return "null";
1399+ return NULL;
11201400 int nano = (int)(value % 1000000000);
11211401 value -= nano;
11221402 value /= 1000000000;
@@ -1148,16 +1428,19 @@
11481428
11491429 }
11501430
1151- static class UUIDCodec extends TypeCodec<UUID> {
1152-
1153- public static final UUIDCodec instance = new UUIDCodec();
1431+ /**
1432+ * Base class for codecs handling CQL UUID types such as {@link DataType#uuid()} and {@link DataType#timeuuid()}.
1433+ */
1434+ public static abstract class AbstractUUIDCodec extends TypeCodec<UUID> {
11541435
1155- protected UUIDCodec() {}
1436+ private AbstractUUIDCodec(DataType cqlType) {
1437+ super(cqlType, UUID.class);
1438+ }
11561439
11571440 @Override
11581441 public UUID parse(String value) {
11591442 try {
1160- return UUID.fromString(value);
1443+ return value == null || value.isEmpty() || value.equals(NULL) ? null : UUID.fromString(value);
11611444 } catch (IllegalArgumentException e) {
11621445 throw new InvalidTypeException(String.format("Cannot parse UUID value from \"%s\"", value));
11631446 }
@@ -1165,11 +1448,15 @@
11651448
11661449 @Override
11671450 public String format(UUID value) {
1451+ if (value == null)
1452+ return NULL;
11681453 return value.toString();
11691454 }
11701455
11711456 @Override
1172- public ByteBuffer serialize(UUID value) {
1457+ public ByteBuffer serialize(UUID value, ProtocolVersion protocolVersion) {
1458+ if(value == null)
1459+ return null;
11731460 ByteBuffer bb = ByteBuffer.allocate(16);
11741461 bb.putLong(0, value.getMostSignificantBits());
11751462 bb.putLong(8, value.getLeastSignificantBits());
@@ -1177,44 +1464,78 @@
11771464 }
11781465
11791466 @Override
1180- public UUID deserialize(ByteBuffer bytes) {
1181- return new UUID(bytes.getLong(bytes.position()), bytes.getLong(bytes.position() + 8));
1467+ public UUID deserialize(ByteBuffer bytes, ProtocolVersion protocolVersion) {
1468+ return bytes == null || bytes.remaining() == 0 ? null : new UUID(bytes.getLong(bytes.position()), bytes.getLong(bytes.position() + 8));
1469+ }
1470+ }
1471+
1472+ /**
1473+ * This codec maps a CQL {@link DataType#uuid()} to a Java {@link UUID}.
1474+ */
1475+ public static class UUIDCodec extends AbstractUUIDCodec {
1476+
1477+ public static final UUIDCodec instance = new UUIDCodec();
1478+
1479+ private UUIDCodec() {
1480+ super(uuid());
11821481 }
1482+
11831483 }
11841484
1185- static class TimeUUIDCodec extends UUIDCodec {
1485+ /**
1486+ * This codec maps a CQL {@link DataType#timeuuid()} to a Java {@link UUID}.
1487+ */
1488+ public static class TimeUUIDCodec extends AbstractUUIDCodec {
11861489
11871490 public static final TimeUUIDCodec instance = new TimeUUIDCodec();
11881491
1189- private TimeUUIDCodec() {}
1492+ private TimeUUIDCodec() {
1493+ super(timeuuid());
1494+ }
11901495
11911496 @Override
1192- public UUID parse(String value) {
1193- UUID id = super.parse(value);
1194- if (id.version() != 1)
1195- throw new InvalidTypeException(String.format("Cannot parse type 1 UUID value from \"%s\": represents a type %d UUID", value, id.version()));
1196- return id;
1497+ public boolean accepts(Object value) {
1498+ if (super.accepts(value)) {
1499+ // only accept time-based uuids
1500+ return ((UUID)value).version() == 1;
1501+ }
1502+ return false;
1503+ }
1504+
1505+ @Override
1506+ public String format(UUID value) {
1507+ if (value == null)
1508+ return NULL;
1509+ if (value.version() != 1)
1510+ throw new InvalidTypeException(String.format("%s is not a Type 1 (time-based) UUID", value));
1511+ return super.format(value);
11971512 }
11981513
11991514 @Override
1200- public UUID deserialize(ByteBuffer bytes) {
1201- UUID id = super.deserialize(bytes);
1202- if (id.version() != 1)
1203- throw new InvalidTypeException(String.format("Error deserializing type 1 UUID: deserialized value %s represents a type %d UUID", id, id.version()));
1204- return id;
1515+ public ByteBuffer serialize(UUID value, ProtocolVersion protocolVersion) {
1516+ if(value == null)
1517+ return null;
1518+ if (value.version() != 1)
1519+ throw new InvalidTypeException(String.format("%s is not a Type 1 (time-based) UUID", value));
1520+ return super.serialize(value, protocolVersion);
12051521 }
12061522 }
12071523
1208- static class BigIntegerCodec extends TypeCodec<BigInteger> {
1524+ /**
1525+ * This codec maps a CQL {@link DataType#varint()} to a Java {@link BigInteger}.
1526+ */
1527+ public static class VarintCodec extends TypeCodec<BigInteger> {
12091528
1210- public static final BigIntegerCodec instance = new BigIntegerCodec();
1529+ public static final VarintCodec instance = new VarintCodec();
12111530
1212- private BigIntegerCodec() {}
1531+ private VarintCodec() {
1532+ super(varint(), BigInteger.class);
1533+ }
12131534
12141535 @Override
12151536 public BigInteger parse(String value) {
12161537 try {
1217- return new BigInteger(value);
1538+ return value == null || value.isEmpty() || value.equals(NULL) ? null : new BigInteger(value);
12181539 } catch (NumberFormatException e) {
12191540 throw new InvalidTypeException(String.format("Cannot parse varint value from \"%s\"", value));
12201541 }
@@ -1222,42 +1543,107 @@
12221543
12231544 @Override
12241545 public String format(BigInteger value) {
1546+ if (value == null)
1547+ return NULL;
12251548 return value.toString();
12261549 }
12271550
12281551 @Override
1229- public ByteBuffer serialize(BigInteger value) {
1230- return ByteBuffer.wrap(value.toByteArray());
1552+ public ByteBuffer serialize(BigInteger value, ProtocolVersion protocolVersion) {
1553+ return value == null ? null : ByteBuffer.wrap(value.toByteArray());
12311554 }
12321555
12331556 @Override
1234- public BigInteger deserialize(ByteBuffer bytes) {
1235- return new BigInteger(Bytes.getArray(bytes));
1557+ public BigInteger deserialize(ByteBuffer bytes, ProtocolVersion protocolVersion) {
1558+ return bytes == null || bytes.remaining() == 0 ? null : new BigInteger(Bytes.getArray(bytes));
12361559 }
12371560 }
12381561
1239- static class ListCodec<T> extends TypeCodec<List<T>> {
1562+ /**
1563+ * Base class for codecs handling CQL collection types such as {@link DataType#list(DataType)}
1564+ * or {@link DataType#set(DataType)}.
1565+ * Note that for practical reasons, {@link MapCodec} does not inherit from this class.
1566+ */
1567+ public abstract static class CollectionCodec<E, C extends Collection<E>> extends TypeCodec<C> {
12401568
1241- private final TypeCodec<T> eltCodec;
1242- private final ProtocolVersion protocolVersion;
1569+ protected final TypeCodec<E> eltCodec;
12431570
1244- public ListCodec(TypeCodec<T> eltCodec, ProtocolVersion protocolVersion) {
1571+ public CollectionCodec(CollectionType cqlType, TypeToken<C> javaType, TypeCodec<E> eltCodec) {
1572+ super(cqlType, javaType);
12451573 this.eltCodec = eltCodec;
1246- this.protocolVersion = protocolVersion;
12471574 }
12481575
12491576 @Override
1250- public List<T> parse(String value) {
1577+ public ByteBuffer serialize(C value, ProtocolVersion protocolVersion) {
1578+ if(value == null)
1579+ return null;
1580+ List<ByteBuffer> bbs = new ArrayList<ByteBuffer>(value.size());
1581+ for (E elt : value) {
1582+ if (elt == null) {
1583+ throw new NullPointerException("Collection elements cannot be null");
1584+ }
1585+ ByteBuffer bb;
1586+ try {
1587+ bb = eltCodec.serialize(elt, protocolVersion);
1588+ } catch (ClassCastException e) {
1589+ throw new InvalidTypeException(
1590+ String.format("Invalid type for %s element, expecting %s but got %s",
1591+ cqlType, eltCodec.getJavaType(), elt.getClass()), e);
1592+ }
1593+ bbs.add(bb);
1594+ }
1595+ return CodecUtils.pack(bbs, value.size(), protocolVersion);
1596+ }
1597+
1598+ @Override
1599+ public C deserialize(ByteBuffer bytes, ProtocolVersion protocolVersion) {
1600+ if (bytes == null || bytes.remaining() == 0)
1601+ return unmodifiable(newInstance(0));
1602+ try {
1603+ ByteBuffer input = bytes.duplicate();
1604+ int n = CodecUtils.readCollectionSize(input, protocolVersion);
1605+ C coll = newInstance(n);
1606+ for (int i = 0; i < n; i++) {
1607+ ByteBuffer databb = CodecUtils.readCollectionValue(input, protocolVersion);
1608+ coll.add(eltCodec.deserialize(databb, protocolVersion));
1609+ }
1610+ return unmodifiable(coll);
1611+ } catch (BufferUnderflowException e) {
1612+ throw new InvalidTypeException("Not enough bytes to deserialize list");
1613+ }
1614+ }
1615+
1616+ @Override
1617+ public String format(C value) {
1618+ if (value == null)
1619+ return NULL;
1620+ StringBuilder sb = new StringBuilder();
1621+ sb.append(getOpeningChar());
1622+ int i = 0;
1623+ for (E v : value) {
1624+ if (i++ != 0)
1625+ sb.append(",");
1626+ sb.append(eltCodec.format(v));
1627+ }
1628+ sb.append(getClosingChar());
1629+ return sb.toString();
1630+ }
1631+
1632+ @Override
1633+ public C parse(String value) {
1634+ if (value == null || value.isEmpty() || value.equals(NULL))
1635+ return null;
1636+
12511637 int idx = ParseUtils.skipSpaces(value, 0);
1252- if (value.charAt(idx++) != '[')
1638+ if (value.charAt(idx++) != getOpeningChar())
12531639 throw new InvalidTypeException(String.format("cannot parse list value from \"%s\", at character %d expecting '[' but got '%c'", value, idx, value.charAt(idx)));
12541640
12551641 idx = ParseUtils.skipSpaces(value, idx);
12561642
1257- if (value.charAt(idx) == ']')
1258- return Collections.<T>emptyList();
1643+ if (value.charAt(idx) == getClosingChar())
1644+ return newInstance(0);
12591645
1260- List<T> l = new ArrayList<T>();
1646+ C l = newInstance(10);
12611647 while (idx < value.length()) {
12621648 int n;
12631649 try {
@@ -1270,7 +1656,7 @@
12701656 idx = n;
12711657
12721658 idx = ParseUtils.skipSpaces(value, idx);
1273- if (value.charAt(idx) == ']')
1659+ if (value.charAt(idx) == getClosingChar())
12741660 return l;
12751661 if (value.charAt(idx++) != ',')
12761662 throw new InvalidTypeException(String.format("Cannot parse list value from \"%s\", at character %d expecting ',' but got '%c'", value, idx, value.charAt(idx)));
@@ -1281,142 +1667,122 @@
12811667 }
12821668
12831669 @Override
1284- public String format(List<T> value) {
1285- StringBuilder sb = new StringBuilder();
1286- sb.append("[");
1287- for (int i = 0; i < value.size(); i++) {
1288- if (i != 0)
1289- sb.append(", ");
1290- sb.append(eltCodec.format(value.get(i)));
1291- }
1292- sb.append("]");
1293- return sb.toString();
1670+ public boolean accepts(Object value) {
1671+ if (getJavaType().getRawType().isAssignableFrom(value.getClass())) {
1672+ // runtime type ok, now check element type
1673+ Collection<?> list = (Collection<?>)value;
1674+ if (list.isEmpty())
1675+ return true;
1676+ Object elt = list.iterator().next();
1677+ return eltCodec.accepts(elt);
1678+ }
1679+ return false;
12941680 }
12951681
1296- @Override
1297- public ByteBuffer serialize(List<T> value) {
1298- List<ByteBuffer> bbs = new ArrayList<ByteBuffer>(value.size());
1299- for (T elt : value)
1300- bbs.add(eltCodec.serialize(elt));
1682+ protected abstract C newInstance(int capacity);
13011683
1302- return pack(bbs, value.size(), protocolVersion);
1303- }
1684+ protected abstract C unmodifiable(C coll);
13041685
1305- @Override
1306- public List<T> deserialize(ByteBuffer bytes) {
1307- try {
1308- ByteBuffer input = bytes.duplicate();
1309- int n = readCollectionSize(input, protocolVersion);
1310- List<T> l = new ArrayList<T>(n);
1311- for (int i = 0; i < n; i++) {
1312- ByteBuffer databb = readCollectionValue(input, protocolVersion);
1313- l.add(eltCodec.deserialize(databb));
1314- }
1315- return l;
1316- } catch (BufferUnderflowException e) {
1317- throw new InvalidTypeException("Not enough bytes to deserialize list");
1318- }
1319- }
1320- }
1686+ protected abstract char getOpeningChar();
13211687
1322- static class SetCodec<T> extends TypeCodec<Set<T>> {
1688+ protected abstract char getClosingChar();
13231689
1324- private final TypeCodec<T> eltCodec;
1325- private final ProtocolVersion protocolVersion;
1690+ }
13261691
1327- public SetCodec(TypeCodec<T> eltCodec, ProtocolVersion protocolVersion) {
1328- this.eltCodec = eltCodec;
1329- this.protocolVersion = protocolVersion;
1692+ /**
1693+ * This codec maps a CQL {@link DataType#list(DataType) list type} to a Java {@link List}.
1694+ */
1695+ public static class ListCodec<T> extends CollectionCodec<T, List<T>> {
1696+
1697+ public ListCodec(TypeCodec<T> eltCodec) {
1698+ super(list(eltCodec.getCqlType()), listOf(eltCodec.getJavaType()), eltCodec);
13301699 }
13311700
13321701 @Override
1333- public Set<T> parse(String value) {
1334- int idx = ParseUtils.skipSpaces(value, 0);
1335- if (value.charAt(idx++) != '{')
1336- throw new InvalidTypeException(String.format("cannot parse set value from \"%s\", at character %d expecting '{' but got '%c'", value, idx, value.charAt(idx)));
1702+ protected List<T> newInstance(int capacity) {
1703+ return new ArrayList<T>(capacity);
1704+ }
13371705
1338- idx = ParseUtils.skipSpaces(value, idx);
1706+ @Override
1707+ protected List<T> unmodifiable(List<T> coll) {
1708+ return Collections.unmodifiableList(coll);
1709+ }
13391710
1340- if (value.charAt(idx) == '}')
1341- return Collections.<T>emptySet();
1711+ @Override
1712+ protected char getOpeningChar() {
1713+ return '[';
1714+ }
13421715
1343- Set<T> s = new HashSet<T>();
1344- while (idx < value.length()) {
1345- int n;
1346- try {
1347- n = ParseUtils.skipCQLValue(value, idx);
1348- } catch (IllegalArgumentException e) {
1349- throw new InvalidTypeException(String.format("Cannot parse set value from \"%s\", invalid CQL value at character %d", value, idx), e);
1350- }
1716+ @Override
1717+ protected char getClosingChar() {
1718+ return ']';
1719+ }
13511720
1352- s.add(eltCodec.parse(value.substring(idx, n)));
1353- idx = n;
1721+ }
13541722
1355- idx = ParseUtils.skipSpaces(value, idx);
1356- if (value.charAt(idx) == '}')
1357- return s;
1358- if (value.charAt(idx++) != ',')
1359- throw new InvalidTypeException(String.format("Cannot parse set value from \"%s\", at character %d expecting ',' but got '%c'", value, idx, value.charAt(idx)));
1723+ /**
1724+ * This codec maps a CQL {@link DataType#set(DataType) set type} to a Java {@link Set}.
1725+ */
1726+ public static class SetCodec<T> extends CollectionCodec<T, Set<T>> {
13601727
1361- idx = ParseUtils.skipSpaces(value, idx);
1362- }
1363- throw new InvalidTypeException(String.format("Malformed set value \"%s\", missing closing '}'", value));
1728+ public SetCodec(TypeCodec<T> eltCodec) {
1729+ super(set(eltCodec.cqlType), setOf(eltCodec.getJavaType()), eltCodec);
13641730 }
13651731
13661732 @Override
1367- public String format(Set<T> value) {
1368- StringBuilder sb = new StringBuilder();
1369- sb.append("{");
1370- int i = 0;
1371- for (T v : value) {
1372- if (i++ != 0)
1373- sb.append(", ");
1374- sb.append(eltCodec.format(v));
1375- }
1376- sb.append("}");
1377- return sb.toString();
1733+ protected Set<T> newInstance(int capacity) {
1734+ return new LinkedHashSet<T>(capacity);
13781735 }
13791736
13801737 @Override
1381- public ByteBuffer serialize(Set<T> value) {
1382- List<ByteBuffer> bbs = new ArrayList<ByteBuffer>(value.size());
1383- for (T elt : value)
1384- bbs.add(eltCodec.serialize(elt));
1738+ protected Set<T> unmodifiable(Set<T> coll) {
1739+ return Collections.unmodifiableSet(coll);
1740+ }
13851741
1386- return pack(bbs, value.size(), protocolVersion);
1742+ @Override
1743+ protected char getOpeningChar() {
1744+ return '{';
13871745 }
13881746
13891747 @Override
1390- public Set<T> deserialize(ByteBuffer bytes) {
1391- try {
1392- ByteBuffer input = bytes.duplicate();
1393- int n = readCollectionSize(input, protocolVersion);
1394- Set<T> l = new LinkedHashSet<T>(n);
1395- for (int i = 0; i < n; i++) {
1396- ByteBuffer databb = readCollectionValue(input, protocolVersion);
1397- l.add(eltCodec.deserialize(databb));
1398- }
1399- return l;
1400- } catch (BufferUnderflowException e) {
1401- throw new InvalidTypeException("Not enough bytes to deserialize a set");
1402- }
1748+ protected char getClosingChar() {
1749+ return '}';
14031750 }
14041751 }
14051752
1406- static class MapCodec<K, V> extends TypeCodec<Map<K, V>> {
1753+ /**
1754+ * This codec maps a CQL {@link DataType#map(DataType, DataType) map type} to a Java {@link Map}.
1755+ */
1756+ public static class MapCodec<K, V> extends TypeCodec<Map<K, V>> {
14071757
14081758 private final TypeCodec<K> keyCodec;
1759+
14091760 private final TypeCodec<V> valueCodec;
1410- private final ProtocolVersion protocolVersion;
14111761
1412- public MapCodec(TypeCodec<K> keyCodec, TypeCodec<V> valueCodec, ProtocolVersion protocolVersion) {
1762+ public MapCodec(TypeCodec<K> keyCodec, TypeCodec<V> valueCodec) {
1763+ super(map(keyCodec.getCqlType(), valueCodec.getCqlType()), mapOf(keyCodec.getJavaType(), valueCodec.getJavaType()));
14131764 this.keyCodec = keyCodec;
14141765 this.valueCodec = valueCodec;
1415- this.protocolVersion = protocolVersion;
1766+ }
1767+
1768+ @Override
1769+ public boolean accepts(Object value) {
1770+ if (value instanceof Map) {
1771+ // runtime type ok, now check key and value types
1772+ Map<?, ?> map = (Map<?, ?>)value;
1773+ if (map.isEmpty())
1774+ return true;
1775+ Map.Entry<?, ?> entry = map.entrySet().iterator().next();
1776+ return keyCodec.accepts(entry.getKey()) && valueCodec.accepts(entry.getValue());
1777+ }
1778+ return false;
14161779 }
14171780
14181781 @Override
14191782 public Map<K, V> parse(String value) {
1783+ if (value == null || value.isEmpty() || value.equals(NULL))
1784+ return null;
1785+
14201786 int idx = ParseUtils.skipSpaces(value, 0);
14211787 if (value.charAt(idx++) != '{')
14221788 throw new InvalidTypeException(String.format("cannot parse map value from \"%s\", at character %d expecting '{' but got '%c'", value, idx, value.charAt(idx)));
@@ -1424,7 +1790,7 @@
14241790 idx = ParseUtils.skipSpaces(value, idx);
14251791
14261792 if (value.charAt(idx) == '}')
1427- return Collections.<K, V>emptyMap();
1793+ return Collections.emptyMap();
14281794
14291795 Map<K, V> m = new HashMap<K, V>();
14301796 while (idx < value.length()) {
@@ -1468,12 +1834,14 @@
14681834
14691835 @Override
14701836 public String format(Map<K, V> value) {
1837+ if (value == null)
1838+ return NULL;
14711839 StringBuilder sb = new StringBuilder();
14721840 sb.append("{");
14731841 int i = 0;
14741842 for (Map.Entry<K, V> e : value.entrySet()) {
14751843 if (i++ != 0)
1476- sb.append(", ");
1844+ sb.append(",");
14771845 sb.append(keyCodec.format(e.getKey()));
14781846 sb.append(":");
14791847 sb.append(valueCodec.format(e.getValue()));
@@ -1483,57 +1851,146 @@
14831851 }
14841852
14851853 @Override
1486- public ByteBuffer serialize(Map<K, V> value) {
1854+ public ByteBuffer serialize(Map<K, V> value, ProtocolVersion protocolVersion) {
1855+ if (value == null)
1856+ return null;
14871857 List<ByteBuffer> bbs = new ArrayList<ByteBuffer>(2 * value.size());
14881858 for (Map.Entry<K, V> entry : value.entrySet()) {
1489- bbs.add(keyCodec.serialize(entry.getKey()));
1490- bbs.add(valueCodec.serialize(entry.getValue()));
1859+ ByteBuffer bbk;
1860+ K key = entry.getKey();
1861+ if (key == null) {
1862+ throw new NullPointerException("Map keys cannot be null");
1863+ }
1864+ try {
1865+ bbk = keyCodec.serialize(key, protocolVersion);
1866+ } catch (ClassCastException e) {
1867+ throw new InvalidTypeException(String.format("Invalid type for map key, expecting % but got %s", keyCodec.getJavaType(), key.getClass()), e);
1868+ }
1869+ ByteBuffer bbv;
1870+ V v = entry.getValue();
1871+ if (v == null) {
1872+ throw new NullPointerException("Map values cannot be null");
1873+ }
1874+ try {
1875+ bbv = valueCodec.serialize(v, protocolVersion);
1876+ } catch (ClassCastException e) {
1877+ throw new InvalidTypeException(String.format("Invalid type for map value, expecting % but got %s", valueCodec.getJavaType(), v.getClass()), e);
1878+ }
1879+ bbs.add(bbk);
1880+ bbs.add(bbv);
14911881 }
1492- return pack(bbs, value.size(), protocolVersion);
1882+ return CodecUtils.pack(bbs, value.size(), protocolVersion);
14931883 }
14941884
14951885 @Override
1496- public Map<K, V> deserialize(ByteBuffer bytes) {
1886+ public Map<K, V> deserialize(ByteBuffer bytes, ProtocolVersion protocolVersion) {
1887+ if (bytes == null || bytes.remaining() == 0)
1888+ return Collections.emptyMap();
14971889 try {
14981890 ByteBuffer input = bytes.duplicate();
1499- int n = readCollectionSize(input, protocolVersion);
1891+ int n = CodecUtils.readCollectionSize(input, protocolVersion);
15001892 Map<K, V> m = new LinkedHashMap<K, V>(n);
15011893 for (int i = 0; i < n; i++) {
1502- ByteBuffer kbb = readCollectionValue(input, protocolVersion);
1503- ByteBuffer vbb = readCollectionValue(input, protocolVersion);
1504- m.put(keyCodec.deserialize(kbb), valueCodec.deserialize(vbb));
1894+ ByteBuffer kbb = CodecUtils.readCollectionValue(input, protocolVersion);
1895+ ByteBuffer vbb = CodecUtils.readCollectionValue(input, protocolVersion);
1896+ m.put(keyCodec.deserialize(kbb, protocolVersion), valueCodec.deserialize(vbb, protocolVersion));
15051897 }
1506- return m;
1898+ return Collections.unmodifiableMap(m);
15071899 } catch (BufferUnderflowException e) {
15081900 throw new InvalidTypeException("Not enough bytes to deserialize a map");
15091901 }
15101902 }
15111903 }
15121904
1513- static class UDTCodec extends TypeCodec<UDTValue> {
1905+ /**
1906+ * This codec maps a CQL {@link UserType} to a {@link UDTValue}.
1907+ */
1908+ public static class UDTCodec extends TypeCodec<UDTValue> {
15141909
15151910 private final UserType definition;
15161911
1517- @SuppressWarnings("unused")
1518- private final ProtocolVersion protocolVersion;
1519-
1520- public UDTCodec(UserType definition, ProtocolVersion protocolVersion) {
1912+ public UDTCodec(UserType definition) {
1913+ super(definition, UDTValue.class);
15211914 this.definition = definition;
1522- this.protocolVersion = protocolVersion;
1915+ }
1916+
1917+ @Override
1918+ public boolean accepts(Object value) {
1919+ if(value instanceof UDTValue) {
1920+ return ((UDTValue) value).getType().equals(definition);
1921+ }
1922+ return false;
15231923 }
15241924
15251925 @Override
15261926 public UDTValue parse(String value) {
1527- return definition.parseValue(value);
1927+ if (value == null || value.isEmpty() || value.equals(NULL))
1928+ return null;
1929+
1930+ UDTValue v = definition.newValue();
1931+
1932+ int idx = ParseUtils.skipSpaces(value, 0);
1933+ if (value.charAt(idx++) != '{')
1934+ throw new InvalidTypeException(String.format("Cannot parse UDT value from \"%s\", at character %d expecting '{' but got '%c'", value, idx, value.charAt(idx)));
1935+
1936+ idx = ParseUtils.skipSpaces(value, idx);
1937+
1938+ if (value.charAt(idx) == '}')
1939+ return v;
1940+
1941+ while (idx < value.length()) {
1942+
1943+ int n;
1944+ try {
1945+ n = ParseUtils.skipCQLId(value, idx);
1946+ } catch (IllegalArgumentException e) {
1947+ throw new InvalidTypeException(String.format("Cannot parse UDT value from \"%s\", cannot parse a CQL identifier at character %d", value, idx), e);
1948+ }
1949+ String name = value.substring(idx, n);
1950+ idx = n;
1951+
1952+ if (!definition.contains(name))
1953+ throw new InvalidTypeException(String.format("Unknown field %s in value \"%s\"", name, value));
1954+
1955+ idx = ParseUtils.skipSpaces(value, idx);
1956+ if (value.charAt(idx++) != ':')
1957+ throw new InvalidTypeException(String.format("Cannot parse UDT value from \"%s\", at character %d expecting ':' but got '%c'", value, idx, value.charAt(idx)));
1958+ idx = ParseUtils.skipSpaces(value, idx);
1959+
1960+ try {
1961+ n = ParseUtils.skipCQLValue(value, idx);
1962+ } catch (IllegalArgumentException e) {
1963+ throw new InvalidTypeException(String.format("Cannot parse UDT value from \"%s\", invalid CQL value at character %d", value, idx), e);
1964+ }
1965+
1966+ DataType dt = definition.getFieldType(name);
1967+ TypeCodec<Object> codec = definition.getCodecRegistry().codecFor(dt);
1968+ v.set(name, codec.parse(value.substring(idx, n)), codec.getJavaType());
1969+ idx = n;
1970+
1971+ idx = ParseUtils.skipSpaces(value, idx);
1972+ if (value.charAt(idx) == '}')
1973+ return v;
1974+ if (value.charAt(idx) != ',')
1975+ throw new InvalidTypeException(String.format("Cannot parse UDT value from \"%s\", at character %d expecting ',' but got '%c'", value, idx, value.charAt(idx)));
1976+ ++idx; // skip ','
1977+
1978+ idx = ParseUtils.skipSpaces(value, idx);
1979+ }
1980+ throw new InvalidTypeException(String.format("Malformed UDT value \"%s\", missing closing '}'", value));
15281981 }
15291982
15301983 @Override
15311984 public String format(UDTValue value) {
1985+ if (value == null)
1986+ return NULL;
15321987 return value.toString();
15331988 }
15341989
15351990 @Override
1536- public ByteBuffer serialize(UDTValue value) {
1991+ public ByteBuffer serialize(UDTValue value, ProtocolVersion protocolVersion) {
1992+ if (value == null)
1993+ return null;
15371994 int size = 0;
15381995 for (ByteBuffer v : value.values)
15391996 size += 4 + (v == null ? 0 : v.remaining());
@@ -1551,32 +2008,53 @@
15512008 }
15522009
15532010 @Override
1554- public UDTValue deserialize(ByteBuffer bytes) {
2011+ public UDTValue deserialize(ByteBuffer bytes, ProtocolVersion protocolVersion) {
2012+ if (bytes == null || bytes.remaining() == 0)
2013+ return null;
15552014 ByteBuffer input = bytes.duplicate();
15562015 UDTValue value = definition.newValue();
15572016
15582017 int i = 0;
15592018 while (input.hasRemaining() && i < value.values.length) {
15602019 int n = input.getInt();
1561- value.values[i++] = n < 0 ? null : readBytes(input, n);
2020+ value.values[i++] = n < 0 ? null : CodecUtils.readBytes(input, n);
15622021 }
15632022 return value;
15642023 }
15652024 }
15662025
1567- static class TupleCodec extends TypeCodec<TupleValue> {
2026+ /**
2027+ * This codec maps a CQL {@link TupleType} to a {@link TupleValue}.
2028+ */
2029+ public static class TupleCodec extends TypeCodec<TupleValue> {
2030+
2031+ private final TupleType definition;
15682032
1569- private final TupleType type;
1570- private final ProtocolVersion protocolVersion;
2033+ public TupleCodec(TupleType definition) {
2034+ super(definition, TupleValue.class);
2035+ this.definition = definition;
2036+ }
2037+
2038+ @Override
2039+ public boolean accepts(DataType cqlType) {
2040+ // a tuple codec should accept tuple values of a different type,
2041+ // provided that the latter is contained in this codec's type.
2042+ return cqlType instanceof TupleType && definition.contains((TupleType)cqlType);
2043+ }
15712044
1572- public TupleCodec(TupleType type, ProtocolVersion protocolVersion) {
1573- this.type = type;
1574- this.protocolVersion = protocolVersion;
2045+ @Override
2046+ public boolean accepts(Object value) {
2047+ // a tuple codec should accept tuple values of a different type,
2048+ // provided that the latter is contained in this codec's type.
2049+ return value instanceof TupleValue && definition.contains(((TupleValue) value).getType());
15752050 }
15762051
15772052 @Override
15782053 public TupleValue parse(String value) {
1579- TupleValue v = type.newValue();
2054+ if (value == null || value.isEmpty() || value.equals(NULL))
2055+ return null;
2056+
2057+ TupleValue v = definition.newValue();
15802058
15812059 int idx = ParseUtils.skipSpaces(value, 0);
15822060 if (value.charAt(idx++) != '(')
@@ -1596,8 +2074,9 @@
15962074 throw new InvalidTypeException(String.format("Cannot parse tuple value from \"%s\", invalid CQL value at character %d", value, idx), e);
15972075 }
15982076
1599- DataType dt = type.getComponentTypes().get(i);
1600- v.setBytesUnsafe(i, dt.serialize(dt.parse(value.substring(idx, n)), protocolVersion));
2077+ DataType dt = definition.getComponentTypes().get(i);
2078+ TypeCodec<Object> codec = definition.getCodecRegistry().codecFor(dt);
2079+ v.set(i, codec.parse(value.substring(idx, n)), codec.getJavaType());
16012080 idx = n;
16022081 i += 1;
16032082
@@ -1615,11 +2094,15 @@
16152094
16162095 @Override
16172096 public String format(TupleValue value) {
2097+ if (value == null)
2098+ return NULL;
16182099 return value.toString();
16192100 }
16202101
16212102 @Override
1622- public ByteBuffer serialize(TupleValue value) {
2103+ public ByteBuffer serialize(TupleValue value, ProtocolVersion protocolVersion) {
2104+ if (value == null)
2105+ return null;
16232106 int size = 0;
16242107 for (ByteBuffer v : value.values)
16252108 size += 4 + (v == null ? 0 : v.remaining());
@@ -1637,16 +2120,226 @@
16372120 }
16382121
16392122 @Override
1640- public TupleValue deserialize(ByteBuffer bytes) {
2123+ public TupleValue deserialize(ByteBuffer bytes, ProtocolVersion protocolVersion) {
2124+ if (bytes == null || bytes.remaining() == 0)
2125+ return null;
16412126 ByteBuffer input = bytes.duplicate();
1642- TupleValue value = type.newValue();
2127+ TupleValue value = definition.newValue();
16432128
16442129 int i = 0;
16452130 while (input.hasRemaining() && i < value.values.length) {
16462131 int n = input.getInt();
1647- value.values[i++] = n < 0 ? null : readBytes(input, n);
2132+ value.values[i++] = n < 0 ? null : CodecUtils.readBytes(input, n);
16482133 }
16492134 return value;
16502135 }
16512136 }
2137+
2138+ /**
2139+ * An abstract TypeCodec that actually stores objects as serialized strings.
2140+ * This can serve as a base for codecs dealing with XML or JSON formats.
2141+ *
2142+ * @param <T> The Java type this codec serializes from and deserializes to.
2143+ */
2144+ public abstract static class StringParsingCodec<T> extends TypeCodec<T> {
2145+
2146+ private final TypeCodec<String> innerCodec;
2147+
2148+ public StringParsingCodec(Class<T> javaType) {
2149+ this(TypeToken.of(javaType));
2150+ }
2151+
2152+ public StringParsingCodec(TypeToken<T> javaType) {
2153+ this(VarcharCodec.instance, javaType);
2154+ }
2155+
2156+ public StringParsingCodec(TypeCodec<String> innerCodec, Class<T> javaType) {
2157+ this(innerCodec, TypeToken.of(javaType));
2158+ }
2159+
2160+ public StringParsingCodec(TypeCodec<String> innerCodec, TypeToken<T> javaType) {
2161+ super(innerCodec.getCqlType(), javaType);
2162+ this.innerCodec = innerCodec;
2163+ }
2164+
2165+ @Override
2166+ public ByteBuffer serialize(T value, ProtocolVersion protocolVersion) throws InvalidTypeException {
2167+ return value == null ? null : innerCodec.serialize(toString(value), protocolVersion);
2168+ }
2169+
2170+ @Override
2171+ public T deserialize(ByteBuffer bytes, ProtocolVersion protocolVersion) throws InvalidTypeException {
2172+ String value = innerCodec.deserialize(bytes, protocolVersion);
2173+ return value == null ? null : fromString(value);
2174+ }
2175+
2176+ @Override
2177+ public String format(T value) throws InvalidTypeException {
2178+ return value == null ? null : innerCodec.format(toString(value));
2179+ }
2180+
2181+ @Override
2182+ public T parse(String value) throws InvalidTypeException {
2183+ return value == null || value.isEmpty() || value.equals(NULL) ? null : fromString(innerCodec.parse(value));
2184+ }
2185+
2186+ /**
2187+ * Return the String representation of the given object;
2188+ * no special CQL quoting should be applied here.
2189+ * Null values should be accepted; in most cases, implementors
2190+ * should return null for null inputs.
2191+ *
2192+ * @param value the value to convert into a string
2193+ * @return the String representation of the given object
2194+ */
2195+ protected abstract String toString(T value);
2196+
2197+ /**
2198+ * Parse the given string into an object;
2199+ * no special CQL unquoting should be applied here.
2200+ * Null values should be accepted; in most cases, implementors
2201+ * should return null for null inputs.
2202+ *
2203+ * @param value the string to parse
2204+ * @return the parsed object.
2205+ */
2206+ protected abstract T fromString(String value);
2207+
2208+ }
2209+
2210+ /**
2211+ * An abstract TypeCodec that maps a Java Pojo to another Java object
2212+ * that can in turn be serialized into a CQL type.
2213+ * This can serve as a base for libraries dealing with Pojo mappings.
2214+ *
2215+ * @param <T> The outer Java type
2216+ * @param <U> The inner Java type
2217+ */
2218+ public abstract static class MappingCodec<T, U> extends TypeCodec<T> {
2219+
2220+ protected final TypeCodec<U> innerCodec;
2221+
2222+ public MappingCodec(TypeCodec<U> innerCodec, Class<T> javaType) {
2223+ this(innerCodec, TypeToken.of(javaType));
2224+ }
2225+
2226+ public MappingCodec(TypeCodec<U> innerCodec, TypeToken<T> javaType) {
2227+ super(innerCodec.getCqlType(), javaType);
2228+ this.innerCodec = innerCodec;
2229+ }
2230+
2231+ @Override
2232+ public ByteBuffer serialize(T value, ProtocolVersion protocolVersion) throws InvalidTypeException {
2233+ return innerCodec.serialize(serialize(value), protocolVersion);
2234+ }
2235+
2236+ @Override
2237+ public T deserialize(ByteBuffer bytes, ProtocolVersion protocolVersion) throws InvalidTypeException {
2238+ return deserialize(innerCodec.deserialize(bytes, protocolVersion));
2239+ }
2240+
2241+ @Override
2242+ public T parse(String value) throws InvalidTypeException {
2243+ return value == null || value.isEmpty() || value.equals(NULL) ? null : deserialize(innerCodec.parse(value));
2244+ }
2245+
2246+ @Override
2247+ public String format(T value) throws InvalidTypeException {
2248+ return value == null ? null : innerCodec.format(serialize(value));
2249+ }
2250+
2251+ protected abstract T deserialize(U value);
2252+
2253+ protected abstract U serialize(T value);
2254+
2255+ }
2256+
2257+ /**
2258+ * A codec that serializes {@link Enum} instances as CQL {@link DataType#varchar() varchar}s
2259+ * representing their programmatic names as returned by {@link Enum#name()}.
2260+ * <p>
2261+ * This codec is automatically used by the driver to create codecs for {@link Enum}
2262+ * instances on the fly.
2263+ *
2264+ * @param <E> The Enum class this codec serializes from and deserializes to.
2265+ */
2266+ public static class EnumStringCodec<E extends Enum<E>> extends StringParsingCodec<E> {
2267+
2268+ private final Class<E> enumClass;
2269+
2270+ public EnumStringCodec(Class<E> enumClass) {
2271+ super(enumClass);
2272+ this.enumClass = enumClass;
2273+ }
2274+
2275+ public EnumStringCodec(TypeCodec<String> innerCodec, Class<E> enumClass) {
2276+ super(innerCodec, enumClass);
2277+ this.enumClass = enumClass;
2278+ }
2279+
2280+ @Override
2281+ protected String toString(E value) {
2282+ return value == null ? null : value.name();
2283+ }
2284+
2285+ @Override
2286+ protected E fromString(String value) {
2287+ return value == null ? null : Enum.valueOf(enumClass, value);
2288+ }
2289+
2290+ }
2291+
2292+ /**
2293+ * A codec that serializes {@link Enum} instances as CQL {@link DataType#cint() int}s
2294+ * representing their ordinal values as returned by {@link Enum#ordinal()}.
2295+ * <p>
2296+ * Note that, by default, the driver uses {@link EnumStringCodec} to serialize {@link Enum} instances;
2297+ * to force the use of this codec instead for a specific {@link Enum} instance,
2298+ * the appropriate {@link EnumIntCodec} instance must be explicitly
2299+ * {@link CodecRegistry#register(TypeCodec) registered}.
2300+ * <p>
2301+ * <strong>Note that this codec relies on the enum constants declaration order;
2302+ * it is therefore vital that this order remains immutable.</strong>
2303+ *
2304+ * @param <E> The Enum class this codec serializes from and deserializes to.
2305+ */
2306+ public static class EnumIntCodec<E extends Enum<E>> extends TypeCodec<E> {
2307+
2308+ private final E[] enumConstants;
2309+
2310+ private final TypeCodec<Integer> innerCodec;
2311+
2312+ public EnumIntCodec(Class<E> enumClass) {
2313+ this(IntCodec.instance, enumClass);
2314+ }
2315+
2316+ public EnumIntCodec(TypeCodec<Integer> innerCodec, Class<E> enumClass) {
2317+ super(innerCodec.getCqlType(), enumClass);
2318+ this.enumConstants = enumClass.getEnumConstants();
2319+ this.innerCodec = innerCodec;
2320+ }
2321+
2322+ @Override
2323+ public ByteBuffer serialize(E value, ProtocolVersion protocolVersion) throws InvalidTypeException {
2324+ return innerCodec.serialize(value.ordinal(), protocolVersion);
2325+ }
2326+
2327+ @Override
2328+ public E deserialize(ByteBuffer bytes, ProtocolVersion protocolVersion) throws InvalidTypeException {
2329+ return enumConstants[innerCodec.deserialize(bytes, protocolVersion)];
2330+ }
2331+
2332+ @Override
2333+ public E parse(String value) throws InvalidTypeException {
2334+ return value == null || value.isEmpty() || value.equals(NULL) ? null : enumConstants[Integer.parseInt(value)];
2335+ }
2336+
2337+ @Override
2338+ public String format(E value) throws InvalidTypeException {
2339+ if (value == null)
2340+ return NULL;
2341+ return Integer.toString(value.ordinal());
2342+ }
2343+ }
2344+
16522345 }
modified driver-core/src/main/java/com/datastax/driver/core/UDTValue.java +17 −5
@@ -15,6 +15,8 @@
1515 */
1616 package com.datastax.driver.core;
1717
18+import com.google.common.base.Joiner;
19+
1820 /**
1921 * A value for a User Defined Type.
2022 */
@@ -23,8 +25,7 @@
2325 private final UserType definition;
2426
2527 UDTValue(UserType definition) {
26- // All things in a UDT are encoded with the protocol v3
27- super(ProtocolVersion.V3, definition.size());
28+ super(definition.getProtocolVersion(), definition.size());
2829 this.definition = definition;
2930 }
3031
@@ -36,6 +37,11 @@
3637 return definition.byIdx[i].getName();
3738 }
3839
40+ @Override
41+ protected CodecRegistry getCodecRegistry() {
42+ return definition.getCodecRegistry();
43+ }
44+
3945 protected int[] getAllIndexesOf(String name) {
4046 int[] indexes = definition.byName.get(Metadata.handleId(name));
4147 if (indexes == null)
@@ -75,12 +81,18 @@
7581 sb.append("{");
7682 for (int i = 0; i < values.length; i++) {
7783 if (i > 0)
78- sb.append(", ");
84+ sb.append(",");
7985
8086 sb.append(getName(i));
8187 sb.append(":");
82- DataType dt = getType(i);
83- sb.append(values[i] == null ? "null" : dt.format(dt.deserialize(values[i], ProtocolVersion.V3)));
88+
89+ if(values[i] == null)
90+ sb.append("null");
91+ else {
92+ DataType dt = getType(i);
93+ TypeCodec<Object> codec = getCodecRegistry().codecFor(dt);
94+ sb.append(codec.format(codec.deserialize(values[i], protocolVersion)));
95+ }
8496 }
8597 sb.append("}");
8698 return sb.toString();
modified driver-core/src/main/java/com/datastax/driver/core/UserType.java +34 −73
@@ -19,9 +19,6 @@
1919
2020 import com.google.common.collect.ImmutableMap;
2121 import com.google.common.collect.Iterators;
22-import com.google.common.reflect.TypeToken;
23-
24-import com.datastax.driver.core.exceptions.InvalidTypeException;
2522
2623 /**
2724 * A User Defined Type (UDT).
@@ -36,6 +33,9 @@
3633
3734 private final String keyspace;
3835 private final String typeName;
36+ private final ProtocolVersion protocolVersion;
37+
38+ private volatile CodecRegistry codecRegistry;
3939
4040 // Note that we don't expose the order of fields, from an API perspective this is a map
4141 // of String->Field, but internally we care about the order because the serialization format
@@ -46,11 +46,14 @@
4646 // implementation.
4747 final Map<String, int[]> byName;
4848
49- UserType(String keyspace, String typeName, Collection<Field> fields) {
49+ UserType(String keyspace, String typeName, Collection<Field> fields, ProtocolVersion protocolVersion, CodecRegistry codecRegistry) {
5050 super(DataType.Name.UDT);
51-
5251 this.keyspace = keyspace;
5352 this.typeName = typeName;
53+ this.protocolVersion = protocolVersion;
54+ // codecRegistry can be null, if this object is being constructed from a response message
55+ // see Responses.Result.Rows.Metadata.decode()
56+ this.codecRegistry = codecRegistry;
5457 this.byIdx = fields.toArray(new Field[fields.size()]);
5558
5659 ImmutableMap.Builder<String, int[]> builder = new ImmutableMap.Builder<String, int[]>();
@@ -59,7 +62,7 @@
5962 this.byName = builder.build();
6063 }
6164
62- static UserType build(Row row) {
65+ static UserType build(Row row, ProtocolVersion protocolVersion, CodecRegistry codecRegistry) {
6366 String keyspace = row.getString(KeyspaceMetadata.KS_NAME);
6467 String name = row.getString(TYPE_NAME);
6568
@@ -68,15 +71,9 @@
6871
6972 List<Field> fields = new ArrayList<Field>(fieldNames.size());
7073 for (int i = 0; i < fieldNames.size(); i++)
71- fields.add(new Field(fieldNames.get(i), CassandraTypeParser.parseOne(fieldTypes.get(i))));
72-
73- return new UserType(keyspace, name, fields);
74- }
74+ fields.add(new Field(fieldNames.get(i), CassandraTypeParser.parseOne(fieldTypes.get(i), protocolVersion, codecRegistry)));
7575
76- @SuppressWarnings("unchecked")
77- @Override
78- TypeCodec<Object> codec(ProtocolVersion protocolVersion) {
79- return (TypeCodec)TypeCodec.udtOf(this, protocolVersion);
76+ return new UserType(keyspace, name, fields, protocolVersion, codecRegistry);
8077 }
8178
8279 /**
@@ -172,11 +169,6 @@
172169 return true;
173170 }
174171
175- @Override
176- boolean canBeDeserializedAs(TypeToken typeToken) {
177- return typeToken.isAssignableFrom(getName().javaType);
178- }
179-
180172 @Override
181173 public final int hashCode() {
182174 return Arrays.hashCode(new Object[]{ name, keyspace, typeName, byIdx });
@@ -224,6 +216,29 @@
224216 return asCQLQuery(false);
225217 }
226218
219+ /**
220+ * Return the protocol version that has been used to deserialize
221+ * this UDT, or that will be used to serialize it.
222+ * In most cases this should be the version
223+ * currently in use by the cluster instance
224+ * that this UDT belongs to, as reported by
225+ * {@link ProtocolOptions#getProtocolVersion()}.
226+ *
227+ * @return the protocol version that has been used to deserialize
228+ * this UDT, or that will be used to serialize it.
229+ */
230+ ProtocolVersion getProtocolVersion() {
231+ return protocolVersion;
232+ }
233+
234+ CodecRegistry getCodecRegistry() {
235+ return codecRegistry;
236+ }
237+
238+ void setCodecRegistry(CodecRegistry codecRegistry) {
239+ this.codecRegistry = codecRegistry;
240+ }
241+
227242 private String asCQLQuery(boolean formatted) {
228243 StringBuilder sb = new StringBuilder();
229244
@@ -244,60 +259,6 @@
244259 return "frozen<" + Metadata.escapeId(getKeyspace()) + '.' + Metadata.escapeId(getTypeName()) + ">";
245260 }
246261
247- // We don't want to expose that, it's already exposed through DataType.parse
248- UDTValue parseValue(String value) {
249- UDTValue v = newValue();
250-
251- int idx = ParseUtils.skipSpaces(value, 0);
252- if (value.charAt(idx++) != '{')
253- throw new InvalidTypeException(String.format("Cannot parse UDT value from \"%s\", at character %d expecting '{' but got '%c'", value, idx, value.charAt(idx)));
254-
255- idx = ParseUtils.skipSpaces(value, idx);
256-
257- if (value.charAt(idx) == '}')
258- return v;
259-
260- while (idx < value.length()) {
261-
262- int n;
263- try {
264- n = ParseUtils.skipCQLId(value, idx);
265- } catch (IllegalArgumentException e) {
266- throw new InvalidTypeException(String.format("Cannot parse UDT value from \"%s\", cannot parse a CQL identifier at character %d", value, idx), e);
267- }
268- String name = value.substring(idx, n);
269- idx = n;
270-
271- if (!contains(name))
272- throw new InvalidTypeException(String.format("Unknown field %s in value \"%s\"", name, value));
273-
274- idx = ParseUtils.skipSpaces(value, idx);
275- if (value.charAt(idx++) != ':')
276- throw new InvalidTypeException(String.format("Cannot parse UDT value from \"%s\", at character %d expecting ':' but got '%c'", value, idx, value.charAt(idx)));
277- idx = ParseUtils.skipSpaces(value, idx);
278-
279- try {
280- n = ParseUtils.skipCQLValue(value, idx);
281- } catch (IllegalArgumentException e) {
282- throw new InvalidTypeException(String.format("Cannot parse UDT value from \"%s\", invalid CQL value at character %d", value, idx), e);
283- }
284-
285- DataType dt = getFieldType(name);
286- v.setBytesUnsafe(name, dt.serialize(dt.parse(value.substring(idx, n)), ProtocolVersion.V3));
287- idx = n;
288-
289- idx = ParseUtils.skipSpaces(value, idx);
290- if (value.charAt(idx) == '}')
291- return v;
292- if (value.charAt(idx) != ',')
293- throw new InvalidTypeException(String.format("Cannot parse UDT value from \"%s\", at character %d expecting ',' but got '%c'", value, idx, value.charAt(idx)));
294- ++idx; // skip ','
295-
296- idx = ParseUtils.skipSpaces(value, idx);
297- }
298- throw new InvalidTypeException(String.format("Malformed UDT value \"%s\", missing closing '}'", value));
299- }
300-
301262 /**
302263 * A UDT field.
303264 */
added driver-core/src/main/java/com/datastax/driver/core/exceptions/CodecNotFoundException.java +52 −0
@@ -0,0 +1,52 @@
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.exceptions;
17+
18+import com.google.common.reflect.TypeToken;
19+
20+import com.datastax.driver.core.DataType;
21+
22+/**
23+ * Thrown when a suitable {@link com.datastax.driver.core.TypeCodec} cannot be found by
24+ * {@link com.datastax.driver.core.CodecRegistry} instances.
25+ */
26+@SuppressWarnings("serial")
27+public class CodecNotFoundException extends DriverException {
28+
29+ private final DataType cqlType;
30+
31+ private final TypeToken<?> javaType;
32+
33+ public CodecNotFoundException(String msg, DataType cqlType, TypeToken<?> javaType) {
34+ super(msg);
35+ this.cqlType = cqlType;
36+ this.javaType = javaType;
37+ }
38+
39+ public CodecNotFoundException(Throwable cause, DataType cqlType, TypeToken<?> javaType) {
40+ super(cause);
41+ this.cqlType = cqlType;
42+ this.javaType = javaType;
43+ }
44+
45+ public DataType getCqlType() {
46+ return cqlType;
47+ }
48+
49+ public TypeToken<?> getJavaType() {
50+ return javaType;
51+ }
52+}
modified driver-core/src/main/java/com/datastax/driver/core/querybuilder/Assignment.java +15 −14
@@ -15,9 +15,10 @@
1515 */
1616 package com.datastax.driver.core.querybuilder;
1717
18-import java.nio.ByteBuffer;
1918 import java.util.List;
2019
20+import com.datastax.driver.core.CodecRegistry;
21+
2122 import static com.datastax.driver.core.querybuilder.Utils.appendName;
2223 import static com.datastax.driver.core.querybuilder.Utils.appendValue;
2324
@@ -50,10 +51,10 @@
5051 }
5152
5253 @Override
53- void appendTo(StringBuilder sb, List<Object> variables) {
54+ void appendTo(StringBuilder sb, List<Object> variables, CodecRegistry codecRegistry) {
5455 appendName(name, sb);
5556 sb.append('=');
56- appendValue(value, sb, variables);
57+ appendValue(value, codecRegistry, sb, variables);
5758 }
5859
5960 @Override
@@ -84,10 +85,10 @@
8485 }
8586
8687 @Override
87- void appendTo(StringBuilder sb, List<Object> variables) {
88+ void appendTo(StringBuilder sb, List<Object> variables, CodecRegistry codecRegistry) {
8889 appendName(name, sb).append('=');
8990 appendName(name, sb).append(isIncr ? "+" : "-");
90- appendValue(value, sb, variables);
91+ appendValue(value, codecRegistry, sb, variables);
9192 }
9293
9394 @Override
@@ -111,9 +112,9 @@
111112 }
112113
113114 @Override
114- void appendTo(StringBuilder sb, List<Object> variables) {
115+ void appendTo(StringBuilder sb, List<Object> variables, CodecRegistry codecRegistry) {
115116 appendName(name, sb).append('=');
116- appendValue(value, sb, variables);
117+ appendValue(value, codecRegistry, sb, variables);
117118 sb.append('+');
118119 appendName(name, sb);
119120 }
@@ -141,9 +142,9 @@
141142 }
142143
143144 @Override
144- void appendTo(StringBuilder sb, List<Object> variables) {
145+ void appendTo(StringBuilder sb, List<Object> variables, CodecRegistry codecRegistry) {
145146 appendName(name, sb).append('[').append(idx).append("]=");
146- appendValue(value, sb, variables);
147+ appendValue(value, codecRegistry, sb, variables);
147148 }
148149
149150 @Override
@@ -175,10 +176,10 @@
175176 }
176177
177178 @Override
178- void appendTo(StringBuilder sb, List<Object> variables) {
179+ void appendTo(StringBuilder sb, List<Object> variables, CodecRegistry codecRegistry) {
179180 appendName(name, sb).append('=');
180181 appendName(name, sb).append(isAdd ? "+" : "-");
181- appendValue(collection, sb, variables);
182+ appendValue(collection, codecRegistry, sb, variables);
182183 }
183184
184185 @Override
@@ -204,11 +205,11 @@
204205 }
205206
206207 @Override
207- void appendTo(StringBuilder sb, List<Object> variables) {
208+ void appendTo(StringBuilder sb, List<Object> variables, CodecRegistry codecRegistry) {
208209 appendName(name, sb).append('[');
209- appendValue(key, sb, variables);
210+ appendValue(key, codecRegistry, sb, variables);
210211 sb.append("]=");
211- appendValue(value, sb, variables);
212+ appendValue(value, codecRegistry, sb, variables);
212213 }
213214
214215 @Override
modified driver-core/src/main/java/com/datastax/driver/core/querybuilder/Batch.java +14 −14
@@ -19,9 +19,7 @@
1919 import java.util.ArrayList;
2020 import java.util.List;
2121
22-import com.datastax.driver.core.ProtocolVersion;
23-import com.datastax.driver.core.RegularStatement;
24-import com.datastax.driver.core.SimpleStatement;
22+import com.datastax.driver.core.*;
2523
2624 /**
2725 * A built BATCH statement.
@@ -31,13 +29,12 @@
3129 private final List<RegularStatement> statements;
3230 private final boolean logged;
3331 private final Options usings;
34- private ByteBuffer routingKey;
3532
3633 // Only used when we add at last one statement that is not a BuiltStatement subclass
3734 private int nonBuiltStatementValues;
3835
39- Batch(RegularStatement[] statements, boolean logged) {
40- super((String)null);
36+ Batch(Cluster cluster, RegularStatement[] statements, boolean logged) {
37+ super((String)null, cluster);
4138 this.statements = statements.length == 0
4239 ? new ArrayList<RegularStatement>()
4340 : new ArrayList<RegularStatement>(statements.length);
@@ -58,7 +55,7 @@
5855
5956 if (!usings.usings.isEmpty()) {
6057 builder.append(" USING ");
61- Utils.joinAndAppend(builder, " AND ", usings.usings, variables);
58+ Utils.joinAndAppend(builder, getCodecRegistry(), " AND ", usings.usings, variables);
6259 }
6360 builder.append(' ');
6461
@@ -116,21 +113,18 @@
116113
117114 checkForBindMarkers(null);
118115
119- if (routingKey == null && statement.getRoutingKey() != null)
120- routingKey = statement.getRoutingKey();
121-
122116 return this;
123117 }
124118
125119 @Override
126- public ByteBuffer[] getValues(ProtocolVersion protocolVersion) {
120+ public ByteBuffer[] getValues() {
127121 // If there is some non-BuiltStatement inside the batch with values, we shouldn't
128122 // use super.getValues() since it will ignore the values of said non-BuiltStatement.
129123 // If that's the case, we just collects all those values (and we know
130124 // super.getValues() == null in that case since we've explicitely set this.hasBindMarker
131125 // to true). Otherwise, we simply call super.getValues().
132126 if (nonBuiltStatementValues == 0)
133- return super.getValues(protocolVersion);
127+ return super.getValues();
134128
135129 ByteBuffer[] values = new ByteBuffer[nonBuiltStatementValues];
136130 int i = 0;
@@ -139,7 +133,7 @@
139133 if (statement instanceof BuiltStatement)
140134 continue;
141135
142- ByteBuffer[] statementValues = statement.getValues(protocolVersion);
136+ ByteBuffer[] statementValues = statement.getValues();
143137 System.arraycopy(statementValues, 0, values, i, statementValues.length);
144138 i += statementValues.length;
145139 }
@@ -164,7 +158,13 @@
164158 */
165159 @Override
166160 public ByteBuffer getRoutingKey() {
167- return routingKey;
161+ for (RegularStatement statement : statements) {
162+ ByteBuffer routingKey = statement.getRoutingKey();
163+ if (routingKey != null) {
164+ return routingKey;
165+ }
166+ }
167+ return null;
168168 }
169169
170170 /**
modified driver-core/src/main/java/com/datastax/driver/core/querybuilder/BuiltStatement.java +57 −60
@@ -17,12 +17,16 @@
1717
1818 import java.nio.ByteBuffer;
1919 import java.util.ArrayList;
20+import java.util.Arrays;
2021 import java.util.List;
2122 import java.util.regex.Pattern;
2223
2324 import com.datastax.driver.core.*;
2425 import com.datastax.driver.core.policies.RetryPolicy;
2526
27+import static com.datastax.driver.core.CodecUtils.compose;
28+import static com.datastax.driver.core.CodecUtils.convert;
29+
2630 /**
2731 * Common ancestor to the query builder built statements.
2832 */
@@ -31,13 +35,13 @@
3135 private static final Pattern lowercaseId = Pattern.compile("[a-z][a-z0-9_]*");
3236
3337 private final List<ColumnMetadata> partitionKey;
34- private final ByteBuffer[] routingKey;
38+ private final List<Object> routingKeyValues;
3539 final String keyspace;
40+ protected final Cluster cluster;
3641
3742 private boolean dirty;
3843 private String cache;
3944 private List<Object> values;
40-
4145 Boolean isCounterOp;
4246 boolean hasNonIdempotentOps;
4347
@@ -46,16 +50,18 @@
4650 boolean hasBindMarkers;
4751 private boolean forceNoValues;
4852
49- BuiltStatement(String keyspace) {
53+ BuiltStatement(String keyspace, Cluster cluster) {
5054 this.partitionKey = null;
51- this.routingKey = null;
55+ this.routingKeyValues = null;
5256 this.keyspace = keyspace;
57+ this.cluster = cluster;
5358 }
5459
55- BuiltStatement(TableMetadata tableMetadata) {
60+ BuiltStatement(TableMetadata tableMetadata, Cluster cluster) {
5661 this.partitionKey = tableMetadata.getPartitionKey();
57- this.routingKey = new ByteBuffer[tableMetadata.getPartitionKey().size()];
62+ this.routingKeyValues = Arrays.asList(new Object[tableMetadata.getPartitionKey().size()]);
5863 this.keyspace = escapeId(tableMetadata.getKeyspace().getName());
64+ this.cluster = cluster;
5965 }
6066
6167 // Same as Metadata.escapeId, but we don't have access to it here.
@@ -142,32 +148,47 @@
142148
143149 // TODO: Correctly document the InvalidTypeException
144150 void maybeAddRoutingKey(String name, Object value) {
145- if (routingKey == null || name == null || value == null || value instanceof BindMarker)
151+ if (routingKeyValues == null || name == null || value == null || value instanceof BindMarker)
146152 return;
147153
148154 for (int i = 0; i < partitionKey.size(); i++) {
149155 if (name.equals(partitionKey.get(i).getName()) && Utils.isRawValue(value)) {
150- DataType dt = partitionKey.get(i).getType();
151- // We don't really care which protocol version we use, since the only place it matters if for
152- // collections (not inside UDT), and those are not allowed in a partition key anyway, hence the hardcoding.
153- routingKey[i] = dt.serialize(dt.parse(Utils.toRawString(value)), ProtocolVersion.NEWEST_SUPPORTED);
156+ routingKeyValues.set(i, value);
154157 return;
155158 }
156159 }
157160 }
158161
162+ CodecRegistry getCodecRegistry(){
163+ return cluster.getConfiguration().getCodecRegistry();
164+ }
165+
166+ ProtocolVersion getProtocolVersion() {
167+ cluster.init();
168+ return cluster.getConfiguration().getProtocolOptions().getProtocolVersion();
169+ }
170+
171+ /**
172+ * {@inheritDoc}
173+ * <p>
174+ * Note: Calling this method may trigger the underlying {@link Cluster} initialization.
175+ */
159176 @Override
160177 public ByteBuffer getRoutingKey() {
161- if (routingKey == null)
178+ if (routingKeyValues == null)
162179 return null;
163-
164- for (ByteBuffer bb : routingKey)
165- if (bb == null)
180+ ByteBuffer[] routingKeyParts = new ByteBuffer[partitionKey.size()];
181+ CodecRegistry codecRegistry = getCodecRegistry();
182+ for (int i = 0; i < partitionKey.size(); i++) {
183+ Object value = routingKeyValues.get(i);
184+ if(value == null)
166185 return null;
167-
168- return routingKey.length == 1
169- ? routingKey[0]
170- : compose(routingKey);
186+ TypeCodec<Object> codec = codecRegistry.codecFor(partitionKey.get(i).getType(), value);
187+ routingKeyParts[i] = codec.serialize(value, getProtocolVersion());
188+ }
189+ return routingKeyParts.length == 1
190+ ? routingKeyParts[0]
191+ : compose(routingKeyParts);
171192 }
172193
173194 @Override
@@ -175,10 +196,15 @@
175196 return keyspace;
176197 }
177198
199+ /**
200+ * {@inheritDoc}
201+ * <p>
202+ * Note: Calling this method may trigger the underlying {@link Cluster} initialization.
203+ */
178204 @Override
179- public ByteBuffer[] getValues(ProtocolVersion protocolVersion) {
205+ public ByteBuffer[] getValues() {
180206 maybeRebuildCache();
181- return values == null ? null : Utils.convert(values, protocolVersion);
207+ return values == null ? null : convert(values.toArray(), getProtocolVersion(), getCodecRegistry());
182208 }
183209
184210 @Override
@@ -197,20 +223,19 @@
197223 return !hasNonIdempotentOps();
198224 }
199225
226+ /**
227+ * {@inheritDoc}
228+ * <p>
229+ * Note: Calling this method may trigger the underlying {@link Cluster} initialization.
230+ */
200231 @Override
201232 public String toString() {
202- if (forceNoValues)
233+ if (forceNoValues) {
203234 return getQueryString();
204-
235+ }
205236 return maybeAddSemicolon(buildQueryString(null)).toString();
206237 }
207238
208- // Not meant to be public
209- List<Object> getRawValues() {
210- maybeRebuildCache();
211- return values;
212- }
213-
214239 /**
215240 * Allows to force this builder to not generate values (through its {@code getValues()} method).
216241 * <p>
@@ -245,29 +270,6 @@
245270 return this;
246271 }
247272
248- // This is a duplicate of the one in SimpleStatement, but I don't want to expose this publicly so...
249- static ByteBuffer compose(ByteBuffer... buffers) {
250- int totalLength = 0;
251- for (ByteBuffer bb : buffers)
252- totalLength += 2 + bb.remaining() + 1;
253-
254- ByteBuffer out = ByteBuffer.allocate(totalLength);
255- for (ByteBuffer buffer : buffers)
256- {
257- ByteBuffer bb = buffer.duplicate();
258- putShortLength(out, bb.remaining());
259- out.put(bb);
260- out.put((byte) 0);
261- }
262- out.flip();
263- return out;
264- }
265-
266- private static void putShortLength(ByteBuffer bb, int length) {
267- bb.put((byte) ((length >> 8) & 0xFF));
268- bb.put((byte) (length & 0xFF));
269- }
270-
271273 /**
272274 * An utility class to create a BuiltStatement that encapsulate another one.
273275 */
@@ -276,7 +278,7 @@
276278 T statement;
277279
278280 ForwardingStatement(T statement) {
279- super((String)null);
281+ super((String)null, statement.cluster);
280282 this.statement = statement;
281283 }
282284
@@ -316,11 +318,6 @@
316318 return this;
317319 }
318320
319- @Override
320- List<Object> getRawValues() {
321- return statement.getRawValues();
322- }
323-
324321 @Override
325322 public Statement setConsistencyLevel(ConsistencyLevel consistency) {
326323 statement.setConsistencyLevel(consistency);
@@ -361,8 +358,8 @@
361358 }
362359
363360 @Override
364- public ByteBuffer[] getValues(ProtocolVersion protocolVersion) {
365- return statement.getValues(protocolVersion);
361+ public ByteBuffer[] getValues() {
362+ return statement.getValues();
366363 }
367364
368365 @Override
modified driver-core/src/main/java/com/datastax/driver/core/querybuilder/Clause.java +14 −12
@@ -17,6 +17,8 @@
1717
1818 import java.util.List;
1919
20+import com.datastax.driver.core.CodecRegistry;
21+
2022 public abstract class Clause extends Utils.Appendeable {
2123
2224 abstract String name();
@@ -47,9 +49,9 @@
4749 }
4850
4951 @Override
50- void appendTo(StringBuilder sb, List<Object> variables) {
52+ void appendTo(StringBuilder sb, List<Object> variables, CodecRegistry codecRegistry) {
5153 Utils.appendName(name, sb).append(op);
52- Utils.appendValue(value, sb, variables);
54+ Utils.appendValue(value, codecRegistry, sb, variables);
5355 }
5456
5557 @Override
@@ -78,7 +80,7 @@
7880 }
7981
8082 @Override
81- void appendTo(StringBuilder sb, List<Object> variables) {
83+ void appendTo(StringBuilder sb, List<Object> variables, CodecRegistry codecRegistry) {
8284
8385 // We special case the case of just one bind marker because there is little
8486 // reasons to do:
@@ -93,7 +95,7 @@
9395 }
9496
9597 Utils.appendName(name, sb).append(" IN (");
96- Utils.joinAndAppendValues(sb, ",", values, variables).append(')');
98+ Utils.joinAndAppendValues(sb, codecRegistry, ",", values, variables).append(')');
9799 }
98100
99101 @Override
@@ -123,9 +125,9 @@
123125 }
124126
125127 @Override
126- void appendTo(StringBuilder sb, List<Object> variables) {
128+ void appendTo(StringBuilder sb, List<Object> variables, CodecRegistry codecRegistry) {
127129 Utils.appendName(name, sb).append(" CONTAINS ");
128- Utils.appendValue(value, sb, variables);
130+ Utils.appendValue(value, codecRegistry, sb, variables);
129131 }
130132
131133 @Override
@@ -153,9 +155,9 @@
153155 }
154156
155157 @Override
156- void appendTo(StringBuilder sb, List<Object> variables) {
158+ void appendTo(StringBuilder sb, List<Object> variables, CodecRegistry codecRegistry) {
157159 Utils.appendName(name, sb).append(" CONTAINS KEY ");
158- Utils.appendValue(value, sb, variables);
160+ Utils.appendValue(value, codecRegistry, sb, variables);
159161 }
160162
161163 @Override
@@ -198,14 +200,14 @@
198200
199201 @Override
200202 boolean containsBindMarker() {
201- for (int i = 0; i < values.size(); i++)
202- if (Utils.containsBindMarker(values.get(i)))
203+ for (Object value : values)
204+ if (Utils.containsBindMarker(value))
203205 return true;
204206 return false;
205207 }
206208
207209 @Override
208- void appendTo(StringBuilder sb, List<Object> variables) {
210+ void appendTo(StringBuilder sb, List<Object> variables, CodecRegistry codecRegistry) {
209211 sb.append("(");
210212 for (int i = 0; i < names.size(); i++) {
211213 if (i > 0)
@@ -216,7 +218,7 @@
216218 for (int i = 0; i < values.size(); i++) {
217219 if (i > 0)
218220 sb.append(",");
219- Utils.appendValue(values.get(i), sb, variables);
221+ Utils.appendValue(values.get(i), codecRegistry, sb, variables);
220222 }
221223 sb.append(")");
222224 }
modified driver-core/src/main/java/com/datastax/driver/core/querybuilder/Delete.java +28 −19
@@ -18,6 +18,8 @@
1818 import java.util.ArrayList;
1919 import java.util.List;
2020
21+import com.datastax.driver.core.Cluster;
22+import com.datastax.driver.core.CodecRegistry;
2123 import com.datastax.driver.core.TableMetadata;
2224
2325 /**
@@ -32,8 +34,8 @@
3234 private final Conditions conditions;
3335 private boolean ifExists;
3436
35- Delete(String keyspace, String table, List<Selector> columns) {
36- super(keyspace);
37+ Delete(Cluster cluster, String keyspace, String table, List<Selector> columns) {
38+ super(keyspace, cluster);
3739 this.table = table;
3840 this.columns = columns;
3941 this.where = new Where(this);
@@ -41,8 +43,8 @@
4143 this.conditions = new Conditions(this);
4244 }
4345
44- Delete(TableMetadata table, List<Selector> columns) {
45- super(table);
46+ Delete(Cluster cluster, TableMetadata table, List<Selector> columns) {
47+ super(table, cluster);
4648 this.table = escapeId(table.getName());
4749 this.columns = columns;
4850 this.where = new Where(this);
@@ -54,9 +56,10 @@
5456 StringBuilder buildQueryString(List<Object> variables) {
5557 StringBuilder builder = new StringBuilder();
5658
59+ CodecRegistry codecRegistry = getCodecRegistry();
5760 builder.append("DELETE");
5861 if (!columns.isEmpty())
59- Utils.joinAndAppend(builder.append(" "), ",", columns, variables);
62+ Utils.joinAndAppend(builder.append(" "), codecRegistry, ",", columns, variables);
6063
6164 builder.append(" FROM ");
6265 if (keyspace != null)
@@ -64,12 +67,12 @@
6467 Utils.appendName(table, builder);
6568 if (!usings.usings.isEmpty()) {
6669 builder.append(" USING ");
67- Utils.joinAndAppend(builder, " AND ", usings.usings, variables);
70+ Utils.joinAndAppend(builder, codecRegistry, " AND ", usings.usings, variables);
6871 }
6972
7073 if (!where.clauses.isEmpty()) {
7174 builder.append(" WHERE ");
72- Utils.joinAndAppend(builder, " AND ", where.clauses, variables);
75+ Utils.joinAndAppend(builder, codecRegistry, " AND ", where.clauses, variables);
7376 }
7477
7578 if (ifExists) {
@@ -78,7 +81,7 @@
7881
7982 if (!conditions.conditions.isEmpty()) {
8083 builder.append(" IF ");
81- Utils.joinAndAppend(builder, " AND ", conditions.conditions, variables);
84+ Utils.joinAndAppend(builder, codecRegistry, " AND ", conditions.conditions, variables);
8285 }
8386
8487 return builder;
@@ -274,12 +277,16 @@
274277 */
275278 public static class Builder {
276279
280+ private final Cluster cluster;
281+
277282 List<Selector> columns = new ArrayList<Selector>();
278283
279- Builder() {
284+ Builder(Cluster cluster) {
285+ this.cluster = cluster;
280286 }
281287
282- Builder(String... columnNames) {
288+ Builder(Cluster cluster, String... columnNames) {
289+ this.cluster = cluster;
283290 for (String columnName : columnNames) {
284291 this.columns.add(new Selector(columnName));
285292 }
@@ -303,7 +310,7 @@
303310 * @return a newly built DELETE statement that deletes from {@code keyspace.table}.
304311 */
305312 public Delete from(String keyspace, String table) {
306- return new Delete(keyspace, table, columns);
313+ return new Delete(cluster, keyspace, table, columns);
307314 }
308315
309316 /**
@@ -313,7 +320,7 @@
313320 * @return a newly built DELETE statement that deletes from {@code table}.
314321 */
315322 public Delete from(TableMetadata table) {
316- return new Delete(table, columns);
323+ return new Delete(cluster, table, columns);
317324 }
318325 }
319326
@@ -322,6 +329,10 @@
322329 */
323330 public static class Selection extends Builder {
324331
332+ Selection(Cluster cluster) {
333+ super(cluster);
334+ }
335+
325336 /**
326337 * Deletes all columns (i.e. "DELETE FROM ...")
327338 *
@@ -424,7 +435,7 @@
424435 }
425436
426437 @Override
427- void appendTo(StringBuilder sb, List<Object> values) {
438+ void appendTo(StringBuilder sb, List<Object> values, CodecRegistry codecRegistry) {
428439 Utils.appendName(columnName, sb);
429440 }
430441
@@ -435,9 +446,7 @@
435446
436447 @Override
437448 public String toString() {
438- StringBuilder sb = new StringBuilder();
439- appendTo(sb, new ArrayList<Object>());
440- return sb.toString();
449+ return columnName;
441450 }
442451 }
443452
@@ -454,10 +463,10 @@
454463 }
455464
456465 @Override
457- void appendTo(StringBuilder sb, List<Object> values) {
458- super.appendTo(sb, values);
466+ void appendTo(StringBuilder sb, List<Object> values, CodecRegistry codecRegistry) {
467+ super.appendTo(sb, values, codecRegistry);
459468 sb.append('[');
460- Utils.appendValue(key, sb);
469+ Utils.appendValue(key, codecRegistry, sb, values);
461470 sb.append(']');
462471 }
463472
modified driver-core/src/main/java/com/datastax/driver/core/querybuilder/Insert.java +10 −7
@@ -19,6 +19,8 @@
1919 import java.util.Arrays;
2020 import java.util.List;
2121
22+import com.datastax.driver.core.Cluster;
23+import com.datastax.driver.core.CodecRegistry;
2224 import com.datastax.driver.core.TableMetadata;
2325
2426 /**
@@ -32,14 +34,14 @@
3234 private final Options usings;
3335 private boolean ifNotExists;
3436
35- Insert(String keyspace, String table) {
36- super(keyspace);
37+ Insert(Cluster cluster, String keyspace, String table) {
38+ super(keyspace, cluster);
3739 this.table = table;
3840 this.usings = new Options(this);
3941 }
4042
41- Insert(TableMetadata table) {
42- super(table);
43+ Insert(Cluster cluster, TableMetadata table) {
44+ super(table, cluster);
4345 this.table = escapeId(table.getName());
4446 this.usings = new Options(this);
4547 }
@@ -48,14 +50,15 @@
4850 StringBuilder buildQueryString(List<Object> variables) {
4951 StringBuilder builder = new StringBuilder();
5052
53+ CodecRegistry codecRegistry = getCodecRegistry();
5154 builder.append("INSERT INTO ");
5255 if (keyspace != null)
5356 Utils.appendName(keyspace, builder).append('.');
5457 Utils.appendName(table, builder);
5558 builder.append('(');
56- Utils.joinAndAppendNames(builder, ",", names);
59+ Utils.joinAndAppendNames(builder, codecRegistry, ",", names);
5760 builder.append(") VALUES (");
58- Utils.joinAndAppendValues(builder, ",", values, variables);
61+ Utils.joinAndAppendValues(builder, codecRegistry, ",", values, variables);
5962 builder.append(')');
6063
6164 if (ifNotExists)
@@ -63,7 +66,7 @@
6366
6467 if (!usings.usings.isEmpty()) {
6568 builder.append(" USING ");
66- Utils.joinAndAppend(builder, " AND ", usings.usings, variables);
69+ Utils.joinAndAppend(builder, codecRegistry, " AND ", usings.usings, variables);
6770 }
6871 return builder;
6972 }
modified driver-core/src/main/java/com/datastax/driver/core/querybuilder/Ordering.java +3 −1
@@ -17,6 +17,8 @@
1717
1818 import java.util.List;
1919
20+import com.datastax.driver.core.CodecRegistry;
21+
2022 public class Ordering extends Utils.Appendeable {
2123
2224 private final String name;
@@ -28,7 +30,7 @@
2830 }
2931
3032 @Override
31- void appendTo(StringBuilder sb, List<Object> variables) {
33+ void appendTo(StringBuilder sb, List<Object> variables, CodecRegistry codecRegistry) {
3234 Utils.appendName(name, sb);
3335 sb.append(isDesc ? " DESC" : " ASC");
3436 }
modified driver-core/src/main/java/com/datastax/driver/core/querybuilder/QueryBuilder.java +48 −35
@@ -17,12 +17,13 @@
1717
1818 import java.util.*;
1919
20+import com.datastax.driver.core.Cluster;
2021 import com.datastax.driver.core.RegularStatement;
2122 import com.datastax.driver.core.TableMetadata;
2223 import com.datastax.driver.core.exceptions.InvalidQueryException;
2324
2425 /**
25- * Static methods to build a CQL3 query.
26+ * Builds CQL3 query via a fluent API.
2627 * <p>
2728 * The queries built by this builder will provide a value for the
2829 * {@link com.datastax.driver.core.Statement#getRoutingKey} method only when a
@@ -30,15 +31,27 @@
3031 * It is thus advised to do so if a {@link com.datastax.driver.core.policies.TokenAwarePolicy}
3132 * is in use.
3233 * <p>
33- * The provided builders perform very little validation of the built query.
34+ * The provider builders perform very little validation of the built query.
3435 * There is thus no guarantee that a built query is valid, and it is
3536 * definitively possible to create invalid queries.
3637 * <p>
37- * Note that it could be convenient to use an 'import static' to use the methods of this class.
38+ * Note that it could be convenient to use an 'import static' to bring the static methods of
39+ * this class into scope.
3840 */
3941 public final class QueryBuilder {
4042
41- private QueryBuilder() {}
43+ private final Cluster cluster;
44+
45+ /**
46+ * 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.
49+ *
50+ * @param cluster The {@link Cluster} instance this object should be attached to.
51+ */
52+ public QueryBuilder(Cluster cluster) {
53+ this.cluster = cluster;
54+ }
4255
4356 /**
4457 * Start building a new SELECT query that selects the provided names.
@@ -49,8 +62,8 @@
4962 * @return an in-construction SELECT query (you will need to provide at
5063 * least a FROM clause to complete the query).
5164 */
52- public static Select.Builder select(String... columns) {
53- return new Select.Builder(Arrays.asList((Object[])columns));
65+ public Select.Builder select(String... columns) {
66+ return new Select.Builder(cluster, Arrays.asList((Object[])columns));
5467 }
5568
5669 /**
@@ -59,9 +72,9 @@
5972 * @return an in-construction SELECT query (you will need to provide a
6073 * column selection and at least a FROM clause to complete the query).
6174 */
62- public static Select.Selection select() {
75+ public Select.Selection select() {
6376 // Note: the fact we return Select.Selection as return type is on purpose.
64- return new Select.SelectionOrAlias();
77+ return new Select.SelectionOrAlias(cluster);
6578 }
6679
6780 /**
@@ -70,8 +83,8 @@
7083 * @param table the name of the table in which to insert.
7184 * @return an in-construction INSERT query.
7285 */
73- public static Insert insertInto(String table) {
74- return new Insert(null, table);
86+ public Insert insertInto(String table) {
87+ return new Insert(cluster, null, table);
7588 }
7689
7790 /**
@@ -81,8 +94,8 @@
8194 * @param table the name of the table to insert into.
8295 * @return an in-construction INSERT query.
8396 */
84- public static Insert insertInto(String keyspace, String table) {
85- return new Insert(keyspace, table);
97+ public Insert insertInto(String keyspace, String table) {
98+ return new Insert(cluster, keyspace, table);
8699 }
87100
88101 /**
@@ -91,8 +104,8 @@
91104 * @param table the name of the table to insert into.
92105 * @return an in-construction INSERT query.
93106 */
94- public static Insert insertInto(TableMetadata table) {
95- return new Insert(table);
107+ public Insert insertInto(TableMetadata table) {
108+ return new Insert(cluster, table);
96109 }
97110
98111 /**
@@ -102,8 +115,8 @@
102115 * @return an in-construction UPDATE query (at least a SET and a WHERE
103116 * clause needs to be provided to complete the query).
104117 */
105- public static Update update(String table) {
106- return new Update(null, table);
118+ public Update update(String table) {
119+ return new Update(cluster, null, table);
107120 }
108121
109122 /**
@@ -114,8 +127,8 @@
114127 * @return an in-construction UPDATE query (at least a SET and a WHERE
115128 * clause needs to be provided to complete the query).
116129 */
117- public static Update update(String keyspace, String table) {
118- return new Update(keyspace, table);
130+ public Update update(String keyspace, String table) {
131+ return new Update(cluster, keyspace, table);
119132 }
120133
121134 /**
@@ -125,8 +138,8 @@
125138 * @return an in-construction UPDATE query (at least a SET and a WHERE
126139 * clause needs to be provided to complete the query).
127140 */
128- public static Update update(TableMetadata table) {
129- return new Update(table);
141+ public Update update(TableMetadata table) {
142+ return new Update(cluster, table);
130143 }
131144
132145 /**
@@ -136,8 +149,8 @@
136149 * @return an in-construction DELETE query (At least a FROM and a WHERE
137150 * clause needs to be provided to complete the query).
138151 */
139- public static Delete.Builder delete(String... columns) {
140- return new Delete.Builder(columns);
152+ public Delete.Builder delete(String... columns) {
153+ return new Delete.Builder(cluster, columns);
141154 }
142155
143156 /**
@@ -147,8 +160,8 @@
147160 * column selection and at least a FROM and a WHERE clause to complete the
148161 * query).
149162 */
150- public static Delete.Selection delete() {
151- return new Delete.Selection();
163+ public Delete.Selection delete() {
164+ return new Delete.Selection(cluster);
152165 }
153166
154167 /**
@@ -164,8 +177,8 @@
164177 * @param statements the statements to batch.
165178 * @return a new {@code RegularStatement} that batch {@code statements}.
166179 */
167- public static Batch batch(RegularStatement... statements) {
168- return new Batch(statements, true);
180+ public Batch batch(RegularStatement... statements) {
181+ return new Batch(cluster, statements, true);
169182 }
170183
171184 /**
@@ -185,8 +198,8 @@
185198 * @return a new {@code RegularStatement} that batch {@code statements} without
186199 * using the batch log.
187200 */
188- public static Batch unloggedBatch(RegularStatement... statements) {
189- return new Batch(statements, false);
201+ public Batch unloggedBatch(RegularStatement... statements) {
202+ return new Batch(cluster, statements, false);
190203 }
191204
192205 /**
@@ -195,8 +208,8 @@
195208 * @param table the name of the table to truncate.
196209 * @return the truncation query.
197210 */
198- public static Truncate truncate(String table) {
199- return new Truncate(null, table);
211+ public Truncate truncate(String table) {
212+ return new Truncate(cluster, null, table);
200213 }
201214
202215 /**
@@ -206,8 +219,8 @@
206219 * @param table the name of the table to truncate.
207220 * @return the truncation query.
208221 */
209- public static Truncate truncate(String keyspace, String table) {
210- return new Truncate(keyspace, table);
222+ public Truncate truncate(String keyspace, String table) {
223+ return new Truncate(cluster, keyspace, table);
211224 }
212225
213226 /**
@@ -216,8 +229,8 @@
216229 * @param table the table to truncate.
217230 * @return the truncation query.
218231 */
219- public static Truncate truncate(TableMetadata table) {
220- return new Truncate(table);
232+ public Truncate truncate(TableMetadata table) {
233+ return new Truncate(cluster, table);
221234 }
222235
223236 /**
@@ -255,7 +268,7 @@
255268 public static String token(String... columnNames) {
256269 StringBuilder sb = new StringBuilder();
257270 sb.append("token(");
258- Utils.joinAndAppendNames(sb, ",", Arrays.asList((Object[])columnNames));
271+ Utils.joinAndAppendNames(sb, null, ",", Arrays.asList((Object[])columnNames));
259272 sb.append(')');
260273 return sb.toString();
261274 }
modified driver-core/src/main/java/com/datastax/driver/core/querybuilder/Select.java +25 −13
@@ -15,12 +15,13 @@
1515 */
1616 package com.datastax.driver.core.querybuilder;
1717
18-import java.nio.ByteBuffer;
1918 import java.util.ArrayList;
2019 import java.util.Arrays;
2120 import java.util.Collections;
2221 import java.util.List;
2322
23+import com.datastax.driver.core.Cluster;
24+import com.datastax.driver.core.CodecRegistry;
2425 import com.datastax.driver.core.TableMetadata;
2526
2627 /**
@@ -38,16 +39,16 @@
3839 private Object limit;
3940 private boolean allowFiltering;
4041
41- Select(String keyspace, String table, List<Object> columnNames, boolean isDistinct) {
42- super(keyspace);
42+ Select(Cluster cluster, String keyspace, String table, List<Object> columnNames, boolean isDistinct) {
43+ super(keyspace, cluster);
4344 this.table = table;
4445 this.isDistinct = isDistinct;
4546 this.columnNames = columnNames;
4647 this.where = new Where(this);
4748 }
4849
49- Select(TableMetadata table, List<Object> columnNames, boolean isDistinct) {
50- super(table);
50+ Select(Cluster cluster, TableMetadata table, List<Object> columnNames, boolean isDistinct) {
51+ super(table, cluster);
5152 this.table = escapeId(table.getName());
5253 this.isDistinct = isDistinct;
5354 this.columnNames = columnNames;
@@ -58,13 +59,14 @@
5859 StringBuilder buildQueryString(List<Object> variables) {
5960 StringBuilder builder = new StringBuilder();
6061
62+ CodecRegistry codecRegistry = getCodecRegistry();
6163 builder.append("SELECT ");
6264 if (isDistinct)
6365 builder.append("DISTINCT ");
6466 if (columnNames == null) {
6567 builder.append('*');
6668 } else {
67- Utils.joinAndAppendNames(builder, ",", columnNames);
69+ Utils.joinAndAppendNames(builder, codecRegistry, ",", columnNames);
6870 }
6971 builder.append(" FROM ");
7072 if (keyspace != null)
@@ -73,12 +75,12 @@
7375
7476 if (!where.clauses.isEmpty()) {
7577 builder.append(" WHERE ");
76- Utils.joinAndAppend(builder, " AND ", where.clauses, variables);
78+ Utils.joinAndAppend(builder, codecRegistry, " AND ", where.clauses, variables);
7779 }
7880
7981 if (orderings != null) {
8082 builder.append(" ORDER BY ");
81- Utils.joinAndAppend(builder, ",", orderings, variables);
83+ Utils.joinAndAppend(builder, codecRegistry, ",", orderings, variables);
8284 }
8385
8486 if (limit != null) {
@@ -255,12 +257,16 @@
255257 */
256258 public static class Builder {
257259
260+ private final Cluster cluster;
258261 List<Object> columnNames;
259262 boolean isDistinct;
260263
261- Builder() {}
264+ Builder(Cluster cluster) {
265+ this.cluster = cluster;
266+ }
262267
263- Builder(List<Object> columnNames) {
268+ Builder(Cluster cluster, List<Object> columnNames) {
269+ this.cluster = cluster;
264270 this.columnNames = columnNames;
265271 }
266272
@@ -292,7 +298,7 @@
292298 * @return a newly built SELECT statement that selects from {@code keyspace.table}.
293299 */
294300 public Select from(String keyspace, String table) {
295- return new Select(keyspace, table, columnNames, isDistinct);
301+ return new Select(cluster, keyspace, table, columnNames, isDistinct);
296302 }
297303
298304 /**
@@ -302,7 +308,7 @@
302308 * @return a newly built SELECT statement that selects from {@code table}.
303309 */
304310 public Select from(TableMetadata table) {
305- return new Select(table, columnNames, isDistinct);
311+ return new Select(cluster, table, columnNames, isDistinct);
306312 }
307313 }
308314
@@ -311,6 +317,10 @@
311317 */
312318 public static abstract class Selection extends Builder {
313319
320+ Selection(Cluster cluster) {
321+ super(cluster);
322+ }
323+
314324 /**
315325 * Uses DISTINCT selection.
316326 *
@@ -395,7 +405,9 @@
395405
396406 private Object previousSelection;
397407
398- SelectionOrAlias() {}
408+ SelectionOrAlias(Cluster cluster) {
409+ super(cluster);
410+ }
399411
400412 /**
401413 * Adds an alias for the just selected item.
modified driver-core/src/main/java/com/datastax/driver/core/querybuilder/Truncate.java +5 −5
@@ -15,9 +15,9 @@
1515 */
1616 package com.datastax.driver.core.querybuilder;
1717
18-import java.nio.ByteBuffer;
1918 import java.util.List;
2019
20+import com.datastax.driver.core.Cluster;
2121 import com.datastax.driver.core.TableMetadata;
2222
2323 /**
@@ -27,13 +27,13 @@
2727
2828 private final String table;
2929
30- Truncate(String keyspace, String table) {
31- super(keyspace);
30+ Truncate(Cluster cluster, String keyspace, String table) {
31+ super(keyspace, cluster);
3232 this.table = table;
3333 }
3434
35- Truncate(TableMetadata table) {
36- super(table);
35+ Truncate(Cluster cluster, TableMetadata table) {
36+ super(table, cluster);
3737 this.table = escapeId(table.getName());
3838 }
3939
modified driver-core/src/main/java/com/datastax/driver/core/querybuilder/Update.java +11 −9
@@ -15,10 +15,11 @@
1515 */
1616 package com.datastax.driver.core.querybuilder;
1717
18-import java.nio.ByteBuffer;
1918 import java.util.ArrayList;
2019 import java.util.List;
2120
21+import com.datastax.driver.core.Cluster;
22+import com.datastax.driver.core.CodecRegistry;
2223 import com.datastax.driver.core.TableMetadata;
2324 import com.datastax.driver.core.querybuilder.Assignment.CounterAssignment;
2425
@@ -33,8 +34,8 @@
3334 private final Options usings;
3435 private final Conditions conditions;
3536
36- Update(String keyspace, String table) {
37- super(keyspace);
37+ Update(Cluster cluster, String keyspace, String table) {
38+ super(keyspace, cluster);
3839 this.table = table;
3940 this.assignments = new Assignments(this);
4041 this.where = new Where(this);
@@ -42,8 +43,8 @@
4243 this.conditions = new Conditions(this);
4344 }
4445
45- Update(TableMetadata table) {
46- super(table);
46+ Update(Cluster cluster, TableMetadata table) {
47+ super(table, cluster);
4748 this.table = escapeId(table.getName());
4849 this.assignments = new Assignments(this);
4950 this.where = new Where(this);
@@ -60,24 +61,25 @@
6061 Utils.appendName(keyspace, builder).append('.');
6162 Utils.appendName(table, builder);
6263
64+ CodecRegistry codecRegistry = getCodecRegistry();
6365 if (!usings.usings.isEmpty()) {
6466 builder.append(" USING ");
65- Utils.joinAndAppend(builder, " AND ", usings.usings, variables);
67+ Utils.joinAndAppend(builder, codecRegistry, " AND ", usings.usings, variables);
6668 }
6769
6870 if (!assignments.assignments.isEmpty()) {
6971 builder.append(" SET ");
70- Utils.joinAndAppend(builder, ",", assignments.assignments, variables);
72+ Utils.joinAndAppend(builder, codecRegistry, ",", assignments.assignments, variables);
7173 }
7274
7375 if (!where.clauses.isEmpty()) {
7476 builder.append(" WHERE ");
75- Utils.joinAndAppend(builder, " AND ", where.clauses, variables);
77+ Utils.joinAndAppend(builder, codecRegistry, " AND ", where.clauses, variables);
7678 }
7779
7880 if (!conditions.conditions.isEmpty()) {
7981 builder.append(" IF ");
80- Utils.joinAndAppend(builder, " AND ", conditions.conditions, variables);
82+ Utils.joinAndAppend(builder, codecRegistry, " AND ", conditions.conditions, variables);
8183 }
8284
8385 return builder;
modified driver-core/src/main/java/com/datastax/driver/core/querybuilder/Using.java +4 −2
@@ -17,6 +17,8 @@
1717
1818 import java.util.List;
1919
20+import com.datastax.driver.core.CodecRegistry;
21+
2022 public abstract class Using extends Utils.Appendeable {
2123
2224 final String optionName;
@@ -34,7 +36,7 @@
3436 }
3537
3638 @Override
37- void appendTo(StringBuilder sb, List<Object> variables) {
39+ void appendTo(StringBuilder sb, List<Object> variables, CodecRegistry codecRegistry) {
3840 sb.append(optionName).append(' ').append(value);
3941 }
4042
@@ -53,7 +55,7 @@
5355 }
5456
5557 @Override
56- void appendTo(StringBuilder sb, List<Object> variables) {
58+ void appendTo(StringBuilder sb, List<Object> variables, CodecRegistry codecRegistry) {
5759 sb.append(optionName).append(' ').append(marker);
5860 }
5961
modified driver-core/src/main/java/com/datastax/driver/core/querybuilder/Utils.java +40 −196
@@ -17,241 +17,93 @@
1717
1818 import java.math.BigDecimal;
1919 import java.math.BigInteger;
20-import java.net.InetAddress;
21-import java.nio.ByteBuffer;
22-import java.util.*;
20+import java.util.Collection;
21+import java.util.List;
22+import java.util.Map;
2323 import java.util.regex.Pattern;
2424
2525 import static com.google.common.base.Preconditions.checkNotNull;
2626
27-import com.datastax.driver.core.DataType;
28-import com.datastax.driver.core.ProtocolVersion;
29-import com.datastax.driver.core.TupleValue;
30-import com.datastax.driver.core.UDTValue;
27+import com.datastax.driver.core.CodecRegistry;
28+import com.datastax.driver.core.TypeCodec;
3129
3230 // Static utilities private to the query builder
3331 abstract class Utils {
3432
3533 private static final Pattern cnamePattern = Pattern.compile("\\w+(?:\\[.+\\])?");
3634
37- static StringBuilder joinAndAppend(StringBuilder sb, String separator, List<? extends Appendeable> values, List<Object> variables) {
35+ static StringBuilder joinAndAppend(StringBuilder sb, CodecRegistry codecRegistry, String separator, List<? extends Appendeable> values, List<Object> variables) {
3836 for (int i = 0; i < values.size(); i++) {
3937 if (i > 0)
4038 sb.append(separator);
41- values.get(i).appendTo(sb, variables);
39+ values.get(i).appendTo(sb, variables, codecRegistry);
4240 }
4341 return sb;
4442 }
4543
46- static StringBuilder joinAndAppendNames(StringBuilder sb, String separator, List<?> values) {
44+ static StringBuilder joinAndAppendNames(StringBuilder sb, CodecRegistry codecRegistry, String separator, List<?> values) {
4745 for (int i = 0; i < values.size(); i++) {
4846 if (i > 0)
4947 sb.append(separator);
50- appendName(values.get(i), sb);
48+ appendName(values.get(i), codecRegistry, sb);
5149 }
5250 return sb;
5351 }
5452
55- static StringBuilder joinAndAppendValues(StringBuilder sb, String separator, List<?> values, List<Object> variables) {
53+ static StringBuilder joinAndAppendValues(StringBuilder sb, CodecRegistry codecRegistry, String separator, List<?> values, List<Object> variables) {
5654 for (int i = 0; i < values.size(); i++) {
5755 if (i > 0)
5856 sb.append(separator);
59- appendValue(values.get(i), sb, variables);
57+ appendValue(values.get(i), codecRegistry, sb, variables);
6058 }
6159 return sb;
6260 }
6361
64- // Returns false if it's not really serializable (function call, bind markers, ...)
65- static boolean isSerializable(Object value) {
66- if (value instanceof BindMarker || value instanceof FCall || value instanceof CName)
67- return false;
68-
69- if (value instanceof RawString)
70- return false;
71-
72- // We also don't serialize fixed size number types. The reason is that if we do it, we will
73- // force a particular size (4 bytes for ints, ...) and for the query builder, we don't want
62+ private static boolean isForceAppendToQueryString(Object value) {
63+ // Force append to query string for all fixed-size number types.
64+ // The reason is that if we don't do it, we will
65+ // force a particular size (4 bytes for ints, ...)
66+ // and for the query builder, we don't want
7467 // users to have to bother with that.
75- if (value instanceof Number && !(value instanceof BigInteger || value instanceof BigDecimal))
76- return false;
77-
78- return true;
79- }
80-
81- static ByteBuffer[] convert(List<Object> values, ProtocolVersion protocolVersion) {
82- ByteBuffer[] serializedValues = new ByteBuffer[values.size()];
83- for (int i = 0; i < values.size(); i++) {
84- try {
85- serializedValues[i] = DataType.serializeValue(values.get(i), protocolVersion);
86- } catch (IllegalArgumentException e) {
87- // Catch and rethrow to provide a more helpful error message (one that include which value is bad)
88- throw new IllegalArgumentException(String.format("Value %d of type %s does not correspond to any CQL3 type", i, values.get(i).getClass()));
89- }
90- }
91- return serializedValues;
92- }
93-
94- static StringBuilder appendValue(Object value, StringBuilder sb, List<Object> variables) {
95- if (variables == null || !isSerializable(value))
96- return appendValue(value, sb);
97-
98- sb.append('?');
99- variables.add(value);
100- return sb;
101- }
102-
103- static StringBuilder appendValue(Object value, StringBuilder sb) {
104- // That is kind of lame but lacking a better solution
105- if (appendValueIfLiteral(value, sb))
106- return sb;
107-
108- if (appendValueIfCollection(value, sb))
109- return sb;
110-
111- if (appendValueIfUdt(value, sb))
112- return sb;
113-
114- if (appendValueIfTuple(value, sb))
115- return sb;
116-
117- appendStringIfValid(value, sb);
118- return sb;
119- }
120-
121- private static void appendStringIfValid(Object value, StringBuilder sb) {
122- if (value instanceof RawString) {
123- sb.append(value.toString());
124- } else {
125- if (!(value instanceof String)) {
126- String msg = String.format("Invalid value %s of type unknown to the query builder", value);
127- if (value instanceof byte[])
128- msg += " (for blob values, make sure to use a ByteBuffer)";
129- throw new IllegalArgumentException(msg);
130- }
131- appendValueString((String)value, sb);
132- }
68+ // TODO this probably does not work well with custom codecs for fixed-size numbers (int, bigint, float, double)
69+ return value instanceof Number && !(value instanceof BigInteger || value instanceof BigDecimal);
13370 }
13471
135- private static boolean appendValueIfLiteral(Object value, StringBuilder sb) {
136- if (value instanceof Number || value instanceof UUID || value instanceof Boolean) {
137- sb.append(value);
138- return true;
139- } else if (value instanceof InetAddress) {
140- sb.append(DataType.inet().format(value));
141- return true;
142- } else if (value instanceof Date) {
143- sb.append(DataType.timestamp().format(value));
144- return true;
145- } else if (value instanceof ByteBuffer) {
146- sb.append(DataType.blob().format(value));
147- return true;
72+ static StringBuilder appendValue(Object value, CodecRegistry codecRegistry, StringBuilder sb, List<Object> variables) {
73+ if (value == null) {
74+ sb.append("null");
14875 } else if (value instanceof BindMarker) {
14976 sb.append(value);
150- return true;
15177 } else if (value instanceof FCall) {
15278 FCall fcall = (FCall)value;
15379 sb.append(fcall.name).append('(');
15480 for (int i = 0; i < fcall.parameters.length; i++) {
15581 if (i > 0)
15682 sb.append(',');
157- appendValue(fcall.parameters[i], sb, null);
83+ appendValue(fcall.parameters[i], codecRegistry, sb, variables);
15884 }
15985 sb.append(')');
160- return true;
16186 } else if (value instanceof CName) {
162- appendName(((CName)value).name, sb);
163- return true;
164- } else if (value == null) {
165- sb.append("null");
166- return true;
167- } else {
168- return false;
169- }
170- }
171-
172- @SuppressWarnings("rawtypes")
173- private static boolean appendValueIfCollection(Object value, StringBuilder sb) {
174- if (value instanceof List) {
175- appendList((List)value, sb);
176- return true;
177- } else if (value instanceof Set) {
178- appendSet((Set)value, sb);
179- return true;
180- } else if (value instanceof Map) {
181- appendMap((Map)value, sb);
182- return true;
183- } else {
184- return false;
185- }
186- }
187-
188- static StringBuilder appendCollection(Object value, StringBuilder sb, List<Object> variables) {
189- if (variables == null || !isSerializable(value)) {
190- boolean wasCollection = appendValueIfCollection(value, sb);
191- assert wasCollection;
87+ appendName(((CName)value).name, codecRegistry, sb);
88+ } else if (value instanceof RawString) {
89+ sb.append(value.toString());
90+ } else if (variables == null || isForceAppendToQueryString(value)) {
91+ // we are not collecting statement values (variables == null)
92+ // or the value is meant to be forcefully appended to the query string:
93+ // format it with the appropriate codec and append it now
94+ TypeCodec<Object> codec = codecRegistry.codecFor(value);
95+ sb.append(codec.format(value));
19296 } else {
97+ // Do not format the value nor append it to the query string:
98+ // use a bind marker instead,
99+ // but add the value the the statement's variables list
193100 sb.append('?');
194101 variables.add(value);
102+ return sb;
195103 }
196104 return sb;
197105 }
198106
199- static StringBuilder appendList(List<?> l, StringBuilder sb) {
200- sb.append('[');
201- for (int i = 0; i < l.size(); i++) {
202- if (i > 0)
203- sb.append(',');
204- appendValue(l.get(i), sb);
205- }
206- sb.append(']');
207- return sb;
208- }
209-
210- static StringBuilder appendSet(Set<?> s, StringBuilder sb) {
211- sb.append('{');
212- boolean first = true;
213- for (Object elt : s) {
214- if (first) first = false; else sb.append(',');
215- appendValue(elt, sb);
216- }
217- sb.append('}');
218- return sb;
219- }
220-
221- static StringBuilder appendMap(Map<?, ?> m, StringBuilder sb) {
222- sb.append('{');
223- boolean first = true;
224- for (Map.Entry<?, ?> entry : m.entrySet()) {
225- if (first)
226- first = false;
227- else
228- sb.append(',');
229- appendValue(entry.getKey(), sb);
230- sb.append(':');
231- appendValue(entry.getValue(), sb);
232- }
233- sb.append('}');
234- return sb;
235- }
236-
237- private static boolean appendValueIfUdt(Object value, StringBuilder sb) {
238- if (value instanceof UDTValue) {
239- sb.append(((UDTValue)value).toString());
240- return true;
241- } else {
242- return false;
243- }
244- }
245-
246- private static boolean appendValueIfTuple(Object value, StringBuilder sb) {
247- if (value instanceof TupleValue) {
248- sb.append(((TupleValue)value).toString());
249- return true;
250- } else {
251- return false;
252- }
253- }
254-
255107 static boolean containsBindMarker(Object value) {
256108 if (value instanceof BindMarker)
257109 return true;
@@ -291,10 +143,6 @@
291143 return true;
292144 }
293145
294- private static StringBuilder appendValueString(String value, StringBuilder sb) {
295- return sb.append(DataType.text().format(value));
296- }
297-
298146 static boolean isRawValue(Object value) {
299147 return value != null
300148 && !(value instanceof FCall)
@@ -302,10 +150,6 @@
302150 && !(value instanceof BindMarker);
303151 }
304152
305- static String toRawString(Object value) {
306- return appendValue(value, new StringBuilder()).toString();
307- }
308-
309153 static StringBuilder appendName(String name, StringBuilder sb) {
310154 name = name.trim();
311155 // FIXME: checking for token( specifically is uber ugly, we'll need some better solution.
@@ -316,23 +160,23 @@
316160 return sb;
317161 }
318162
319- static StringBuilder appendName(Object name, StringBuilder sb) {
163+ static StringBuilder appendName(Object name, CodecRegistry codecRegistry, StringBuilder sb) {
320164 if (name instanceof String) {
321165 appendName((String)name, sb);
322166 } else if (name instanceof CName) {
323- appendName(((CName)name).name, sb);
167+ appendName(((CName)name).name, codecRegistry, sb);
324168 } else if (name instanceof FCall) {
325169 FCall fcall = (FCall)name;
326170 sb.append(fcall.name).append('(');
327171 for (int i = 0; i < fcall.parameters.length; i++) {
328172 if (i > 0)
329173 sb.append(',');
330- appendValue(fcall.parameters[i], sb, null);
174+ appendValue(fcall.parameters[i], codecRegistry, sb, null);
331175 }
332176 sb.append(')');
333177 } else if (name instanceof Alias) {
334178 Alias alias = (Alias)name;
335- appendName(alias.column, sb);
179+ appendName(alias.column, codecRegistry, sb);
336180 sb.append(" AS ").append(alias.alias);
337181 } else if (name instanceof RawString) {
338182 sb.append(((RawString)name).str);
@@ -343,7 +187,7 @@
343187 }
344188
345189 static abstract class Appendeable {
346- abstract void appendTo(StringBuilder sb, List<Object> values);
190+ abstract void appendTo(StringBuilder sb, List<Object> values, CodecRegistry codecRegistry);
347191 abstract boolean containsBindMarker();
348192 }
349193
modified driver-core/src/main/java/com/datastax/driver/core/schemabuilder/SchemaStatement.java +1 −2
@@ -21,7 +21,6 @@
2121
2222 import com.google.common.base.Strings;
2323
24-import com.datastax.driver.core.ProtocolVersion;
2524 import com.datastax.driver.core.RegularStatement;
2625
2726 /**
@@ -51,7 +50,7 @@
5150 }
5251
5352 @Override
54- public ByteBuffer[] getValues(ProtocolVersion protocolVersion) {
53+ public ByteBuffer[] getValues() {
5554 // DDL statements never have values
5655 return new ByteBuffer[0];
5756 }
modified driver-core/src/test/java/com/datastax/driver/core/AbstractPoliciesTest.java +13 −8
@@ -20,11 +20,16 @@
2020 import java.util.HashMap;
2121 import java.util.Map;
2222
23-import static org.testng.Assert.*;
23+import static org.testng.Assert.assertEquals;
24+import static org.testng.Assert.assertTrue;
25+import static org.testng.Assert.fail;
2426
25-import static com.datastax.driver.core.TestUtils.*;
26-import static com.datastax.driver.core.querybuilder.QueryBuilder.batch;
27-import static com.datastax.driver.core.querybuilder.QueryBuilder.insertInto;
27+import com.datastax.driver.core.querybuilder.QueryBuilder;
28+
29+import static com.datastax.driver.core.TestUtils.CREATE_KEYSPACE_GENERIC_FORMAT;
30+import static com.datastax.driver.core.TestUtils.CREATE_KEYSPACE_SIMPLE_FORMAT;
31+import static com.datastax.driver.core.TestUtils.SIMPLE_KEYSPACE;
32+import static com.datastax.driver.core.TestUtils.SIMPLE_TABLE;
2833
2934 public abstract class AbstractPoliciesTest {
3035 private static final boolean DEBUG = false;
@@ -179,11 +184,11 @@
179184 for (int i = 0; i < n; ++i)
180185 if (batch)
181186 // BUG: WriteType == SIMPLE
182- c.session.execute(batch()
183- .add(insertInto(SIMPLE_TABLE).values(new String[]{ "k", "i"}, new Object[]{ 0, 0 }))
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 }))
184189 .setConsistencyLevel(cl));
185190 else
186- c.session.execute(new SimpleStatement(String.format("INSERT INTO %s(k, i) VALUES (0, 0)", SIMPLE_TABLE)).setConsistencyLevel(cl));
191+ c.session.execute(c.session.newSimpleStatement(String.format("INSERT INTO %s(k, i) VALUES (0, 0)", SIMPLE_TABLE)).setConsistencyLevel(cl));
187192 }
188193
189194
@@ -211,7 +216,7 @@
211216 ByteBuffer routingKey = ByteBuffer.allocate(4);
212217 routingKey.putInt(0, 0);
213218 for (int i = 0; i < n; ++i)
214- addCoordinator(c.session.execute(new SimpleStatement(String.format("SELECT * FROM %s WHERE k = 0", SIMPLE_TABLE)).setRoutingKey(routingKey).setConsistencyLevel(cl)));
219+ addCoordinator(c.session.execute(c.session.newSimpleStatement(String.format("SELECT * FROM %s WHERE k = 0", SIMPLE_TABLE)).setRoutingKey(routingKey).setConsistencyLevel(cl)));
215220 }
216221 }
217222 }
modified driver-core/src/test/java/com/datastax/driver/core/AbstractReplicationStrategyTest.java +1 −1
@@ -39,7 +39,7 @@
3939 private final String address;
4040
4141 private HostMock(String address) throws UnknownHostException {
42- super(new InetSocketAddress(InetAddress.getByName(address), 9042), new ConvictionPolicy.Simple.Factory(), null);
42+ super(new InetSocketAddress(InetAddress.getByName(address), 9042), new ConvictionPolicy.Simple.Factory(), new Cluster("test", null, Configuration.builder().build()).manager);
4343 this.address = address;
4444 }
4545
modified driver-core/src/test/java/com/datastax/driver/core/AggregateMetadataTest.java +9 −8
@@ -33,6 +33,7 @@
3333 // These tests needs a protocol version to (de)serialize INITCONDs. Since we're using basic types, I don't think the binary format
3434 // is going to change at any time in the future, so the actual version does not matter.
3535 private static final ProtocolVersion PROTOCOL_VERSION = ProtocolVersion.NEWEST_SUPPORTED;
36+ private CodecRegistry codecRegistry = new CodecRegistry();
3637
3738 KeyspaceMetadata keyspace;
3839
@@ -46,7 +47,7 @@
4647 FunctionMetadata stateFunc = mock(FunctionMetadata.class);
4748 keyspace.functions.put("cat(text,int)", stateFunc);
4849
49- AggregateMetadata aggregate = AggregateMetadata.build(keyspace, SYSTEM_ROW_CAT_TOS, PROTOCOL_VERSION);
50+ AggregateMetadata aggregate = AggregateMetadata.build(keyspace, SYSTEM_ROW_CAT_TOS, PROTOCOL_VERSION, codecRegistry);
5051
5152 assertThat(aggregate).isNotNull();
5253 assertThat(aggregate.getFullName()).isEqualTo("cat_tos(int)");
@@ -72,7 +73,7 @@
7273 FunctionMetadata stateFunc = mock(FunctionMetadata.class);
7374 keyspace.functions.put("inc(int)", stateFunc);
7475
75- AggregateMetadata aggregate = AggregateMetadata.build(keyspace, SYSTEM_ROW_MYCOUNT, PROTOCOL_VERSION);
76+ AggregateMetadata aggregate = AggregateMetadata.build(keyspace, SYSTEM_ROW_MYCOUNT, PROTOCOL_VERSION, codecRegistry);
7677
7778 assertThat(aggregate).isNotNull();
7879 assertThat(aggregate.getFullName()).isEqualTo("mycount()");
@@ -100,7 +101,7 @@
100101 FunctionMetadata finalFunc = mock(FunctionMetadata.class);
101102 keyspace.functions.put("announce(int)", finalFunc);
102103
103- AggregateMetadata aggregate = AggregateMetadata.build(keyspace, SYSTEM_ROW_PRETTYSUM, PROTOCOL_VERSION);
104+ AggregateMetadata aggregate = AggregateMetadata.build(keyspace, SYSTEM_ROW_PRETTYSUM, PROTOCOL_VERSION, codecRegistry);
104105
105106 assertThat(aggregate).isNotNull();
106107 assertThat(aggregate.getFullName()).isEqualTo("prettysum(int)");
@@ -127,7 +128,7 @@
127128 FunctionMetadata stateFunc = mock(FunctionMetadata.class);
128129 keyspace.functions.put("plus(int,int)", stateFunc);
129130
130- AggregateMetadata aggregate = AggregateMetadata.build(keyspace, SYSTEM_ROW_SUM, PROTOCOL_VERSION);
131+ AggregateMetadata aggregate = AggregateMetadata.build(keyspace, SYSTEM_ROW_SUM, PROTOCOL_VERSION, codecRegistry);
131132
132133 assertThat(aggregate).isNotNull();
133134 assertThat(aggregate.getFullName()).isEqualTo("sum(int)");
@@ -151,13 +152,13 @@
151152 private static final String TEXT = "org.apache.cassandra.db.marshal.UTF8Type";
152153
153154 private static final Row SYSTEM_ROW_CAT_TOS = mockRow("cat_tos", ImmutableList.of("int"), ImmutableList.of(INT),
154- null, DataType.text().serialize("0", PROTOCOL_VERSION), TEXT, "cat", TEXT);
155+ null, TypeCodec.VarcharCodec.instance.serialize("0", PROTOCOL_VERSION), TEXT, "cat", TEXT);
155156
156157 private static final Row SYSTEM_ROW_MYCOUNT = mockRow("mycount", Collections.<String>emptyList(), Collections.<String>emptyList(),
157- null, DataType.cint().serialize(0, PROTOCOL_VERSION), INT, "inc", INT);
158+ null, TypeCodec.IntCodec.instance.serialize(0, PROTOCOL_VERSION), INT, "inc", INT);
158159
159160 private static final Row SYSTEM_ROW_PRETTYSUM = mockRow("prettysum", ImmutableList.of("int"), ImmutableList.of(INT),
160- "announce", DataType.cint().serialize(0, PROTOCOL_VERSION), TEXT, "plus", INT);
161+ "announce", TypeCodec.IntCodec.instance.serialize(0, PROTOCOL_VERSION), TEXT, "plus", INT);
161162
162163 private static final Row SYSTEM_ROW_SUM = mockRow("sum", ImmutableList.of("int"), ImmutableList.of(INT),
163164 null, null, INT, "plus", INT);
@@ -177,4 +178,4 @@
177178
178179 return row;
179180 }
180-}
No newline at the end of the file
181+}
modified driver-core/src/test/java/com/datastax/driver/core/Assertions.java +6 −2
@@ -20,7 +20,7 @@
2020 /**
2121 * Augment AssertJ with custom assertions for the Java driver.
2222 */
23-public class Assertions extends org.assertj.core.api.Assertions{
23+public class Assertions extends org.assertj.core.api.Assertions {
2424 public static ClusterAssert assertThat(Cluster cluster) {
2525 return new ClusterAssert(cluster);
2626 }
@@ -36,7 +36,7 @@
3636 public static DataTypeAssert assertThat(DataType type) {
3737 return new DataTypeAssert(type);
3838 }
39-
39+
4040 public static IndexMetadataAssert assertThat(IndexMetadata indexMetadata) {
4141 return new IndexMetadataAssert(indexMetadata);
4242 }
@@ -53,4 +53,8 @@
5353 return new ColumnMetadataAssert(column);
5454 }
5555
56+ public static TypeCodecAssert assertThat(TypeCodec codec) {
57+ return new TypeCodecAssert(codec);
58+ }
59+
5660 }
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 = new SimpleStatement("select * from ints").setFetchSize(fetchSize);
60+ Statement statement = session.newSimpleStatement("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(new SimpleStatement("INSERT INTO test (k, v) VALUES (?, ?)", "key1", 0));
43+ batch.add(session.newSimpleStatement("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(new SimpleStatement("INSERT INTO test (k, v) VALUES (?, ?)", "key1", 0));
90+ batch.add(session.newSimpleStatement("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/CassandraTypeParserTest.java +17 −14
@@ -29,24 +29,27 @@
2929
3030 public class CassandraTypeParserTest {
3131
32+ private ProtocolVersion protocolVersion = TestUtils.getDesiredProtocolVersion();
33+ private CodecRegistry codecRegistry = new CodecRegistry();
34+
3235 @Test(groups = "unit")
3336 public void parseOneTest() {
3437
35- assertEquals(CassandraTypeParser.parseOne("org.apache.cassandra.db.marshal.ByteType"), DataType.tinyint());
36- assertEquals(CassandraTypeParser.parseOne("org.apache.cassandra.db.marshal.ShortType"), DataType.smallint());
37- assertEquals(CassandraTypeParser.parseOne("org.apache.cassandra.db.marshal.SimpleDateType"), DataType.date());
38- assertEquals(CassandraTypeParser.parseOne("org.apache.cassandra.db.marshal.TimeType"), DataType.time());
39- assertEquals(CassandraTypeParser.parseOne("org.apache.cassandra.db.marshal.InetAddressType"), DataType.inet());
40- assertEquals(CassandraTypeParser.parseOne("org.apache.cassandra.db.marshal.ListType(org.apache.cassandra.db.marshal.UTF8Type)"), DataType.list(DataType.text()));
41- assertEquals(CassandraTypeParser.parseOne("org.apache.cassandra.db.marshal.ReversedType(org.apache.cassandra.db.marshal.UTF8Type)"), DataType.text());
38+ assertEquals(CassandraTypeParser.parseOne("org.apache.cassandra.db.marshal.ByteType", protocolVersion, codecRegistry), DataType.tinyint());
39+ assertEquals(CassandraTypeParser.parseOne("org.apache.cassandra.db.marshal.ShortType", protocolVersion, codecRegistry), DataType.smallint());
40+ assertEquals(CassandraTypeParser.parseOne("org.apache.cassandra.db.marshal.SimpleDateType", protocolVersion, codecRegistry), DataType.date());
41+ assertEquals(CassandraTypeParser.parseOne("org.apache.cassandra.db.marshal.TimeType", protocolVersion, codecRegistry), DataType.time());
42+ assertEquals(CassandraTypeParser.parseOne("org.apache.cassandra.db.marshal.InetAddressType", protocolVersion, codecRegistry), DataType.inet());
43+ assertEquals(CassandraTypeParser.parseOne("org.apache.cassandra.db.marshal.ListType(org.apache.cassandra.db.marshal.UTF8Type)", protocolVersion, codecRegistry), DataType.list(DataType.text()));
44+ assertEquals(CassandraTypeParser.parseOne("org.apache.cassandra.db.marshal.ReversedType(org.apache.cassandra.db.marshal.UTF8Type)", protocolVersion, codecRegistry), DataType.text());
4245
4346 String s;
4447
4548 s = "org.apache.cassandra.db.marshal.CompositeType(org.apache.cassandra.db.marshal.UTF8Type, org.apache.cassandra.db.marshal.Int32Type)";
46- assertEquals(CassandraTypeParser.parseOne(s), DataType.custom(s));
49+ assertEquals(CassandraTypeParser.parseOne(s, protocolVersion, codecRegistry), DataType.custom(s));
4750
4851 s = "org.apache.cassandra.db.marshal.ReversedType(org.apache.cassandra.db.marshal.ListType(org.apache.cassandra.db.marshal.Int32Type))";
49- assertEquals(CassandraTypeParser.parseOne(s), DataType.list(DataType.cint()));
52+ assertEquals(CassandraTypeParser.parseOne(s, protocolVersion, codecRegistry), DataType.list(DataType.cint()));
5053 }
5154
5255 @Test(groups = "unit")
@@ -54,13 +57,13 @@
5457
5558 String s = "org.apache.cassandra.db.marshal.CompositeType(org.apache.cassandra.db.marshal.Int32Type, org.apache.cassandra.db.marshal.UTF8Type,";
5659 s += "org.apache.cassandra.db.marshal.ColumnToCollectionType(6162:org.apache.cassandra.db.marshal.ListType(org.apache.cassandra.db.marshal.Int32Type)))";
57- CassandraTypeParser.ParseResult r1 = CassandraTypeParser.parseWithComposite(s);
60+ CassandraTypeParser.ParseResult r1 = CassandraTypeParser.parseWithComposite(s, protocolVersion, codecRegistry);
5861 assertTrue(r1.isComposite);
5962 assertEquals(r1.types, Arrays.asList(DataType.cint(), DataType.text()));
6063 assertEquals(r1.collections.size(), 1);
6164 assertEquals(r1.collections.get("ab"), DataType.list(DataType.cint()));
6265
63- CassandraTypeParser.ParseResult r2 = CassandraTypeParser.parseWithComposite("org.apache.cassandra.db.marshal.TimestampType");
66+ CassandraTypeParser.ParseResult r2 = CassandraTypeParser.parseWithComposite("org.apache.cassandra.db.marshal.TimestampType", protocolVersion, codecRegistry);
6467 assertFalse(r2.isComposite);
6568 assertEquals(r2.types, Arrays.asList(DataType.timestamp()));
6669 assertEquals(r2.collections.size(), 0);
@@ -70,7 +73,7 @@
7073 public void parseUserTypes() {
7174
7275 String s = "org.apache.cassandra.db.marshal.UserType(foo,61646472657373,737472656574:org.apache.cassandra.db.marshal.UTF8Type,7a6970636f6465:org.apache.cassandra.db.marshal.Int32Type,70686f6e6573:org.apache.cassandra.db.marshal.SetType(org.apache.cassandra.db.marshal.UserType(foo,70686f6e65,6e616d65:org.apache.cassandra.db.marshal.UTF8Type,6e756d626572:org.apache.cassandra.db.marshal.UTF8Type)))";
73- UserType def = (UserType)CassandraTypeParser.parseOne(s);
76+ UserType def = (UserType)CassandraTypeParser.parseOne(s, protocolVersion, codecRegistry);
7477
7578 assertEquals(def.getKeyspace(), "foo");
7679 assertEquals(def.getTypeName(), "address");
@@ -109,7 +112,7 @@
109112 @Test(groups = "unit")
110113 public void parseTupleTest() {
111114 String s = "org.apache.cassandra.db.marshal.TupleType(org.apache.cassandra.db.marshal.Int32Type,org.apache.cassandra.db.marshal.UTF8Type,org.apache.cassandra.db.marshal.FloatType)";
112- TupleType type = (TupleType)CassandraTypeParser.parseOne(s);
115+ TupleType type = (TupleType)CassandraTypeParser.parseOne(s, protocolVersion, codecRegistry);
113116 assertNotNull(type);
114117 assertEquals(type.getComponentTypes().get(0), DataType.cint());
115118 assertEquals(type.getComponentTypes().get(1), DataType.text());
@@ -121,7 +124,7 @@
121124 // map<text, frozen<map<int,int>>>
122125 String s = "org.apache.cassandra.db.marshal.MapType(org.apache.cassandra.db.marshal.UTF8Type,org.apache.cassandra.db.marshal.FrozenType(org.apache.cassandra.db.marshal.MapType(org.apache.cassandra.db.marshal.Int32Type,org.apache.cassandra.db.marshal.Int32Type)))";
123126
124- DataType parentMap = CassandraTypeParser.parseOne(s);
127+ DataType parentMap = CassandraTypeParser.parseOne(s, protocolVersion, codecRegistry);
125128 assertThat(parentMap)
126129 .hasName(DataType.Name.MAP)
127130 .isNotFrozen()
modified driver-core/src/test/java/com/datastax/driver/core/ClusterInitTest.java +2 −2
@@ -35,10 +35,10 @@
3535 import com.datastax.driver.core.exceptions.NoHostAvailableException;
3636 import com.datastax.driver.core.policies.ConstantReconnectionPolicy;
3737 import com.datastax.driver.core.querybuilder.Insert;
38+import com.datastax.driver.core.querybuilder.QueryBuilder;
3839 import com.datastax.driver.core.utils.UUIDs;
3940
4041 import static com.datastax.driver.core.FakeHost.Behavior.THROWING_CONNECT_TIMEOUTS;
41-import static com.datastax.driver.core.querybuilder.QueryBuilder.insertInto;
4242
4343 public class ClusterInitTest {
4444 private static final Logger logger = LoggerFactory.getLogger(ClusterInitTest.class);
@@ -141,7 +141,7 @@
141141 .one().getString("release_version");
142142
143143 for (int i = 2; i <= 6; i++) {
144- Insert insertStmt = insertInto("peers")
144+ Insert insertStmt = new QueryBuilder(cluster).insertInto("peers")
145145 .value("peer", InetAddress.getByName(CCMBridge.ipOfNode(i)))
146146 .value("data_center", "datacenter1")
147147 .value("host_id", UUIDs.random())
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(new SimpleStatement("SELECT * FROM test WHERE k1 = 1").setFetchSize(1));
81+ ResultSet rs = session.execute(session.newSimpleStatement("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 −14
@@ -64,7 +64,7 @@
6464
6565 @Test(groups = "short")
6666 public void should_echo_custom_payload_when_executing_statement() throws Exception {
67- Statement statement = new SimpleStatement("SELECT c2 FROM t1 where c1 = ?", 1);
67+ Statement statement = session.newSimpleStatement("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(new SimpleStatement("INSERT INTO t1 (c1, c2) values (1, 'foo')"));
76+ Statement statement = new BatchStatement().add(session.newSimpleStatement("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,7 +82,8 @@
8282
8383 @Test(groups = "short")
8484 public void should_echo_custom_payload_when_building_statement() throws Exception {
85- Statement statement = QueryBuilder.select("c2").from("t1").where(eq("c1", 1)).setOutgoingPayload(payload1);
85+ QueryBuilder builder = new QueryBuilder(cluster);
86+ Statement statement = builder.select("c2").from("t1").where(eq("c1", 1)).setOutgoingPayload(payload1);
8687 ResultSet rows = session.execute(statement);
8788 Map<String, ByteBuffer> actual = rows.getExecutionInfo().getIncomingPayload();
8889 assertThat(actual).isEqualTo(payload1);
@@ -96,7 +97,7 @@
9697 */
9798 @Test(groups = "short")
9899 public void should_propagate_incoming_payload_to_bound_statement() throws Exception {
99- RegularStatement statement = new SimpleStatement("SELECT c2 as col1 FROM t1 where c1 = ?");
100+ RegularStatement statement = session.newSimpleStatement("SELECT c2 as col1 FROM t1 where c1 = ?");
100101 statement.setOutgoingPayload(payload1);
101102 PreparedStatement ps = session.prepare(statement);
102103 // Prepared statement should inherit outgoing payload
@@ -123,7 +124,7 @@
123124 */
124125 @Test(groups = "short")
125126 public void should_override_incoming_payload_when_outgoing_payload_explicitly_set_on_preparing_statement() throws Exception {
126- RegularStatement statement = new SimpleStatement("SELECT c2 as col2 FROM t1 where c1 = ?");
127+ RegularStatement statement = session.newSimpleStatement("SELECT c2 as col2 FROM t1 where c1 = ?");
127128 statement.setOutgoingPayload(payload1);
128129 PreparedStatement ps = session.prepare(statement);
129130 // Prepared statement should inherit outgoing payload
@@ -150,7 +151,7 @@
150151 */
151152 @Test(groups = "short")
152153 public void should_not_set_any_payload_on_bound_statement() throws Exception {
153- RegularStatement statement = new SimpleStatement("SELECT c2 as col3 FROM t1 where c1 = ?");
154+ RegularStatement statement = session.newSimpleStatement("SELECT c2 as col3 FROM t1 where c1 = ?");
154155 PreparedStatement ps = session.prepare(statement);
155156 assertThat(ps.getOutgoingPayload()).isNull();
156157 assertThat(ps.getIncomingPayload()).isNull();
@@ -181,7 +182,7 @@
181182 public void should_echo_custom_payload_when_paginating() throws Exception {
182183 session.execute("INSERT INTO t1 (c1) VALUES (1)");
183184 session.execute("INSERT INTO t1 (c1) VALUES (2)");
184- Statement statement = new SimpleStatement("SELECT c2 FROM t1 where c1 IN (1,2)");
185+ Statement statement = session.newSimpleStatement("SELECT c2 FROM t1 where c1 IN (1,2)");
185186 statement.setFetchSize(1);
186187 statement.setOutgoingPayload(payload1);
187188 ResultSet rows = session.execute(statement);
@@ -200,7 +201,7 @@
200201 public void should_encode_null_values() throws Exception {
201202 Map<String, ByteBuffer> payload = new HashMap<String, ByteBuffer>();
202203 payload.put("k1", Statement.NULL_PAYLOAD_VALUE);
203- Statement statement = new SimpleStatement("SELECT c2 FROM t1 where c1 = ?", 1);
204+ Statement statement = session.newSimpleStatement("SELECT c2 FROM t1 where c1 = ?", 1);
204205 statement.setOutgoingPayload(payload);
205206 ResultSet rows = session.execute(statement);
206207 Map<String, ByteBuffer> actual = rows.getExecutionInfo().getIncomingPayload();
@@ -211,28 +212,28 @@
211212 public void should_throw_npe_when_null_key_on_regular_statement() throws Exception {
212213 Map<String, ByteBuffer> payload = new HashMap<String, ByteBuffer>();
213214 payload.put(null, ByteBuffer.wrap(new byte[]{ 1 }));
214- new SimpleStatement("SELECT c2 FROM t1 where c1 = ?", 1).setOutgoingPayload(payload);
215+ session.newSimpleStatement("SELECT c2 FROM t1 where c1 = ?", 1).setOutgoingPayload(payload);
215216 }
216217
217218 @Test(groups = "unit", expectedExceptions = NullPointerException.class)
218219 public void should_throw_npe_when_null_value_on_regular_statement() throws Exception {
219220 Map<String, ByteBuffer> payload = new HashMap<String, ByteBuffer>();
220221 payload.put("k1", null);
221- new SimpleStatement("SELECT c2 FROM t1 where c1 = ?", 1).setOutgoingPayload(payload);
222+ session.newSimpleStatement("SELECT c2 FROM t1 where c1 = ?", 1).setOutgoingPayload(payload);
222223 }
223224
224225 @Test(groups = "short", expectedExceptions = NullPointerException.class)
225226 public void should_throw_npe_when_null_key_on_prepared_statement() throws Exception {
226227 Map<String, ByteBuffer> payload = new HashMap<String, ByteBuffer>();
227228 payload.put(null, ByteBuffer.wrap(new byte[]{ 1 }));
228- session.prepare(new SimpleStatement("SELECT c2 FROM t1 where c1 = 1")).setOutgoingPayload(payload);
229+ session.prepare(session.newSimpleStatement("SELECT c2 FROM t1 where c1 = 1")).setOutgoingPayload(payload);
229230 }
230231
231232 @Test(groups = "short", expectedExceptions = NullPointerException.class)
232233 public void should_throw_npe_when_null_value_on_prepared_statement() throws Exception {
233234 Map<String, ByteBuffer> payload = new HashMap<String, ByteBuffer>();
234235 payload.put("k1", null);
235- session.prepare(new SimpleStatement("SELECT c2 FROM t1 where c1 = 2")).setOutgoingPayload(payload);
236+ session.prepare(session.newSimpleStatement("SELECT c2 FROM t1 where c1 = 2")).setOutgoingPayload(payload);
236237 }
237238
238239 @Test(groups = "short")
@@ -246,7 +247,7 @@
246247 .build()
247248 .init();
248249 v3session = v3cluster.connect();
249- Statement statement = new SimpleStatement("SELECT c2 FROM t1 where c1 = ?", 1);
250+ Statement statement = session.newSimpleStatement("SELECT c2 FROM t1 where c1 = ?", 1);
250251 statement.setOutgoingPayload(payload1);
251252 v3session.execute(statement);
252253 fail("Should not send custom payloads with protocol V3");
@@ -282,7 +283,7 @@
282283 try {
283284 logger.setLevel(TRACE);
284285 logger.addAppender(appender);
285- Statement statement = new SimpleStatement("SELECT c2 FROM t1 where c1 = ?", 1);
286+ Statement statement = session.newSimpleStatement("SELECT c2 FROM t1 where c1 = ?", 1);
286287 statement.setOutgoingPayload(payload1);
287288 session.execute(statement);
288289 String logs = appender.waitAndGet(10000);
modified driver-core/src/test/java/com/datastax/driver/core/DataTypeAssert.java +0 −11
@@ -15,7 +15,6 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import com.google.common.reflect.TypeToken;
1918 import org.assertj.core.api.AbstractAssert;
2019
2120 import static com.datastax.driver.core.Assertions.assertThat;
@@ -40,16 +39,6 @@
4039 return this;
4140 }
4241
43- public DataTypeAssert canBeDeserializedAs(TypeToken typeToken) {
44- assertThat(actual.canBeDeserializedAs(typeToken)).isTrue();
45- return this;
46- }
47-
48- public DataTypeAssert cannotBeDeserializedAs(TypeToken typeToken) {
49- assertThat(actual.canBeDeserializedAs(typeToken)).isFalse();
50- return this;
51- }
52-
5342 public DataTypeAssert hasTypeArgument(int position, DataType expected) {
5443 assertThat(actual.getTypeArguments().get(position)).isEqualTo(expected);
5544 return this;
modified driver-core/src/test/java/com/datastax/driver/core/DataTypeIntegrationTest.java +126 −40
@@ -22,6 +22,7 @@
2222 import com.google.common.collect.*;
2323 import org.slf4j.Logger;
2424 import org.slf4j.LoggerFactory;
25+import org.testng.annotations.AfterClass;
2526 import org.testng.annotations.Test;
2627
2728 import static org.assertj.core.api.Assertions.assertThat;
@@ -62,6 +63,16 @@
6263 return statements;
6364 }
6465
66+ @AfterClass
67+ @Override
68+ public void afterClass() {
69+ // drop tables one by one to avoid a timeout when issuing the DROP KEYSPACE statement
70+ for (TestTable table : tables) {
71+ session.execute("DROP TABLE " + table.tableName);
72+ }
73+ super.afterClass();
74+ }
75+
6576 @Test(groups = "long")
6677 public void should_insert_and_retrieve_data_with_legacy_statements() {
6778 should_insert_and_retrieve_data(StatementType.RAW_STRING);
@@ -80,58 +91,77 @@
8091
8192 protected void should_insert_and_retrieve_data(StatementType statementType) {
8293 ProtocolVersion protocolVersion = cluster.getConfiguration().getProtocolOptions().getProtocolVersion();
94+ CodecRegistry codecRegistry = cluster.getConfiguration().getCodecRegistry();
8395
8496 for (TestTable table : tables) {
8597 if (cassandraVersion.compareTo(table.minCassandraVersion) < 0)
8698 continue;
8799
100+ TypeCodec<Object> codec = codecRegistry.codecFor(table.testColumnType);
88101 switch (statementType) {
89102 case RAW_STRING:
90- session.execute(table.insertStatement.replace("?", table.testColumnType.format(table.sampleValue)));
103+ String formatValue = codec.format(table.sampleValue);
104+ assertThat(formatValue).isNotNull();
105+ String query = table.insertStatement.replace("?", formatValue);
106+ session.execute(query);
91107 break;
92108 case SIMPLE_WITH_PARAM:
93- SimpleStatement statement = new SimpleStatement(table.insertStatement, table.sampleValue);
109+ SimpleStatement statement = session.newSimpleStatement(table.insertStatement, table.sampleValue);
94110 checkGetValuesReturnsSerializedValue(protocolVersion, statement, table);
95111 session.execute(statement);
96112 break;
97113 case PREPARED:
98114 PreparedStatement ps = session.prepare(table.insertStatement);
99115 BoundStatement bs = ps.bind(table.sampleValue);
100- checkGetterReturnsBoundValue(bs, table);
116+ checkGetterReturnsValue(bs, table);
101117 session.execute(bs);
102118 break;
103119 }
104120
105121 Row row = session.execute(table.selectStatement).one();
106- Object queriedValue = table.testColumnType.deserialize(row.getBytesUnsafe("v"), protocolVersion);
122+ Object queriedValue = codec.deserialize(row.getBytesUnsafe("v"), protocolVersion);
107123
124+ // Since codec.deserialize will get the unboxed version for primitive check against expected unboxed value.
108125 assertThat(queriedValue)
109- .as("Test failure on %s statement with table:%n%s;%n" +
110- "insert statement:%n%s;%n",
111- statementType,
112- table.createStatement,
113- table.insertStatement)
114- .isEqualTo(table.sampleValue);
126+ .as("Test failure on %s statement with table:%n%s;%n" +
127+ "insert statement:%n%s;%n",
128+ statementType,
129+ table.createStatement,
130+ table.insertStatement)
131+ .isEqualTo(table.expectedValue);
132+
133+
134+ // Since calling row.get* will return boxed version for primitives check against expected primitive value.
135+ assertThat(getValue(row, table.testColumnType))
136+ .as("Test failure on %s statement with table:%n%s;%n" +
137+ "insert statement:%n%s;%n",
138+ statementType,
139+ table.createStatement,
140+ table.insertStatement)
141+ .isEqualTo(table.expectedPrimitiveValue);
142+
115143
116144 session.execute(table.truncateStatement);
117145 }
118146 }
119147
120- private void checkGetterReturnsBoundValue(BoundStatement bs, TestTable table) {
121- Object getterResult = getBoundValue(bs, table.testColumnType);
122- assertThat(getterResult).isEqualTo(table.sampleValue);
148+ private void checkGetterReturnsValue(BoundStatement bs, TestTable table) {
149+ // Driver will not serialize null references in a statement.
150+ Object getterResult = getValue(bs, table.testColumnType);
151+ assertThat(getterResult).as("Expected values to match for " + table.testColumnType).isEqualTo(table.expectedPrimitiveValue);
123152
124153 // Ensure that bs.getObject() also returns the expected value.
125- assertThat(bs.getObject(0)).isEqualTo(table.sampleValue);
126- assertThat(bs.getObject("v")).isEqualTo(table.sampleValue);
154+ assertThat(bs.getObject(0)).as("Expected values to match for " + table.testColumnType).isEqualTo(table.sampleValue);
155+ assertThat(bs.getObject("v")).as("Expected values to match for " + table.testColumnType).isEqualTo(table.sampleValue);
127156 }
128157
129158 public void checkGetValuesReturnsSerializedValue(ProtocolVersion protocolVersion, SimpleStatement statement, TestTable table) {
130- ByteBuffer[] values = statement.getValues(protocolVersion);
159+ CodecRegistry codecRegistry = cluster.getConfiguration().getCodecRegistry();
160+ ByteBuffer[] values = statement.getValues();
131161 assertThat(values.length).isEqualTo(1);
132162 assertThat(values[0])
133- .as("Value not serialized as expected for " + table.sampleValue)
134- .isEqualTo(DataType.serializeValue(table.sampleValue, protocolVersion));
163+ .as("Value not serialized as expected for " + table.sampleValue)
164+ .isEqualTo(codecRegistry.codecFor(table.testColumnType).serialize(table.sampleValue, protocolVersion));
135165 }
136166
137167 /**
@@ -143,6 +173,8 @@
143173
144174 final DataType testColumnType;
145175 final Object sampleValue;
176+ final Object expectedValue;
177+ final Object expectedPrimitiveValue;
146178
147179 final String createStatement;
148180 final String insertStatement = String.format("INSERT INTO %s (k, v) VALUES (1, ?)", tableName);
@@ -152,8 +184,18 @@
152184 final VersionNumber minCassandraVersion;
153185
154186 TestTable(DataType testColumnType, Object sampleValue, String minCassandraVersion) {
187+ this(testColumnType, sampleValue, sampleValue, minCassandraVersion);
188+ }
189+
190+ TestTable(DataType testColumnType, Object sampleValue, Object expectedValue, String minCassandraVersion) {
191+ this(testColumnType, sampleValue, expectedValue, expectedValue, minCassandraVersion);
192+ }
193+
194+ TestTable(DataType testColumnType, Object sampleValue, Object expectedValue, Object expectedPrimitiveValue, String minCassandraVersion) {
155195 this.testColumnType = testColumnType;
156196 this.sampleValue = sampleValue;
197+ this.expectedValue = expectedValue;
198+ this.expectedPrimitiveValue = expectedPrimitiveValue;
157199 this.minCassandraVersion = VersionNumber.parse(minCassandraVersion);
158200
159201 this.createStatement = String.format("CREATE TABLE %s (k int PRIMARY KEY, v %s)", tableName, testColumnType);
@@ -164,6 +206,7 @@
164206 List<TestTable> tables = Lists.newArrayList();
165207
166208 tables.addAll(tablesWithPrimitives());
209+ tables.addAll(tablesWithPrimitivesNull());
167210 tables.addAll(tablesWithCollectionsOfPrimitives());
168211 tables.addAll(tablesWithMapsOfPrimitives());
169212 tables.addAll(tablesWithNestedCollections());
@@ -179,6 +222,46 @@
179222 return tables;
180223 }
181224
225+ private static List<TestTable> tablesWithPrimitivesNull() {
226+ List<TestTable> tables = Lists.newArrayList();
227+ // Create a test table for each primitive type testing with null values. If the
228+ // type maps to a java primitive type it's value will by the default value instead of null.
229+ for (DataType dataType : DataType.allPrimitiveTypes(TestUtils.getDesiredProtocolVersion())) {
230+ Object expectedPrimitiveValue = null;
231+ Object expectedValue = null;
232+ switch(dataType.getName()) {
233+ case BIGINT:
234+ case TIME:
235+ expectedPrimitiveValue = 0L;
236+ break;
237+ case DOUBLE:
238+ expectedPrimitiveValue = 0.0;
239+ break;
240+ case FLOAT:
241+ expectedPrimitiveValue = 0.0f;
242+ break;
243+ case INT:
244+ expectedPrimitiveValue = 0;
245+ break;
246+ case SMALLINT:
247+ expectedPrimitiveValue = (short)0;
248+ break;
249+ case TINYINT:
250+ expectedPrimitiveValue = (byte)0;
251+ break;
252+ case BOOLEAN:
253+ expectedPrimitiveValue = false;
254+ break;
255+ }
256+
257+ if(!dataType.getName().equals(DataType.Name.COUNTER)) {
258+ tables.add(new TestTable(dataType, null, expectedValue, expectedPrimitiveValue, "1.2.0"));
259+ }
260+ }
261+ return tables;
262+
263+ }
264+
182265 private static List<TestTable> tablesWithCollectionsOfPrimitives() {
183266 List<TestTable> tables = Lists.newArrayList();
184267 for (Map.Entry<DataType, Object> entry : PrimitiveTypeSamples.ALL.entrySet()) {
@@ -260,7 +343,7 @@
260343
261344 int typeIdx = type.getTypeArguments().size() > 1 ? 1 : 0;
262345 DataType argument = type.getTypeArguments().get(typeIdx);
263- boolean isAtBottom = !argument.isCollection();
346+ boolean isAtBottom = !(argument instanceof DataType.CollectionType);
264347
265348 if(isAtBottom) {
266349 switch(type.getName()) {
@@ -343,51 +426,54 @@
343426 return null;
344427 }
345428
346- private Object getBoundValue(BoundStatement bs, DataType dataType) {
429+ private Object getValue(GettableByIndexData data, DataType dataType) {
347430 // This is kind of lame, but better than testing all getters manually
431+ CodecRegistry codecRegistry = cluster.getConfiguration().getCodecRegistry();
348432 switch (dataType.getName()) {
349433 case ASCII:
350- return bs.getString(0);
434+ return data.getString(0);
351435 case BIGINT:
352- return bs.getLong(0);
436+ return data.getLong(0);
353437 case BLOB:
354- return bs.getBytes(0);
438+ return data.getBytes(0);
355439 case BOOLEAN:
356- return bs.getBool(0);
440+ return data.getBool(0);
357441 case DECIMAL:
358- return bs.getDecimal(0);
442+ return data.getDecimal(0);
359443 case DOUBLE:
360- return bs.getDouble(0);
444+ return data.getDouble(0);
361445 case FLOAT:
362- return bs.getFloat(0);
446+ return data.getFloat(0);
363447 case INET:
364- return bs.getInet(0);
448+ return data.getInet(0);
365449 case TINYINT:
366- return bs.getByte(0);
450+ return data.getByte(0);
367451 case SMALLINT:
368- return bs.getShort(0);
452+ return data.getShort(0);
369453 case INT:
370- return bs.getInt(0);
454+ return data.getInt(0);
371455 case TEXT:
372456 case VARCHAR:
373- return bs.getString(0);
457+ return data.getString(0);
374458 case TIMESTAMP:
375- return bs.getTimestamp(0);
459+ return data.getTimestamp(0);
376460 case DATE:
377- return bs.getDate(0);
461+ return data.getDate(0);
378462 case TIME:
379- return bs.getTime(0);
463+ return data.getTime(0);
380464 case UUID:
381465 case TIMEUUID:
382- return bs.getUUID(0);
466+ return data.getUUID(0);
383467 case VARINT:
384- return bs.getVarint(0);
468+ return data.getVarint(0);
385469 case LIST:
386- return bs.getList(0, dataType.getTypeArguments().get(0).asJavaClass());
470+ return data.getList(0, codecRegistry.codecFor(dataType.getTypeArguments().get(0)).getJavaType());
387471 case SET:
388- return bs.getSet(0, dataType.getTypeArguments().get(0).asJavaClass());
472+ return data.getSet(0, codecRegistry.codecFor(dataType.getTypeArguments().get(0)).getJavaType());
389473 case MAP:
390- return bs.getMap(0, dataType.getTypeArguments().get(0).asJavaClass(), dataType.getTypeArguments().get(1).asJavaClass());
474+ return data.getMap(0,
475+ codecRegistry.codecFor(dataType.getTypeArguments().get(0)).getJavaType(),
476+ codecRegistry.codecFor(dataType.getTypeArguments().get(1)).getJavaType());
391477 case CUSTOM:
392478 case COUNTER:
393479 default:
modified driver-core/src/test/java/com/datastax/driver/core/DataTypeTest.java +71 −66
@@ -22,9 +22,9 @@
2222 import java.util.*;
2323
2424 import com.google.common.collect.Lists;
25-import com.google.common.reflect.TypeToken;
2625 import org.testng.annotations.Test;
2726
27+import static com.google.common.collect.Lists.newArrayList;
2828 import static org.testng.Assert.assertEquals;
2929 import static org.testng.Assert.fail;
3030
@@ -38,6 +38,10 @@
3838 */
3939 public class DataTypeTest {
4040
41+ CodecRegistry codecRegistry = new CodecRegistry();
42+
43+ ProtocolVersion protocolVersion = TestUtils.getDesiredProtocolVersion();
44+
4145 static boolean exclude(DataType t) {
4246 return t.getName() == DataType.Name.COUNTER;
4347 }
@@ -65,80 +69,97 @@
6569 case VARCHAR:
6670 return new TestValue[]{
6771 new TestValue("foo", "'foo'", "'foo'"),
68- new TestValue("fo'o", "'fo''o'", "'fo''o'") };
72+ new TestValue("fo'o", "'fo''o'", "'fo''o'"),
73+ new TestValue(null, null, "NULL") };
6974 case BIGINT:
7075 return new TestValue[]{
7176 new TestValue(42L, "42", "42"),
7277 new TestValue(91294377723L, "91294377723", "91294377723"),
73- new TestValue(-133L, "-133", "-133") };
78+ new TestValue(-133L, "-133", "-133"),
79+ new TestValue(null, null, "NULL") };
7480 case TIMESTAMP:
7581 // input: single quotes are optional for long literals, mandatory for date patterns
7682 return new TestValue[]{
7783 new TestValue(new Date(42L), "42", "42"),
7884 new TestValue(new Date(91294377723L), "91294377723", "91294377723"),
7985 new TestValue(new Date(-133L), "-133", "-133"),
80- new TestValue(new Date(784041330999L), "'1994-11-05T14:15:30.999+0100'", "784041330999") };
86+ new TestValue(new Date(784041330999L), "'1994-11-05T14:15:30.999+0100'", "784041330999"),
87+ new TestValue(null, null, "NULL") };
8188 case DATE:
8289 // input: single quotes are optional for long literals, mandatory for date patterns
8390 return new TestValue[]{
8491 new TestValue(LocalDate.fromDaysSinceEpoch(16071), "'2014-01-01'", "'2014-01-01'"),
8592 new TestValue(LocalDate.fromDaysSinceEpoch(0), "'1970-01-01'", "'1970-01-01'"),
8693 new TestValue(LocalDate.fromDaysSinceEpoch((int)(2147483648L - (1L << 31))), "'2147483648'", "'1970-01-01'"),
87- new TestValue(LocalDate.fromDaysSinceEpoch((int)(0 - (1L << 31))), "0", "'-5877641-06-23'") };
94+ new TestValue(LocalDate.fromDaysSinceEpoch((int)(0 - (1L << 31))), "0", "'-5877641-06-23'"),
95+ new TestValue(null, null, "NULL") };
8896 case TIME:
8997 // input: all literals must by enclosed in single quotes
9098 return new TestValue[]{
9199 new TestValue(54012123450000L, "'54012123450000'", "'15:00:12.123450000'"),
92100 new TestValue(0L, "'0'", "'00:00:00.000000000'"),
93- new TestValue(54012012345000L, "'15:00:12.012345000'", "'15:00:12.012345000'") };
101+ new TestValue(54012012345000L, "'15:00:12.012345000'", "'15:00:12.012345000'"),
102+ new TestValue(null, null, "NULL") };
94103 case BLOB:
95104 return new TestValue[]{
96105 new TestValue(Bytes.fromHexString("0x2450"), "0x2450", "0x2450"),
97- new TestValue(ByteBuffer.allocate(0), "0x", "0x") };
106+ new TestValue(ByteBuffer.allocate(0), "0x", "0x"),
107+ new TestValue(null, null, "NULL") };
98108 case BOOLEAN:
99109 return new TestValue[]{
100110 new TestValue(true, "true", "true"),
101- new TestValue(false, "false", "false") };
111+ new TestValue(false, "false", "false"),
112+ new TestValue(null, null, "NULL") };
102113 case DECIMAL:
103114 return new TestValue[]{
104- new TestValue(new BigDecimal("1.23E+8"), "1.23E+8", "1.23E+8") };
115+ new TestValue(new BigDecimal("1.23E+8"), "1.23E+8", "1.23E+8"),
116+ new TestValue(null, null, "NULL") };
105117 case DOUBLE:
106118 return new TestValue[]{
107119 new TestValue(2.39324324, "2.39324324", "2.39324324"),
108- new TestValue(-12., "-12.0", "-12.0") };
120+ new TestValue(-12., "-12.0", "-12.0"),
121+ new TestValue(null, null, "NULL") };
109122 case FLOAT:
110123 return new TestValue[]{
111124 new TestValue(2.39f, "2.39", "2.39"),
112- new TestValue(-12.f, "-12.0", "-12.0") };
125+ new TestValue(-12.f, "-12.0", "-12.0"),
126+ new TestValue(null, null, "NULL") };
113127 case INET:
114128 try {
115129 return new TestValue[]{
116- new TestValue(InetAddress.getByName("128.2.12.3"), "'128.2.12.3'", "'128.2.12.3'") };
130+ new TestValue(InetAddress.getByName("128.2.12.3"), "'128.2.12.3'", "'128.2.12.3'"),
131+ new TestValue(null, null, "NULL") };
117132 } catch (java.net.UnknownHostException e) {
118133 throw new RuntimeException();
119134 }
120135 case TINYINT:
121136 return new TestValue[]{
122137 new TestValue((byte)-4, "-4", "-4"),
123- new TestValue((byte)44, "44", "44") };
138+ new TestValue((byte)44, "44", "44"),
139+ new TestValue(null, null, "NULL") };
124140 case SMALLINT:
125141 return new TestValue[]{
126142 new TestValue((short)-3, "-3", "-3"),
127- new TestValue((short)43, "43", "43") };
143+ new TestValue((short)43, "43", "43"),
144+ new TestValue(null, null, "NULL") };
128145 case INT:
129146 return new TestValue[]{
130147 new TestValue(-2, "-2", "-2"),
131- new TestValue(42, "42", "42") };
148+ new TestValue(42, "42", "42"),
149+ new TestValue(null, null, "NULL") };
132150 case TIMEUUID:
133151 return new TestValue[]{
134- new TestValue(UUID.fromString("FE2B4360-28C6-11E2-81C1-0800200C9A66"), "fe2b4360-28c6-11e2-81c1-0800200c9a66", "fe2b4360-28c6-11e2-81c1-0800200c9a66") };
152+ new TestValue(UUID.fromString("FE2B4360-28C6-11E2-81C1-0800200C9A66"), "fe2b4360-28c6-11e2-81c1-0800200c9a66", "fe2b4360-28c6-11e2-81c1-0800200c9a66"),
153+ new TestValue(null, null, "NULL") };
135154 case UUID:
136155 return new TestValue[]{
137156 new TestValue(UUID.fromString("FE2B4360-28C6-11E2-81C1-0800200C9A66"), "fe2b4360-28c6-11e2-81c1-0800200c9a66", "fe2b4360-28c6-11e2-81c1-0800200c9a66"),
138- new TestValue(UUID.fromString("067e6162-3b6f-4ae2-a171-2470b63dff00"), "067e6162-3b6f-4ae2-a171-2470b63dff00", "067e6162-3b6f-4ae2-a171-2470b63dff00") };
157+ new TestValue(UUID.fromString("067e6162-3b6f-4ae2-a171-2470b63dff00"), "067e6162-3b6f-4ae2-a171-2470b63dff00", "067e6162-3b6f-4ae2-a171-2470b63dff00"),
158+ new TestValue(null, null, "NULL") };
139159 case VARINT:
140160 return new TestValue[]{
141- new TestValue(new BigInteger("12387290982347987032483422342432"), "12387290982347987032483422342432", "12387290982347987032483422342432") };
161+ new TestValue(new BigInteger("12387290982347987032483422342432"), "12387290982347987032483422342432", "12387290982347987032483422342432"),
162+ new TestValue(null, null, "NULL") };
142163 default:
143164 throw new RuntimeException("Missing handling of " + dt);
144165 }
@@ -151,7 +172,7 @@
151172 continue;
152173
153174 for (TestValue value : primitiveTestValues(dt))
154- assertThat(dt.parse(value.cqlInputString))
175+ assertThat(codecRegistry.codecFor(dt).parse(value.cqlInputString))
155176 .as("Parsing input %s to a %s", value.cqlInputString, dt)
156177 .isEqualTo(value.javaObject);
157178 }
@@ -164,7 +185,7 @@
164185 continue;
165186
166187 for (TestValue value : primitiveTestValues(dt))
167- assertThat(dt.format(value.javaObject))
188+ assertThat(codecRegistry.codecFor(dt).format(value.javaObject))
168189 .as("Formatting a %s expecting %s", dt, value.cqlOutputString)
169190 .isEqualTo(value.cqlOutputString);
170191 }
@@ -172,46 +193,47 @@
172193
173194 @Test(groups = "unit")
174195 public void parseFormatListTest() {
175- String toParse = "['Foo', 'Bar', 'Foo''bar']";
196+ String toParse = "['Foo','Bar','Foo''bar']";
176197 List<String> toFormat = Arrays.asList("Foo", "Bar", "Foo'bar");
177198 DataType dt = DataType.list(DataType.text());
178- assertEquals(dt.parse(toParse), toFormat);
179- assertEquals(dt.format(toFormat), toParse);
199+ assertEquals(codecRegistry.codecFor(dt).parse(toParse), toFormat);
200+ assertEquals(codecRegistry.codecFor(dt).format(toFormat), toParse);
180201 }
181202
182203 @SuppressWarnings("serial")
183204 @Test(groups = "unit")
184205 public void parseFormatSetTest() {
185- String toParse = "{'Foo', 'Bar', 'Foo''bar'}";
186- Set<String> toFormat = new LinkedHashSet<String>(){{ add("Foo"); add("Bar"); add("Foo'bar"); }};
206+ String toParse = "{'Foo','Bar','Foo''bar'}";
207+ Set<String> toFormat = new LinkedHashSet<String>() {{ add("Foo");
208+ add("Bar"); add("Foo'bar"); }};
187209 DataType dt = DataType.set(DataType.text());
188- assertEquals(dt.parse(toParse), toFormat);
189- assertEquals(dt.format(toFormat), toParse);
210+ assertEquals(codecRegistry.codecFor(dt).parse(toParse), toFormat);
211+ assertEquals(codecRegistry.codecFor(dt).format(toFormat), toParse);
190212 }
191213
192214 @SuppressWarnings("serial")
193215 @Test(groups = "unit")
194216 public void parseFormatMapTest() {
195- String toParse = "{'Foo':3, 'Bar':42, 'Foo''bar':-24}";
217+ String toParse = "{'Foo':3,'Bar':42,'Foo''bar':-24}";
196218 Map<String, Integer> toFormat = new LinkedHashMap<String, Integer>(){{ put("Foo", 3); put("Bar", 42); put("Foo'bar", -24); }};
197219 DataType dt = DataType.map(DataType.text(), DataType.cint());
198- assertEquals(dt.parse(toParse), toFormat);
199- assertEquals(dt.format(toFormat), toParse);
220+ assertEquals(codecRegistry.codecFor(dt).parse(toParse), toFormat);
221+ assertEquals(codecRegistry.codecFor(dt).format(toFormat), toParse);
200222 }
201223
202224 @SuppressWarnings("serial")
203225 @Test(groups = "unit")
204226 public void parseFormatUDTTest() {
205227
206- String toParse = "{t:'fo''o', i:3, l:['a', 'b'], s:{3:{a:0x01}}}";
228+ String toParse = "{t:'fo''o',i:3,l:['a','b'],s:{3:{a:0x01}}}";
207229
208- final UserType udt1 = new UserType("ks", "t", Arrays.asList(new UserType.Field("a", DataType.blob())));
230+ final UserType udt1 = new UserType("ks", "t", Arrays.asList(new UserType.Field("a", DataType.blob())), protocolVersion, codecRegistry);
209231 UserType udt2 = new UserType("ks", "t", Arrays.asList(
210232 new UserType.Field("t", DataType.text()),
211233 new UserType.Field("i", DataType.cint()),
212234 new UserType.Field("l", DataType.list(DataType.text())),
213235 new UserType.Field("s", DataType.map(DataType.cint(), udt1))
214- ));
236+ ), protocolVersion, codecRegistry);
215237
216238 UDTValue toFormat = udt2.newValue();
217239 toFormat.setString("t", "fo'o");
@@ -219,19 +241,20 @@
219241 toFormat.setList("l", Arrays.<String>asList("a", "b"));
220242 toFormat.setMap("s", new HashMap<Integer, UDTValue>(){{ put(3, udt1.newValue().setBytes("a", ByteBuffer.wrap(new byte[]{1}))); }});
221243
222- assertEquals(udt2.parse(toParse), toFormat);
223- assertEquals(udt2.format(toFormat), toParse);
244+ assertEquals(codecRegistry.codecFor(udt2).parse(toParse), toFormat);
245+ assertEquals(codecRegistry.codecFor(udt2).format(toFormat), toParse);
224246 }
225247
248+ @SuppressWarnings("deprecation")
226249 @Test(groups = "unit")
227250 public void parseFormatTupleTest() {
228251
229252 String toParse = "(1, 'foo', 1.0)";
230- TupleType t = TupleType.of(DataType.cint(), DataType.text(), DataType.cfloat());
253+ TupleType t = new TupleType(newArrayList(DataType.cint(), DataType.text(), DataType.cfloat()), protocolVersion, codecRegistry);
231254 TupleValue toFormat = t.newValue(1, "foo", 1.0f);
232255
233- assertEquals(t.parse(toParse), toFormat);
234- assertEquals(t.format(toFormat), toParse);
256+ assertEquals(codecRegistry.codecFor(t).parse(toParse), toFormat);
257+ assertEquals(codecRegistry.codecFor(t).format(toFormat), toParse);
235258 }
236259
237260 @Test(groups = "unit")
@@ -247,17 +270,15 @@
247270 continue;
248271
249272 Object value = TestUtils.getFixedValue(dt);
250- assertEquals(dt.deserialize(dt.serialize(value, version), version), value);
273+ TypeCodec<Object> codec = codecRegistry.codecFor(dt);
274+ assertEquals(codec.deserialize(codec.serialize(value, version), version), value);
251275 }
252276
253- try {
254- DataType.bigint().serialize(4, version);
255- fail("This should not have worked");
256- } catch (InvalidTypeException e) { /* That's what we want */ }
277+ TypeCodec<Long> codec = codecRegistry.codecFor(DataType.bigint());
257278
258279 try {
259280 ByteBuffer badValue = ByteBuffer.allocate(4);
260- DataType.bigint().deserialize(badValue, version);
281+ codec.deserialize(badValue, version);
261282 fail("This should not have worked");
262283 } catch (InvalidTypeException e) { /* That's what we want */ }
263284 }
@@ -273,39 +294,23 @@
273294 List<String> l = Arrays.asList("foo", "bar");
274295
275296 DataType dt = DataType.list(DataType.text());
276- assertEquals(dt.deserialize(dt.serialize(l, version), version), l);
297+ TypeCodec<List<String>> codec = codecRegistry.codecFor(dt);
298+ assertEquals(codec.deserialize(codec.serialize(l, version), version), l);
277299
278300 try {
279- DataType.list(DataType.bigint()).serialize(l, version);
301+ DataType listOfBigint = DataType.list(DataType.bigint());
302+ codec = codecRegistry.codecFor(listOfBigint);
303+ codec.serialize(l, version);
280304 fail("This should not have worked");
281305 } catch (InvalidTypeException e) { /* That's what we want */ }
282306 }
283307
284- @Test(groups = "unit")
285- public void should_check_which_java_type_it_can_be_deserialized_to() {
286- assertThat(DataType.cint())
287- .canBeDeserializedAs(TypeToken.of(Integer.class))
288- .canBeDeserializedAs(TypeToken.of(Number.class))
289- .cannotBeDeserializedAs(TypeToken.of(String.class));
290-
291- assertThat(DataType.list(DataType.cint()))
292- .canBeDeserializedAs(new TypeToken<List<Integer>>(){})
293- .canBeDeserializedAs(new TypeToken<Collection<Integer>>(){})
294- .cannotBeDeserializedAs(new TypeToken<Set<Integer>>(){})
295- .cannotBeDeserializedAs(new TypeToken<List<String>>(){});
296-
297- assertThat(DataType.map(DataType.cint(), DataType.frozenList(DataType.text())))
298- .canBeDeserializedAs(new TypeToken<Map<Integer, List<String>>>(){})
299- .canBeDeserializedAs(new TypeToken<Map<Number, Collection<String>>>(){})
300- .cannotBeDeserializedAs(new TypeToken<Map<Integer, Collection<Integer>>>(){});
301- }
302-
303308 @Test(groups = "unit")
304309 public void should_not_return_v4_types_in_all_primitive_types_with_v3() {
305310 Set<DataType> dataTypes = DataType.allPrimitiveTypes(ProtocolVersion.V3);
306311
307312 // Ensure it does not contain specific newer types tinyint and smallint.
308- assertThat(dataTypes).doesNotContainAnyElementsOf(Lists.newArrayList(DataType.tinyint(), DataType.smallint()));
313+ assertThat(dataTypes).doesNotContainAnyElementsOf(newArrayList(DataType.tinyint(), DataType.smallint()));
309314
310315 // Ensure all values are <= V3.
311316 for(DataType dataType : dataTypes) {
modified driver-core/src/test/java/com/datastax/driver/core/ExceptionsTest.java +11 −11
@@ -202,12 +202,12 @@
202202 c.session.execute("USE " + keyspace);
203203 c.session.execute(String.format("CREATE TABLE %s (k text PRIMARY KEY, t text, i int, f float)", table));
204204
205- c.session.execute(new SimpleStatement(String.format(Locale.US, "INSERT INTO %s (k, t, i, f) VALUES ('%s', '%s', %d, %f)", table, key, "foo", 42, 24.03f)).setConsistencyLevel(ConsistencyLevel.ALL));
206- c.session.execute(new SimpleStatement(String.format(TestUtils.SELECT_ALL_FORMAT, table)).setConsistencyLevel(ConsistencyLevel.ALL));
205+ c.session.execute(c.session.newSimpleStatement(String.format(Locale.US, "INSERT INTO %s (k, t, i, f) VALUES ('%s', '%s', %d, %f)", table, key, "foo", 42, 24.03f)).setConsistencyLevel(ConsistencyLevel.ALL));
206+ c.session.execute(c.session.newSimpleStatement(String.format(TestUtils.SELECT_ALL_FORMAT, table)).setConsistencyLevel(ConsistencyLevel.ALL));
207207
208208 c.cassandraCluster.forceStop(2);
209209 try{
210- c.session.execute(new SimpleStatement(String.format(TestUtils.SELECT_ALL_FORMAT, table)).setConsistencyLevel(ConsistencyLevel.ALL));
210+ c.session.execute(c.session.newSimpleStatement(String.format(TestUtils.SELECT_ALL_FORMAT, table)).setConsistencyLevel(ConsistencyLevel.ALL));
211211 } catch (ReadTimeoutException e) {
212212 assertEquals(e.getConsistencyLevel(), ConsistencyLevel.ALL);
213213 assertEquals(e.getReceivedAcknowledgements(), 2);
@@ -318,15 +318,15 @@
318318 c.session.execute("USE " + keyspace);
319319 c.session.execute(String.format("CREATE TABLE %s (k text PRIMARY KEY, t text, i int, f float)", table));
320320
321- c.session.execute(new SimpleStatement(String.format(Locale.US, "INSERT INTO %s (k, t, i, f) VALUES ('%s', '%s', %d, %f)", table, key, "foo", 42, 24.03f)).setConsistencyLevel(ConsistencyLevel.ALL));
322- c.session.execute(new SimpleStatement(String.format(TestUtils.SELECT_ALL_FORMAT, table)).setConsistencyLevel(ConsistencyLevel.ALL));
321+ c.session.execute(c.session.newSimpleStatement(String.format(Locale.US, "INSERT INTO %s (k, t, i, f) VALUES ('%s', '%s', %d, %f)", table, key, "foo", 42, 24.03f)).setConsistencyLevel(ConsistencyLevel.ALL));
322+ c.session.execute(c.session.newSimpleStatement(String.format(TestUtils.SELECT_ALL_FORMAT, table)).setConsistencyLevel(ConsistencyLevel.ALL));
323323
324324 c.cassandraCluster.stop(2);
325325
326326 waitForDownWithWait(CCMBridge.IP_PREFIX + '2', c.cluster, 10);
327327
328328 try{
329- c.session.execute(new SimpleStatement(String.format(TestUtils.SELECT_ALL_FORMAT, table)).setConsistencyLevel(ConsistencyLevel.ALL));
329+ c.session.execute(c.session.newSimpleStatement(String.format(TestUtils.SELECT_ALL_FORMAT, table)).setConsistencyLevel(ConsistencyLevel.ALL));
330330 } catch (UnavailableException e) {
331331 String expectedError = String.format("Not enough replica available for query at consistency %s (%d required but only %d alive)", "ALL", 3, 2);
332332 assertEquals(e.getMessage(), expectedError);
@@ -336,7 +336,7 @@
336336 }
337337
338338 try{
339- c.session.execute(new SimpleStatement(String.format(Locale.US, "INSERT INTO %s (k, t, i, f) VALUES ('%s', '%s', %d, %f)", table, key, "foo", 42, 24.03f)).setConsistencyLevel(ConsistencyLevel.ALL));
339+ c.session.execute(c.session.newSimpleStatement(String.format(Locale.US, "INSERT INTO %s (k, t, i, f) VALUES ('%s', '%s', %d, %f)", table, key, "foo", 42, 24.03f)).setConsistencyLevel(ConsistencyLevel.ALL));
340340 } catch (UnavailableException e) {
341341 String expectedError = String.format("Not enough replica available for query at consistency %s (%d required but only %d alive)", "ALL", 3, 2);
342342 assertEquals(e.getMessage(), expectedError);
@@ -371,12 +371,12 @@
371371 c.session.execute("USE " + keyspace);
372372 c.session.execute(String.format("CREATE TABLE %s (k text PRIMARY KEY, t text, i int, f float)", table));
373373
374- c.session.execute(new SimpleStatement(String.format(Locale.US, "INSERT INTO %s (k, t, i, f) VALUES ('%s', '%s', %d, %f)", table, key, "foo", 42, 24.03f)).setConsistencyLevel(ConsistencyLevel.ALL));
375- c.session.execute(new SimpleStatement(String.format(TestUtils.SELECT_ALL_FORMAT, table)).setConsistencyLevel(ConsistencyLevel.ALL));
374+ c.session.execute(c.session.newSimpleStatement(String.format(Locale.US, "INSERT INTO %s (k, t, i, f) VALUES ('%s', '%s', %d, %f)", table, key, "foo", 42, 24.03f)).setConsistencyLevel(ConsistencyLevel.ALL));
375+ c.session.execute(c.session.newSimpleStatement(String.format(TestUtils.SELECT_ALL_FORMAT, table)).setConsistencyLevel(ConsistencyLevel.ALL));
376376
377377 c.cassandraCluster.forceStop(2);
378378 try{
379- c.session.execute(new SimpleStatement(String.format(Locale.US, "INSERT INTO %s (k, t, i, f) VALUES ('%s', '%s', %d, %f)", table, key, "foo", 42, 24.03f)).setConsistencyLevel(ConsistencyLevel.ALL));
379+ c.session.execute(c.session.newSimpleStatement(String.format(Locale.US, "INSERT INTO %s (k, t, i, f) VALUES ('%s', '%s', %d, %f)", table, key, "foo", 42, 24.03f)).setConsistencyLevel(ConsistencyLevel.ALL));
380380 } catch (WriteTimeoutException e) {
381381 assertEquals(e.getConsistencyLevel(), ConsistencyLevel.ALL);
382382 assertEquals(e.getReceivedAcknowledgements(), 2);
@@ -429,7 +429,7 @@
429429
430430 try {
431431 // Query with a CL of ALL to hit all replicas.
432- session.execute(new SimpleStatement(String.format(Locale.US, "INSERT INTO testtable (k, t, i, f) VALUES ('%s', '%s', %d, %f)", "1", "2", 3, 4.0f))
432+ session.execute(session.newSimpleStatement(String.format(Locale.US, "INSERT INTO testtable (k, t, i, f) VALUES ('%s', '%s', %d, %f)", "1", "2", 3, 4.0f))
433433 .setConsistencyLevel(ConsistencyLevel.ALL));
434434 } catch(WriteFailureException e) {
435435 // Expect a failure for node configured to fail writes.
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 = new SimpleStatement(String.format("SELECT v FROM test WHERE k='%s'", key));
46+ SimpleStatement st = session.newSimpleStatement(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/FunctionMetadataTest.java +5 −3
@@ -29,6 +29,8 @@
2929
3030 public class FunctionMetadataTest {
3131 KeyspaceMetadata keyspace;
32+ private ProtocolVersion protocolVersion = TestUtils.getDesiredProtocolVersion();
33+ private CodecRegistry codecRegistry = new CodecRegistry();
3234
3335 @BeforeMethod(groups = "unit")
3436 public void setup() {
@@ -37,7 +39,7 @@
3739
3840 @Test(groups = "unit")
3941 public void should_parse_and_format_simple_function() {
40- FunctionMetadata function = FunctionMetadata.build(keyspace, SYSTEM_ROW_PLUS);
42+ FunctionMetadata function = FunctionMetadata.build(keyspace, SYSTEM_ROW_PLUS, protocolVersion, codecRegistry);
4143
4244 assertThat(function).isNotNull();
4345 assertThat(function.getKeyspace()).isEqualTo(keyspace);
@@ -68,7 +70,7 @@
6870
6971 @Test(groups = "unit")
7072 public void should_parse_and_format_function_with_no_arguments() {
71- FunctionMetadata function = FunctionMetadata.build(keyspace, SYSTEM_ROW_PI);
73+ FunctionMetadata function = FunctionMetadata.build(keyspace, SYSTEM_ROW_PI, protocolVersion, codecRegistry);
7274
7375 assertThat(function).isNotNull();
7476 assertThat(function.getKeyspace()).isEqualTo(keyspace);
@@ -120,4 +122,4 @@
120122
121123 return row;
122124 }
123-}
No newline at the end of the file
125+}
modified driver-core/src/test/java/com/datastax/driver/core/IndexMetadataTest.java +17 −17
@@ -15,29 +15,22 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import static com.datastax.driver.core.Assertions.assertThat;
19-import static com.datastax.driver.core.ColumnMetadata.COLUMN_NAME;
20-import static com.datastax.driver.core.ColumnMetadata.COMPONENT_INDEX;
21-import static com.datastax.driver.core.ColumnMetadata.INDEX_NAME;
22-import static com.datastax.driver.core.ColumnMetadata.INDEX_OPTIONS;
23-import static com.datastax.driver.core.ColumnMetadata.INDEX_TYPE;
24-import static com.datastax.driver.core.ColumnMetadata.KIND;
25-import static com.datastax.driver.core.ColumnMetadata.VALIDATOR;
26-import static com.datastax.driver.core.DataType.cint;
27-import static com.datastax.driver.core.DataType.text;
28-
2918 import java.nio.ByteBuffer;
3019 import java.util.Collection;
3120 import java.util.List;
3221
22+import com.google.common.collect.ImmutableList;
23+import com.google.common.primitives.Ints;
3324 import org.testng.annotations.Test;
3425
35-import com.datastax.driver.core.ColumnMetadata.IndexMetadata;
36-import com.datastax.driver.core.ColumnMetadata.Raw;
26+import com.datastax.driver.core.ColumnMetadata.*;
3727 import com.datastax.driver.core.Token.M3PToken;
3828 import com.datastax.driver.core.utils.CassandraVersion;
39-import com.google.common.collect.ImmutableList;
40-import com.google.common.primitives.Ints;
29+
30+import static com.datastax.driver.core.Assertions.assertThat;
31+import static com.datastax.driver.core.ColumnMetadata.*;
32+import static com.datastax.driver.core.DataType.cint;
33+import static com.datastax.driver.core.DataType.text;
4134
4235 @CassandraVersion(
4336 major = 1.2)
@@ -55,6 +48,10 @@
5548 definition(VALIDATOR, text()),
5649 definition(INDEX_OPTIONS, text())
5750 });
51+
52+ static {
53+ defs.setCodecRegistry(new CodecRegistry());
54+ }
5855
5956 @Override
6057 protected Collection<String> getTableDefinitions() {
@@ -205,7 +202,7 @@
205202 wrap("{\"foo\" : \"bar\", \"class_name\" : \"dummy.DummyIndex\"}") // index options
206203 );
207204 Row row = ArrayBackedRow.fromData(defs, M3PToken.FACTORY, ProtocolVersion.V3, data);
208- ColumnMetadata column = ColumnMetadata.fromRaw(table, Raw.fromRow(row, VersionNumber.parse("2.1")));
205+ ColumnMetadata column = ColumnMetadata.fromRaw(table, Raw.fromRow(row, VersionNumber.parse("2.1"), ProtocolVersion.V3, new CodecRegistry()));
209206 IndexMetadata index = column.getIndex();
210207 assertThat(index).hasName("custom_index")
211208 .isNotKeys()
@@ -240,7 +237,10 @@
240237 wrap("null") // index options
241238 );
242239 Row row = ArrayBackedRow.fromData(defs, M3PToken.FACTORY, ProtocolVersion.V3, data);
243- ColumnMetadata column = ColumnMetadata.fromRaw(table, Raw.fromRow(row, VersionNumber.parse("2.1")));
240+ ColumnMetadata column = ColumnMetadata.fromRaw(table,
241+ Raw.fromRow(row, VersionNumber.parse("2.1"),
242+ cluster.getConfiguration().getProtocolOptions().getProtocolVersion(),
243+ cluster.getConfiguration().getCodecRegistry()));
244244 IndexMetadata index = column.getIndex();
245245
246246 assertThat(index).hasName("cfs_archive_parent_path")
added driver-core/src/test/java/com/datastax/driver/core/JodaCodecs.java +191 −0
@@ -0,0 +1,191 @@
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 org.joda.time.DateTime;
19+import org.joda.time.DateTimeZone;
20+import org.joda.time.LocalTime;
21+
22+import java.util.Date;
23+import java.util.List;
24+import java.util.concurrent.TimeUnit;
25+
26+import static com.google.common.base.Preconditions.checkArgument;
27+
28+import static com.datastax.driver.core.DataType.timestamp;
29+import static com.datastax.driver.core.DataType.varchar;
30+
31+/**
32+ * A collection of convenience {@link TypeCodec} instances useful for
33+ * serializing between CQL types and Joda types like {@link DateTime}.
34+ *
35+ * These codecs may either be registered individually or they may all
36+ * be registered via {@link JodaCodecs#withCodecs(CodecRegistry)}.
37+ */
38+public class JodaCodecs {
39+
40+ /**
41+ * <p>
42+ * Registers all defined {@link TypeCodec} instances in this class
43+ * (with exception to {@link TimeZonePreservingDateTimeCodec}) with
44+ * the given {@link CodecRegistry}.
45+ * </p>
46+ * @param registry registry to add Codecs to.
47+ * @return updated registry with codecs.
48+ */
49+ public static CodecRegistry withCodecs(CodecRegistry registry) {
50+ return registry.register(LocalTimeCodec.instance, LocalDateCodec.instance, DateTimeCodec.instance);
51+ }
52+
53+ /**
54+ * {@link TypeCodec} that maps {@link LocalTime} <-> Long representing nanoseconds since midnight
55+ * allowing the setting and retrieval of <code>time</code> columns as {@link LocalTime}
56+ * instances.
57+ *
58+ * IMPORTANT: {@link LocalTime} as millisecond precision; nanoseconds below one millisecond will be lost
59+ * during deserialization.
60+ */
61+ public static class LocalTimeCodec extends TypeCodec.MappingCodec<LocalTime, Long> {
62+
63+ public static final LocalTimeCodec instance = new LocalTimeCodec();
64+
65+ private LocalTimeCodec() {
66+ super(TimeCodec.instance, LocalTime.class);
67+ }
68+
69+ @Override
70+ protected LocalTime deserialize(Long value) {
71+ if (value == null)
72+ return null;
73+ return LocalTime.fromMillisOfDay(TimeUnit.NANOSECONDS.toMillis(value));
74+ }
75+
76+ @Override
77+ protected Long serialize(LocalTime value) {
78+ if (value == null)
79+ return null;
80+ return TimeUnit.MILLISECONDS.toNanos(value.getMillisOfDay());
81+ }
82+ }
83+
84+ /**
85+ * {@link TypeCodec} that maps
86+ * {@link org.joda.time.LocalDate} <-> {@link LocalDate} allowing the
87+ * setting and retrieval of <code>date</code> columns as
88+ * {@link org.joda.time.LocalDate} instances.
89+ */
90+ public static class LocalDateCodec extends TypeCodec.MappingCodec<org.joda.time.LocalDate, LocalDate> {
91+
92+ public static final LocalDateCodec instance = new LocalDateCodec();
93+
94+ private LocalDateCodec() {
95+ super(DateCodec.instance, org.joda.time.LocalDate.class);
96+ }
97+
98+ @Override
99+ protected org.joda.time.LocalDate deserialize(LocalDate value) {
100+ return value == null ? null : new org.joda.time.LocalDate(value.getYear(), value.getMonth(), value.getDay());
101+ }
102+
103+ @Override
104+ protected LocalDate serialize(org.joda.time.LocalDate value) {
105+ return value == null ? null : LocalDate.fromYearMonthDay(value.getYear(), value.getMonthOfYear(), value.getDayOfMonth());
106+ }
107+ }
108+
109+ /**
110+ * <p>
111+ * {@link TypeCodec} that maps {@link DateTime} <-> {@link Date}
112+ * allowing the setting and retrieval of <code>timestamp</code>
113+ * columns as {@link DateTime} instances.
114+ * </p>
115+ *
116+ * <p>
117+ * Since C* <code>timestamp</code> columns do not preserve timezones
118+ * any attached timezone information will be lost.
119+ * </p>
120+ *
121+ * @see TimeZonePreservingDateTimeCodec
122+ */
123+ public static class DateTimeCodec extends TypeCodec.MappingCodec<DateTime, Date> {
124+
125+ public static final DateTimeCodec instance = new DateTimeCodec();
126+
127+ private DateTimeCodec() {
128+ super(TimestampCodec.instance, DateTime.class);
129+ }
130+
131+ @Override
132+ protected DateTime deserialize(Date value) {
133+ return new DateTime(value);
134+ }
135+
136+ @Override
137+ protected Date serialize(DateTime value) {
138+ return value.toDate();
139+ }
140+ }
141+
142+ /**
143+ * <p>
144+ * {@link TypeCodec} that maps
145+ * {@link LocalTime} <-> <code>tuple&lt;timestamp,varchar&gt;</code>
146+ * providing a pattern for maintaining timezone information in
147+ * cassandra.
148+ * </p>
149+ *
150+ * <p>
151+ * Since cassandra's <code>timestamp</code> type preserves only
152+ * milliseconds since epoch, any timezone information passed in with
153+ * a {@link Date} instance would normally be lost. By using a
154+ * <code>tuple&lt;timestamp,varchar&gt;</code> a timezone ID can be
155+ * persisted in the <code>varchar</code> field such that when the
156+ * value is deserialized into a {@link DateTime} the timezone is
157+ * preserved.
158+ * </p>
159+ *
160+ */
161+ public static class TimeZonePreservingDateTimeCodec extends TypeCodec.MappingCodec<DateTime, TupleValue> {
162+
163+ private final TupleType tupleType;
164+
165+ public TimeZonePreservingDateTimeCodec(TypeCodec<TupleValue> innerCodec) {
166+ super(innerCodec, DateTime.class);
167+ tupleType = (TupleType)innerCodec.getCqlType();
168+ List<DataType> types = tupleType.getComponentTypes();
169+ checkArgument(
170+ types.size() == 2 && types.get(0).equals(timestamp()) && types.get(1).equals(varchar()),
171+ "Expected tuple<timestamp,varchar>, got %s",
172+ tupleType);
173+ }
174+
175+ @Override
176+ protected DateTime deserialize(TupleValue value) {
177+ Date date = value.getTimestamp(0);
178+ String zoneID = value.getString(1);
179+ return new DateTime(date).withZone(DateTimeZone.forID(zoneID));
180+ }
181+
182+ @Override
183+ protected TupleValue serialize(DateTime value) {
184+ TupleValue tupleValue = new TupleValue(tupleType);
185+ tupleValue.setTimestamp(0, value.toDate());
186+ tupleValue.setString(1, value.getZone().getID());
187+ return tupleValue;
188+ }
189+ }
190+
191+}
added driver-core/src/test/java/com/datastax/driver/core/JsonCodec.java +58 −0
@@ -0,0 +1,58 @@
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.io.IOException;
19+
20+import com.fasterxml.jackson.core.JsonProcessingException;
21+import com.fasterxml.jackson.databind.ObjectMapper;
22+
23+import com.datastax.driver.core.exceptions.InvalidTypeException;
24+
25+/**
26+ * A simple Json codec for TypeCodec tests.
27+ */
28+public class JsonCodec<T> extends TypeCodec.StringParsingCodec<T> {
29+
30+ private final ObjectMapper objectMapper = new ObjectMapper();
31+
32+ public JsonCodec(Class<T> javaType) {
33+ super(javaType);
34+ }
35+
36+ @Override
37+ @SuppressWarnings("unchecked")
38+ public T fromString(String value) {
39+ if (value == null)
40+ return null;
41+ try {
42+ return (T) objectMapper.readValue(value, getJavaType().getRawType());
43+ } catch (IOException e) {
44+ throw new InvalidTypeException(e.getMessage(), e);
45+ }
46+ }
47+
48+ @Override
49+ public String toString(T value) {
50+ if (value == null)
51+ return null;
52+ try {
53+ return objectMapper.writeValueAsString(value);
54+ } catch (JsonProcessingException e) {
55+ throw new InvalidTypeException(e.getMessage(), e);
56+ }
57+ }
58+}
modified driver-core/src/test/java/com/datastax/driver/core/LargeDataTest.java +19 −14
@@ -18,17 +18,17 @@
1818 import java.nio.ByteBuffer;
1919
2020 import org.testng.annotations.Test;
21+
2122 import static org.testng.Assert.assertEquals;
2223 import static org.testng.Assert.assertTrue;
2324
24-import com.datastax.driver.core.exceptions.InvalidQueryException;
2525 import com.datastax.driver.core.querybuilder.Batch;
2626 import com.datastax.driver.core.querybuilder.Insert;
27+import com.datastax.driver.core.querybuilder.QueryBuilder;
2728 import com.datastax.driver.core.utils.CassandraVersion;
2829
2930 import static com.datastax.driver.core.TestUtils.CREATE_KEYSPACE_SIMPLE_FORMAT;
30-import static com.datastax.driver.core.TestUtils.versionCheck;
31-import static com.datastax.driver.core.querybuilder.QueryBuilder.*;
31+import static com.datastax.driver.core.querybuilder.QueryBuilder.eq;
3232
3333 /**
3434 * Test limitations when using large amounts of data with the driver
@@ -43,12 +43,13 @@
4343 */
4444 private void testWideRows(CCMBridge.CCMCluster c, int key) throws Throwable {
4545 // Write data
46+ QueryBuilder builder = new QueryBuilder(c.cluster);
4647 for (int i = 0; i < 1000000; ++i) {
47- c.session.execute(insertInto("wide_rows").value("k", key).value("i", i).setConsistencyLevel(ConsistencyLevel.QUORUM));
48+ c.session.execute(builder.insertInto("wide_rows").value("k", key).value("i", i).setConsistencyLevel(ConsistencyLevel.QUORUM));
4849 }
4950
5051 // Read data
51- ResultSet rs = c.session.execute(select("i").from("wide_rows").where(eq("k", key)));
52+ ResultSet rs = c.session.execute(builder.select("i").from("wide_rows").where(eq("k", key)));
5253
5354 // Verify data
5455 int i = 0;
@@ -65,14 +66,15 @@
6566 */
6667 private void testWideBatchRows(CCMBridge.CCMCluster c, int key) throws Throwable {
6768 // Write data
68- Batch q = batch();
69+ QueryBuilder builder = new QueryBuilder(c.cluster);
70+ Batch q = builder.batch();
6971 for (int i = 0; i < 4000; ++i) {
70- q = q.add(insertInto("wide_batch_rows").value("k", key).value("i", i));
72+ q = q.add(builder.insertInto("wide_batch_rows").value("k", key).value("i", i));
7173 }
7274 c.session.execute(q.setConsistencyLevel(ConsistencyLevel.QUORUM));
7375
7476 // Read data
75- ResultSet rs = c.session.execute(select("i").from("wide_batch_rows").where(eq("k", key)));
77+ ResultSet rs = c.session.execute(builder.select("i").from("wide_batch_rows").where(eq("k", key)));
7678
7779 // Verify data
7880 int i = 0;
@@ -94,12 +96,13 @@
9496 bb.flip();
9597
9698 // Write data
99+ QueryBuilder builder = new QueryBuilder(c.cluster);
97100 for (int i = 0; i < 1000000; ++i) {
98- c.session.execute(insertInto("wide_byte_rows").value("k", key).value("i", bb).setConsistencyLevel(ConsistencyLevel.QUORUM));
101+ c.session.execute(builder.insertInto("wide_byte_rows").value("k", key).value("i", bb).setConsistencyLevel(ConsistencyLevel.QUORUM));
99102 }
100103
101104 // Read data
102- ResultSet rs = c.session.execute(select("i").from("wide_byte_rows").where(eq("k", key)));
105+ ResultSet rs = c.session.execute(builder.select("i").from("wide_byte_rows").where(eq("k", key)));
103106
104107 // Verify data
105108 for (Row row : rs) {
@@ -115,15 +118,16 @@
115118 */
116119 private void testLargeText(CCMBridge.CCMCluster c, int key) throws Throwable {
117120 // Write data
121+ QueryBuilder builder = new QueryBuilder(c.cluster);
118122 StringBuilder b = new StringBuilder();
119123 for (int i = 0; i < 1000000; ++i) {
120124 // Create ultra-long text
121125 b.append(i);
122126 }
123- c.session.execute(insertInto("large_text").value("k", key).value("txt", b.toString()).setConsistencyLevel(ConsistencyLevel.QUORUM));
127+ c.session.execute(builder.insertInto("large_text").value("k", key).value("txt", b.toString()).setConsistencyLevel(ConsistencyLevel.QUORUM));
124128
125129 // Read data
126- Row row = c.session.execute(select().all().from("large_text").where(eq("k", key))).one();
130+ Row row = c.session.execute(builder.select().all().from("large_text").where(eq("k", key))).one();
127131
128132 // Verify data
129133 assertTrue(b.toString().equals(row.getString("txt")));
@@ -163,14 +167,15 @@
163167 */
164168 private void testWideTable(CCMBridge.CCMCluster c, int key) throws Throwable {
165169 // Write data
166- Insert insertStatement = insertInto("wide_table").value("k", key);
170+ QueryBuilder builder = new QueryBuilder(c.cluster);
171+ Insert insertStatement = builder.insertInto("wide_table").value("k", key);
167172 for (int i = 0; i < 330; ++i) {
168173 insertStatement = insertStatement.value(createColumnName(i), i);
169174 }
170175 c.session.execute(insertStatement.setConsistencyLevel(ConsistencyLevel.QUORUM));
171176
172177 // Read data
173- Row row = c.session.execute(select().all().from("wide_table").where(eq("k", key))).one();
178+ Row row = c.session.execute(builder.select().all().from("wide_table").where(eq("k", key))).one();
174179
175180 // Verify data
176181 for (int i = 0; i < 330; ++i) {
modified driver-core/src/test/java/com/datastax/driver/core/MetricsTest.java +1 −1
@@ -66,7 +66,7 @@
6666 retryDecision = RetryDecision.retry(ConsistencyLevel.ONE);
6767
6868 // We only have one node, this will throw an unavailable exception
69- Statement statement = new SimpleStatement("SELECT v FROM test WHERE k = 1").setConsistencyLevel(ConsistencyLevel.TWO);
69+ Statement statement = session.newSimpleStatement("SELECT v FROM test WHERE k = 1").setConsistencyLevel(ConsistencyLevel.TWO);
7070 session.execute(statement);
7171
7272 Errors errors = cluster.getMetrics().getErrorMetrics();
added driver-core/src/test/java/com/datastax/driver/core/OptionalCodec.java +71 −0
@@ -0,0 +1,71 @@
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.Collection;
19+import java.util.Map;
20+
21+import com.google.common.base.Optional;
22+import com.google.common.base.Predicate;
23+import com.google.common.reflect.TypeParameter;
24+import com.google.common.reflect.TypeToken;
25+
26+import static com.google.common.base.Predicates.*;
27+
28+public class OptionalCodec<T> extends TypeCodec.MappingCodec<Optional<T>, T> {
29+
30+ private final Predicate<T> isAbsent;
31+
32+ @SuppressWarnings("unchecked")
33+ public OptionalCodec(TypeCodec<T> codec) {
34+ this(codec, (Predicate<T>) isAbsent());
35+ }
36+
37+ private static <T> Predicate<T> isAbsent() {
38+ return or(isNull(), new Predicate<T>() {
39+ @Override
40+ public boolean apply(T input) {
41+ return (input instanceof Collection && ((Collection)input).isEmpty()) ||
42+ (input instanceof Map && ((Map)input).isEmpty());
43+ }
44+ });
45+ }
46+
47+ public OptionalCodec(TypeCodec<T> codec, Predicate<T> isAbsent) {
48+ super(codec, new TypeToken<Optional<T>>(){}.where(new TypeParameter<T>(){}, codec.getJavaType()));
49+ this.isAbsent = isAbsent;
50+ }
51+
52+ @Override
53+ protected Optional<T> deserialize(T value) {
54+ return isAbsent(value) ? Optional.<T>absent() : Optional.of(value);
55+ }
56+
57+ @Override
58+ protected T serialize(Optional<T> value) {
59+ return value.isPresent() ? value.get() : absentValue();
60+ }
61+
62+ protected T absentValue() {
63+ return null;
64+ }
65+
66+ protected boolean isAbsent(T value) {
67+ return isAbsent.apply(value);
68+ }
69+
70+
71+}
modified driver-core/src/test/java/com/datastax/driver/core/PagingStateTest.java +9 −9
@@ -19,7 +19,6 @@
1919 import java.util.Collections;
2020 import java.util.Iterator;
2121
22-import com.datastax.driver.core.utils.CassandraVersion;
2322 import org.slf4j.Logger;
2423 import org.slf4j.LoggerFactory;
2524 import org.testng.annotations.BeforeClass;
@@ -28,6 +27,7 @@
2827 import static org.assertj.core.api.Assertions.assertThat;
2928
3029 import com.datastax.driver.core.exceptions.PagingStateException;
30+import com.datastax.driver.core.utils.CassandraVersion;
3131
3232 @CassandraVersion(major=2.0)
3333 public class PagingStateTest extends CCMBridge.PerClassSingleNodeCluster {
@@ -55,12 +55,12 @@
5555 */
5656 @Test(groups = "short")
5757 public void should_complete_when_using_paging_state() {
58- SimpleStatement st = new SimpleStatement(String.format("SELECT v FROM test WHERE k='%s'", KEY));
58+ SimpleStatement st = session.newSimpleStatement(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 = new SimpleStatement(String.format("SELECT v FROM test WHERE k='%s'", KEY));
63+ st = session.newSimpleStatement(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 = new SimpleStatement(String.format("SELECT v FROM test WHERE k='%s'", KEY));
88+ SimpleStatement st = session.newSimpleStatement(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 = new SimpleStatement(String.format("SELECT v FROM test WHERE k='%s'", "paging"));
109+ st = session.newSimpleStatement(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 = new SimpleStatement(String.format("SELECT v FROM test WHERE k='%s'", KEY));
173+ SimpleStatement st = session.newSimpleStatement(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 = new SimpleStatement(String.format("SELECT v FROM test WHERE k='%s'", KEY));
184+ st = session.newSimpleStatement(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 = new SimpleStatement(String.format("SELECT v FROM test WHERE k='%s'", KEY));
221+ SimpleStatement st = session.newSimpleStatement(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 = new SimpleStatement(String.format("SELECT v FROM test WHERE k='%s'", KEY));
226+ st = session.newSimpleStatement(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 +14 −14
@@ -128,7 +128,7 @@
128128 session.execute(setBoundValue(bs, name, type, getFixedValue(type)));
129129
130130 Row row = session.execute(String.format("SELECT %s FROM %s WHERE k='prepared_native'", name, ALL_NATIVE_TABLE)).one();
131- assertEquals(getValue(row, name, type), getFixedValue(type), "For type " + type);
131+ assertEquals(getValue(row, name, type, cluster.getConfiguration().getCodecRegistry()), getFixedValue(type), "For type " + type);
132132 }
133133 }
134134
@@ -149,7 +149,7 @@
149149 session.execute(setBoundValue(bs, name, type, getFixedValue2(type)));
150150
151151 Row row = session.execute(String.format("SELECT %s FROM %s WHERE k='prepared_native'", name, ALL_NATIVE_TABLE)).one();
152- assertEquals(getValue(row, name, type), getFixedValue2(type), "For type " + type);
152+ assertEquals(getValue(row, name, type, cluster.getConfiguration().getCodecRegistry()), getFixedValue2(type), "For type " + type);
153153 }
154154 }
155155
@@ -170,7 +170,7 @@
170170 session.execute(setBoundValue(bs, name, type, value));
171171
172172 Row row = session.execute(String.format("SELECT %s FROM %s WHERE k='prepared_list'", name, ALL_LIST_TABLE)).one();
173- assertEquals(getValue(row, name, type), value, "For type " + type);
173+ assertEquals(getValue(row, name, type, cluster.getConfiguration().getCodecRegistry()), value, "For type " + type);
174174 }
175175 }
176176
@@ -194,7 +194,7 @@
194194 session.execute(setBoundValue(bs, name, type, value));
195195
196196 Row row = session.execute(String.format("SELECT %s FROM %s WHERE k='prepared_list'", name, ALL_LIST_TABLE)).one();
197- assertEquals(getValue(row, name, type), value, "For type " + type);
197+ assertEquals(getValue(row, name, type, cluster.getConfiguration().getCodecRegistry()), value, "For type " + type);
198198 }
199199 }
200200
@@ -215,7 +215,7 @@
215215 session.execute(setBoundValue(bs, name, type, value));
216216
217217 Row row = session.execute(String.format("SELECT %s FROM %s WHERE k='prepared_set'", name, ALL_SET_TABLE)).one();
218- assertEquals(getValue(row, name, type), value, "For type " + type);
218+ assertEquals(getValue(row, name, type, cluster.getConfiguration().getCodecRegistry()), value, "For type " + type);
219219 }
220220 }
221221
@@ -239,7 +239,7 @@
239239 session.execute(setBoundValue(bs, name, type, value));
240240
241241 Row row = session.execute(String.format("SELECT %s FROM %s WHERE k='prepared_set'", name, ALL_SET_TABLE)).one();
242- assertEquals(getValue(row, name, type), value, "For type " + type);
242+ assertEquals(getValue(row, name, type, cluster.getConfiguration().getCodecRegistry()), value, "For type " + type);
243243 }
244244 }
245245
@@ -265,7 +265,7 @@
265265 session.execute(setBoundValue(bs, name, type, value));
266266
267267 Row row = session.execute(String.format("SELECT %s FROM %s WHERE k='prepared_map'", name, ALL_MAP_TABLE)).one();
268- assertEquals(getValue(row, name, type), value, "For type " + type);
268+ assertEquals(getValue(row, name, type, cluster.getConfiguration().getCodecRegistry()), value, "For type " + type);
269269 }
270270 }
271271 }
@@ -295,7 +295,7 @@
295295 session.execute(setBoundValue(bs, name, type, value));
296296
297297 Row row = session.execute(String.format("SELECT %s FROM %s WHERE k='prepared_map'", name, ALL_MAP_TABLE)).one();
298- assertEquals(getValue(row, name, type), value, "For type " + type);
298+ assertEquals(getValue(row, name, type, cluster.getConfiguration().getCodecRegistry()), value, "For type " + type);
299299 }
300300 }
301301 }
@@ -368,7 +368,7 @@
368368 @Test(groups = "short")
369369 public void prepareStatementInheritPropertiesTest() {
370370
371- RegularStatement toPrepare = new SimpleStatement("SELECT * FROM test WHERE k=?");
371+ RegularStatement toPrepare = session.newSimpleStatement("SELECT * FROM test WHERE k=?");
372372 toPrepare.setConsistencyLevel(ConsistencyLevel.QUORUM);
373373 toPrepare.enableTracing();
374374
@@ -400,7 +400,7 @@
400400 BatchStatement bs = new BatchStatement();
401401 bs.add(ps1.bind("one", "foo"));
402402 bs.add(ps2.bind("two"));
403- bs.add(new SimpleStatement("INSERT INTO " + SIMPLE_TABLE2 + " (k, v) VALUES ('three', 'foobar')"));
403+ bs.add(session.newSimpleStatement("INSERT INTO " + SIMPLE_TABLE2 + " (k, v) VALUES ('three', 'foobar')"));
404404
405405 session.execute(bs);
406406
@@ -540,7 +540,7 @@
540540 st2.setString(0, "foo");
541541 // i is UNSET
542542 session.execute(st2);
543- Statement st3 = new SimpleStatement("SELECT i from " + SIMPLE_TABLE + " where k = 'foo'");
543+ Statement st3 = session.newSimpleStatement("SELECT i from " + SIMPLE_TABLE + " where k = 'foo'");
544544 st3.enableTracing();
545545 ResultSet rows = session.execute(st3);
546546 assertThat(rows.one().getInt("i")).isEqualTo(1234);
@@ -569,7 +569,7 @@
569569 st2.setString(0, "foo");
570570 // i is UNSET
571571 session.execute(new BatchStatement().add(st2));
572- Statement st3 = new SimpleStatement("SELECT i from " + SIMPLE_TABLE + " where k = 'foo'");
572+ Statement st3 = session.newSimpleStatement("SELECT i from " + SIMPLE_TABLE + " where k = 'foo'");
573573 st3.enableTracing();
574574 ResultSet rows = session.execute(st3);
575575 assertThat(rows.one().getInt("i")).isEqualTo(1234);
@@ -591,7 +591,7 @@
591591 st1.setString(0, "foo");
592592 st1.setToNull(1);
593593 session.execute(st1);
594- Statement st2 = new SimpleStatement("SELECT i from " + SIMPLE_TABLE + " where k = 'foo'");
594+ Statement st2 = session.newSimpleStatement("SELECT i from " + SIMPLE_TABLE + " where k = 'foo'");
595595 st2.enableTracing();
596596 ResultSet rows = session.execute(st2);
597597 assertThat(rows.one().isNull(0)).isTrue();
@@ -614,7 +614,7 @@
614614 st1.setString(0, "foo");
615615 st1.setToNull(1);
616616 session.execute(new BatchStatement().add(st1));
617- Statement st2 = new SimpleStatement("SELECT i from " + SIMPLE_TABLE + " where k = 'foo'");
617+ Statement st2 = session.newSimpleStatement("SELECT i from " + SIMPLE_TABLE + " where k = 'foo'");
618618 st2.enableTracing();
619619 ResultSet rows = session.execute(st2);
620620 assertThat(rows.one().isNull(0)).isTrue();
modified driver-core/src/test/java/com/datastax/driver/core/QueryLoggerTest.java +5 −2
@@ -277,6 +277,7 @@
277277 public ByteBuffer getRoutingKey() {
278278 return null;
279279 }
280+
280281 @Override
281282 public String getKeyspace() {
282283 return null;
@@ -495,8 +496,10 @@
495496 .contains("Query completed normally")
496497 .contains(ipOfNode(1))
497498 .contains(query);
499+ CodecRegistry codecRegistry = cluster.getConfiguration().getCodecRegistry();
498500 for (DataType type : dataTypes) {
499- assertThat(line).contains(type.format(getFixedValue(type)));
501+ TypeCodec<Object> codec = codecRegistry.codecFor(type);
502+ assertThat(line).contains(codec.format(getFixedValue(type)));
500503 }
501504 }
502505
@@ -726,4 +729,4 @@
726729 return Lists.newArrayList("CREATE TABLE test (pk int PRIMARY KEY, " + definitions + ")");
727730 }
728731
729-}
No newline at the end of the file
732+}
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(new SimpleStatement(query).setDefaultTimestamp(30));
65+ session.execute(session.newSimpleStatement(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(new SimpleStatement(query).setDefaultTimestamp(30));
75+ session.execute(session.newSimpleStatement(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(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"));
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"));
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(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"));
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"));
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(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"));
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"));
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 = new SimpleStatement("INSERT INTO foo (k, v) VALUES (1, 1)");
147+ SimpleStatement statement = session.newSimpleStatement("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/SchemaAgreementTest.java +1 −1
@@ -102,7 +102,7 @@
102102
103103 private static void forceSchemaVersion(Session session, InetAddress peerAddress, UUID schemaVersion) {
104104 session.execute(String.format("UPDATE system.peers SET schema_version = %s WHERE peer = %s",
105- DataType.uuid().format(schemaVersion), DataType.inet().format(peerAddress)));
105+ TypeCodec.UUIDCodec.instance.format(schemaVersion), TypeCodec.InetCodec.instance.format(peerAddress)));
106106 }
107107
108108 @AfterMethod(groups = "short")
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(new SimpleStatement(String.format(TestUtils.SELECT_ALL_FORMAT, TABLE1)).setConsistencyLevel(ConsistencyLevel.ONE)), key);
65+ checkExecuteResultSet(session.execute(session.newSimpleStatement(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(new SimpleStatement(String.format(TestUtils.SELECT_ALL_FORMAT, TABLE1)).setConsistencyLevel(ConsistencyLevel.ONE)).getUninterruptibly(), key);
69+ checkExecuteResultSet(session.executeAsync(session.newSimpleStatement(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(new SimpleStatement(SELECT_ALL).setConsistencyLevel(ConsistencyLevel.ONE)), key);
154+ checkExecuteResultSet(compressedSession.execute(session.newSimpleStatement(SELECT_ALL).setConsistencyLevel(ConsistencyLevel.ONE)), key);
155155
156156 // executeAsync
157157 checkExecuteResultSet(compressedSession.executeAsync(SELECT_ALL).getUninterruptibly(), key);
158- checkExecuteResultSet(compressedSession.executeAsync(new SimpleStatement(SELECT_ALL).setConsistencyLevel(ConsistencyLevel.ONE)).getUninterruptibly(), key);
158+ checkExecuteResultSet(compressedSession.executeAsync(session.newSimpleStatement(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 +17 −1
@@ -18,12 +18,28 @@
1818 import java.util.Collections;
1919 import java.util.List;
2020
21+import org.testng.annotations.BeforeClass;
2122 import org.testng.annotations.Test;
2223
24+import static org.mockito.Mockito.mock;
25+import static org.mockito.Mockito.when;
26+
2327 public class SimpleStatementTest {
28+ Cluster cluster;
29+ CodecRegistry codecRegistry = new CodecRegistry();
30+
31+ @BeforeClass(groups = "unit")
32+ public void setup() {
33+ cluster = mock(Cluster.class);
34+ Configuration configuration = mock(Configuration.class);
35+ when(cluster.getConfiguration()).thenReturn(configuration);
36+ ProtocolOptions protocolOptions = mock(ProtocolOptions.class);
37+ when(configuration.getProtocolOptions()).thenReturn(protocolOptions);
38+ }
39+
2440 @Test(groups = "unit", expectedExceptions = { IllegalArgumentException.class })
2541 public void should_fail_if_too_many_variables() {
2642 List<Object> args = Collections.nCopies(1 << 16, (Object)1);
27- new SimpleStatement("mock query", args.toArray());
43+ new SimpleStatement("mock query", cluster, args.toArray());
2844 }
2945 }
No newline at the end of the file
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(new SimpleStatement("insert into foo(k,v) values (?,1)", k));
70+ batch.add(session.newSimpleStatement("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
@@ -104,7 +104,7 @@
104104 long execStartCount = errors.getSpeculativeExecutions().getCount();
105105 long retriesStartCount = errors.getRetriesOnUnavailable().getCount();
106106
107- SimpleStatement statement = new SimpleStatement("mock query");
107+ SimpleStatement statement = session.newSimpleStatement("mock query");
108108 statement.setConsistencyLevel(ConsistencyLevel.TWO);
109109 ResultSet rs = session.execute(statement);
110110 Row row = rs.one();
modified driver-core/src/test/java/com/datastax/driver/core/StatementIdempotenceTest.java +65 −43
@@ -19,19 +19,41 @@
1919 import com.google.common.collect.ImmutableMap;
2020 import com.google.common.collect.Lists;
2121 import com.google.common.collect.Sets;
22+import org.testng.annotations.BeforeMethod;
2223 import org.testng.annotations.Test;
2324
2425 import static org.assertj.core.api.Assertions.assertThat;
26+import static org.mockito.Mockito.mock;
27+import static org.mockito.Mockito.when;
2528
2629 import com.datastax.driver.core.querybuilder.BuiltStatement;
30+import com.datastax.driver.core.querybuilder.QueryBuilder;
2731
2832 import static com.datastax.driver.core.querybuilder.QueryBuilder.*;
2933
3034 public class StatementIdempotenceTest {
35+
36+ private Cluster cluster;
37+
38+ private QueryBuilder builder;
39+
40+ @BeforeMethod(groups = "unit")
41+ public void setUpQueryBuilder() throws Exception {
42+ CodecRegistry codecRegistry = new CodecRegistry();
43+ cluster = mock(Cluster.class);
44+ Configuration configuration = mock(Configuration.class);
45+ ProtocolOptions protocolOptions = mock(ProtocolOptions.class);
46+ when(cluster.getConfiguration()).thenReturn(configuration);
47+ when(configuration.getCodecRegistry()).thenReturn(codecRegistry);
48+ when(configuration.getProtocolOptions()).thenReturn(protocolOptions);
49+ when(protocolOptions.getProtocolVersion()).thenReturn(TestUtils.getDesiredProtocolVersion());
50+ builder = new QueryBuilder(cluster);
51+ }
52+
3153 @Test(groups = "unit")
3254 public void should_default_to_false_when_not_set_on_statement_nor_query_options() {
3355 QueryOptions queryOptions = new QueryOptions();
34- SimpleStatement statement = new SimpleStatement("");
56+ SimpleStatement statement = new SimpleStatement("", cluster);
3557
3658 assertThat(statement.isIdempotentWithDefault(queryOptions)).isFalse();
3759 }
@@ -39,7 +61,7 @@
3961 @Test(groups = "unit")
4062 public void should_use_query_options_when_not_set_on_statement() {
4163 QueryOptions queryOptions = new QueryOptions();
42- SimpleStatement statement = new SimpleStatement("");
64+ SimpleStatement statement = new SimpleStatement("", cluster);
4365
4466 for (boolean valueInOptions : new boolean[]{ true, false }) {
4567 queryOptions.setDefaultIdempotence(valueInOptions);
@@ -50,7 +72,7 @@
5072 @Test(groups = "unit")
5173 public void should_use_statement_when_set_on_statement() {
5274 QueryOptions queryOptions = new QueryOptions();
53- SimpleStatement statement = new SimpleStatement("");
75+ SimpleStatement statement = new SimpleStatement("", cluster);
5476
5577 for (boolean valueInOptions : new boolean[]{ true, false })
5678 for (boolean valueInStatement : new boolean[]{ true, false }) {
@@ -88,68 +110,68 @@
88110 }
89111 }
90112
91- private static ImmutableList<BuiltStatement> idempotentBuiltStatements() {
113+ private ImmutableList<BuiltStatement> idempotentBuiltStatements() {
92114 return ImmutableList.<BuiltStatement>of(
93- update("foo").with(set("v", 1)).where(eq("k", 1)), // set simple value
94- update("foo").with(add("s", 1)).where(eq("k", 1)), // add to set
95- update("foo").with(put("m", "a", 1)).where(eq("k", 1)), // put in map
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
96118
97119 // select statements should be idempotent even with function calls
98- select().countAll() .from("foo").where(eq("k", 1)),
99- select().ttl("v") .from("foo").where(eq("k", 1)),
100- select().writeTime("v") .from("foo").where(eq("k", 1)),
101- select().fcall("token", "k").from("foo").where(eq("k", 1))
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))
102124
103125 );
104126 }
105127
106- private static ImmutableList<BuiltStatement> nonIdempotentBuiltStatements() {
128+ private ImmutableList<BuiltStatement> nonIdempotentBuiltStatements() {
107129 return ImmutableList.of(
108- update("foo").with(append("l", 1)).where(eq("k", 1)), // append to list
109- update("foo").with(set("v", 1)).and(prepend("l", 1)).where(eq("k", 1)), // prepend to list
110- update("foo").with(incr("c")).where(eq("k", 1)), // counter update
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
111133
112134 // function calls
113135
114- insertInto("foo").value("k", 1).value("v", fcall("token", "k")),
115- insertInto("foo").value("k", 1).value("v", now()),
116- insertInto("foo").value("k", 1).value("v", uuid()),
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()),
117139
118- insertInto("foo").value("k", 1).value("v", Sets.newHashSet(fcall("token", "k"))),
119- insertInto("foo").value("k", 1).value("v", Sets.newHashSet(now())),
120- insertInto("foo").value("k", 1).value("v", Sets.newHashSet(uuid())),
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())),
121143
122- insertInto("foo").values(new String[]{"k", "v"}, new Object[]{1, fcall("token", "k")}),
123- insertInto("foo").values(new String[]{"k", "v"}, new Object[]{1, now()}),
124- insertInto("foo").values(new String[]{"k", "v"}, new Object[]{1, uuid()}),
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()}),
125147
126- insertInto("foo").values(new String[]{"k", "v"}, new Object[]{1, ImmutableMap.of("foo", fcall("token", "k"))}),
127- insertInto("foo").values(new String[]{"k", "v"}, new Object[]{1, ImmutableMap.of("foo", now())}),
128- insertInto("foo").values(new String[]{"k", "v"}, new Object[]{1, ImmutableMap.of("foo", uuid())}),
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())}),
129151
130- insertInto("foo").values(new String[]{"k", "v"}, new Object[]{1, ImmutableMap.of(fcall("token", "k"), "foo")}),
131- insertInto("foo").values(new String[]{"k", "v"}, new Object[]{1, ImmutableMap.of(now() , "foo")}),
132- insertInto("foo").values(new String[]{"k", "v"}, new Object[]{1, ImmutableMap.of(uuid() , "foo")}),
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")}),
133155
134- update("foo").with(set("v", fcall("token", "k"))) .where(eq("k", 1)),
135- update("foo").with(set("v", now())) .where(eq("k", 1)),
136- update("foo").with(set("v", uuid())) .where(eq("k", 1)),
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)),
137159
138- update("foo").with(set("v", Lists.newArrayList(fcall("token", "k")))).where(eq("k", 1)),
139- update("foo").with(set("v", Lists.newArrayList(now()))) .where(eq("k", 1)),
140- update("foo").with(set("v", Lists.newArrayList(uuid()))) .where(eq("k", 1)),
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)),
141163
142164 // raw() calls
143165
144- insertInto("foo").value("k", 1).value("v", raw("foo()")),
145- insertInto("foo").value("k", 1).value("v", Sets.newHashSet(raw("foo()"))),
166+ builder.insertInto("foo").value("k", 1).value("v", raw("foo()")),
167+ builder.insertInto("foo").value("k", 1).value("v", Sets.newHashSet(raw("foo()"))),
146168
147- insertInto("foo").values(new String[]{"k", "v"}, new Object[]{1, raw("foo()")}),
148- insertInto("foo").values(new String[]{"k", "v"}, new Object[]{1, ImmutableMap.of("foo", raw("foo()"))}),
149- insertInto("foo").values(new String[]{"k", "v"}, new Object[]{1, ImmutableMap.of(raw("foo()"), "foo")}),
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")}),
150172
151- update("foo").with(set("v", raw("foo()"))) .where(eq("k", 1)),
152- update("foo").with(set("v", Lists.newArrayList(raw("foo()")))).where(eq("k", 1))
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))
153175
154176 );
155177 }
modified driver-core/src/test/java/com/datastax/driver/core/StatementWrapperTest.java +3 −3
@@ -48,7 +48,7 @@
4848 public void should_pass_wrapped_statement_to_load_balancing_policy() {
4949 loadBalancingPolicy.customStatementsHandled.set(0);
5050
51- SimpleStatement s = new SimpleStatement("select * from system.local");
51+ SimpleStatement s = session.newSimpleStatement("select * from system.local");
5252 session.execute(s);
5353 assertThat(loadBalancingPolicy.customStatementsHandled.get()).isEqualTo(0);
5454
@@ -60,7 +60,7 @@
6060 public void should_pass_wrapped_statement_to_speculative_execution_policy() {
6161 speculativeExecutionPolicy.customStatementsHandled.set(0);
6262
63- SimpleStatement s = new SimpleStatement("select * from system.local");
63+ SimpleStatement s = session.newSimpleStatement("select * from system.local");
6464 session.execute(s);
6565 assertThat(speculativeExecutionPolicy.customStatementsHandled.get()).isEqualTo(0);
6666
@@ -74,7 +74,7 @@
7474
7575 // Set CL TWO with only one node, so the statement will always cause UNAVAILABLE,
7676 // which our custom policy ignores.
77- Statement s = new SimpleStatement("select * from system.local")
77+ Statement s = session.newSimpleStatement("select * from system.local")
7878 .setConsistencyLevel(ConsistencyLevel.TWO);
7979
8080 session.execute(s);
modified driver-core/src/test/java/com/datastax/driver/core/TestUtils.java +8 −4
@@ -130,7 +130,7 @@
130130 return bs;
131131 }
132132
133- public static Object getValue(Row row, String name, DataType type) {
133+ public static Object getValue(Row row, String name, DataType type, CodecRegistry codecRegistry) {
134134 switch (type.getName()) {
135135 case ASCII:
136136 return row.getString(name);
@@ -173,11 +173,15 @@
173173 case TIMEUUID:
174174 return row.getUUID(name);
175175 case LIST:
176- return row.getList(name, type.getTypeArguments().get(0).asJavaClass());
176+ Class<?> listEltClass = codecRegistry.codecFor(type.getTypeArguments().get(0)).getJavaType().getRawType();
177+ return row.getList(name, listEltClass);
177178 case SET:
178- return row.getSet(name, type.getTypeArguments().get(0).asJavaClass());
179+ Class<?> setEltClass = codecRegistry.codecFor(type.getTypeArguments().get(0)).getJavaType().getRawType();
180+ return row.getSet(name, setEltClass);
179181 case MAP:
180- return row.getMap(name, type.getTypeArguments().get(0).asJavaClass(), type.getTypeArguments().get(1).asJavaClass());
182+ Class<?> keyClass = codecRegistry.codecFor(type.getTypeArguments().get(0)).getJavaType().getRawType();
183+ Class<?> valueClass = codecRegistry.codecFor(type.getTypeArguments().get(1)).getJavaType().getRawType();
184+ return row.getMap(name, keyClass, valueClass);
181185 }
182186 throw new RuntimeException("Missing handling of " + type);
183187 }
modified driver-core/src/test/java/com/datastax/driver/core/TokenIntegrationTest.java +1 −1
@@ -114,7 +114,7 @@
114114
115115 // Find the replica for a given partition key
116116 int testKey = 1;
117- Set<Host> replicas = metadata.getReplicas("test", DataType.cint().serialize(testKey, cluster.getConfiguration().getProtocolOptions().getProtocolVersion()));
117+ Set<Host> replicas = metadata.getReplicas("test", TypeCodec.IntCodec.instance.serialize(testKey, cluster.getConfiguration().getProtocolOptions().getProtocolVersion()));
118118 assertThat(replicas).hasSize(1);
119119 Host replica = replicas.iterator().next();
120120
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 = new SimpleStatement(String.format("SELECT v FROM test WHERE k='%s'", KEY));
61+ SimpleStatement st = session.newSimpleStatement(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 = new SimpleStatement(String.format("SELECT v FROM test WHERE k='%s'", KEY));
90+ SimpleStatement st = session.newSimpleStatement(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/TupleTest.java +17 −15
@@ -30,6 +30,8 @@
3030 @CassandraVersion(major=2.1)
3131 public class TupleTest extends CCMBridge.PerClassSingleNodeCluster {
3232
33+ ProtocolVersion protocolVersion = TestUtils.getDesiredProtocolVersion();
34+
3335 @Override
3436 protected Collection<String> getTableDefinitions() {
3537 return Arrays.asList("CREATE TABLE t (k int PRIMARY KEY, v frozen<tuple<int, text, float>>)");
@@ -37,7 +39,7 @@
3739
3840 @Test(groups = "short")
3941 public void simpleValueTest() throws Exception {
40- TupleType t = TupleType.of(DataType.cint(), DataType.text(), DataType.cfloat());
42+ TupleType t = cluster.getMetadata().newTupleType(DataType.cint(), DataType.text(), DataType.cfloat());
4143 TupleValue v = t.newValue();
4244 v.setInt(0, 1);
4345 v.setString(1, "a");
@@ -52,7 +54,7 @@
5254 assertEquals(v.getString(1), "a");
5355 assertEquals(v.getFloat(2), 1.0f);
5456
55- assertEquals(t.format(v), "(1, 'a', 1.0)");
57+ assertEquals(new TypeCodec.TupleCodec(t).format(v), "(1, 'a', 1.0)");
5658 }
5759
5860 @Test(groups = "short")
@@ -62,7 +64,7 @@
6264 PreparedStatement ins = session.prepare("INSERT INTO t(k, v) VALUES (?, ?)");
6365 PreparedStatement sel = session.prepare("SELECT * FROM t WHERE k=?");
6466
65- TupleType t = TupleType.of(DataType.cint(), DataType.text(), DataType.cfloat());
67+ TupleType t = cluster.getMetadata().newTupleType(DataType.cint(), DataType.text(), DataType.cfloat());
6668
6769 int k = 1;
6870 TupleValue v = t.newValue(1, "a", 1.0f);
@@ -99,7 +101,7 @@
99101 session.execute("USE test_tuple_type");
100102 session.execute("CREATE TABLE mytable (a int PRIMARY KEY, b frozen<tuple<ascii, int, boolean>>)");
101103
102- TupleType t = TupleType.of(DataType.ascii(), DataType.cint(), DataType.cboolean());
104+ TupleType t = cluster.getMetadata().newTupleType(DataType.ascii(), DataType.cint(), DataType.cboolean());
103105
104106 // test non-prepared statement
105107 TupleValue complete = t.newValue("foo", 123, true);
@@ -114,7 +116,7 @@
114116 } catch (IllegalArgumentException e) {}
115117
116118 // test incomplete tuples with new TupleType
117- TupleType t1 = TupleType.of(DataType.ascii(), DataType.cint());
119+ TupleType t1 = cluster.getMetadata().newTupleType(DataType.ascii(), DataType.cint());
118120 TupleValue partial = t1.newValue("bar", 456);
119121 TupleValue partionResult = t.newValue("bar", 456, null);
120122 session.execute("INSERT INTO mytable (a, b) VALUES (0, ?)", partial);
@@ -128,7 +130,7 @@
128130 } catch (IllegalArgumentException e) {}
129131
130132 // test single value tuples with new TupleType
131- TupleType t2 = TupleType.of(DataType.ascii());
133+ TupleType t2 = cluster.getMetadata().newTupleType(DataType.ascii());
132134 TupleValue subpartial = t2.newValue("zoo");
133135 TupleValue subpartialResult = t.newValue("zoo", null, null);
134136 session.execute("INSERT INTO mytable (a, b) VALUES (0, ?)", subpartial);
@@ -188,7 +190,7 @@
188190 dataTypes.add(DataType.cint());
189191 values.add(j);
190192 }
191- TupleType t = new TupleType(dataTypes);
193+ TupleType t = new TupleType(dataTypes, protocolVersion, cluster.getConfiguration().getCodecRegistry());
192194 TupleValue createdTuple = t.newValue(values.toArray());
193195
194196 // write tuple
@@ -250,8 +252,8 @@
250252 }
251253
252254 // actually create the tuples
253- TupleType t = new TupleType(dataTypes);
254- TupleType t2 = new TupleType(completeDataTypes);
255+ TupleType t = new TupleType(dataTypes, protocolVersion, cluster.getConfiguration().getCodecRegistry());
256+ TupleType t2 = new TupleType(completeDataTypes, protocolVersion, cluster.getConfiguration().getCodecRegistry());
255257 TupleValue createdTuple = t.newValue(createdValues.toArray());
256258 TupleValue completeTuple = t2.newValue(completeValues.toArray());
257259
@@ -318,7 +320,7 @@
318320 dataTypes.add(DataType.list(datatype));
319321 createdValues.add(Arrays.asList(PrimitiveTypeSamples.ALL.get(datatype)));
320322
321- TupleType t = new TupleType(dataTypes);
323+ TupleType t = new TupleType(dataTypes, protocolVersion, cluster.getConfiguration().getCodecRegistry());
322324 TupleValue createdTuple = t.newValue(createdValues.toArray());
323325
324326 // write tuple
@@ -341,7 +343,7 @@
341343 dataTypes.add(DataType.set(datatype));
342344 createdValues.add(new HashSet<Object>(Arrays.asList(PrimitiveTypeSamples.ALL.get(datatype))));
343345
344- TupleType t = new TupleType(dataTypes);
346+ TupleType t = new TupleType(dataTypes, protocolVersion, cluster.getConfiguration().getCodecRegistry());
345347 TupleValue createdTuple = t.newValue(createdValues.toArray());
346348
347349 // write tuple
@@ -367,7 +369,7 @@
367369 dataTypes.add(DataType.map(datatype, datatype));
368370 createdValues.add(hm);
369371
370- TupleType t = new TupleType(dataTypes);
372+ TupleType t = new TupleType(dataTypes, protocolVersion, cluster.getConfiguration().getCodecRegistry());
371373 TupleValue createdTuple = t.newValue(createdValues.toArray());
372374
373375 // write tuple
@@ -405,11 +407,11 @@
405407 */
406408 private TupleValue nestedTuplesCreatorHelper(int depth) {
407409 if (depth == 1) {
408- TupleType baseTuple = TupleType.of(DataType.cint());
410+ TupleType baseTuple = cluster.getMetadata().newTupleType(DataType.cint());
409411 return baseTuple.newValue(303);
410412 } else {
411413 TupleValue innerTuple = nestedTuplesCreatorHelper(depth - 1);
412- TupleType t = TupleType.of(innerTuple.getType());
414+ TupleType t = cluster.getMetadata().newTupleType(innerTuple.getType());
413415 return t.newValue(innerTuple);
414416 }
415417 }
@@ -479,7 +481,7 @@
479481 UserType userTypeDef = cluster.getMetadata().getKeyspace("testTuplesWithNulls").getUserType("user");
480482 UDTValue userType = userTypeDef.newValue();
481483
482- TupleType t = TupleType.of(DataType.text(), DataType.cint(), DataType.uuid(), DataType.blob());
484+ TupleType t = cluster.getMetadata().newTupleType(DataType.text(), DataType.cint(), DataType.uuid(), DataType.blob());
483485 TupleValue v = t.newValue(null, null, null, null);
484486 userType.setTupleValue("b", v);
485487
added driver-core/src/test/java/com/datastax/driver/core/TypeCodecArraysIntegrationTest.java +233 −0
@@ -0,0 +1,233 @@
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.nio.ByteBuffer;
19+import java.util.Collection;
20+import java.util.List;
21+
22+import com.google.common.collect.Lists;
23+import com.google.common.primitives.Ints;
24+import org.testng.annotations.Test;
25+
26+import static com.google.common.base.Preconditions.checkArgument;
27+import static org.assertj.core.api.Assertions.assertThat;
28+
29+import com.datastax.driver.core.exceptions.InvalidTypeException;
30+
31+/**
32+ * Demonstrates how to write custom codecs for high-performance deserialization of CQL collections to primitive arrays.
33+ */
34+public class TypeCodecArraysIntegrationTest extends CCMBridge.PerClassSingleNodeCluster {
35+
36+ @Override
37+ protected Collection<String> getTableDefinitions() {
38+ return Lists.newArrayList(
39+ "CREATE TABLE lists(i int PRIMARY KEY, l list<int>)",
40+ "INSERT INTO lists (i, l) VALUES (1, [1, 2, 3])"
41+ );
42+ }
43+
44+ @Override
45+ protected Cluster.Builder configure(Cluster.Builder builder) {
46+ return builder.withCodecRegistry(
47+ new CodecRegistry().register(new IntArrayCodec())
48+ );
49+ }
50+
51+ @Test(groups = "short")
52+ public void should_read_list_column_as_array() {
53+ Row row = session.execute("SELECT l FROM lists WHERE i = 1").one();
54+
55+ int[] ints = row.get("l", int[].class);
56+
57+ assertThat(ints).containsExactly(1, 2, 3);
58+ }
59+
60+ @Test(groups = "short")
61+ public void should_set_list_column_with_array() {
62+ PreparedStatement pst = session.prepare("INSERT INTO lists (i, l) VALUES (:i, :l)");
63+ BoundStatement bs = pst.bind()
64+ .setInt("i", 2)
65+ .set("l", new int[]{ 2, 3, 4 }, int[].class);
66+ session.execute(bs);
67+
68+ Row row = session.execute("SELECT l FROM lists WHERE i = 2").one();
69+ assertThat(row.getList("l", Integer.class)).containsExactly(2, 3, 4);
70+ }
71+
72+ @Test(groups = "short")
73+ public void should_format_array_as_cql_literal() {
74+ IntArrayCodec codec = new IntArrayCodec();
75+
76+ assertThat(codec.format(new int[]{ 1, 2, 3 }))
77+ .isEqualTo("[1,2,3]");
78+ assertThat(codec.format(new int[0]))
79+ .isEqualTo("[]");
80+ assertThat(codec.format(null))
81+ .isEqualTo("null");
82+ }
83+
84+ @Test(groups = "short")
85+ public void should_parse_array_from_cql_literal() {
86+ IntArrayCodec codec = new IntArrayCodec();
87+
88+ assertThat(codec.parse("[1,2,3]"))
89+ .containsExactly(1, 2, 3);
90+ assertThat(codec.parse("null"))
91+ .isNull();
92+ assertThat(codec.parse(""))
93+ .isNull();
94+ assertThat(codec.parse(null))
95+ .isNull();
96+ }
97+
98+ public static class IntArrayCodec extends TypeCodec<int[]> {
99+
100+ private static final int SIZE_OF_INT = 4;
101+
102+ public IntArrayCodec() {
103+ super(DataType.list(DataType.cint()), int[].class);
104+ }
105+
106+ @Override
107+ public ByteBuffer serialize(int[] ints, ProtocolVersion protocolVersion) throws InvalidTypeException {
108+ if (ints == null)
109+ return null;
110+
111+ boolean isProtocolV3OrAbove = protocolVersion.compareTo(ProtocolVersion.V2) > 0;
112+
113+ checkArgument(isProtocolV3OrAbove || ints.length < 65536,
114+ "Native protocol version %d supports up to 65535 elements in any collection - but collection contains %d elements",
115+ protocolVersion.toInt(), ints.length);
116+
117+ /*
118+ * Encoding of lists in the native protocol:
119+ * [size of list] [size of element 1][element1] [size of element 2][element2]...
120+ * Sizes are encoded on 2 bytes in protocol v1 and v2, 4 bytes otherwise.
121+ * Integers are always encoded on 4 bytes.
122+ * (See native_protocol_v*.spec in https://github.com/apache/cassandra/blob/trunk/doc/)
123+ */
124+
125+ // Number of bytes to encode sizes
126+ int sizeOfSize = isProtocolV3OrAbove ? 4 : 2;
127+
128+ // Number of bytes to encode each element (preceded by its size)
129+ int sizeOfElement = sizeOfSize + SIZE_OF_INT;
130+
131+ // Number of bytes to encode the whole collection (size of collection + all elements)
132+ int totalSize = sizeOfSize + ints.length * sizeOfElement;
133+
134+ ByteBuffer output = ByteBuffer.allocate(totalSize);
135+
136+ writeSize(output, ints.length, protocolVersion);
137+ for (int i : ints) {
138+ writeSize(output, SIZE_OF_INT, protocolVersion);
139+ output.putInt(i);
140+ }
141+ output.flip();
142+ return output;
143+ }
144+
145+ @Override
146+ public int[] deserialize(ByteBuffer bytes, ProtocolVersion protocolVersion) throws InvalidTypeException {
147+ if (bytes == null || bytes.remaining() == 0)
148+ return new int[0];
149+
150+ boolean isProtocolV3OrAbove = protocolVersion.compareTo(ProtocolVersion.V2) > 0;
151+ int sizeOfSize = isProtocolV3OrAbove ? 4 : 2;
152+
153+ ByteBuffer input = bytes.duplicate();
154+
155+ int size = CodecUtils.readCollectionSize(input, protocolVersion);
156+ int[] ints = new int[size];
157+ for (int i = 0; i < size; i++) {
158+ // Skip size (we know it will always be 4 since the elements are ints)
159+ input.position(input.position() + sizeOfSize);
160+ ints[i] = input.getInt();
161+ }
162+ return ints;
163+ }
164+
165+ @Override
166+ public String format(int[] ints) throws InvalidTypeException {
167+ if (ints == null)
168+ return "null";
169+
170+ StringBuilder sb = new StringBuilder();
171+ sb.append('[');
172+ for (int i = 0; i < ints.length; i++) {
173+ if (i != 0)
174+ sb.append(",");
175+ sb.append(ints[i]);
176+ }
177+ sb.append(']');
178+ return sb.toString();
179+ }
180+
181+ @Override
182+ public int[] parse(String value) throws InvalidTypeException {
183+ if (value == null || value.isEmpty() || value.equals("null"))
184+ return null;
185+
186+ int idx = ParseUtils.skipSpaces(value, 0);
187+ if (value.charAt(idx++) != '[')
188+ throw new InvalidTypeException(String.format("cannot parse list value from \"%s\", at character %d expecting '[' but got '%c'", value, idx, value.charAt(idx)));
189+
190+ idx = ParseUtils.skipSpaces(value, idx);
191+
192+ if (value.charAt(idx) == ']')
193+ return new int[0];
194+
195+ List<Integer> l = Lists.newArrayList();
196+ while (idx < value.length()) {
197+ int n;
198+ try {
199+ n = ParseUtils.skipCQLValue(value, idx);
200+ } catch (IllegalArgumentException e) {
201+ throw new InvalidTypeException(String.format("Cannot parse list value from \"%s\", invalid CQL value at character %d", value, idx), e);
202+ }
203+
204+ l.add(Integer.parseInt(value.substring(idx, n)));
205+ idx = n;
206+
207+ idx = ParseUtils.skipSpaces(value, idx);
208+ if (value.charAt(idx) == ']')
209+ return Ints.toArray(l);
210+ if (value.charAt(idx++) != ',')
211+ throw new InvalidTypeException(String.format("Cannot parse list value from \"%s\", at character %d expecting ',' but got '%c'", value, idx, value.charAt(idx)));
212+
213+ idx = ParseUtils.skipSpaces(value, idx);
214+ }
215+ throw new InvalidTypeException(String.format("Malformed list value \"%s\", missing closing ']'", value));
216+ }
217+
218+ private void writeSize(ByteBuffer output, int size, ProtocolVersion protocolVersion) {
219+ switch (protocolVersion) {
220+ case V1:
221+ case V2:
222+ output.putShort((short)size);
223+ break;
224+ case V3:
225+ case V4:
226+ output.putInt(size);
227+ break;
228+ default:
229+ throw protocolVersion.unsupported();
230+ }
231+ }
232+ }
233+}
No newline at the end of the file
added driver-core/src/test/java/com/datastax/driver/core/TypeCodecAssert.java +94 −0
@@ -0,0 +1,94 @@
1+/*
2+ * Copyright (C) 2012-2015 DataStax Inc.
3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ */
16+package com.datastax.driver.core;
17+
18+import com.google.common.reflect.TypeToken;
19+import org.assertj.core.api.AbstractAssert;
20+
21+import static org.assertj.core.api.Assertions.assertThat;
22+import static org.assertj.core.api.Fail.fail;
23+
24+/**
25+ */
26+@SuppressWarnings("unused")
27+public class TypeCodecAssert extends AbstractAssert<TypeCodecAssert, TypeCodec> {
28+
29+ private ProtocolVersion version = TestUtils.getDesiredProtocolVersion();
30+
31+ protected TypeCodecAssert(TypeCodec<?> actual) {
32+ super(actual, TypeCodecAssert.class);
33+ }
34+
35+ public TypeCodecAssert accepts(Class<?> clazz) {
36+ return accepts(TypeToken.of(clazz));
37+ }
38+
39+ public TypeCodecAssert accepts(TypeToken<?> javaType) {
40+ assertThat(actual.accepts(javaType)).isTrue();
41+ return this;
42+ }
43+
44+ public TypeCodecAssert doesNotAccept(TypeToken<?> javaType) {
45+ assertThat(actual.accepts(javaType)).isFalse();
46+ return this;
47+ }
48+
49+ public TypeCodecAssert accepts(Object value) {
50+ assertThat(actual.accepts(value)).as("Codec %s should accept %s but it does not", actual, value).isTrue();
51+ return this;
52+ }
53+
54+ public TypeCodecAssert doesNotAccept(Object value) {
55+ assertThat(actual.accepts(value)).isFalse();
56+ return this;
57+ }
58+
59+ public TypeCodecAssert accepts(DataType cqlType) {
60+ assertThat(actual.accepts(cqlType)).isTrue();
61+ return this;
62+ }
63+
64+ public TypeCodecAssert doesNotAccept(DataType cqlType) {
65+ assertThat(actual.accepts(cqlType)).isFalse();
66+ return this;
67+ }
68+
69+ public TypeCodecAssert withProtocolVersion(ProtocolVersion version) {
70+ if(version == null) fail("ProtocolVersion cannot be null");
71+ this.version = version;
72+ return this;
73+ }
74+
75+ @SuppressWarnings("unchecked")
76+ public TypeCodecAssert canSerialize(Object value) {
77+ if(version == null) fail("ProtocolVersion cannot be null");
78+ assertThat(actual.deserialize(actual.serialize(value, version), version)).isEqualTo(value);
79+ return this;
80+ }
81+
82+ @SuppressWarnings("unchecked")
83+ public TypeCodecAssert cannotSerialize(Object value) {
84+ if(version == null) fail("ProtocolVersion cannot be null");
85+ try {
86+ assertThat(actual.deserialize(actual.serialize(value, version), version))
87+ .describedAs(String.format("Codec is not supposed to serialize this value but it actually does: %s", value))
88+ .isNotEqualTo(value);
89+ } catch (Exception e) {
90+ //ok
91+ }
92+ return this;
93+ }
94+}
added driver-core/src/test/java/com/datastax/driver/core/TypeCodecCollectionsIntegrationTest.java +206 −0
@@ -0,0 +1,206 @@
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.math.BigDecimal;
19+import java.math.BigInteger;
20+import java.util.Collection;
21+import java.util.List;
22+import java.util.Map;
23+import java.util.Set;
24+
25+import com.datastax.driver.core.querybuilder.QueryBuilder;
26+import com.datastax.driver.core.utils.CassandraVersion;
27+import com.google.common.collect.ImmutableMap;
28+import com.google.common.reflect.TypeToken;
29+import org.testng.annotations.BeforeMethod;
30+import org.testng.annotations.Test;
31+
32+import static com.google.common.collect.Lists.newArrayList;
33+import static com.google.common.collect.Sets.newHashSet;
34+import static org.assertj.core.api.Assertions.assertThat;
35+
36+import com.datastax.driver.core.querybuilder.BuiltStatement;
37+
38+import static com.datastax.driver.core.CodecUtils.listOf;
39+import static com.datastax.driver.core.CodecUtils.mapOf;
40+import static com.datastax.driver.core.CodecUtils.setOf;
41+import static com.datastax.driver.core.querybuilder.QueryBuilder.bindMarker;
42+import static com.datastax.driver.core.querybuilder.QueryBuilder.eq;
43+
44+@CassandraVersion(major=2.0)
45+public class TypeCodecCollectionsIntegrationTest extends CCMBridge.PerClassSingleNodeCluster {
46+
47+ private final String insertQuery = "INSERT INTO \"myTable2\" (c_int, l_int, l_bigint, s_float, s_double, m_varint, m_decimal) VALUES (?, ?, ?, ?, ?, ?, ?)";
48+
49+ private final String selectQuery = "SELECT c_int, l_int, l_bigint, s_float, s_double, m_varint, m_decimal FROM \"myTable2\" WHERE c_int = ?";
50+
51+ private BuiltStatement insertStmt;
52+ private BuiltStatement selectStmt;
53+
54+ private int n_int = 42;
55+ private List<Integer> l_int = newArrayList(42, 43);
56+ private List<Long> l_bigint = newArrayList(42l, 43l);
57+ private Set<Float> s_float = newHashSet(42.42f, 43.43f);
58+ private Set<Double> s_double = newHashSet(42.42d, 43.43d);
59+ private Map<Integer, BigInteger> m_varint = ImmutableMap.of(42, new BigInteger("424242"), 43, new BigInteger("434343"));
60+ private Map<Integer, BigDecimal> m_decimal = ImmutableMap.of(42, new BigDecimal("424242.42"), 43, new BigDecimal("434343.43"));
61+
62+ @Override
63+ protected Collection<String> getTableDefinitions() {
64+ return newArrayList(
65+ "CREATE TABLE IF NOT EXISTS \"myTable2\" ("
66+ + "c_int int PRIMARY KEY, "
67+ + "l_int list<int>, "
68+ + "l_bigint list<bigint>, "
69+ + "s_float set<float>, "
70+ + "s_double set<double>, "
71+ + "m_varint map<int,varint>, "
72+ + "m_decimal map<int,decimal>"
73+ + ")");
74+ }
75+
76+ @BeforeMethod(groups = "short")
77+ public void createBuiltStatements() throws Exception {
78+ insertStmt = new QueryBuilder(cluster).insertInto("\"myTable2\"")
79+ .value("c_int", bindMarker())
80+ .value("l_int", bindMarker())
81+ .value("l_bigint", bindMarker())
82+ .value("s_float", bindMarker())
83+ .value("s_double", bindMarker())
84+ .value("m_varint", bindMarker())
85+ .value("m_decimal", bindMarker());
86+ selectStmt = new QueryBuilder(cluster).select("c_int", "l_int", "l_bigint", "s_float", "s_double", "m_varint", "m_decimal")
87+ .from("\"myTable2\"")
88+ .where(eq("c_int", bindMarker()));
89+ }
90+
91+ @Test(groups = "short")
92+ public void should_use_collection_codecs_with_simple_statements() {
93+ session.execute(insertQuery, n_int, l_int, l_bigint, s_float, s_double, m_varint, m_decimal);
94+ ResultSet rows = session.execute(selectQuery, n_int);
95+ Row row = rows.one();
96+ assertRow(row);
97+ }
98+
99+ @Test(groups = "short")
100+ public void should_use_collection_codecs_with_prepared_statements_1() {
101+ session.execute(session.prepare(insertQuery).bind(n_int, l_int, l_bigint, s_float, s_double, m_varint, m_decimal));
102+ PreparedStatement ps = session.prepare(selectQuery);
103+ ResultSet rows = session.execute(ps.bind(n_int));
104+ Row row = rows.one();
105+ assertRow(row);
106+ }
107+
108+ @Test(groups = "short")
109+ public void should_use_collection_codecs_with_prepared_statements_2() {
110+ session.execute(session.prepare(insertQuery).bind()
111+ .setInt(0, n_int)
112+ .setList(1, l_int)
113+ .setList(2, l_bigint, Long.class) // variant with element type explicitly set
114+ .setSet(3, s_float)
115+ .setSet(4, s_double, TypeToken.of(Double.class)) // variant with element type explicitly set
116+ .setMap(5, m_varint)
117+ .setMap(6, m_decimal, Integer.class, BigDecimal.class) // variant with element type explicitly set
118+ );
119+ PreparedStatement ps = session.prepare(selectQuery);
120+ ResultSet rows = session.execute(ps.bind()
121+ .setInt(0, n_int)
122+ );
123+ Row row = rows.one();
124+ assertRow(row);
125+ }
126+
127+ @Test(groups = "short")
128+ public void should_use_collection_codecs_with_prepared_statements_3() {
129+ session.execute(session.prepare(insertQuery).bind()
130+ .setInt(0, n_int)
131+ .setObject(1, l_int)
132+ .setObject(2, l_bigint)
133+ .setObject(3, s_float)
134+ .setObject(4, s_double)
135+ .setObject(5, m_varint)
136+ .setObject(6, m_decimal)
137+ );
138+ PreparedStatement ps = session.prepare(selectQuery);
139+ ResultSet rows = session.execute(ps.bind()
140+ .setInt(0, n_int)
141+ );
142+ Row row = rows.one();
143+ assertRow(row);
144+ }
145+
146+ @Test(groups = "short")
147+ public void should_use_collection_codecs_with_prepared_statements_4() {
148+ session.execute(session.prepare(insertQuery).bind()
149+ .setInt(0, n_int)
150+ .set(1, l_int, listOf(Integer.class))
151+ .set(2, l_bigint, listOf(Long.class))
152+ .set(3, s_float, setOf(Float.class))
153+ .set(4, s_double, setOf(Double.class))
154+ .set(5, m_varint, mapOf(Integer.class, BigInteger.class))
155+ .set(6, m_decimal, mapOf(Integer.class, BigDecimal.class))
156+ );
157+ PreparedStatement ps = session.prepare(selectQuery);
158+ ResultSet rows = session.execute(ps.bind()
159+ .setInt(0, n_int)
160+ );
161+ Row row = rows.one();
162+ assertRow(row);
163+ }
164+
165+ @Test(groups = "short")
166+ public void should_use_collection_codecs_with_built_statements() {
167+ session.execute(session.prepare(insertStmt).bind()
168+ .setInt(0, n_int)
169+ .set(1, l_int, listOf(Integer.class))
170+ .set(2, l_bigint, listOf(Long.class))
171+ .set(3, s_float, setOf(Float.class))
172+ .set(4, s_double, setOf(Double.class))
173+ .set(5, m_varint, mapOf(Integer.class, BigInteger.class))
174+ .set(6, m_decimal, mapOf(Integer.class, BigDecimal.class))
175+ );
176+ PreparedStatement ps = session.prepare(selectStmt);
177+ ResultSet rows = session.execute(ps.bind()
178+ .setInt(0, n_int)
179+ );
180+ Row row = rows.one();
181+ assertRow(row);
182+ }
183+ private void assertRow(Row row) {
184+ assertThat(row.getInt(0)).isEqualTo(n_int);
185+ assertThat(row.getList(1, Integer.class)).isEqualTo(l_int);
186+ assertThat(row.getList(2, Long.class)).isEqualTo(l_bigint);
187+ assertThat(row.getSet(3, Float.class)).isEqualTo(s_float);
188+ assertThat(row.getSet(4, Double.class)).isEqualTo(s_double);
189+ assertThat(row.getMap(5, Integer.class, BigInteger.class)).isEqualTo(m_varint);
190+ assertThat(row.getMap(6, Integer.class, BigDecimal.class)).isEqualTo(m_decimal);
191+ // with get + type
192+ assertThat(row.get(1, listOf(Integer.class))).isEqualTo(l_int);
193+ assertThat(row.get(2, listOf(Long.class))).isEqualTo(l_bigint);
194+ assertThat(row.get(3, setOf(Float.class))).isEqualTo(s_float);
195+ assertThat(row.get(4, setOf(Double.class))).isEqualTo(s_double);
196+ assertThat(row.get(5, mapOf(Integer.class, BigInteger.class))).isEqualTo(m_varint);
197+ assertThat(row.get(6, mapOf(Integer.class, BigDecimal.class))).isEqualTo(m_decimal);
198+ // with getObject
199+ assertThat(row.getObject(1)).isEqualTo(l_int);
200+ assertThat(row.getObject(2)).isEqualTo(l_bigint);
201+ assertThat(row.getObject(3)).isEqualTo(s_float);
202+ assertThat(row.getObject(4)).isEqualTo(s_double);
203+ assertThat(row.getObject(5)).isEqualTo(m_varint);
204+ assertThat(row.getObject(6)).isEqualTo(m_decimal);
205+ }
206+}
added driver-core/src/test/java/com/datastax/driver/core/TypeCodecEncapsulationIntegrationTest.java +319 −0
@@ -0,0 +1,319 @@
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.math.BigDecimal;
19+import java.math.BigInteger;
20+import java.nio.ByteBuffer;
21+import java.util.Collection;
22+
23+import com.google.common.base.Objects;
24+import com.google.common.reflect.TypeParameter;
25+import com.google.common.reflect.TypeToken;
26+import org.testng.annotations.BeforeMethod;
27+import org.testng.annotations.Test;
28+
29+import static com.google.common.collect.Lists.newArrayList;
30+import static org.assertj.core.api.Assertions.assertThat;
31+
32+import com.datastax.driver.core.TypeCodec.*;
33+import com.datastax.driver.core.exceptions.InvalidTypeException;
34+import com.datastax.driver.core.querybuilder.BuiltStatement;
35+import com.datastax.driver.core.querybuilder.QueryBuilder;
36+import com.datastax.driver.core.utils.CassandraVersion;
37+
38+import static com.datastax.driver.core.querybuilder.QueryBuilder.bindMarker;
39+import static com.datastax.driver.core.querybuilder.QueryBuilder.eq;
40+
41+public class TypeCodecEncapsulationIntegrationTest extends CCMBridge.PerClassSingleNodeCluster {
42+
43+ private final String insertQuery = "INSERT INTO \"myTable\" (c_int, c_bigint, c_float, c_double, c_varint, c_decimal) VALUES (?, ?, ?, ?, ?, ?)";
44+
45+ private final String selectQuery = "SELECT c_int, c_bigint, c_float, c_double, c_varint, c_decimal FROM \"myTable\" WHERE c_int = ? and c_bigint = ?";
46+
47+ private BuiltStatement insertStmt;
48+ private BuiltStatement selectStmt;
49+
50+ private int n_int = 42;
51+ private long n_bigint = 4242;
52+ private float n_float = 42.42f;
53+ private double n_double = 4242.42d;
54+ private BigInteger n_varint = new BigInteger("424242");
55+ private BigDecimal n_decimal = new BigDecimal("424242.42");
56+
57+ @Override
58+ protected Collection<String> getTableDefinitions() {
59+ return newArrayList(
60+ "CREATE TABLE \"myTable\" ("
61+ + "c_int int, "
62+ + "c_bigint bigint, "
63+ + "c_float float, "
64+ + "c_double double, "
65+ + "c_varint varint, "
66+ + "c_decimal decimal, "
67+ + "PRIMARY KEY (c_int, c_bigint)"
68+ + ")"
69+ );
70+ }
71+
72+ @Override
73+ protected Cluster.Builder configure(Cluster.Builder builder) {
74+ return builder.withCodecRegistry(
75+ new CodecRegistry()
76+ .register(
77+ new NumberBoxCodec<Integer>(IntCodec.instance),
78+ new NumberBoxCodec<Long>(BigintCodec.instance),
79+ new NumberBoxCodec<Float>(FloatCodec.instance),
80+ new NumberBoxCodec<Double>(DoubleCodec.instance),
81+ new NumberBoxCodec<BigInteger>(VarintCodec.instance),
82+ new NumberBoxCodec<BigDecimal>(DecimalCodec.instance)
83+ )
84+ );
85+ }
86+
87+ @BeforeMethod(groups = "short")
88+ public void createBuiltStatements() throws Exception {
89+ insertStmt = new QueryBuilder(cluster).insertInto("\"myTable\"")
90+ .value("c_int", bindMarker())
91+ .value("c_bigint", bindMarker())
92+ .value("c_float", bindMarker())
93+ .value("c_double", bindMarker())
94+ .value("c_varint", bindMarker())
95+ .value("c_decimal", bindMarker());
96+ selectStmt = new QueryBuilder(cluster).select("c_int", "c_bigint", "c_float", "c_double", "c_varint", "c_decimal")
97+ .from("\"myTable\"")
98+ .where(eq("c_int", bindMarker()))
99+ .and(eq("c_bigint", bindMarker()));
100+ }
101+
102+ @Test(groups = "short")
103+ @CassandraVersion(major=2.0)
104+ public void should_use_custom_codecs_with_simple_statements() {
105+ session.execute(insertQuery,
106+ n_int,
107+ new NumberBox<Long>(n_bigint),
108+ new NumberBox<Float>(n_float),
109+ new NumberBox<Double>(n_double),
110+ new NumberBox<BigInteger>(n_varint),
111+ new NumberBox<BigDecimal>(n_decimal));
112+ ResultSet rows = session.execute(selectQuery, n_int, new NumberBox<Long>(n_bigint));
113+ Row row = rows.one();
114+ assertRow(row);
115+ }
116+
117+ @Test(groups = "short")
118+ public void should_use_custom_codecs_with_prepared_statements_1() {
119+ session.execute(session.prepare(insertQuery).bind(
120+ n_int,
121+ new NumberBox<Long>(n_bigint),
122+ new NumberBox<Float>(n_float),
123+ new NumberBox<Double>(n_double),
124+ new NumberBox<BigInteger>(n_varint),
125+ new NumberBox<BigDecimal>(n_decimal)));
126+ PreparedStatement ps = session.prepare(selectQuery);
127+ ResultSet rows = session.execute(ps.bind(n_int, new NumberBox<Long>(n_bigint)));
128+ Row row = rows.one();
129+ assertRow(row);
130+ }
131+
132+ @Test(groups = "short")
133+ public void should_use_custom_codecs_with_prepared_statements_2() {
134+ session.execute(session.prepare(insertQuery).bind()
135+ .setObject(0, new NumberBox<Integer>(n_int))
136+ .setObject(1, new NumberBox<Long>(n_bigint))
137+ .setObject(2, new NumberBox<Float>(n_float))
138+ .setObject(3, new NumberBox<Double>(n_double))
139+ .setObject(4, new NumberBox<BigInteger>(n_varint))
140+ .setObject(5, new NumberBox<BigDecimal>(n_decimal))
141+ );
142+ PreparedStatement ps = session.prepare(selectQuery);
143+ ResultSet rows = session.execute(ps.bind()
144+ .setObject(0, new NumberBox<Integer>(n_int))
145+ .setObject(1, new NumberBox<Long>(n_bigint))
146+ );
147+ Row row = rows.one();
148+ assertRow(row);
149+ }
150+
151+ @Test(groups = "short")
152+ public void should_use_custom_codecs_with_prepared_statements_3() {
153+ session.execute(session.prepare(insertQuery).bind()
154+ .set(0, new NumberBox<Integer>(n_int), new TypeToken<NumberBox<Integer>>() {})
155+ .set(1, new NumberBox<Long>(n_bigint), new TypeToken<NumberBox<Long>>() {})
156+ .set(2, new NumberBox<Float>(n_float), new TypeToken<NumberBox<Float>>() {})
157+ .set(3, new NumberBox<Double>(n_double), new TypeToken<NumberBox<Double>>() {})
158+ .set(4, new NumberBox<BigInteger>(n_varint), new TypeToken<NumberBox<BigInteger>>() {})
159+ .set(5, new NumberBox<BigDecimal>(n_decimal), new TypeToken<NumberBox<BigDecimal>>() {})
160+ );
161+ PreparedStatement ps = session.prepare(selectQuery);
162+ ResultSet rows = session.execute(ps.bind()
163+ .set(0, new NumberBox<Integer>(n_int), new TypeToken<NumberBox<Integer>>() {})
164+ .set(1, new NumberBox<Long>(n_bigint), new TypeToken<NumberBox<Long>>() {})
165+ );
166+ Row row = rows.one();
167+ assertRow(row);
168+ }
169+
170+ @Test(groups = "short")
171+ public void should_use_custom_codecs_with_built_statements_1() {
172+ session.execute(session.prepare(insertStmt).bind(
173+ n_int,
174+ new NumberBox<Long>(n_bigint),
175+ new NumberBox<Float>(n_float),
176+ new NumberBox<Double>(n_double),
177+ new NumberBox<BigInteger>(n_varint),
178+ new NumberBox<BigDecimal>(n_decimal)));
179+ PreparedStatement ps = session.prepare(selectStmt);
180+ ResultSet rows = session.execute(ps.bind(n_int, new NumberBox<Long>(n_bigint)));
181+ Row row = rows.one();
182+ assertRow(row);
183+ }
184+
185+ @Test(groups = "short")
186+ public void should_use_custom_codecs_with_built_statements_2() {
187+ session.execute(session.prepare(insertStmt).bind()
188+ .setObject(0, new NumberBox<Integer>(n_int))
189+ .setObject(1, new NumberBox<Long>(n_bigint))
190+ .setObject(2, new NumberBox<Float>(n_float))
191+ .setObject(3, new NumberBox<Double>(n_double))
192+ .setObject(4, new NumberBox<BigInteger>(n_varint))
193+ .setObject(5, new NumberBox<BigDecimal>(n_decimal))
194+ );
195+ PreparedStatement ps = session.prepare(selectStmt);
196+ ResultSet rows = session.execute(ps.bind()
197+ .setObject(0, new NumberBox<Integer>(n_int))
198+ .setObject(1, new NumberBox<Long>(n_bigint))
199+ );
200+ Row row = rows.one();
201+ assertRow(row);
202+ }
203+
204+ @Test(groups = "short")
205+ public void should_use_custom_codecs_with_built_statements_3() {
206+ session.execute(session.prepare(insertStmt).bind()
207+ .set(0, new NumberBox<Integer>(n_int), new TypeToken<NumberBox<Integer>>() {})
208+ .set(1, new NumberBox<Long>(n_bigint), new TypeToken<NumberBox<Long>>() {})
209+ .set(2, new NumberBox<Float>(n_float), new TypeToken<NumberBox<Float>>() {})
210+ .set(3, new NumberBox<Double>(n_double), new TypeToken<NumberBox<Double>>() {})
211+ .set(4, new NumberBox<BigInteger>(n_varint), new TypeToken<NumberBox<BigInteger>>() {})
212+ .set(5, new NumberBox<BigDecimal>(n_decimal), new TypeToken<NumberBox<BigDecimal>>() {})
213+ );
214+ PreparedStatement ps = session.prepare(selectStmt);
215+ ResultSet rows = session.execute(ps.bind()
216+ .set(0, new NumberBox<Integer>(n_int), new TypeToken<NumberBox<Integer>>() {})
217+ .set(1, new NumberBox<Long>(n_bigint), new TypeToken<NumberBox<Long>>() {})
218+ );
219+ Row row = rows.one();
220+ assertRow(row);
221+ }
222+
223+ private void assertRow(Row row) {
224+ // using getInt, etc: the default codecs are used
225+ // and values are deserialized the traditional way
226+ assertThat(row.getInt(0)).isEqualTo(n_int);
227+ assertThat(row.getLong(1)).isEqualTo(n_bigint);
228+ assertThat(row.getFloat(2)).isEqualTo(n_float);
229+ assertThat(row.getDouble(3)).isEqualTo(n_double);
230+ assertThat(row.getVarint(4)).isEqualTo(n_varint);
231+ assertThat(row.getDecimal(5)).isEqualTo(n_decimal);
232+ // with getObject, the first matching codec is the default one
233+ assertThat(row.getObject(0)).isEqualTo(n_int);
234+ assertThat(row.getObject(1)).isEqualTo(n_bigint);
235+ assertThat(row.getObject(2)).isEqualTo(n_float);
236+ assertThat(row.getObject(3)).isEqualTo(n_double);
237+ assertThat(row.getObject(4)).isEqualTo(n_varint);
238+ assertThat(row.getObject(5)).isEqualTo(n_decimal);
239+ // with get + type
240+ // we go back to the default codecs
241+ assertThat(row.get(0, Integer.class)).isEqualTo(n_int);
242+ assertThat(row.get(1, Long.class)).isEqualTo(n_bigint);
243+ assertThat(row.get(2, Float.class)).isEqualTo(n_float);
244+ assertThat(row.get(3, Double.class)).isEqualTo(n_double);
245+ assertThat(row.get(4, BigInteger.class)).isEqualTo(n_varint);
246+ assertThat(row.get(5, BigDecimal.class)).isEqualTo(n_decimal);
247+ // with get + type, but enforcing NumberBox types
248+ // we get the NumberBox codecs instead
249+ assertThat(row.get(0, new TypeToken<NumberBox<Integer>>() {})).isEqualTo(new NumberBox<Integer>(n_int));
250+ assertThat(row.get(1, new TypeToken<NumberBox<Long>>() {})).isEqualTo(new NumberBox<Long>(n_bigint));
251+ assertThat(row.get(2, new TypeToken<NumberBox<Float>>() {})).isEqualTo(new NumberBox<Float>(n_float));
252+ assertThat(row.get(3, new TypeToken<NumberBox<Double>>() {})).isEqualTo(new NumberBox<Double>(n_double));
253+ assertThat(row.get(4, new TypeToken<NumberBox<BigInteger>>() {})).isEqualTo(new NumberBox<BigInteger>(n_varint));
254+ assertThat(row.get(5, new TypeToken<NumberBox<BigDecimal>>() {})).isEqualTo(new NumberBox<BigDecimal>(n_decimal));
255+ }
256+
257+ private class NumberBoxCodec<T extends Number> extends TypeCodec<NumberBox<T>> {
258+
259+ private final TypeCodec<T> numberCodec;
260+
261+ protected NumberBoxCodec(TypeCodec<T> numberCodec) {
262+ super(numberCodec.getCqlType(), new TypeToken<NumberBox<T>>(){}.where(new TypeParameter<T>(){}, numberCodec.getJavaType()));
263+ this.numberCodec = numberCodec;
264+ }
265+
266+ public boolean accepts(Object value) {
267+ return value instanceof NumberBox && numberCodec.accepts(((NumberBox)value).getNumber());
268+ }
269+
270+ @Override
271+ public ByteBuffer serialize(NumberBox<T> value, ProtocolVersion protocolVersion) throws InvalidTypeException {
272+ return numberCodec.serialize(value.getNumber(), protocolVersion);
273+ }
274+
275+ @Override
276+ public NumberBox<T> deserialize(ByteBuffer bytes, ProtocolVersion protocolVersion) throws InvalidTypeException {
277+ return new NumberBox<T>(numberCodec.deserialize(bytes, protocolVersion));
278+ }
279+
280+ @Override
281+ public NumberBox<T> parse(String value) throws InvalidTypeException {
282+ return new NumberBox<T>(numberCodec.parse(value));
283+ }
284+
285+ @Override
286+ public String format(NumberBox<T> value) throws InvalidTypeException {
287+ return numberCodec.format(value.getNumber());
288+ }
289+
290+ }
291+
292+ private class NumberBox<T extends Number> {
293+
294+ private final T number;
295+
296+ private NumberBox(T number) {
297+ this.number = number;
298+ }
299+
300+ public T getNumber() {
301+ return number;
302+ }
303+
304+ @Override
305+ public boolean equals(Object o) {
306+ if (this == o)
307+ return true;
308+ if (o == null || getClass() != o.getClass())
309+ return false;
310+ NumberBox numberBox = (NumberBox)o;
311+ return Objects.equal(number, numberBox.number);
312+ }
313+
314+ @Override
315+ public int hashCode() {
316+ return Objects.hashCode(number);
317+ }
318+ }
319+}
added driver-core/src/test/java/com/datastax/driver/core/TypeCodecEnumIntegrationTest.java +199 −0
@@ -0,0 +1,199 @@
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.Collection;
19+import java.util.List;
20+import java.util.Map;
21+import java.util.Set;
22+
23+import com.google.common.collect.ImmutableMap;
24+import com.google.common.reflect.TypeToken;
25+import org.testng.annotations.BeforeMethod;
26+import org.testng.annotations.Test;
27+
28+import static com.google.common.collect.Lists.newArrayList;
29+import static com.google.common.collect.Sets.newHashSet;
30+import static org.assertj.core.api.Assertions.assertThat;
31+
32+import com.datastax.driver.core.TypeCodec.EnumIntCodec;
33+import com.datastax.driver.core.utils.CassandraVersion;
34+
35+import static com.datastax.driver.core.DataType.cint;
36+import static com.datastax.driver.core.DataType.text;
37+import static com.datastax.driver.core.TypeCodecEnumIntegrationTest.Foo.*;
38+import static com.datastax.driver.core.TypeCodecEnumIntegrationTest.Bar.*;
39+
40+/**
41+ * A test that validates that Enums are correctly mapped to varchars (with the default EnumStringCodec)
42+ * or alternatively to ints (with the alternative EnumIntCodec).
43+ * It also validates that both codecs may coexist in the same CodecRegistry.
44+ */
45+@CassandraVersion(major=2.1)
46+public class TypeCodecEnumIntegrationTest extends CCMBridge.PerClassSingleNodeCluster {
47+
48+ private final String insertQuery = "INSERT INTO \"myTable\" (pk, foo, foos, bar, bars, foobars, tup, udt) VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
49+
50+ private final String selectQuery = "SELECT pk, foo, foos, bar, bars, foobars, tup, udt FROM \"myTable\" WHERE pk = ?";
51+
52+ private final int pk = 42;
53+
54+ private final List<Foo> foos = newArrayList(FOO_1, FOO_2);
55+ private final Set<Bar> bars = newHashSet(BAR_1, BAR_2);
56+ private final Map<Foo, Bar> foobars = ImmutableMap.of(FOO_1, BAR_1, FOO_2, BAR_2);
57+
58+ private TupleValue tupleValue;
59+ private UDTValue udtValue;
60+
61+ @Override
62+ protected Collection<String> getTableDefinitions() {
63+ return newArrayList(
64+ "CREATE TYPE IF NOT EXISTS \"myType\" ("
65+ + "foo int,"
66+ + "bar text)",
67+ "CREATE TABLE IF NOT EXISTS \"myTable\" ("
68+ + "pk int PRIMARY KEY, "
69+ + "foo int, "
70+ + "foos list<int>, "
71+ + "bar text, "
72+ + "bars set<text>, "
73+ + "foobars map<int,text>, "
74+ + "tup frozen<tuple<int,varchar>>, "
75+ + "udt frozen<\"myType\">"
76+ + ")"
77+ );
78+ }
79+
80+ @Override
81+ protected Cluster.Builder configure(Cluster.Builder builder) {
82+ // explicitly register an EnumIntCodec for Foo enums
83+ // Bar enums will use the default EnumStringCodec so it doesn't need to be explicitly registered.
84+ return builder.withCodecRegistry(
85+ new CodecRegistry().register(new EnumIntCodec<Foo>(Foo.class))
86+ );
87+ }
88+
89+ @BeforeMethod(groups="short")
90+ public void before() {
91+ TupleType tup = cluster.getMetadata().newTupleType(cint(), text());
92+ tupleValue = tup.newValue()
93+ .set(0, FOO_1, Foo.class)
94+ .set(1, BAR_1, Bar.class);
95+ UserType udt = cluster.getMetadata().getKeyspace(keyspace).getUserType("\"myType\"");
96+ udtValue = udt.newValue()
97+ .set("foo", FOO_1, Foo.class)
98+ .set("bar", BAR_1, Bar.class);
99+ }
100+
101+ @Test(groups = "short")
102+ public void should_use_enum_codecs_with_simple_statements() {
103+ session.execute(insertQuery, pk, FOO_1, foos, BAR_1, bars, foobars, tupleValue, udtValue);
104+ ResultSet rows = session.execute(selectQuery, pk);
105+ Row row = rows.one();
106+ assertRow(row);
107+ }
108+
109+ @Test(groups = "short")
110+ public void should_use_enum_codecs_with_prepared_statements_1() {
111+ session.execute(session.prepare(insertQuery).bind(pk, FOO_1, foos, BAR_1, bars, foobars, tupleValue, udtValue));
112+ PreparedStatement ps = session.prepare(selectQuery);
113+ ResultSet rows = session.execute(ps.bind(pk));
114+ Row row = rows.one();
115+ assertRow(row);
116+ }
117+
118+ @Test(groups = "short")
119+ public void should_use_enum_codecs_with_prepared_statements_2() {
120+ session.execute(session.prepare(insertQuery).bind()
121+ .setInt(0, pk)
122+ .set(1, FOO_1, Foo.class)
123+ .setList(2, foos, Foo.class)
124+ .set(3, BAR_1, Bar.class)
125+ .set(4, bars, new TypeToken<Set<Bar>>(){})
126+ .setMap(5, foobars, Foo.class, Bar.class)
127+ .setTupleValue(6, tupleValue)
128+ .setUDTValue(7, udtValue)
129+ );
130+ PreparedStatement ps = session.prepare(selectQuery);
131+ ResultSet rows = session.execute(ps.bind()
132+ .setInt(0, pk)
133+ );
134+ Row row = rows.one();
135+ assertRow(row);
136+ }
137+
138+ private void assertRow(Row row) {
139+
140+ assertThat(row.getInt(0)).isEqualTo(pk);
141+
142+ assertThat(row.getObject(1)).isEqualTo(FOO_1.ordinal()); // uses the built-in IntCodec because CQL type is int
143+ assertThat(row.getInt("foo")).isEqualTo(FOO_1.ordinal()); // uses the built-in IntCodec
144+ assertThat(row.get(1, Integer.class)).isEqualTo(FOO_1.ordinal()); // forces IntCodec
145+ assertThat(row.get("foo", Foo.class)).isEqualTo(FOO_1); // forces EnumIntCodec
146+
147+ assertThat(row.getObject(2)).isEqualTo(newArrayList(FOO_1.ordinal(), FOO_2.ordinal())); // uses the built-in ListCodec(IntCodec) because CQL type is list<int>
148+ assertThat(row.getList(2, Integer.class)).isEqualTo(newArrayList(FOO_1.ordinal(), FOO_2.ordinal()));
149+ assertThat(row.getList("foos", Foo.class)).isEqualTo(newArrayList(FOO_1, FOO_2));
150+ assertThat(row.get(2, new TypeToken<List<Integer>>(){})).isEqualTo(newArrayList(FOO_1.ordinal(), FOO_2.ordinal()));
151+ assertThat(row.get("foos", new TypeToken<List<Foo>>(){})).isEqualTo(newArrayList(FOO_1, FOO_2));
152+
153+ assertThat(row.getObject(3)).isEqualTo(BAR_1.name()); // uses the built-in VarcharCodec because CQL type is varchar
154+ assertThat(row.getString("bar")).isEqualTo(BAR_1.name()); // forces VarcharCodec
155+ assertThat(row.get(3, String.class)).isEqualTo(BAR_1.name()); // forces VarcharCodec
156+ assertThat(row.get("bar", Bar.class)).isEqualTo(BAR_1); // forces EnumStringCodec
157+
158+ assertThat(row.getObject(4)).isEqualTo(newHashSet(BAR_1.name(), BAR_2.name())); // uses the built-in SetCodec(VarcharCodec) because CQL type is set<varchar>
159+ assertThat(row.getSet(4, String.class)).isEqualTo(newHashSet(BAR_1.name(), BAR_2.name()));
160+ assertThat(row.getSet("bars", Bar.class)).isEqualTo(newHashSet(BAR_1, BAR_2));
161+ assertThat(row.get(4, new TypeToken<Set<String>>(){})).isEqualTo(newHashSet(BAR_1.name(), BAR_2.name()));
162+ assertThat(row.get("bars", new TypeToken<Set<Bar>>(){})).isEqualTo(newHashSet(BAR_1, BAR_2));
163+
164+ // uses default built-in codec MapCodec(IntCodec, VarcharCodec) because CQL type is map<int, varchar>
165+ assertThat(row.getObject(5)).isEqualTo(ImmutableMap.of(FOO_1.ordinal(), BAR_1.name(), FOO_2.ordinal(), BAR_2.name()));
166+
167+ // getMap with combinations of built-in or EnumX codecs
168+ assertThat(row.getMap(5, Integer.class, String.class)).isEqualTo(ImmutableMap.of(FOO_1.ordinal(), BAR_1.name(), FOO_2.ordinal(), BAR_2.name()));
169+ assertThat(row.getMap(5, Foo.class, String.class)).isEqualTo(ImmutableMap.of(FOO_1, BAR_1.name(), FOO_2, BAR_2.name()));
170+ assertThat(row.getMap(5, Integer.class, Bar.class)).isEqualTo(ImmutableMap.of(FOO_1.ordinal(), BAR_1, FOO_2.ordinal(), BAR_2));
171+ assertThat(row.getMap(5, Foo.class, Bar.class)).isEqualTo(ImmutableMap.of(FOO_1, BAR_1, FOO_2, BAR_2));
172+
173+ // get + TypeToken with combinations of built-in or EnumX codecs
174+ assertThat(row.get("foobars", new TypeToken<Map<Integer, String>>(){})).isEqualTo(ImmutableMap.of(FOO_1.ordinal(), BAR_1.name(), FOO_2.ordinal(), BAR_2.name()));
175+ assertThat(row.get("foobars", new TypeToken<Map<Foo, String>>(){})).isEqualTo(ImmutableMap.of(FOO_1, BAR_1.name(), FOO_2, BAR_2.name()));
176+ assertThat(row.get("foobars", new TypeToken<Map<Integer, Bar>>(){})).isEqualTo(ImmutableMap.of(FOO_1.ordinal(), BAR_1, FOO_2.ordinal(), BAR_2));
177+ assertThat(row.get("foobars", new TypeToken<Map<Foo, Bar>>(){})).isEqualTo(ImmutableMap.of(FOO_1, BAR_1, FOO_2, BAR_2));
178+
179+ assertThat(row.getTupleValue(6).getInt(0)).isEqualTo(FOO_1.ordinal());
180+ assertThat(row.get(6, TupleValue.class).get(0, Foo.class)).isEqualTo(FOO_1);
181+ assertThat(row.getTupleValue("tup").getString(1)).isEqualTo(BAR_1.name());
182+ assertThat(row.get("tup", TupleValue.class).get(1, Bar.class)).isEqualTo(BAR_1);
183+
184+ assertThat(row.getUDTValue(7).getInt("foo")).isEqualTo(FOO_1.ordinal());
185+ assertThat(row.get(7, UDTValue.class).get("foo", Foo.class)).isEqualTo(FOO_1);
186+ assertThat(row.getUDTValue("udt").getString("bar")).isEqualTo(BAR_1.name());
187+ assertThat(row.get("udt", UDTValue.class).get("bar", Bar.class)).isEqualTo(BAR_1);
188+
189+ }
190+
191+ enum Foo {
192+ FOO_1, FOO_2
193+ }
194+
195+ enum Bar {
196+ BAR_1, BAR_2
197+ }
198+
199+}
added driver-core/src/test/java/com/datastax/driver/core/TypeCodecJodaIntegrationTest.java +175 −0
@@ -0,0 +1,175 @@
1+/*
2+ * Copyright (C) 2012-2015 DataStax Inc.
3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ */
16+package com.datastax.driver.core;
17+
18+import com.datastax.driver.core.utils.CassandraVersion;
19+import org.joda.time.DateTime;
20+import org.joda.time.DateTimeZone;
21+import org.joda.time.LocalTime;
22+import org.testng.annotations.Test;
23+
24+import java.util.Collection;
25+import java.util.Collections;
26+import java.util.Date;
27+import java.util.concurrent.TimeUnit;
28+
29+import static org.assertj.core.api.Assertions.assertThat;
30+
31+import static com.datastax.driver.core.DataType.*;
32+
33+@CassandraVersion(major=2.2)
34+public class TypeCodecJodaIntegrationTest extends CCMBridge.PerClassSingleNodeCluster {
35+ @Override
36+ protected Collection<String> getTableDefinitions() {
37+ return Collections.singletonList(
38+ "CREATE TABLE IF NOT EXISTS foo (c1 text PRIMARY KEY, " +
39+ "cd date, ctime time, " +
40+ "ctimestamp timestamp, " +
41+ "ctuple tuple<timestamp,varchar>)");
42+ }
43+
44+ @Override
45+ protected Cluster.Builder configure(Cluster.Builder builder) {
46+ return builder.withCodecRegistry(JodaCodecs.withCodecs(new CodecRegistry()));
47+ }
48+
49+ /**
50+ * <p>
51+ * Validates that a <code>time</code> column can be mapped to a {@link LocalTime} by using
52+ * {@link com.datastax.driver.core.JodaCodecs.LocalTimeCodec}.
53+ * </p>
54+ *
55+ * @test_category data_types:serialization
56+ * @expected_result properly maps.
57+ * @jira_ticket JAVA-721
58+ * @since 2.2.0
59+ */
60+ @Test(groups="short")
61+ public void should_map_time_to_localtime() {
62+ long lTime =
63+ TimeUnit.HOURS.toNanos(12) +
64+ TimeUnit.MINUTES.toNanos(16) +
65+ TimeUnit.SECONDS.toNanos(34) +
66+ TimeUnit.MILLISECONDS.toNanos(999);
67+ LocalTime time = new LocalTime(12, 16, 34, 999);
68+
69+ session.execute("insert into foo (c1, ctime) values (?, ?)", "should_map_time_to_localtime", time);
70+
71+ ResultSet result = session.execute("select ctime from foo where c1=?", "should_map_time_to_localtime");
72+
73+ assertThat(result.getAvailableWithoutFetching()).isEqualTo(1);
74+
75+ Row row = result.one();
76+ assertThat(row.get("ctime", LocalTime.class)).isEqualTo(time);
77+ assertThat(row.getTime("ctime")).isEqualTo(lTime);
78+ }
79+
80+ /**
81+ * <p>
82+ * Validates that a <code>date</code> column can be mapped to a {@link org.joda.time.LocalDate} by using
83+ * {@link com.datastax.driver.core.JodaCodecs.LocalDateCodec}.
84+ * </p>
85+ *
86+ * @test_category data_types:serialization
87+ * @expected_result properly maps.
88+ * @jira_ticket JAVA-721
89+ * @since 2.2.0
90+ */
91+ @Test(groups="short")
92+ public void should_map_date_to_localdate() {
93+ org.joda.time.LocalDate date = new org.joda.time.LocalDate(2015, 1, 1);
94+ LocalDate lDate = LocalDate.fromYearMonthDay(2015, 1, 1);
95+
96+ session.execute("insert into foo (c1, cd) values (?, ?)", "should_map_date_to_localdate", date);
97+
98+ ResultSet result = session.execute("select cd from foo where c1=?", "should_map_date_to_localdate");
99+
100+ assertThat(result.getAvailableWithoutFetching()).isEqualTo(1);
101+
102+ Row row = result.one();
103+ assertThat(row.get("cd", org.joda.time.LocalDate.class)).isEqualTo(date);
104+ assertThat(row.getDate("cd")).isEqualTo(lDate);
105+ }
106+
107+
108+ /**
109+ * <p>
110+ * Validates that a <code>timestamp</code> column can be mapped to a {@link DateTime} by using
111+ * {@link com.datastax.driver.core.JodaCodecs.DateTimeCodec}.
112+ * </p>
113+ *
114+ * @test_category data_types:serialization
115+ * @expected_result properly maps.
116+ * @jira_ticket JAVA-721
117+ * @since 2.2.0
118+ */
119+ @Test(groups="short")
120+ public void should_map_timestamp_to_datetime() {
121+ DateTime dateTime = DateTime.parse("2010-06-30T01:20+05:00");
122+ Date date = dateTime.toDate();
123+ DateTimeZone timeZone = dateTime.getZone();
124+
125+ session.execute("insert into foo (c1, ctimestamp) values (?, ?)", "should_map_timestamp_to_datetime", dateTime);
126+
127+ ResultSet result = session.execute("select ctimestamp from foo where c1=?", "should_map_timestamp_to_datetime");
128+
129+ assertThat(result.getAvailableWithoutFetching()).isEqualTo(1);
130+
131+ Row row = result.one();
132+ // Since timezone is not preserved in timestamp type, set it.
133+ DateTime rDateTime = row.get("ctimestamp", DateTime.class).withZone(timeZone);
134+ assertThat(rDateTime).isEqualTo(dateTime);
135+ assertThat(row.getTimestamp("ctimestamp")).isEqualTo(date);
136+ }
137+
138+
139+ /**
140+ * <p>
141+ * Validates that a <code>tuple&lt;timestamp,text&gt;</code> column can be mapped to a {@link DateTime} by using
142+ * {@link com.datastax.driver.core.JodaCodecs.TimeZonePreservingDateTimeCodec}.
143+ * </p>
144+ *
145+ * @test_category data_types:serialization
146+ * @expected_result properly maps.
147+ * @jira_ticket JAVA-721
148+ * @since 2.2.0
149+ */
150+ @Test(groups="short")
151+ public void should_map_tuple_to_datetime() {
152+ // Register codec that maps DateTime <-> tuple<timestamp,varchar>
153+ TupleType dateWithTimeZoneType = cluster.getMetadata().newTupleType(timestamp(), varchar());
154+ JodaCodecs.TimeZonePreservingDateTimeCodec dateTimeCodec = new JodaCodecs.TimeZonePreservingDateTimeCodec(new TypeCodec.TupleCodec(dateWithTimeZoneType));
155+ cluster.getConfiguration().getCodecRegistry().register(dateTimeCodec);
156+
157+ DateTime dateTime = DateTime.parse("2010-06-30T01:20+05:30");
158+ DateTimeZone timeZone = dateTime.getZone();
159+
160+ PreparedStatement insertStmt = session.prepare("insert into foo (c1, ctuple) values (?, ?)");
161+ session.execute(insertStmt.bind("should_map_tuple_to_datetime", dateTime));
162+
163+ ResultSet result = session.execute("select ctuple from foo where c1=?", "should_map_tuple_to_datetime");
164+
165+ assertThat(result.getAvailableWithoutFetching()).isEqualTo(1);
166+
167+ Row row = result.one();
168+ DateTime rDateTime = row.get("ctuple", DateTime.class);
169+ // Since timezone is preserved in the tuple, the date times should match perfectly.
170+ assertThat(rDateTime).isEqualTo(dateTime);
171+ // Ensure the timezones match as well.
172+ // (This is just a safety check as the previous assert would have failed otherwise).
173+ assertThat(rDateTime.getZone()).isEqualTo(timeZone);
174+ }
175+}
added driver-core/src/test/java/com/datastax/driver/core/TypeCodecJsonIntegrationTest.java +163 −0
@@ -0,0 +1,163 @@
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.ArrayList;
19+import java.util.Collection;
20+
21+import com.google.common.collect.Lists;
22+import org.testng.annotations.Test;
23+
24+import static org.assertj.core.api.Assertions.assertThat;
25+
26+import com.datastax.driver.core.TypeCodecTest.User;
27+import com.datastax.driver.core.querybuilder.BuiltStatement;
28+import com.datastax.driver.core.querybuilder.QueryBuilder;
29+import com.datastax.driver.core.utils.CassandraVersion;
30+
31+import static com.datastax.driver.core.querybuilder.QueryBuilder.bindMarker;
32+import static com.datastax.driver.core.querybuilder.QueryBuilder.eq;
33+
34+public class TypeCodecJsonIntegrationTest extends CCMBridge.PerClassSingleNodeCluster {
35+
36+ private static final JsonCodec<User> jsonCodec = new JsonCodec<User>(User.class);
37+
38+ private static final User alice = new User(1, "Alice");
39+ private static final User bob = new User(2, "Bob");
40+ private static final User charlie = new User(3, "Charlie");
41+
42+ private static final String bobJson = "{\"id\":2,\"name\":\"Bob\"}";
43+ private static final String charlieJson = "{\"id\":3,\"name\":\"Charlie\"}";
44+ private static final String aliceJson = "{\"id\":1,\"name\":\"Alice\"}";
45+
46+ private static final ArrayList<User> bobAndCharlie = Lists.newArrayList(bob, charlie);
47+
48+ private static final String insertQuery = "INSERT INTO \"myTable\" (c1, c2, c3) VALUES (?, ?, ?)";
49+ private static final String selectQuery = "SELECT c1, c2, c3 FROM \"myTable\" WHERE c1 = ? and c2 = ?";
50+
51+ private static final String notAJsonString = "this text is not json";
52+
53+ @Override
54+ protected Collection<String> getTableDefinitions() {
55+ return Lists.newArrayList(
56+ "CREATE TABLE \"myTable\" (c1 text, c2 text, c3 list<text>, PRIMARY KEY (c1, c2))"
57+ );
58+ }
59+
60+ @Override
61+ protected Cluster.Builder configure(Cluster.Builder builder) {
62+ return builder.withCodecRegistry(
63+ new CodecRegistry().register(jsonCodec) // global User <-> varchar codec
64+ );
65+ }
66+
67+ @Test(groups = "short")
68+ @CassandraVersion(major=2.0)
69+ public void should_use_custom_codec_with_simple_statements() {
70+ session.execute(insertQuery, notAJsonString, alice, bobAndCharlie);
71+ ResultSet rows = session.execute(selectQuery, notAJsonString, alice);
72+ Row row = rows.one();
73+ assertRow(row);
74+ }
75+
76+ @Test(groups = "short")
77+ public void should_use_custom_codec_with_built_statements_1() {
78+ BuiltStatement insertStmt = new QueryBuilder(cluster).insertInto("\"myTable\"")
79+ .value("c1", bindMarker())
80+ .value("c2", bindMarker())
81+ .value("c3", bindMarker());
82+ BuiltStatement selectStmt = new QueryBuilder(cluster).select("c1", "c2", "c3")
83+ .from("\"myTable\"")
84+ .where(eq("c1", bindMarker()))
85+ .and(eq("c2", bindMarker()));
86+ session.execute(session.prepare(insertStmt).bind(notAJsonString, alice, bobAndCharlie));
87+ ResultSet rows = session.execute(session.prepare(selectStmt).bind(notAJsonString, alice));
88+ Row row = rows.one();
89+ assertRow(row);
90+ }
91+
92+ @Test(groups = "short")
93+ public void should_use_custom_codec_with_built_statements_2() {
94+ BuiltStatement insertStmt = new QueryBuilder(cluster).insertInto("\"myTable\"")
95+ .value("c1", notAJsonString)
96+ .value("c2", alice)
97+ .value("c3", bobAndCharlie);
98+ BuiltStatement selectStmt =
99+ new QueryBuilder(cluster).select("c1", "c2", "c3")
100+ .from("\"myTable\"")
101+ .where(eq("c1", notAJsonString))
102+ .and(eq("c2", alice));
103+ session.execute(insertStmt);
104+ ResultSet rows = session.execute(selectStmt);
105+ Row row = rows.one();
106+ assertRow(row);
107+ }
108+
109+ @Test(groups = "short")
110+ public void should_use_custom_codec_with_prepared_statements_1() {
111+ session.execute(session.prepare(insertQuery).bind(notAJsonString, alice, bobAndCharlie));
112+ PreparedStatement ps = session.prepare(selectQuery);
113+ // this bind() method does not convey information about the java type of alice
114+ // so the registry will look for a codec accepting varchar <-> ANY
115+ // and will find jsonCodec because it is the first registered
116+ ResultSet rows = session.execute(ps.bind(notAJsonString, alice));
117+ Row row = rows.one();
118+ assertRow(row);
119+ }
120+
121+ @Test(groups = "short")
122+ public void should_use_custom_codec_with_prepared_statements_2() {
123+ session.execute(session.prepare(insertQuery).bind()
124+ .setString(0, notAJsonString)
125+ .set(1, alice, User.class)
126+ .setList(2, bobAndCharlie)
127+ );
128+ PreparedStatement ps = session.prepare(selectQuery);
129+ ResultSet rows = session.execute(ps.bind()
130+ .setString(0, notAJsonString)
131+ // this set() method conveys information about the java type of alice
132+ // so the registry will look for a codec accepting varchar <-> User
133+ // and will find jsonCodec because it is the only matching one
134+ .set(1, alice, User.class)
135+ );
136+ Row row = rows.one();
137+ assertRow(row);
138+ rows = session.execute(ps.bind()
139+ .setString(0, notAJsonString)
140+ // here we lost information about the java type of alice
141+ // so the registry will look for a codec accepting varchar <-> ANY
142+ // and will find jsonCodec because it is the only matching one
143+ .setObject(1, alice)
144+ );
145+ row = rows.one();
146+ assertRow(row);
147+ }
148+
149+ private void assertRow(Row row) {
150+ // getString requires a codec accepting varchar <-> String, so VarcharCodec is used
151+ assertThat(row.getString(0)).isEqualTo(notAJsonString);
152+ // getObject requires a codec accepting varchar <-> ANY;
153+ // the first codec that accepts that is jsonCodec, so it is used
154+ assertThat(row.getObject(1)).isEqualTo(aliceJson);
155+ // getObject uses the default codec VarcharCodec
156+ assertThat(row.get(1, User.class)).isEqualTo(alice);
157+ // we still can get the column as a string using VarcharCodec.instance behind the scenes
158+ assertThat(row.getString(1)).isEqualTo(aliceJson);
159+ assertThat(row.getList(2, User.class)).containsExactly(bob, charlie);
160+ // we still can get the column as a List<String>
161+ assertThat(row.getList(2, String.class)).containsExactly(bobJson, charlieJson);
162+ }
163+}
added driver-core/src/test/java/com/datastax/driver/core/TypeCodecNestedCollectionsIntegrationTest.java +223 −0
@@ -0,0 +1,223 @@
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.nio.ByteBuffer;
19+import java.util.*;
20+
21+import com.google.common.base.Objects;
22+import com.google.common.collect.ImmutableMap;
23+import com.google.common.reflect.TypeToken;
24+import org.testng.annotations.BeforeClass;
25+import org.testng.annotations.BeforeMethod;
26+import org.testng.annotations.Test;
27+
28+import static com.google.common.collect.Lists.newArrayList;
29+import static org.assertj.core.api.Assertions.assertThat;
30+
31+import com.datastax.driver.core.exceptions.InvalidTypeException;
32+import com.datastax.driver.core.querybuilder.BuiltStatement;
33+import com.datastax.driver.core.querybuilder.QueryBuilder;
34+import com.datastax.driver.core.utils.CassandraVersion;
35+
36+import static com.datastax.driver.core.querybuilder.QueryBuilder.bindMarker;
37+import static com.datastax.driver.core.querybuilder.QueryBuilder.eq;
38+
39+/**
40+ * Validates that nested collections are properly encoded,
41+ * even if some inner type requires a custom codec.
42+ */
43+@CassandraVersion(major=2.1)
44+public class TypeCodecNestedCollectionsIntegrationTest extends CCMBridge.PerClassSingleNodeCluster {
45+
46+ private final String insertQuery = "INSERT INTO \"myTable\" (pk, v) VALUES (?, ?)";
47+
48+ private final String selectQuery = "SELECT pk, v FROM \"myTable\" WHERE pk = ?";
49+
50+ private BuiltStatement insertStmt;
51+ private BuiltStatement selectStmt;
52+
53+ private int pk = 42;
54+ private List<Set<Map<MyInt, String>>> v;
55+
56+ private TypeToken<List<Set<Map<MyInt, String>>>> listType = new TypeToken<List<Set<Map<MyInt, String>>>>(){};
57+ private TypeToken<Set<Map<MyInt, String>>> elementsType = new TypeToken<Set<Map<MyInt, String>>>(){};
58+
59+ @Override
60+ protected Collection<String> getTableDefinitions() {
61+ return newArrayList(
62+ "CREATE TABLE IF NOT EXISTS \"myTable\" ("
63+ + "pk int PRIMARY KEY, "
64+ + "v frozen<list<frozen<set<frozen<map<int,text>>>>>>"
65+ + ")"
66+ );
67+ }
68+
69+ @Override
70+ protected Cluster.Builder configure(Cluster.Builder builder) {
71+ return builder.withCodecRegistry(
72+ new CodecRegistry().register(new MyIntCodec()) // global User <-> varchar codec
73+ );
74+ }
75+
76+ @BeforeClass(groups = "short")
77+ public void setupData() {
78+ Map<MyInt, String> map = ImmutableMap.of(new MyInt(42), "foo", new MyInt(43), "bar");
79+ Set<Map<MyInt, String>> set = new HashSet<Map<MyInt, String>>();
80+ set.add(map);
81+ v = new ArrayList<Set<Map<MyInt, String>>>();
82+ v.add(set);
83+ }
84+
85+ @BeforeMethod(groups = "short")
86+ public void createBuiltStatements() throws Exception {
87+ insertStmt = new QueryBuilder(cluster).insertInto("\"myTable\"")
88+ .value("pk", bindMarker())
89+ .value("v", bindMarker());
90+ selectStmt = new QueryBuilder(cluster).select("pk", "v")
91+ .from("\"myTable\"")
92+ .where(eq("pk", bindMarker()));
93+ }
94+
95+ @Test(groups = "short")
96+ public void should_work_with_simple_statements() {
97+ session.execute(insertQuery, pk, v);
98+ ResultSet rows = session.execute(selectQuery, pk);
99+ Row row = rows.one();
100+ assertRow(row);
101+ }
102+
103+ @Test(groups = "short")
104+ public void should_work_with_prepared_statements_1() {
105+ session.execute(session.prepare(insertQuery).bind(pk, v));
106+ PreparedStatement ps = session.prepare(selectQuery);
107+ ResultSet rows = session.execute(ps.bind(pk));
108+ Row row = rows.one();
109+ assertRow(row);
110+ }
111+
112+ @Test(groups = "short")
113+ public void should_work_with_prepared_statements_2() {
114+ session.execute(session.prepare(insertQuery).bind()
115+ .setInt(0, pk)
116+ .setList(1, v, elementsType) // variant with element type explicitly set
117+ );
118+ PreparedStatement ps = session.prepare(selectQuery);
119+ ResultSet rows = session.execute(ps.bind()
120+ .setInt(0, pk)
121+ );
122+ Row row = rows.one();
123+ assertRow(row);
124+ }
125+
126+ @Test(groups = "short")
127+ public void should_work_with_prepared_statements_3() {
128+ session.execute(session.prepare(insertQuery).bind()
129+ .setInt(0, pk)
130+ .setObject(1, v)
131+ );
132+ PreparedStatement ps = session.prepare(selectQuery);
133+ ResultSet rows = session.execute(ps.bind()
134+ .setInt(0, pk)
135+ );
136+ Row row = rows.one();
137+ assertRow(row);
138+ }
139+
140+ @Test(groups = "short")
141+ public void should_work_with_prepared_statements_4() {
142+ session.execute(session.prepare(insertQuery).bind()
143+ .setInt(0, pk)
144+ .set(1, v, listType)
145+ );
146+ PreparedStatement ps = session.prepare(selectQuery);
147+ ResultSet rows = session.execute(ps.bind()
148+ .setInt(0, pk)
149+ );
150+ Row row = rows.one();
151+ assertRow(row);
152+ }
153+
154+ @Test(groups = "short")
155+ public void should_work_with_built_statements() {
156+ session.execute(session.prepare(insertStmt).bind()
157+ .setInt(0, pk)
158+ .set(1, v, listType)
159+ );
160+ PreparedStatement ps = session.prepare(selectStmt);
161+ ResultSet rows = session.execute(ps.bind()
162+ .setInt(0, pk)
163+ );
164+ Row row = rows.one();
165+ assertRow(row);
166+ }
167+
168+ private void assertRow(Row row) {
169+ assertThat(row.getList(1, elementsType)).isEqualTo(v);
170+ assertThat(row.get(1, listType)).isEqualTo(v);
171+ }
172+
173+ private class MyInt {
174+
175+ private final int i;
176+
177+ private MyInt(int i) {
178+ this.i = i;
179+ }
180+
181+ @Override
182+ public boolean equals(Object o) {
183+ if (this == o)
184+ return true;
185+ if (o == null || getClass() != o.getClass())
186+ return false;
187+ MyInt myInt = (MyInt)o;
188+ return Objects.equal(i, myInt.i);
189+ }
190+
191+ @Override
192+ public int hashCode() {
193+ return Objects.hashCode(i);
194+ }
195+ }
196+
197+ private class MyIntCodec extends TypeCodec<MyInt> {
198+
199+ MyIntCodec() {
200+ super(DataType.cint(), MyInt.class);
201+ }
202+
203+ @Override
204+ public ByteBuffer serialize(MyInt value, ProtocolVersion protocolVersion) throws InvalidTypeException {
205+ return IntCodec.instance.serialize(value.i, protocolVersion);
206+ }
207+
208+ @Override
209+ public MyInt deserialize(ByteBuffer bytes, ProtocolVersion protocolVersion) throws InvalidTypeException {
210+ return new MyInt(IntCodec.instance.deserialize(bytes, protocolVersion));
211+ }
212+
213+ @Override
214+ public MyInt parse(String value) throws InvalidTypeException {
215+ return null; // not tested
216+ }
217+
218+ @Override
219+ public String format(MyInt value) throws InvalidTypeException {
220+ return null; // not tested
221+ }
222+ }
223+}
added driver-core/src/test/java/com/datastax/driver/core/TypeCodecNumbersIntegrationTest.java +155 −0
@@ -0,0 +1,155 @@
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.math.BigDecimal;
19+import java.math.BigInteger;
20+import java.util.Collection;
21+
22+import org.testng.annotations.Test;
23+
24+import static com.google.common.collect.Lists.newArrayList;
25+import static org.assertj.core.api.Assertions.assertThat;
26+
27+import com.datastax.driver.core.utils.CassandraVersion;
28+
29+public class TypeCodecNumbersIntegrationTest extends CCMBridge.PerClassSingleNodeCluster{
30+
31+ private final String insertQuery = "INSERT INTO \"myTable\" (c_int, c_bigint, c_float, c_double, c_varint, c_decimal) VALUES (?, ?, ?, ?, ?, ?)";
32+
33+ private final String selectQuery = "SELECT c_int, c_bigint, c_float, c_double, c_varint, c_decimal FROM \"myTable\" WHERE c_int = ? and c_bigint = ?";
34+
35+ private int n_int = 42;
36+ private long n_bigint = 4242;
37+ private float n_float = 42.42f;
38+ private double n_double = 4242.42d;
39+ private BigInteger n_varint = new BigInteger("424242");
40+ private BigDecimal n_decimal = new BigDecimal("424242.42");
41+
42+
43+ @Override
44+ protected Collection<String> getTableDefinitions() {
45+ return newArrayList(
46+ "CREATE TABLE \"myTable\" ("
47+ + "c_int int, "
48+ + "c_bigint bigint, "
49+ + "c_float float, "
50+ + "c_double double, "
51+ + "c_varint varint, "
52+ + "c_decimal decimal, "
53+ + "PRIMARY KEY (c_int, c_bigint)"
54+ + ")"
55+ );
56+ }
57+
58+ @Test(groups = "short")
59+ @CassandraVersion(major=2.0)
60+ public void should_use_defaut_codecs_with_simple_statements() {
61+ session.execute(insertQuery, n_int, n_bigint, n_float, n_double, n_varint, n_decimal);
62+ ResultSet rows = session.execute(selectQuery, n_int, n_bigint);
63+ Row row = rows.one();
64+ assertRow(row);
65+ }
66+
67+ @Test(groups = "short")
68+ public void should_use_defaut_codecs_with_prepared_statements_1() {
69+ session.execute(session.prepare(insertQuery).bind(n_int, n_bigint, n_float, n_double, n_varint, n_decimal));
70+ PreparedStatement ps = session.prepare(selectQuery);
71+ ResultSet rows = session.execute(ps.bind(n_int, n_bigint));
72+ Row row = rows.one();
73+ assertRow(row);
74+ }
75+
76+ @Test(groups = "short")
77+ public void should_use_default_codecs_with_prepared_statements_2() {
78+ session.execute(session.prepare(insertQuery).bind()
79+ .setInt(0, n_int)
80+ .setLong(1, n_bigint)
81+ .setFloat(2, n_float)
82+ .setDouble(3, n_double)
83+ .setVarint(4, n_varint)
84+ .setDecimal(5, n_decimal)
85+ );
86+ PreparedStatement ps = session.prepare(selectQuery);
87+ ResultSet rows = session.execute(ps.bind()
88+ .setInt(0, n_int)
89+ .setLong(1, n_bigint)
90+ );
91+ Row row = rows.one();
92+ assertRow(row);
93+ }
94+
95+ @Test(groups = "short")
96+ public void should_use_default_codecs_with_prepared_statements_3() {
97+ session.execute(session.prepare(insertQuery).bind()
98+ .setObject(0, n_int)
99+ .setObject(1, n_bigint)
100+ .setObject(2, n_float)
101+ .setObject(3, n_double)
102+ .setObject(4, n_varint)
103+ .setObject(5, n_decimal)
104+ );
105+ PreparedStatement ps = session.prepare(selectQuery);
106+ ResultSet rows = session.execute(ps.bind()
107+ .setInt(0, n_int)
108+ .setLong(1, n_bigint)
109+ );
110+ Row row = rows.one();
111+ assertRow(row);
112+ }
113+
114+ @Test(groups = "short")
115+ public void should_use_default_codecs_with_prepared_statements_4() {
116+ session.execute(session.prepare(insertQuery).bind()
117+ .set(0, n_int, Integer.class)
118+ .set(1, n_bigint, Long.class)
119+ .set(2, n_float, Float.class)
120+ .set(3, n_double, Double.class)
121+ .set(4, n_varint, BigInteger.class)
122+ .set(5, n_decimal, BigDecimal.class)
123+ );
124+ PreparedStatement ps = session.prepare(selectQuery);
125+ ResultSet rows = session.execute(ps.bind()
126+ .setInt(0, n_int)
127+ .setLong(1, n_bigint)
128+ );
129+ Row row = rows.one();
130+ assertRow(row);
131+ }
132+
133+ private void assertRow(Row row) {
134+ assertThat(row.getInt(0)).isEqualTo(n_int);
135+ assertThat(row.getLong(1)).isEqualTo(n_bigint);
136+ assertThat(row.getFloat(2)).isEqualTo(n_float);
137+ assertThat(row.getDouble(3)).isEqualTo(n_double);
138+ assertThat(row.getVarint(4)).isEqualTo(n_varint);
139+ assertThat(row.getDecimal(5)).isEqualTo(n_decimal);
140+ // with getObject
141+ assertThat(row.getObject(0)).isEqualTo(n_int);
142+ assertThat(row.getObject(1)).isEqualTo(n_bigint);
143+ assertThat(row.getObject(2)).isEqualTo(n_float);
144+ assertThat(row.getObject(3)).isEqualTo(n_double);
145+ assertThat(row.getObject(4)).isEqualTo(n_varint);
146+ assertThat(row.getObject(5)).isEqualTo(n_decimal);
147+ // with get + type
148+ assertThat(row.get(0, Integer.class)).isEqualTo(n_int);
149+ assertThat(row.get(1, Long.class)).isEqualTo(n_bigint);
150+ assertThat(row.get(2, Float.class)).isEqualTo(n_float);
151+ assertThat(row.get(3, Double.class)).isEqualTo(n_double);
152+ assertThat(row.get(4, BigInteger.class)).isEqualTo(n_varint);
153+ assertThat(row.get(5, BigDecimal.class)).isEqualTo(n_decimal);
154+ }
155+}
added driver-core/src/test/java/com/datastax/driver/core/TypeCodecOptionalIntegrationTest.java +209 −0
@@ -0,0 +1,209 @@
1+/*
2+ * Copyright (C) 2012-2015 DataStax Inc.
3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ */
16+package com.datastax.driver.core;
17+
18+import com.datastax.driver.core.querybuilder.BuiltStatement;
19+import com.datastax.driver.core.querybuilder.QueryBuilder;
20+import com.datastax.driver.core.utils.CassandraVersion;
21+import com.google.common.base.Optional;
22+import com.google.common.collect.Lists;
23+import org.testng.annotations.BeforeMethod;
24+import org.testng.annotations.Test;
25+
26+import java.math.BigDecimal;
27+import java.util.Collection;
28+import java.util.Collections;
29+import java.util.List;
30+
31+import static com.datastax.driver.core.querybuilder.QueryBuilder.*;
32+import static org.assertj.core.api.Assertions.assertThat;
33+
34+public class TypeCodecOptionalIntegrationTest extends CCMBridge.PerClassSingleNodeCluster {
35+
36+ private BuiltStatement insertStmt;
37+ private BuiltStatement selectStmt;
38+
39+ TypeCodec<List<String>> codec = new CodecRegistry().codecFor(DataType.list(DataType.text()));
40+ OptionalCodec<List<String>> optionalCodec = new OptionalCodec<List<String>>(codec);
41+ CodecRegistry registry = new CodecRegistry().register(optionalCodec);
42+
43+ @Override
44+ protected Collection<String> getTableDefinitions() {
45+ return Collections.singletonList("CREATE TABLE foo (c1 text, c2 text, c3 list<text>, c4 bigint, c5 decimal, PRIMARY KEY (c1, c2))");
46+ }
47+
48+ @Override
49+ protected Cluster.Builder configure(Cluster.Builder builder) {
50+ return builder.withCodecRegistry(registry);
51+ }
52+
53+ @BeforeMethod(groups = "short")
54+ public void createBuiltStatements() throws Exception {
55+ insertStmt = new QueryBuilder(cluster).insertInto("foo").value("c1", bindMarker()).value("c2", bindMarker()).value("c3", bindMarker());
56+ selectStmt = new QueryBuilder(cluster).select("c2", "c3").from("foo").where(eq("c1", bindMarker()));
57+ }
58+
59+ /**
60+ * <p>
61+ * Validates that if a column is unset, that retrieving the value using {@link OptionalCodec} should return
62+ * an {@link Optional#absent()} value. Since CQL Lists can't differentiate between null and empty lists, the
63+ * OptionalCodec should be smart enough to map an empty list to absent.
64+ * </p>
65+ *
66+ * @test_category data_types:serialization
67+ * @expected_result an absent value.
68+ * @jira_ticket JAVA-721
69+ * @since 2.2.0
70+ */
71+ @Test(groups="short")
72+ @CassandraVersion(major=2.2)
73+ public void should_map_unset_value_to_absent() {
74+ PreparedStatement insertPrep = session.prepare(this.insertStmt);
75+ PreparedStatement selectPrep = session.prepare(this.selectStmt);
76+
77+ BoundStatement bs = insertPrep.bind();
78+ bs.setString(0, "should_map_unset_value_to_absent");
79+ bs.setString(1, "1");
80+ session.execute(bs);
81+
82+ ResultSet results = session.execute(selectPrep.bind("should_map_unset_value_to_absent"));
83+ assertThat(results.getAvailableWithoutFetching()).isEqualTo(1);
84+
85+ Row row = results.one();
86+ assertThat(row.getString("c2")).isEqualTo("1");
87+ assertThat(row.get("c3", optionalCodec.getJavaType())).isEqualTo(Optional.absent());
88+ }
89+
90+ /**
91+ * <p>
92+ * Validates that if a column is set to {@link Optional#absent()} using {@link OptionalCodec} that it should be
93+ * stored as null and that retrieving it should return {@link Optional#absent()} using {@link OptionalCodec}.
94+ * </p>
95+ *
96+ * @test_category data_types:serialization
97+ * @expected_result an absent value.
98+ * @jira_ticket JAVA-721
99+ * @since 2.2.0
100+ */
101+ @Test(groups="short")
102+ public void should_map_absent_null_value_to_absent() {
103+ PreparedStatement insertPrep = session.prepare(this.insertStmt);
104+ PreparedStatement selectPrep = session.prepare(this.selectStmt);
105+
106+ BoundStatement bs = insertPrep.bind();
107+ bs.setString(0, "should_map_absent_null_value_to_absent");
108+ bs.setString(1, "1");
109+ bs.set(2, Optional.<List<String>>absent(), optionalCodec.javaType);
110+ session.execute(bs);
111+
112+ ResultSet results = session.execute(selectPrep.bind("should_map_absent_null_value_to_absent"));
113+ assertThat(results.getAvailableWithoutFetching()).isEqualTo(1);
114+
115+ Row row = results.one();
116+ assertThat(row.getString("c2")).isEqualTo("1");
117+ assertThat(row.getList("c3", String.class)).isEmpty();
118+ assertThat(row.get("c3", optionalCodec.getJavaType())).isEqualTo(Optional.absent());
119+ }
120+
121+ /**
122+ * <p>
123+ * Validates that if a column is set to an {@link Optional} value using {@link OptionalCodec} that it should be
124+ * stored as the option's value and that retrieving it should return an {@link Optional} using {@link OptionalCodec}
125+ * and its actual value without using it.
126+ * </p>
127+ *
128+ * @test_category data_types:serialization
129+ * @expected_result The options value is stored appropriately and is retrievable with and without OptionalCodec.
130+ * @jira_ticket JAVA-721
131+ * @since 2.2.0
132+ */
133+ @Test(groups="short")
134+ public void should_map_some_back_to_itself() {
135+ PreparedStatement insertPrep = session.prepare(this.insertStmt);
136+ PreparedStatement selectPrep = session.prepare(this.selectStmt);
137+
138+ List<String> data = Lists.newArrayList("1", "2", "3");
139+
140+ BoundStatement bs = insertPrep.bind();
141+ bs.setString(0, "should_map_some_back_to_itself");
142+ bs.setString(1, "1");
143+ bs.set(2, Optional.of(data), optionalCodec.javaType);
144+ session.execute(bs);
145+
146+ ResultSet results = session.execute(selectPrep.bind("should_map_some_back_to_itself"));
147+ assertThat(results.getAvailableWithoutFetching()).isEqualTo(1);
148+
149+ Row row = results.one();
150+ assertThat(row.getString("c2")).isEqualTo("1");
151+
152+ // Ensure data stored correctly.
153+ assertThat(row.getList("c3", String.class)).isEqualTo(data);
154+
155+ // Ensure data retrievable using Option codec.
156+ Optional<List<String>> returnData = row.get("c3", optionalCodec.getJavaType());
157+ assertThat(returnData.isPresent()).isTrue();
158+ assertThat(returnData.get()).isEqualTo(data);
159+ }
160+
161+ @Test(groups="short")
162+ public void should_map_a_primitive_type_to_absent() {
163+ TypeCodec<Long> bigintCodec = registry.codecFor(DataType.bigint());
164+ OptionalCodec<Long> optionalLongCodec = new OptionalCodec<Long>(bigintCodec);
165+ cluster.getConfiguration().getCodecRegistry().register(optionalLongCodec);
166+
167+ PreparedStatement stmt = session.prepare("insert into foo (c1, c2, c4) values (?,?,?)");
168+
169+ BoundStatement bs = stmt.bind();
170+ bs.setString(0, "should_map_a_primitive_type_to_absent");
171+ bs.setString(1, "1");
172+ bs.set(2, Optional.<Long>absent(), optionalLongCodec.javaType);
173+ session.execute(bs);
174+
175+ PreparedStatement selectBigint = session.prepare("select c1, c4 from foo where c1=?");
176+ ResultSet results = session.execute(selectBigint.bind("should_map_a_primitive_type_to_absent"));
177+
178+ assertThat(results.getAvailableWithoutFetching()).isEqualTo(1);
179+
180+ Row row = results.one();
181+ assertThat(row.get("c4", optionalLongCodec.getJavaType())).isEqualTo(Optional.<Long>absent());
182+ assertThat(row.getLong("c4")).isEqualTo(0L); // This will return a 0L since it returns the primitive value.
183+ assertThat(row.get("c4", Long.class)).isNull();
184+ }
185+
186+ @Test(groups="short")
187+ public void should_map_a_nullable_type_to_absent() {
188+ TypeCodec<BigDecimal> decimalCodec = registry.codecFor(DataType.decimal());
189+ OptionalCodec<BigDecimal> optionalDecimalCodec = new OptionalCodec<BigDecimal>(decimalCodec);
190+ cluster.getConfiguration().getCodecRegistry().register(optionalDecimalCodec);
191+
192+ PreparedStatement stmt = session.prepare("insert into foo (c1, c2, c5) values (?,?,?)");
193+
194+ BoundStatement bs = stmt.bind();
195+ bs.setString(0, "should_map_a_nullable_type_to_absent");
196+ bs.setString(1, "1");
197+ bs.set(2, Optional.<BigDecimal>absent(), optionalDecimalCodec.javaType);
198+ session.execute(bs);
199+
200+ PreparedStatement selectDecimal = session.prepare("select c1, c5 from foo where c1=?");
201+ ResultSet results = session.execute(selectDecimal.bind("should_map_a_nullable_type_to_absent"));
202+
203+ assertThat(results.getAvailableWithoutFetching()).isEqualTo(1);
204+
205+ Row row = results.one();
206+ assertThat(row.get("c5", optionalDecimalCodec.getJavaType())).isEqualTo(Optional.<BigDecimal>absent());
207+ assertThat(row.getDecimal("c5")).isNull(); // Since BigDecimal is not a primitive it is nullable so expect null.
208+ }
209+}
added driver-core/src/test/java/com/datastax/driver/core/TypeCodecOverlappingJavaTypeIntegrationTest.java +131 −0
@@ -0,0 +1,131 @@
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.nio.ByteBuffer;
19+import java.util.Collection;
20+import java.util.List;
21+
22+import com.google.common.reflect.TypeToken;
23+import org.testng.annotations.Test;
24+
25+import static com.google.common.collect.Lists.newArrayList;
26+import static org.assertj.core.api.Assertions.assertThat;
27+
28+import com.datastax.driver.core.exceptions.InvalidTypeException;
29+
30+/**
31+ * Test an edge case where the user register 2 codecs for the same Java type (here, String).
32+ * SimpleStatements become almost unusable in these cases, but we are adding tests
33+ * to check that at least it is possible to use prepared statements in these situations.
34+ */
35+public class TypeCodecOverlappingJavaTypeIntegrationTest extends CCMBridge.PerClassSingleNodeCluster {
36+
37+ private static final String insertQuery = "INSERT INTO \"myTable\" (c_int, l_int, c_text) VALUES (?, ?, ?)";
38+
39+ private static final String selectQuery = "SELECT c_int, l_int, c_text FROM \"myTable\" WHERE c_int = ?";
40+
41+ @Override
42+ protected Collection<String> getTableDefinitions() {
43+ return newArrayList(
44+ "CREATE TABLE \"myTable\" ("
45+ + "c_int int PRIMARY KEY, "
46+ + "l_int list<int>, "
47+ + "c_text text "
48+ + ")"
49+ );
50+ }
51+
52+ @Override
53+ protected Cluster.Builder configure(Cluster.Builder builder) {
54+ return builder.withCodecRegistry(
55+ new CodecRegistry().register(new IntToStringCodec(), true)
56+ );
57+ }
58+
59+ @Test(groups = "short")
60+ public void should_use_custom_codecs_with_prepared_statements() {
61+ PreparedStatement ps = session.prepare(insertQuery);
62+ session.execute(
63+ ps.bind()
64+ .setInt(0, 42)
65+ .setList(1, newArrayList(42))
66+ .setString(2, "42") // here we have the CQL type so VarcharCodec will be used even if IntToStringCodec accepts it
67+ );
68+ session.execute(
69+ ps.bind()
70+ .setObject(0, 42)
71+ .setObject(1, newArrayList(42))
72+ .setObject(2, "42") // here we have the CQL type so VarcharCodec will be used even if IntToStringCodec accepts it
73+ );
74+ session.execute(
75+ ps.bind()
76+ .setObject(0, "42")
77+ .setObject(1, newArrayList("42"))
78+ .setObject(2, "42") // here we have the CQL type so VarcharCodec will be used even if IntToStringCodec accepts it
79+ );
80+ ps = session.prepare(selectQuery);
81+ assertRow(session.execute(ps.bind().setInt(0, 42)).one());
82+ assertRow(session.execute(ps.bind().setObject(0, 42)).one());
83+ assertRow(session.execute(ps.bind().setObject(0, "42")).one());
84+ }
85+
86+ private void assertRow(Row row) {
87+ assertThat(row.getInt(0)).isEqualTo(42);
88+ assertThat(row.getObject(0)).isEqualTo(42); // uses the default codec
89+ assertThat(row.get(0, Integer.class)).isEqualTo(42);
90+ assertThat(row.get(0, String.class)).isEqualTo("42");
91+
92+ assertThat(row.getList(1, Integer.class)).isEqualTo(newArrayList(42));
93+ assertThat(row.getList(1, String.class)).isEqualTo(newArrayList("42"));
94+ assertThat(row.getObject(1)).isEqualTo(newArrayList(42)); // uses the default codec
95+ assertThat(row.get(1, new TypeToken<List<Integer>>() {})).isEqualTo(newArrayList(42));
96+ assertThat(row.get(1, new TypeToken<List<String>>() {})).isEqualTo(newArrayList("42"));
97+ }
98+
99+ private class IntToStringCodec extends TypeCodec<String> {
100+
101+ protected IntToStringCodec() {
102+ super(DataType.cint(), String.class);
103+ }
104+
105+ @Override
106+ public ByteBuffer serialize(String value, ProtocolVersion protocolVersion) throws InvalidTypeException {
107+ return IntCodec.instance.serialize(value == null ? null : Integer.parseInt(value), protocolVersion);
108+ }
109+
110+ @Override
111+ public String deserialize(ByteBuffer bytes, ProtocolVersion protocolVersion) throws InvalidTypeException {
112+ Integer i = IntCodec.instance.deserialize(bytes, protocolVersion);
113+ return i == null ? null : Integer.toString(i);
114+ }
115+
116+ @Override
117+ public String parse(String value) throws InvalidTypeException {
118+ return value;
119+ }
120+
121+ @Override
122+ public String format(String value) throws InvalidTypeException {
123+ return value;
124+ }
125+
126+ @Override
127+ public boolean accepts(Object value) {
128+ return value instanceof String && ((String) value).matches("\\d+");
129+ }
130+ }
131+}
modified driver-core/src/test/java/com/datastax/driver/core/TypeCodecTest.java +327 −21
@@ -16,59 +16,365 @@
1616 package com.datastax.driver.core;
1717
1818 import java.nio.ByteBuffer;
19-import java.util.Map;
20-import java.util.Collections;
21-import java.util.List;
19+import java.util.*;
2220
23-import com.google.common.collect.Lists;
21+import com.fasterxml.jackson.annotation.JsonCreator;
22+import com.fasterxml.jackson.annotation.JsonProperty;
23+import com.google.common.base.Function;
24+import com.google.common.base.Joiner;
25+import com.google.common.base.Objects;
2426 import com.google.common.base.Strings;
25-
26-import org.testng.Assert;
27+import com.google.common.collect.Lists;
28+import com.google.common.reflect.TypeToken;
2729 import org.testng.annotations.Test;
2830
29-import static com.datastax.driver.core.DataType.text;
31+import static com.google.common.collect.Lists.newArrayList;
32+import static org.testng.Assert.fail;
33+
34+import com.datastax.driver.core.UserType.Field;
35+import com.datastax.driver.core.exceptions.CodecNotFoundException;
36+import com.datastax.driver.core.exceptions.InvalidTypeException;
37+
38+import static com.datastax.driver.core.Assertions.assertThat;
39+import static com.datastax.driver.core.CodecUtils.listOf;
40+import static com.datastax.driver.core.DataType.*;
41+import static com.datastax.driver.core.ProtocolVersion.V3;
3042
3143 public class TypeCodecTest {
3244
3345 public static final DataType CUSTOM_FOO = DataType.custom("com.example.FooBar");
3446
47+ public static final TypeCodec.CustomCodec CUSTOM_FOO_CODEC = new TypeCodec.CustomCodec(CUSTOM_FOO);
48+
49+ private CodecRegistry codecRegistry = new CodecRegistry()
50+ .register(CUSTOM_FOO_CODEC);
51+
3552 @Test(groups = "unit")
3653 public void testCustomList() throws Exception {
37- TypeCodec<?> listType = TypeCodec.listOf(CUSTOM_FOO, ProtocolVersion.V2);
38- Assert.assertNotNull(listType);
54+ DataType cqlType = list(CUSTOM_FOO);
55+ TypeCodec<List<?>> codec = codecRegistry.codecFor(cqlType);
56+ assertThat(codec).isNotNull().accepts(cqlType);
3957 }
4058
4159 @Test(groups = "unit")
4260 public void testCustomSet() throws Exception {
43- TypeCodec<?> setType = TypeCodec.setOf(CUSTOM_FOO, ProtocolVersion.V2);
44- Assert.assertNotNull(setType);
61+ DataType cqlType = set(CUSTOM_FOO);
62+ TypeCodec<Set<?>> codec = codecRegistry.codecFor(cqlType);
63+ assertThat(codec).isNotNull().accepts(cqlType);
4564 }
4665
4766 @Test(groups = "unit")
4867 public void testCustomKeyMap() throws Exception {
49- TypeCodec<Map<ByteBuffer, String>> mapType = TypeCodec.mapOf(CUSTOM_FOO, text(), ProtocolVersion.V2);
50- Assert.assertNotNull(mapType);
68+ DataType cqlType = map(CUSTOM_FOO, text());
69+ TypeCodec<Map<?, ?>> codec = codecRegistry.codecFor(cqlType);
70+ assertThat(codec).isNotNull().accepts(cqlType);
5171 }
5272
5373 @Test(groups = "unit")
5474 public void testCustomValueMap() throws Exception {
55- TypeCodec<Map<String, ByteBuffer>> mapType = TypeCodec.mapOf(text(), CUSTOM_FOO, ProtocolVersion.V2);
56- Assert.assertNotNull(mapType);
75+ DataType cqlType = map(text(), CUSTOM_FOO);
76+ TypeCodec<Map<?, ?>> codec = codecRegistry.codecFor(cqlType);
77+ assertThat(codec).isNotNull().accepts(cqlType);
5778 }
5879
5980 @Test(groups = "unit", expectedExceptions = { IllegalArgumentException.class })
6081 public void collectionTooLargeTest() throws Exception {
61- TypeCodec<List<Integer>> listType = TypeCodec.listOf(DataType.cint(), ProtocolVersion.V2);
82+ DataType cqlType = DataType.list(DataType.cint());
6283 List<Integer> list = Collections.nCopies(65536, 1);
63-
64- listType.serialize(list);
84+ TypeCodec<List<?>> codec = codecRegistry.codecFor(cqlType);
85+ codec.serialize(list, ProtocolVersion.V2);
6586 }
6687
6788 @Test(groups = "unit", expectedExceptions = { IllegalArgumentException.class })
6889 public void collectionElementTooLargeTest() throws Exception {
69- TypeCodec<List<String>> listType = TypeCodec.listOf(DataType.text(), ProtocolVersion.V2);
70- List<String> list = Lists.newArrayList(Strings.repeat("a", 65536));
90+ DataType cqlType = DataType.list(DataType.text());
91+ List<String> list = newArrayList(Strings.repeat("a", 65536));
92+ TypeCodec<List<?>> codec = codecRegistry.codecFor(cqlType);
93+ codec.serialize(list, ProtocolVersion.V2);
94+ }
95+
96+ @Test(groups = "unit")
97+ public void test_cql_text_to_json() {
98+ JsonCodec<User> codec = new JsonCodec<User>(User.class);
99+ // the codec is expected to format json objects as json strings enclosed in single quotes,
100+ // as it is required for CQL literals of varchar type.
101+ String json = "'{\"id\":1,\"name\":\"John Doe\"}'";
102+ User user = new User(1, "John Doe");
103+ assertThat(codec.format(user)).isEqualTo(json);
104+ assertThat(codec.parse(json)).isEqualToComparingFieldByField(user);
105+ assertThat(codec).canSerialize(user);
106+ }
107+
108+ @Test(groups = "unit")
109+ public void test_cql_list_varchar_to_list_list_integer() {
110+ ListVarcharToListListInteger codec = new ListVarcharToListListInteger();
111+ List<List<Integer>> list = new ArrayList<List<Integer>>();
112+ list.add(newArrayList(1, 2, 3));
113+ list.add(newArrayList(4, 5, 6));
114+ assertThat(codec).canSerialize(list);
115+ }
116+
117+ @Test(groups = "unit")
118+ public void test_ascii_vs_utf8() {
119+ TypeCodec.AsciiCodec asciiCodec = TypeCodec.AsciiCodec.instance;
120+ TypeCodec.VarcharCodec utf8Codec = TypeCodec.VarcharCodec.instance;
121+ String ascii = "The quick brown fox jumps over the lazy dog!";
122+ String utf8 = "Dès Noël, où un zéphyr haï me vêt de glaçons würmiens, je dîne d’exquis rôtis de bœuf au kir à l’aÿ d’âge mûr & cætera!";
123+ assertThat(asciiCodec)
124+ .accepts(String.class)
125+ .accepts(ascii())
126+ .doesNotAccept(varchar())
127+ .doesNotAccept(text())
128+ .accepts(ascii)
129+ .doesNotAccept(utf8)
130+ .canSerialize(ascii)
131+ .cannotSerialize(utf8);
132+ assertThat(utf8Codec)
133+ .accepts(String.class)
134+ .doesNotAccept(ascii())
135+ .accepts(varchar())
136+ .accepts(text())
137+ .accepts(ascii)
138+ .accepts(utf8)
139+ .canSerialize(ascii)
140+ .canSerialize(utf8);
141+ }
142+
143+ @Test(groups = "unit")
144+ public void test_varchar_vs_text() {
145+ assertThat(TypeCodec.VarcharCodec.instance)
146+ .accepts(String.class)
147+ .accepts(varchar())
148+ .accepts(text());
149+ assertThat(new TypeCodec.ListCodec<String>(TypeCodec.VarcharCodec.instance))
150+ .accepts(list(varchar()))
151+ .accepts(list(text()));
152+ assertThat(new TypeCodec.SetCodec<String>(TypeCodec.VarcharCodec.instance))
153+ .accepts(set(varchar()))
154+ .accepts(set(text()));
155+ assertThat(new TypeCodec.MapCodec<String, String>(TypeCodec.VarcharCodec.instance, TypeCodec.VarcharCodec.instance))
156+ .accepts(map(varchar(), varchar()))
157+ .accepts(map(varchar(), text()))
158+ .accepts(map(text(), varchar()))
159+ .accepts(map(text(), text()));
160+ TupleType t1 = new TupleType(newArrayList(varchar(), varchar()), V3, new CodecRegistry());
161+ TupleType t2 = new TupleType(newArrayList(text(), varchar()), V3, new CodecRegistry());
162+ TupleType t3 = new TupleType(newArrayList(varchar(), text()), V3, new CodecRegistry());
163+ TupleType t4 = new TupleType(newArrayList(text(), text()), V3, new CodecRegistry());
164+ assertThat(new TypeCodec.TupleCodec(t1))
165+ .accepts(t2)
166+ .accepts(t3)
167+ .accepts(t4);
168+ UserType u1 = new UserType("ks", "table", newArrayList(new Field("f1", varchar()), new Field("f2", varchar())), V3, new CodecRegistry());
169+ UserType u2 = new UserType("ks", "table", newArrayList(new Field("f1", text()), new Field("f2", varchar())), V3, new CodecRegistry());
170+ UserType u3 = new UserType("ks", "table", newArrayList(new Field("f1", varchar()), new Field("f2", text())), V3, new CodecRegistry());
171+ 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+ .accepts(u2)
174+ .accepts(u3)
175+ .accepts(u4);
176+ }
177+
178+ @Test(groups = "unit")
179+ public void test_enum() {
180+ TypeCodec.EnumStringCodec<FooBarQix> codec = new TypeCodec.EnumStringCodec<FooBarQix>(FooBarQix.class);
181+ assertThat(codec)
182+ .canSerialize(FooBarQix.FOO);
183+ }
184+
185+ @Test(groups = "unit")
186+ public void test_inheritance() {
187+ CodecRegistry codecRegistry = new CodecRegistry();
188+ ACodec aCodec = new ACodec();
189+ codecRegistry.register(aCodec);
190+ assertThat(codecRegistry.codecFor(cint(), A.class)).isNotNull().isSameAs(aCodec);
191+ // inheritance works: B is assignable to A
192+ assertThat(codecRegistry.codecFor(cint(), B.class)).isNotNull().isSameAs(aCodec);
193+ assertThat(codecRegistry.codecFor(list(cint()), new TypeToken<List<A>>(){})).isNotNull().isEqualTo(new TypeCodec.ListCodec<A>(aCodec));
194+ // cannot work: List<B> is not assignable to List<A>
195+ try {
196+ codecRegistry.codecFor(list(cint()), new TypeToken<List<B>>(){});
197+ fail();
198+ } catch (CodecNotFoundException e) {
199+ //ok
200+ }
201+ codecRegistry = new CodecRegistry();
202+ BCodec bCodec = new BCodec();
203+ codecRegistry.register(bCodec);
204+ try {
205+ assertThat(codecRegistry.codecFor(cint(), A.class));
206+ fail();
207+ } catch (CodecNotFoundException e) {
208+ // ok
209+ }
210+ assertThat(codecRegistry.codecFor(cint(), B.class)).isNotNull().isSameAs(bCodec);
211+ try {
212+ codecRegistry.codecFor(list(cint()), new TypeToken<List<A>>(){});
213+ fail();
214+ } catch (CodecNotFoundException e) {
215+ // ok
216+ }
217+ assertThat(codecRegistry.codecFor(list(cint()), new TypeToken<List<B>>(){})).isNotNull().isEqualTo(new TypeCodec.ListCodec<B>(bCodec));
218+ }
219+
220+
221+ private class ListVarcharToListListInteger extends TypeCodec<List<List<Integer>>> {
222+
223+ private final ListCodec<String> codec = new ListCodec<String>(VarcharCodec.instance);
224+
225+ protected ListVarcharToListListInteger() {
226+ super(list(varchar()), listOf(listOf(Integer.class)));
227+ }
228+
229+ @Override
230+ public ByteBuffer serialize(List<List<Integer>> value, ProtocolVersion protocolVersion) {
231+ return codec.serialize(Lists.transform(value, new Function<List<Integer>, String>() {
232+ @Override
233+ public String apply(List<Integer> input) {
234+ return Joiner.on(",").join(input);
235+ }
236+ }), protocolVersion);
237+ }
238+
239+ @Override
240+ public List<List<Integer>> deserialize(ByteBuffer bytes, ProtocolVersion protocolVersion) {
241+ return Lists.transform(codec.deserialize(bytes, protocolVersion), new Function<String, List<Integer>>() {
242+ @Override
243+ public List<Integer> apply(String input) {
244+ return Lists.transform(Arrays.asList(input.split(",")), new Function<String, Integer>() {
245+ @Override
246+ public Integer apply(String input) {
247+ return Integer.parseInt(input);
248+ }
249+ });
250+ }
251+ });
252+ }
253+
254+ @Override
255+ public List<List<Integer>> parse(String value) {
256+ throw new UnsupportedOperationException();
257+ }
258+
259+ @Override
260+ public String format(List<List<Integer>> value) {
261+ throw new UnsupportedOperationException();
262+ }
263+ }
264+
265+ @SuppressWarnings("unused")
266+ public static class User {
267+
268+ private int id;
269+
270+ private String name;
271+
272+ @JsonCreator
273+ public User(@JsonProperty("id") int id, @JsonProperty("name") String name) {
274+ this.id = id;
275+ this.name = name;
276+ }
277+
278+ public int getId() {
279+ return id;
280+ }
281+
282+ public void setId(int id) {
283+ this.id = id;
284+ }
285+
286+ public String getName() {
287+ return name;
288+ }
289+
290+ public void setName(String name) {
291+ this.name = name;
292+ }
293+
294+ @Override
295+ public boolean equals(Object o) {
296+ if (this == o)
297+ return true;
298+ if (o == null || getClass() != o.getClass())
299+ return false;
300+ User user = (User)o;
301+ return Objects.equal(id, user.id) &&
302+ Objects.equal(name, user.name);
303+ }
304+
305+ @Override
306+ public int hashCode() {
307+ return Objects.hashCode(id, name);
308+ }
309+ }
310+
311+ enum FooBarQix {
312+ FOO, BAR, QIX
313+ }
314+
315+ class A {
316+
317+ int i = 0;
318+ }
319+
320+ class B extends A {
321+ {
322+ i = 1;
323+ }
324+ }
325+
326+ class ACodec extends TypeCodec<A> {
327+
328+ protected ACodec() {
329+ super(cint(), A.class);
330+ }
331+
332+ @Override
333+ public ByteBuffer serialize(A value, ProtocolVersion protocolVersion) throws InvalidTypeException {
334+ return null; // not tested
335+ }
336+
337+ @Override
338+ public A deserialize(ByteBuffer bytes, ProtocolVersion protocolVersion) throws InvalidTypeException {
339+ return null; // not tested
340+ }
341+
342+ @Override
343+ public A parse(String value) throws InvalidTypeException {
344+ return null; // not tested
345+ }
346+
347+ @Override
348+ public String format(A value) throws InvalidTypeException {
349+ return null; // not tested
350+ }
351+ }
352+
353+
354+ class BCodec extends TypeCodec<B> {
355+
356+ protected BCodec() {
357+ super(cint(), B.class);
358+ }
359+
360+ @Override
361+ public ByteBuffer serialize(B value, ProtocolVersion protocolVersion) throws InvalidTypeException {
362+ return null; // not tested
363+ }
364+
365+ @Override
366+ public B deserialize(ByteBuffer bytes, ProtocolVersion protocolVersion) throws InvalidTypeException {
367+ return null; // not tested
368+ }
369+
370+ @Override
371+ public B parse(String value) throws InvalidTypeException {
372+ return null; // not tested
373+ }
71374
72- listType.serialize(list);
375+ @Override
376+ public String format(B value) throws InvalidTypeException {
377+ return null; // not tested
378+ }
73379 }
74380 }
added driver-core/src/test/java/com/datastax/driver/core/TypeCodecTupleIntegrationTest.java +273 −0
@@ -0,0 +1,273 @@
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.Collection;
19+import java.util.Collections;
20+import java.util.UUID;
21+
22+import com.google.common.collect.Lists;
23+import org.testng.annotations.Test;
24+
25+import static org.assertj.core.api.Assertions.assertThat;
26+
27+import com.datastax.driver.core.utils.CassandraVersion;
28+
29+import static com.datastax.driver.core.DataType.cfloat;
30+
31+@CassandraVersion(major = 2.1)
32+public class TypeCodecTupleIntegrationTest extends CCMBridge.PerClassSingleNodeCluster {
33+
34+ private final String insertQuery = "INSERT INTO users (id, name, location) VALUES (?, ?, ?)";
35+ private final String selectQuery = "SELECT id, name, location FROM users WHERE id = ?";
36+
37+ private final UUID uuid = UUID.randomUUID();
38+
39+ private TupleType locationType;
40+ private TupleValue locationValue;
41+ private TupleValue partialLocationValueInserted;
42+ private Location location;
43+ private Location partialLocation;
44+ private TupleValue partialLocationValueRetrieved;
45+
46+ @Override
47+ protected Collection<String> getTableDefinitions() {
48+ return Lists.newArrayList(
49+ "CREATE TABLE IF NOT EXISTS \"users\" (id uuid PRIMARY KEY, name text, location frozen<tuple<float,float>>)"
50+ );
51+ }
52+
53+ @Test(groups = "short")
54+ public void should_handle_tuples_with_default_codecs() {
55+ setUpTupleTypes(cluster);
56+ // simple statement
57+ session.execute(insertQuery, uuid, "John Doe", locationValue);
58+ ResultSet rows = session.execute(selectQuery, uuid);
59+ Row row = rows.one();
60+ assertRow(row);
61+ // prepared + values
62+ PreparedStatement ps = session.prepare(insertQuery);
63+ session.execute(ps.bind(uuid, "John Doe", locationValue));
64+ rows = session.execute(selectQuery, uuid);
65+ row = rows.one();
66+ assertRow(row);
67+ // bound with setTupleValue
68+ session.execute(ps.bind().setUUID(0, uuid).setString(1, "John Doe").setTupleValue("location", locationValue));
69+ rows = session.execute(selectQuery, uuid);
70+ row = rows.one();
71+ assertRow(row);
72+ // bound with setObject
73+ session.execute(ps.bind().setUUID(0, uuid).setString(1, "John Doe").setObject(2, locationValue));
74+ rows = session.execute(selectQuery, uuid);
75+ row = rows.one();
76+ assertRow(row);
77+ }
78+
79+ @Test(groups = "short")
80+ public void should_handle_partial_tuples_with_default_codecs() {
81+ setUpTupleTypes(cluster);
82+ // simple statement
83+ session.execute(insertQuery, uuid, "John Doe", partialLocationValueInserted);
84+ ResultSet rows = session.execute(selectQuery, uuid);
85+ Row row = rows.one();
86+ assertPartialRow(row);
87+ // prepared + values
88+ PreparedStatement ps = session.prepare(insertQuery);
89+ session.execute(ps.bind(uuid, "John Doe", partialLocationValueInserted));
90+ rows = session.execute(selectQuery, uuid);
91+ row = rows.one();
92+ assertPartialRow(row);
93+ // bound with setTupleValue
94+ session.execute(ps.bind().setUUID(0, uuid).setString(1, "John Doe").setTupleValue("location", partialLocationValueInserted));
95+ rows = session.execute(selectQuery, uuid);
96+ row = rows.one();
97+ assertPartialRow(row);
98+ // bound with setObject
99+ session.execute(ps.bind().setUUID(0, uuid).setString(1, "John Doe").setObject(2, partialLocationValueInserted));
100+ rows = session.execute(selectQuery, uuid);
101+ row = rows.one();
102+ assertPartialRow(row);
103+ }
104+
105+ @Test(groups = "short")
106+ public void should_handle_tuples_with_custom_codecs() {
107+ CodecRegistry codecRegistry = new CodecRegistry();
108+ Cluster cluster = Cluster.builder()
109+ .addContactPointsWithPorts(Collections.singleton(hostAddress))
110+ .withCodecRegistry(codecRegistry)
111+ .build();
112+
113+ try {
114+ Session session = cluster.connect(keyspace);
115+ setUpTupleTypes(cluster);
116+ codecRegistry
117+ .register(new LocationCodec(new TypeCodec.TupleCodec(locationType)))
118+ ;
119+ session.execute(insertQuery, uuid, "John Doe", locationValue);
120+ ResultSet rows = session.execute(selectQuery, uuid);
121+ Row row = rows.one();
122+ assertThat(row.getUUID(0)).isEqualTo(uuid);
123+ assertThat(row.getObject(0)).isEqualTo(uuid);
124+ assertThat(row.get(0, UUID.class)).isEqualTo(uuid);
125+ assertThat(row.getString(1)).isEqualTo("John Doe");
126+ assertThat(row.getObject(1)).isEqualTo("John Doe");
127+ assertThat(row.get(1, String.class)).isEqualTo("John Doe");
128+ assertThat(row.getTupleValue(2)).isEqualTo(locationValue);
129+ // edge case: getObject should use default codecs;
130+ // but tuple and udt codecs are registered on the fly;
131+ // so if we have another manually-registered codec
132+ // that one will be picked up
133+ assertThat(row.getObject(2)).isEqualTo(location);
134+ assertThat(row.get(2, TupleValue.class)).isEqualTo(locationValue);
135+ assertThat(row.get(2, Location.class)).isEqualTo(location);
136+ } finally {
137+ cluster.close();
138+ }
139+ }
140+
141+ @Test(groups = "short")
142+ public void should_handle_partial_tuples_with_custom_codecs() {
143+ CodecRegistry codecRegistry = new CodecRegistry();
144+ Cluster cluster = Cluster.builder()
145+ .addContactPointsWithPorts(Collections.singleton(hostAddress))
146+ .withCodecRegistry(codecRegistry)
147+ .build();
148+
149+ try {
150+ Session session = cluster.connect(keyspace);
151+ setUpTupleTypes(cluster);
152+ codecRegistry
153+ .register(new LocationCodec(new TypeCodec.TupleCodec(locationType)))
154+ ;
155+ session.execute(insertQuery, uuid, "John Doe", partialLocationValueInserted);
156+ ResultSet rows = session.execute(selectQuery, uuid);
157+ Row row = rows.one();
158+ assertThat(row.getUUID(0)).isEqualTo(uuid);
159+ assertThat(row.getObject(0)).isEqualTo(uuid);
160+ assertThat(row.get(0, UUID.class)).isEqualTo(uuid);
161+ assertThat(row.getString(1)).isEqualTo("John Doe");
162+ assertThat(row.getObject(1)).isEqualTo("John Doe");
163+ assertThat(row.get(1, String.class)).isEqualTo("John Doe");
164+ assertThat(row.getTupleValue(2)).isEqualTo(locationType.newValue(37.387224f, null));
165+ // corner case: getObject should use default codecs;
166+ // but tuple and udt codecs are registered on the fly;
167+ // so if we have another manually-registered codec
168+ // that one will be picked up :(
169+ assertThat(row.getObject(2)).isEqualTo(partialLocation);
170+ assertThat(row.get(2, TupleValue.class)).isEqualTo(locationType.newValue(37.387224f, null));
171+ assertThat(row.get(2, Location.class)).isEqualTo(partialLocation);
172+ } finally {
173+ cluster.close();
174+ }
175+ }
176+
177+ private void assertRow(Row row) {
178+ assertThat(row.getUUID(0)).isEqualTo(uuid);
179+ assertThat(row.getObject(0)).isEqualTo(uuid);
180+ assertThat(row.get(0, UUID.class)).isEqualTo(uuid);
181+ assertThat(row.getString(1)).isEqualTo("John Doe");
182+ assertThat(row.getObject(1)).isEqualTo("John Doe");
183+ assertThat(row.get(1, String.class)).isEqualTo("John Doe");
184+ assertThat(row.getTupleValue(2)).isEqualTo(locationValue);
185+ assertThat(row.getObject(2)).isEqualTo(locationValue);
186+ assertThat(row.get(2, TupleValue.class)).isEqualTo(locationValue);
187+ }
188+
189+ private void assertPartialRow(Row row) {
190+ assertThat(row.getUUID(0)).isEqualTo(uuid);
191+ assertThat(row.getObject(0)).isEqualTo(uuid);
192+ assertThat(row.get(0, UUID.class)).isEqualTo(uuid);
193+ assertThat(row.getString(1)).isEqualTo("John Doe");
194+ assertThat(row.getObject(1)).isEqualTo("John Doe");
195+ assertThat(row.get(1, String.class)).isEqualTo("John Doe");
196+ assertThat(row.getTupleValue(2)).isEqualTo(partialLocationValueRetrieved);
197+ assertThat(row.getObject(2)).isEqualTo(partialLocationValueRetrieved);
198+ assertThat(row.get(2, TupleValue.class)).isEqualTo(partialLocationValueRetrieved);
199+ }
200+
201+ private void setUpTupleTypes(Cluster cluster) {
202+ locationType = cluster.getMetadata().newTupleType(cfloat(), cfloat());
203+ locationValue = locationType.newValue()
204+ .setFloat(0, 37.387224f)
205+ .setFloat(1, -121.9733837f);
206+ // insert a tuple of a different dimension
207+ partialLocationValueInserted = cluster.getMetadata().newTupleType(cfloat()).newValue().setFloat(0, 37.387224f);
208+ // retrieve the partial tuple with null missing values
209+ partialLocationValueRetrieved = locationType.newValue(37.387224f, null);
210+ location = new Location(37.387224f, -121.9733837f);
211+ partialLocation = new Location(37.387224f, 0.0f);
212+ }
213+
214+ static class LocationCodec extends TypeCodec.MappingCodec<Location, TupleValue> {
215+
216+ private final TupleType tupleType;
217+
218+ public LocationCodec(TypeCodec<TupleValue> innerCodec) {
219+ super(innerCodec, Location.class);
220+ tupleType = (TupleType) innerCodec.getCqlType();
221+ }
222+
223+ @Override
224+ protected Location deserialize(TupleValue value) {
225+ return value == null ? null : new Location(value.getFloat(0), value.getFloat(1));
226+ }
227+
228+ @Override
229+ protected TupleValue serialize(Location value) {
230+ return value == null ? null : tupleType.newValue().setFloat(0, value.latitude).setFloat(1, value.longitude);
231+ }
232+ }
233+
234+ static class Location {
235+
236+ float latitude;
237+
238+ float longitude;
239+
240+ public Location(float latitude, float longitude) {
241+ this.latitude = latitude;
242+ this.longitude = longitude;
243+ }
244+
245+ @Override
246+ public boolean equals(Object o) {
247+ if (this == o)
248+ return true;
249+ if (o == null || getClass() != o.getClass())
250+ return false;
251+
252+ Location location = (Location)o;
253+
254+ if (Float.compare(location.latitude, latitude) != 0)
255+ return false;
256+ return Float.compare(location.longitude, longitude) == 0;
257+
258+ }
259+
260+ @Override
261+ public int hashCode() {
262+ int result = (latitude != +0.0f ? Float.floatToIntBits(latitude) : 0);
263+ result = 31 * result + (longitude != +0.0f ? Float.floatToIntBits(longitude) : 0);
264+ return result;
265+ }
266+
267+ @Override
268+ public String toString() {
269+ return "[" + latitude + ", " + longitude + "]";
270+ }
271+ }
272+
273+}
added driver-core/src/test/java/com/datastax/driver/core/TypeCodecUDTIntegrationTest.java +247 −0
@@ -0,0 +1,247 @@
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+@CassandraVersion(major = 2.1)
29+public class TypeCodecUDTIntegrationTest extends CCMBridge.PerClassSingleNodeCluster {
30+
31+ private final String insertQuery = "INSERT INTO users (id, name, address) VALUES (?, ?, ?)";
32+ private final String selectQuery = "SELECT id, name, address FROM users WHERE id = ?";
33+
34+ private final UUID uuid = UUID.randomUUID();
35+
36+ private final Phone phone1 = new Phone("1234567", Sets.newHashSet("home", "iphone"));
37+ private final Phone phone2 = new Phone("2345678", Sets.newHashSet("work"));
38+ private final Address address = new Address("blah", 75010, Lists.newArrayList(phone1, phone2));
39+
40+ private UserType addressType;
41+ private UserType phoneType;
42+
43+ private UDTValue addressValue;
44+
45+ @Override
46+ protected Collection<String> getTableDefinitions() {
47+ return Lists.newArrayList(
48+ "CREATE TYPE IF NOT EXISTS \"phone\" (number text, tags set<text>)",
49+ "CREATE TYPE IF NOT EXISTS \"address\" (street text, zipcode int, phones list<frozen<phone>>)",
50+ "CREATE TABLE IF NOT EXISTS \"users\" (id uuid PRIMARY KEY, name text, address frozen<address>)"
51+ );
52+ }
53+
54+ @Test(groups = "short")
55+ public void should_handle_udts_with_default_codecs() {
56+ setUpUserTypes(cluster);
57+ // simple statement
58+ session.execute(insertQuery, uuid, "John Doe", addressValue);
59+ ResultSet rows = session.execute(selectQuery, uuid);
60+ Row row = rows.one();
61+ assertRow(row);
62+ // prepared + values
63+ PreparedStatement ps = session.prepare(insertQuery);
64+ session.execute(ps.bind(uuid, "John Doe", addressValue));
65+ rows = session.execute(selectQuery, uuid);
66+ row = rows.one();
67+ assertRow(row);
68+ // bound with setUDTValue
69+ session.execute(ps.bind().setUUID(0, uuid).setString(1, "John Doe").setUDTValue(2, addressValue));
70+ rows = session.execute(selectQuery, uuid);
71+ row = rows.one();
72+ assertRow(row);
73+ // bound with setObject
74+ session.execute(ps.bind().setUUID(0, uuid).setString(1, "John Doe").setObject(2, addressValue));
75+ rows = session.execute(selectQuery, uuid);
76+ row = rows.one();
77+ assertRow(row);
78+ }
79+
80+ @Test(groups = "short")
81+ public void should_handle_udts_with_custom_codecs() {
82+ CodecRegistry codecRegistry = new CodecRegistry();
83+ Cluster cluster = Cluster.builder()
84+ .addContactPointsWithPorts(Collections.singleton(hostAddress))
85+ .withCodecRegistry(codecRegistry)
86+ .build();
87+
88+ try {
89+ Session session = cluster.connect(keyspace);
90+ setUpUserTypes(cluster);
91+ TypeCodec<UDTValue> addressTypeCodec = new TypeCodec.UDTCodec(addressType);
92+ TypeCodec<UDTValue> phoneTypeCodec = new TypeCodec.UDTCodec(phoneType);
93+ codecRegistry
94+ .register(new AddressCodec(addressTypeCodec, Address.class))
95+ .register(new PhoneCodec(phoneTypeCodec, Phone.class))
96+ ;
97+ session.execute(insertQuery, uuid, "John Doe", address);
98+ ResultSet rows = session.execute(selectQuery, uuid);
99+ Row row = rows.one();
100+ assertThat(row.getUUID(0)).isEqualTo(uuid);
101+ assertThat(row.getObject(0)).isEqualTo(uuid);
102+ assertThat(row.get(0, UUID.class)).isEqualTo(uuid);
103+ assertThat(row.getString(1)).isEqualTo("John Doe");
104+ assertThat(row.getObject(1)).isEqualTo("John Doe");
105+ assertThat(row.get(1, String.class)).isEqualTo("John Doe");
106+ assertThat(row.getUDTValue(2)).isEqualTo(addressValue);
107+ // corner case: getObject should use default codecs;
108+ // but tuple and udt codecs are registered on the fly;
109+ // so if we have another manually-registered codec
110+ // that one will be picked up :(
111+ assertThat(row.getObject(2)).isEqualTo(address);
112+ assertThat(row.get(2, UDTValue.class)).isEqualTo(addressValue);
113+ assertThat(row.get(2, Address.class)).isEqualTo(address);
114+ } finally {
115+ cluster.close();
116+ }
117+ }
118+
119+ private void assertRow(Row row) {
120+ assertThat(row.getUUID(0)).isEqualTo(uuid);
121+ assertThat(row.getObject(0)).isEqualTo(uuid);
122+ assertThat(row.get(0, UUID.class)).isEqualTo(uuid);
123+ assertThat(row.getString(1)).isEqualTo("John Doe");
124+ assertThat(row.getObject(1)).isEqualTo("John Doe");
125+ assertThat(row.get(1, String.class)).isEqualTo("John Doe");
126+ assertThat(row.getUDTValue(2)).isEqualTo(addressValue);
127+ assertThat(row.getObject(2)).isEqualTo(addressValue);
128+ assertThat(row.get(2, UDTValue.class)).isEqualTo(addressValue);
129+ }
130+
131+ private void setUpUserTypes(Cluster cluster) {
132+ addressType = cluster.getMetadata().getKeyspace(keyspace).getUserType("address");
133+ phoneType = cluster.getMetadata().getKeyspace(keyspace).getUserType("phone");
134+ UDTValue phone1Value = phoneType.newValue()
135+ .setString("number", phone1.number)
136+ .setSet("tags", phone1.tags);
137+ UDTValue phone2Value = phoneType.newValue()
138+ .setString("number", phone2.number)
139+ .setObject("tags", phone2.tags);
140+ addressValue = addressType.newValue()
141+ .setString("street", address.street)
142+ .setInt(1, address.zipcode)
143+ .setList("phones", Lists.newArrayList(phone1Value, phone2Value));
144+ }
145+
146+ static class AddressCodec extends TypeCodec.MappingCodec<Address, UDTValue> {
147+
148+ private final UserType userType;
149+
150+ public AddressCodec(TypeCodec<UDTValue> innerCodec, Class<Address> javaType) {
151+ super(innerCodec, javaType);
152+ userType = (UserType) innerCodec.getCqlType();
153+ }
154+
155+ @Override
156+ protected Address deserialize(UDTValue value) {
157+ return value == null ? null : new Address(value.getString("street"), value.getInt("zipcode"), value.getList("phones", Phone.class));
158+ }
159+
160+ @Override
161+ protected UDTValue serialize(Address value) {
162+ return value == null ? null : userType.newValue().setString("street", value.street).setInt("zipcode", value.zipcode).setList("phones", value.phones);
163+ }
164+ }
165+
166+ static class PhoneCodec extends TypeCodec.MappingCodec<Phone, UDTValue> {
167+
168+ private final UserType userType;
169+
170+ public PhoneCodec(TypeCodec<UDTValue> innerCodec, Class<Phone> javaType) {
171+ super(innerCodec, javaType);
172+ userType = (UserType) innerCodec.getCqlType();
173+ }
174+
175+ @Override
176+ protected Phone deserialize(UDTValue value) {
177+ return value == null ? null : new Phone(value.getString("number"), value.getSet("tags", String.class));
178+ }
179+
180+ @Override
181+ protected UDTValue serialize(Phone value) {
182+ return value == null ? null : userType.newValue().setString("number", value.number).setSet("tags", value.tags);
183+ }
184+ }
185+
186+ static class Address {
187+
188+ String street;
189+
190+ int zipcode;
191+
192+ List<Phone> phones;
193+
194+ public Address(String street, int zipcode, List<Phone> phones) {
195+ this.street = street;
196+ this.zipcode = zipcode;
197+ this.phones = phones;
198+ }
199+
200+ @Override
201+ public boolean equals(Object o) {
202+ if (this == o)
203+ return true;
204+ if (o == null || getClass() != o.getClass())
205+ return false;
206+ Address address = (Address)o;
207+ return zipcode == address.zipcode && street.equals(address.street) && phones.equals(address.phones);
208+ }
209+
210+ @Override
211+ public int hashCode() {
212+ int result = street.hashCode();
213+ result = 31 * result + zipcode;
214+ result = 31 * result + phones.hashCode();
215+ return result;
216+ }
217+ }
218+
219+ static class Phone {
220+
221+ String number;
222+
223+ Set<String> tags;
224+
225+ public Phone(String number, Set<String> tags) {
226+ this.number = number;
227+ this.tags = tags;
228+ }
229+
230+ @Override
231+ public boolean equals(Object o) {
232+ if (this == o)
233+ return true;
234+ if (o == null || getClass() != o.getClass())
235+ return false;
236+ Phone phone = (Phone)o;
237+ return number.equals(phone.number) && tags.equals(phone.tags);
238+ }
239+
240+ @Override
241+ public int hashCode() {
242+ int result = number.hashCode();
243+ result = 31 * result + tags.hashCode();
244+ return result;
245+ }
246+ }
247+}
modified driver-core/src/test/java/com/datastax/driver/core/UserTypesTest.java +1 −1
@@ -394,7 +394,7 @@
394394 alldatatypes.setMap(index, ImmutableMap.of(sampleElement, sampleElement));
395395 break;
396396 case TUPLE:
397- alldatatypes.setTupleValue(index, TupleType.of(dataType).newValue(sampleElement));
397+ alldatatypes.setTupleValue(index, cluster.getMetadata().newTupleType(dataType).newValue(sampleElement));
398398 }
399399 }
400400
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 = new SimpleStatement("SELECT * FROM test.foo WHERE k = 0")
93+ Statement s = session.newSimpleStatement("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/TokenAwarePolicyTest.java +1 −1
@@ -58,7 +58,7 @@
5858 keyspace));
5959
6060 // Actual query does not matter, only the keyspace and routing key will be used
61- SimpleStatement statement = new SimpleStatement("foo");
61+ SimpleStatement statement = session.newSimpleStatement("foo");
6262 statement.setKeyspace(keyspace);
6363 statement.setRoutingKey(routingKey);
6464
modified driver-core/src/test/java/com/datastax/driver/core/querybuilder/QueryBuilder21ExecutionTest.java +13 −4
@@ -20,6 +20,8 @@
2020 import com.datastax.driver.core.ResultSet;
2121 import com.datastax.driver.core.Row;
2222 import com.datastax.driver.core.utils.CassandraVersion;
23+
24+import org.testng.annotations.BeforeMethod;
2325 import org.testng.annotations.Test;
2426
2527 import java.util.Arrays;
@@ -31,6 +33,8 @@
3133 @CassandraVersion(major=2.1)
3234 public class QueryBuilder21ExecutionTest extends CCMBridge.PerClassSingleNodeCluster {
3335
36+ private QueryBuilder builder;
37+
3438 @Override
3539 protected Collection<String> getTableDefinitions() {
3640 // Taken from http://www.datastax.com/dev/blog/cql-in-2-1
@@ -49,9 +53,14 @@
4953 );
5054 }
5155
56+ @BeforeMethod(groups = "short")
57+ public void setUpQueryBuilder() throws Exception {
58+ builder = new QueryBuilder(cluster);
59+ }
60+
5261 @Test(groups="short")
5362 public void should_handle_contains_on_set_with_index() {
54- PreparedStatement byCategory = session.prepare(select("id", "description", "categories")
63+ PreparedStatement byCategory = session.prepare(builder.select("id", "description", "categories")
5564 .from("products")
5665 .where(contains("categories", bindMarker("category"))));
5766
@@ -65,7 +74,7 @@
6574
6675 @Test(groups="short")
6776 public void should_handle_contains_on_list_with_index() {
68- PreparedStatement byBuyer = session.prepare(select("id", "description", "buyers")
77+ PreparedStatement byBuyer = session.prepare(builder.select("id", "description", "buyers")
6978 .from("products")
7079 .where(contains("buyers", bindMarker("buyer"))));
7180
@@ -79,7 +88,7 @@
7988
8089 @Test(groups="short")
8190 public void should_handle_contains_on_map_with_index() {
82- PreparedStatement byFeatures = session.prepare(select("id", "description", "features_values")
91+ PreparedStatement byFeatures = session.prepare(builder.select("id", "description", "features_values")
8392 .from("products")
8493 .where(contains("features_values", bindMarker("feature"))));
8594
@@ -94,7 +103,7 @@
94103
95104 @Test(groups="short")
96105 public void should_handle_contains_key_on_map_with_index() {
97- PreparedStatement byFeatures = session.prepare(select("id", "description", "features_keys")
106+ PreparedStatement byFeatures = session.prepare(builder.select("id", "description", "features_keys")
98107 .from("products")
99108 .where(containsKey("features_keys", bindMarker("feature"))));
100109
modified driver-core/src/test/java/com/datastax/driver/core/querybuilder/QueryBuilderExecutionTest.java +27 −20
@@ -17,6 +17,7 @@
1717
1818 import java.util.*;
1919
20+import org.testng.annotations.BeforeMethod;
2021 import org.testng.annotations.Test;
2122
2223 import static org.assertj.core.api.Assertions.assertThat;
@@ -33,6 +34,8 @@
3334
3435 private static final String TABLE1 = "test1";
3536
37+ private QueryBuilder builder;
38+
3639 @Override
3740 protected Collection<String> getTableDefinitions() {
3841 return Arrays.asList(
@@ -41,13 +44,18 @@
4144 "CREATE TABLE test_coll (k int PRIMARY KEY, a list<int>, b map<int,text>, c set<text>)");
4245 }
4346
47+ @BeforeMethod(groups = "short")
48+ public void setUpQueryBuilder() throws Exception {
49+ builder = new QueryBuilder(cluster);
50+ }
51+
4452 @Test(groups = "short")
4553 public void executeTest() throws Exception {
4654
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")));
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")));
4957
50- List<Row> rows = session.execute(select().from(TABLE1).where(in("k", "k1", "k2"))).all();
58+ List<Row> rows = session.execute(builder.select().from(TABLE1).where(in("k", "k1", "k2"))).all();
5159
5260 assertEquals(2, rows.size());
5361
@@ -68,8 +76,8 @@
6876 public void dateHandlingTest() throws Exception {
6977
7078 Date d = new Date();
71- session.execute(insertInto("dateTest").value("t", d));
72- String query = select().from("dateTest").where(eq(token("t"), fcall("token", d))).toString();
79+ session.execute(builder.insertInto("dateTest").value("t", d));
80+ String query = builder.select().from("dateTest").where(eq(token("t"), fcall("token", d))).toString();
7381 List<Row> rows = session.execute(query).all();
7482
7583 assertEquals(1, rows.size());
@@ -78,26 +86,25 @@
7886 assertEquals(d, r1.getTimestamp("t"));
7987 }
8088
81- @Test(groups = "unit")
89+ @Test(groups = "short")
8290 public void prepareTest() throws Exception {
83-
8491 // Just check we correctly avoid values when there is a bind marker
8592 String query = "INSERT INTO foo(a,b,c,d) VALUES ('foo','bar',?,0);";
86- RegularStatement stmt = insertInto("foo").value("a", "foo").value("b", "bar").value("c", bindMarker()).value("d", 0);
93+ BuiltStatement stmt = builder.insertInto("foo").value("a", "foo").value("b", "bar").value("c", bindMarker()).value("d", 0);
8794 assertEquals(stmt.getQueryString(), query);
8895
8996 query = "INSERT INTO foo(a,b,c,d) VALUES ('foo','bar',:c,0);";
90- stmt = insertInto("foo").value("a", "foo").value("b", "bar").value("c", bindMarker("c")).value("d", 0);
97+ stmt = builder.insertInto("foo").value("a", "foo").value("b", "bar").value("c", bindMarker("c")).value("d", 0);
9198 assertEquals(stmt.getQueryString(), query);
9299 }
93100
94101 @Test(groups = "short")
95102 public void batchNonBuiltStatementTest() throws Exception {
96- SimpleStatement simple = new SimpleStatement("INSERT INTO " + TABLE1 + " (k, t) VALUES ('batchTest1', 'val1')");
97- RegularStatement built = insertInto(TABLE1).value("k", "batchTest2").value("t", "val2");
98- session.execute(batch().add(simple).add(built));
99-
100- List<Row> rows = session.execute(select().from(TABLE1).where(in("k", "batchTest1", "batchTest2"))).all();
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();
101108 assertEquals(2, rows.size());
102109
103110 Row r1 = rows.get(0);
@@ -114,7 +121,7 @@
114121 //given
115122 session.execute("INSERT INTO test_coll (k, a, b) VALUES (1, [1,2,3], null)");
116123 //when
117- BuiltStatement statement = delete().listElt("a", 1).from("test_coll").where(eq("k", 1));
124+ BuiltStatement statement = builder.delete().listElt("a", 1).from("test_coll").where(eq("k", 1));
118125 session.execute(statement);
119126 //then
120127 List<Integer> actual = session.execute("SELECT a FROM test_coll WHERE k = 1").one().getList("a", Integer.class);
@@ -126,7 +133,7 @@
126133 //given
127134 session.execute("INSERT INTO test_coll (k, a) VALUES (1, [1,2,3])");
128135 //when
129- BuiltStatement statement = delete().listElt("a", bindMarker()).from("test_coll").where(eq("k", 1));
136+ BuiltStatement statement = builder.delete().listElt("a", bindMarker()).from("test_coll").where(eq("k", 1));
130137 PreparedStatement ps = session.prepare(statement);
131138 session.execute(ps.bind(1));
132139 //then
@@ -139,7 +146,7 @@
139146 //given
140147 session.execute("INSERT INTO test_coll (k, c) VALUES (1, {'foo','bar','qix'})");
141148 //when
142- BuiltStatement statement = delete().setElt("c", "foo").from("test_coll").where(eq("k", 1));
149+ BuiltStatement statement = builder.delete().setElt("c", "foo").from("test_coll").where(eq("k", 1));
143150 session.execute(statement);
144151 //then
145152 Set<String> actual = session.execute("SELECT c FROM test_coll WHERE k = 1").one().getSet("c", String.class);
@@ -151,7 +158,7 @@
151158 //given
152159 session.execute("INSERT INTO test_coll (k, c) VALUES (1, {'foo','bar','qix'})");
153160 //when
154- BuiltStatement statement = delete().setElt("c", bindMarker()).from("test_coll").where(eq("k", 1));
161+ BuiltStatement statement = builder.delete().setElt("c", bindMarker()).from("test_coll").where(eq("k", 1));
155162 PreparedStatement ps = session.prepare(statement);
156163 session.execute(ps.bind("foo"));
157164 //then
@@ -164,7 +171,7 @@
164171 //given
165172 session.execute("INSERT INTO test_coll (k, b) VALUES (1, {1:'foo', 2:'bar'})");
166173 //when
167- BuiltStatement statement = delete().mapElt("b", 1).from("test_coll").where(eq("k", 1));
174+ BuiltStatement statement = builder.delete().mapElt("b", 1).from("test_coll").where(eq("k", 1));
168175 session.execute(statement);
169176 //then
170177 Map<Integer, String> actual = session.execute("SELECT b FROM test_coll WHERE k = 1").one().getMap("b", Integer.class, String.class);
@@ -176,7 +183,7 @@
176183 //given
177184 session.execute("INSERT INTO test_coll (k, a, b) VALUES (1, null, {1:'foo', 2:'bar'})");
178185 //when
179- BuiltStatement statement = delete().mapElt("b", bindMarker()).from("test_coll").where(eq("k", 1));
186+ BuiltStatement statement = builder.delete().mapElt("b", bindMarker()).from("test_coll").where(eq("k", 1));
180187 PreparedStatement ps = session.prepare(statement);
181188 session.execute(ps.bind().setInt(0, 1));
182189 //then
modified driver-core/src/test/java/com/datastax/driver/core/querybuilder/QueryBuilderITest.java +38 −31
@@ -19,6 +19,7 @@
1919 import java.util.Collection;
2020 import java.util.TreeSet;
2121
22+import org.testng.annotations.BeforeMethod;
2223 import org.testng.annotations.Test;
2324
2425 import static org.testng.Assert.*;
@@ -33,6 +34,7 @@
3334
3435 private static final String TABLE_TEXT = "test_text";
3536 private static final String TABLE_INT = "test_int";
37+ private QueryBuilder builder;
3638
3739 @Override
3840 protected Collection<String> getTableDefinitions() {
@@ -40,6 +42,11 @@
4042 String.format("CREATE TABLE %s (k int PRIMARY KEY, a int, b int)", TABLE_INT));
4143 }
4244
45+ @BeforeMethod(groups = "short")
46+ public void setUpQueryBuilder() throws Exception {
47+ builder = new QueryBuilder(cluster);
48+ }
49+
4350 @Test(groups = "short")
4451 public void remainingDeleteTests() throws Exception {
4552
@@ -48,7 +55,7 @@
4855 assertNotNull(table);
4956
5057 String expected = String.format("DELETE k FROM %s.test_text;", keyspace);
51- query = delete("k").from(table);
58+ query = builder.delete("k").from(table);
5259 assertEquals(query.toString(), expected);
5360 try {
5461 session.execute(query);
@@ -71,7 +78,7 @@
7178 session.execute("USE foo");
7279
7380 query = "SELECT * FROM foo WHERE k=?;";
74- select = select().all().from("foo").where(eq("k", QueryBuilder.bindMarker()));
81+ select = builder.select().all().from("foo").where(eq("k", QueryBuilder.bindMarker()));
7582 System.out.println(select.toString());
7683 System.out.println(session);
7784 ps = session.prepare(select.toString());
@@ -80,45 +87,45 @@
8087 session.execute(bs.setString("k", "4 AND c=5"));
8188
8289 query = "SELECT * FROM foo WHERE k='4'' AND c=''5';";
83- select = select().all().from("foo").where(eq("k", "4' AND c='5"));
90+ select = builder.select().all().from("foo").where(eq("k", "4' AND c='5"));
8491 assertEquals(select.toString(), query);
8592
8693 query = "SELECT * FROM foo WHERE k='4'' OR ''1''=''1';";
87- select = select().all().from("foo").where(eq("k", "4' OR '1'='1"));
94+ select = builder.select().all().from("foo").where(eq("k", "4' OR '1'='1"));
8895 assertEquals(select.toString(), query);
8996
9097 query = "SELECT * FROM foo WHERE k='4; --test comment;';";
91- select = select().all().from("foo").where(eq("k", "4; --test comment;"));
98+ select = builder.select().all().from("foo").where(eq("k", "4; --test comment;"));
9299 assertEquals(select.toString(), query);
93100
94101 query = "SELECT \"*\" FROM foo;";
95- select = select("*").from("foo");
102+ select = builder.select("*").from("foo");
96103 assertEquals(select.toString(), query);
97104
98105 query = "SELECT a,b FROM foo WHERE a IN ('b','c''); --comment');";
99- select = select("a", "b").from("foo")
106+ select = builder.select("a", "b").from("foo")
100107 .where(in("a", "b", "c'); --comment"));
101108 assertEquals(select.toString(), query);
102109
103110 // User Injection?
104111 query = "SELECT * FROM bar; --(b) FROM foo;";
105- select = select().fcall("* FROM bar; --", column("b")).from("foo");
112+ select = builder.select().fcall("* FROM bar; --", column("b")).from("foo");
106113 assertEquals(select.toString(), query);
107114
108115 query = "SELECT writetime(\"a) FROM bar; --\"),ttl(a) FROM foo ALLOW FILTERING;";
109- select = select().writeTime("a) FROM bar; --").ttl("a").from("foo").allowFiltering();
116+ select = builder.select().writeTime("a) FROM bar; --").ttl("a").from("foo").allowFiltering();
110117 assertEquals(select.toString(), query);
111118
112119 query = "SELECT writetime(a),ttl(\"a) FROM bar; --\") FROM foo ALLOW FILTERING;";
113- select = select().writeTime("a").ttl("a) FROM bar; --").from("foo").allowFiltering();
120+ select = builder.select().writeTime("a").ttl("a) FROM bar; --").from("foo").allowFiltering();
114121 assertEquals(select.toString(), query);
115122
116123 query = "SELECT * FROM foo WHERE \"k=1 OR k\">42 LIMIT 42;";
117- select = select().all().from("foo").where(gt("k=1 OR k", 42)).limit(42);
124+ select = builder.select().all().from("foo").where(gt("k=1 OR k", 42)).limit(42);
118125 assertEquals(select.toString(), query);
119126
120127 query = "SELECT * FROM foo WHERE token(\"k)>0 OR token(k\")>token(42);";
121- select = select().all().from("foo").where(gt(token("k)>0 OR token(k"), fcall("token", 42)));
128+ select = builder.select().all().from("foo").where(gt(token("k)>0 OR token(k"), fcall("token", 42)));
122129 assertEquals(select.toString(), query);
123130 }
124131
@@ -130,17 +137,17 @@
130137 Statement insert;
131138
132139 query = "INSERT INTO foo(a) VALUES ('123); --comment');";
133- insert = insertInto("foo")
140+ insert = builder.insertInto("foo")
134141 .value("a", "123); --comment");
135142 assertEquals(insert.toString(), query);
136143
137144 query = "INSERT INTO foo(\"a,b\") VALUES (123);";
138- insert = insertInto("foo")
145+ insert = builder.insertInto("foo")
139146 .value("a,b", 123);
140147 assertEquals(insert.toString(), query);
141148
142149 query = "INSERT INTO foo(a,b) VALUES ({'2''} space','3','4'},3.4) USING TTL 24 AND TIMESTAMP 42;";
143- 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));
150+ 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));
144151 assertEquals(insert.toString(), query);
145152 }
146153
@@ -151,15 +158,15 @@
151158 Statement update;
152159
153160 query = "UPDATE foo.bar USING TIMESTAMP 42 SET a=12 WHERE k='2 OR 1=1';";
154- update = update("foo", "bar").using(timestamp(42)).with(set("a", 12)).where(eq("k", "2 OR 1=1"));
161+ update = builder.update("foo", "bar").using(timestamp(42)).with(set("a", 12)).where(eq("k", "2 OR 1=1"));
155162 assertEquals(update.toString(), query);
156163
157164 query = "UPDATE foo SET b='null WHERE k=1; --comment' WHERE k=2;";
158- update = update("foo").where().and(eq("k", 2)).with(set("b", "null WHERE k=1; --comment"));
165+ update = builder.update("foo").where().and(eq("k", 2)).with(set("b", "null WHERE k=1; --comment"));
159166 assertEquals(update.toString(), query);
160167
161168 query = "UPDATE foo USING TIMESTAMP 42 SET \"b WHERE k=1; --comment\"=[3,2,1]+\"b WHERE k=1; --comment\" WHERE k=2;";
162- update = update("foo").where().and(eq("k", 2)).with(prependAll("b WHERE k=1; --comment", Arrays.asList(3, 2, 1))).using(timestamp(42));
169+ update = builder.update("foo").where().and(eq("k", 2)).with(prependAll("b WHERE k=1; --comment", Arrays.asList(3, 2, 1))).using(timestamp(42));
163170 assertEquals(update.toString(), query);
164171 }
165172
@@ -170,40 +177,40 @@
170177 Statement delete;
171178
172179 query = "DELETE FROM \"foo WHERE k=4\";";
173- delete = delete().from("foo WHERE k=4");
180+ delete = builder.delete().from("foo WHERE k=4");
174181 assertEquals(delete.toString(), query);
175182
176183 query = "DELETE FROM foo WHERE k='4 AND c=5';";
177- delete = delete().from("foo").where(eq("k", "4 AND c=5"));
184+ delete = builder.delete().from("foo").where(eq("k", "4 AND c=5"));
178185 assertEquals(delete.toString(), query);
179186
180187 query = "DELETE FROM foo WHERE k='4'' AND c=''5';";
181- delete = delete().from("foo").where(eq("k", "4' AND c='5"));
188+ delete = builder.delete().from("foo").where(eq("k", "4' AND c='5"));
182189 assertEquals(delete.toString(), query);
183190
184191 query = "DELETE FROM foo WHERE k='4'' OR ''1''=''1';";
185- delete = delete().from("foo").where(eq("k", "4' OR '1'='1"));
192+ delete = builder.delete().from("foo").where(eq("k", "4' OR '1'='1"));
186193 assertEquals(delete.toString(), query);
187194
188195 query = "DELETE FROM foo WHERE k='4; --test comment;';";
189- delete = delete().from("foo").where(eq("k", "4; --test comment;"));
196+ delete = builder.delete().from("foo").where(eq("k", "4; --test comment;"));
190197 assertEquals(delete.toString(), query);
191198
192199 query = "DELETE \"*\" FROM foo;";
193- delete = delete("*").from("foo");
200+ delete = builder.delete("*").from("foo");
194201 assertEquals(delete.toString(), query);
195202
196203 query = "DELETE a,b FROM foo WHERE a IN ('b','c''); --comment');";
197- delete = delete("a", "b").from("foo")
204+ delete = builder.delete("a", "b").from("foo")
198205 .where(in("a", "b", "c'); --comment"));
199206 assertEquals(delete.toString(), query);
200207
201208 query = "DELETE FROM foo WHERE \"k=1 OR k\">42;";
202- delete = delete().from("foo").where(gt("k=1 OR k", 42));
209+ delete = builder.delete().from("foo").where(gt("k=1 OR k", 42));
203210 assertEquals(delete.toString(), query);
204211
205212 query = "DELETE FROM foo WHERE token(\"k)>0 OR token(k\")>token(42);";
206- delete = delete().from("foo").where(gt(token("k)>0 OR token(k"), fcall("token", 42)));
213+ delete = builder.delete().from("foo").where(gt(token("k)>0 OR token(k"), fcall("token", 42)));
207214 assertEquals(delete.toString(), query);
208215 }
209216
@@ -214,21 +221,21 @@
214221
215222 Statement delete;
216223 Row row;
217- delete = delete().from(keyspace, TABLE_INT).where(eq("k", 2)).ifExists();
224+ delete = builder.delete().from(keyspace, TABLE_INT).where(eq("k", 2)).ifExists();
218225 row = session.execute(delete).one();
219226 assertFalse(row.getBool("[applied]"));
220227
221- delete = delete().from(keyspace, TABLE_INT).where(eq("k", 1)).ifExists();
228+ delete = builder.delete().from(keyspace, TABLE_INT).where(eq("k", 1)).ifExists();
222229 row = session.execute(delete).one();
223230 assertTrue(row.getBool("[applied]"));
224231
225232 session.execute(String.format("INSERT INTO %s.test_int (k, a, b) VALUES (1, 1, 1)", keyspace));
226233
227- delete = delete().from(keyspace, TABLE_INT).where(eq("k", 1)).onlyIf(eq("a", 1)).and(eq("b", 2));
234+ delete = builder.delete().from(keyspace, TABLE_INT).where(eq("k", 1)).onlyIf(eq("a", 1)).and(eq("b", 2));
228235 row = session.execute(delete).one();
229236 assertFalse(row.getBool("[applied]"));
230237
231- delete = delete().from(keyspace, TABLE_INT).where(eq("k", 1)).onlyIf(eq("a", 1)).and(eq("b", 1));
238+ delete = builder.delete().from(keyspace, TABLE_INT).where(eq("k", 1)).onlyIf(eq("a", 1)).and(eq("b", 1));
232239 row = session.execute(delete).one();
233240 assertTrue(row.getBool("[applied]"));
234241 }
modified driver-core/src/test/java/com/datastax/driver/core/querybuilder/QueryBuilderRoutingKeyTest.java +17 −16
@@ -42,16 +42,17 @@
4242 @Test(groups = "short")
4343 public void textRoutingKeyTest() throws Exception {
4444
45- Statement query;
45+ BuiltStatement query;
4646 TableMetadata table = cluster.getMetadata().getKeyspace(keyspace).getTable(TABLE_TEXT);
4747 assertNotNull(table);
4848
4949 String txt = "If she weighs the same as a duck... she's made of wood.";
50- query = insertInto(table).values(new String[]{"k", "a", "b"}, new Object[]{txt, 1, 2});
50+ QueryBuilder builder = new QueryBuilder(cluster);
51+ query = builder.insertInto(table).values(new String[]{"k", "a", "b"}, new Object[]{txt, 1, 2});
5152 assertEquals(query.getRoutingKey(), ByteBuffer.wrap(txt.getBytes()));
5253 session.execute(query);
5354
54- query = select().from(table).where(eq("k", txt));
55+ query = builder.select().from(table).where(eq("k", txt));
5556 assertEquals(query.getRoutingKey(), ByteBuffer.wrap(txt.getBytes()));
5657 Row row = session.execute(query).one();
5758 assertEquals(row.getString("k"), txt);
@@ -62,17 +63,17 @@
6263 @Test(groups = "short")
6364 public void intRoutingKeyTest() throws Exception {
6465
65- Statement query;
66+ BuiltStatement query;
6667 TableMetadata table = cluster.getMetadata().getKeyspace(keyspace).getTable(TABLE_INT);
6768 assertNotNull(table);
6869
69- query = insertInto(table).values(new String[]{"k", "a", "b"}, new Object[]{42, 1, 2});
70+ query = new QueryBuilder(cluster).insertInto(table).values(new String[]{"k", "a", "b"}, new Object[]{42, 1, 2});
7071 ByteBuffer bb = ByteBuffer.allocate(4);
7172 bb.putInt(0, 42);
7273 assertEquals(query.getRoutingKey(), bb);
7374 session.execute(query);
7475
75- query = select().from(table).where(eq("k", 42));
76+ query = new QueryBuilder(cluster).select().from(table).where(eq("k", 42));
7677 assertEquals(query.getRoutingKey(), bb);
7778 Row row = session.execute(query).one();
7879 assertEquals(row.getInt("k"), 42);
@@ -83,7 +84,7 @@
8384 @Test(groups = "short")
8485 public void intRoutingBatchKeyTest() throws Exception {
8586
86- RegularStatement query;
87+ BuiltStatement query;
8788 TableMetadata table = cluster.getMetadata().getKeyspace(keyspace).getTable(TABLE_INT);
8889 assertNotNull(table);
8990
@@ -91,18 +92,18 @@
9192 bb.putInt(0, 42);
9293
9394 String batch_query;
94- Statement batch;
95- ResultSet rs;
95+ BuiltStatement batch;
9696
97- query = select().from(table).where(eq("k", 42));
97+ QueryBuilder builder = new QueryBuilder(cluster);
98+ query = builder.select().from(table).where(eq("k", 42));
9899
99100 batch_query = "BEGIN BATCH ";
100101 batch_query += String.format("INSERT INTO %s.test_int(k,a) VALUES (42,1);", keyspace);
101102 batch_query += String.format("UPDATE %s.test_int USING TTL 400;", keyspace);
102103 batch_query += "APPLY BATCH;";
103- batch = batch()
104- .add(insertInto(table).values(new String[]{"k", "a"}, new Object[]{42, 1}))
105- .add(update(table).using(ttl(400)));
104+ batch = builder.batch()
105+ .add(builder.insertInto(table).values(new String[]{"k", "a"}, new Object[]{42, 1}))
106+ .add(builder.update(table).using(ttl(400)));
106107 assertEquals(batch.getRoutingKey(), bb);
107108 assertEquals(batch.toString(), batch_query);
108109 // TODO: rs = session.execute(batch); // Not guaranteed to be valid CQL
@@ -110,7 +111,7 @@
110111 batch_query = "BEGIN BATCH ";
111112 batch_query += String.format("SELECT * FROM %s.test_int WHERE k=42;", keyspace);
112113 batch_query += "APPLY BATCH;";
113- batch = batch(query);
114+ batch = builder.batch(query);
114115 assertEquals(batch.getRoutingKey(), bb);
115116 assertEquals(batch.toString(), batch_query);
116117 // TODO: rs = session.execute(batch); // Not guaranteed to be valid CQL
@@ -118,7 +119,7 @@
118119 batch_query = "BEGIN BATCH ";
119120 batch_query += "SELECT * FROM foo WHERE k=42;";
120121 batch_query += "APPLY BATCH;";
121- batch = batch().add(select().from("foo").where(eq("k", 42)));
122+ batch = builder.batch().add(builder.select().from("foo").where(eq("k", 42)));
122123 assertEquals(batch.getRoutingKey(), null);
123124 assertEquals(batch.toString(), batch_query);
124125 // TODO: rs = session.execute(batch); // Not guaranteed to be valid CQL
@@ -126,7 +127,7 @@
126127 batch_query = "BEGIN BATCH USING TIMESTAMP 42 ";
127128 batch_query += "INSERT INTO foo.bar(a) VALUES (123);";
128129 batch_query += "APPLY BATCH;";
129- batch = batch().using(timestamp(42)).add(insertInto("foo", "bar").value("a", 123));
130+ batch = builder.batch().using(timestamp(42)).add(builder.insertInto("foo", "bar").value("a", 123));
130131 assertEquals(batch.getRoutingKey(), null);
131132 assertEquals(batch.toString(), batch_query);
132133 // TODO: rs = session.execute(batch); // Not guaranteed to be valid CQL
modified driver-core/src/test/java/com/datastax/driver/core/querybuilder/QueryBuilderTest.java +177 −175
@@ -22,23 +22,41 @@
2222
2323 import com.google.common.collect.ImmutableList;
2424 import com.google.common.collect.ImmutableMap;
25+import org.testng.annotations.BeforeMethod;
2526 import org.testng.annotations.Test;
2627
2728 import static org.assertj.core.api.Assertions.assertThat;
29+import static org.mockito.Mockito.mock;
30+import static org.mockito.Mockito.when;
2831 import static org.testng.Assert.assertEquals;
2932 import static org.testng.Assert.assertTrue;
3033 import static org.testng.Assert.fail;
3134
3235 import com.datastax.driver.core.*;
36+import com.datastax.driver.core.exceptions.CodecNotFoundException;
3337 import com.datastax.driver.core.exceptions.InvalidQueryException;
3438 import com.datastax.driver.core.utils.Bytes;
3539 import com.datastax.driver.core.utils.CassandraVersion;
3640
37-import static com.datastax.driver.core.DataType.cint;
3841 import static com.datastax.driver.core.querybuilder.QueryBuilder.*;
3942
4043 public class QueryBuilderTest {
4144
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+ }
59+
4260 @Test(groups = "unit")
4361 public void selectTest() throws Exception {
4462
@@ -46,15 +64,15 @@
4664 Statement select;
4765
4866 query = "SELECT * FROM foo WHERE k=4 AND c>'a' AND c<='z';";
49- select = select().all().from("foo").where(eq("k", 4)).and(gt("c", "a")).and(lte("c", "z"));
67+ select = builder.select().all().from("foo").where(eq("k", 4)).and(gt("c", "a")).and(lte("c", "z"));
5068 assertEquals(select.toString(), query);
5169
5270 // Ensure where() and where(...) are equal
53- select = select().all().from("foo").where().and(eq("k", 4)).and(gt("c", "a")).and(lte("c", "z"));
71+ select = builder.select().all().from("foo").where().and(eq("k", 4)).and(gt("c", "a")).and(lte("c", "z"));
5472 assertEquals(select.toString(), query);
5573
5674 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;";
57- select = select("a", "b", quote("C")).from("foo")
75+ select = builder.select("a", "b", quote("C")).from("foo")
5876 .where(in("a", InetAddress.getByName("127.0.0.1"), InetAddress.getByName("127.0.0.3")))
5977 .and(eq(quote("C"), "foo"))
6078 .orderBy(asc("a"), desc("b"))
@@ -62,114 +80,113 @@
6280 assertEquals(select.toString(), query);
6381
6482 query = "SELECT writetime(a),ttl(a) FROM foo ALLOW FILTERING;";
65- select = select().writeTime("a").ttl("a").from("foo").allowFiltering();
83+ select = builder.select().writeTime("a").ttl("a").from("foo").allowFiltering();
6684 assertEquals(select.toString(), query);
6785
6886 query = "SELECT DISTINCT longName AS a,ttl(longName) AS ttla FROM foo LIMIT :limit;";
69- select = select().distinct().column("longName").as("a").ttl("longName").as("ttla").from("foo").limit(bindMarker("limit"));
87+ select = builder.select().distinct().column("longName").as("a").ttl("longName").as("ttla").from("foo").limit(bindMarker("limit"));
7088 assertEquals(select.toString(), query);
7189
7290 query = "SELECT DISTINCT longName AS a,ttl(longName) AS ttla FROM foo WHERE k IN () LIMIT :limit;";
73- select = select().distinct().column("longName").as("a").ttl("longName").as("ttla").from("foo").where(in("k")).limit(bindMarker("limit"));
91+ select = builder.select().distinct().column("longName").as("a").ttl("longName").as("ttla").from("foo").where(in("k")).limit(bindMarker("limit"));
7492 assertEquals(select.toString(), query);
7593
7694 query = "SELECT * FROM foo WHERE bar=:barmark AND baz=:bazmark LIMIT :limit;";
77- select = select().all().from("foo").where().and(eq("bar", bindMarker("barmark"))).and(eq("baz", bindMarker("bazmark"))).limit(bindMarker("limit"));
95+ select = builder.select().all().from("foo").where().and(eq("bar", bindMarker("barmark"))).and(eq("baz", bindMarker("bazmark"))).limit(bindMarker("limit"));
7896 assertEquals(select.toString(), query);
7997
8098 query = "SELECT a FROM foo WHERE k IN ();";
81- select = select("a").from("foo").where(in("k"));
99+ select = builder.select("a").from("foo").where(in("k"));
82100 assertEquals(select.toString(), query);
83101
84102 query = "SELECT a FROM foo WHERE k IN ?;";
85- select = select("a").from("foo").where(in("k", bindMarker()));
103+ select = builder.select("a").from("foo").where(in("k", bindMarker()));
86104 assertEquals(select.toString(), query);
87105
88106 query = "SELECT DISTINCT a FROM foo WHERE k=1;";
89- select = select("a").distinct().from("foo").where(eq("k", 1));
107+ select = builder.select("a").distinct().from("foo").where(eq("k", 1));
90108 assertEquals(select.toString(), query);
91109
92110 query = "SELECT DISTINCT a,b FROM foo WHERE k=1;";
93- select = select("a", "b").distinct().from("foo").where(eq("k", 1));
111+ select = builder.select("a", "b").distinct().from("foo").where(eq("k", 1));
94112 assertEquals(select.toString(), query);
95113
96114 query = "SELECT count(*) FROM foo;";
97- select = select().countAll().from("foo");
115+ select = builder.select().countAll().from("foo");
98116 assertEquals(select.toString(), query);
99117
100118 query = "SELECT intToBlob(b) FROM foo;";
101- select = select().fcall("intToBlob", column("b")).from("foo");
119+ select = builder.select().fcall("intToBlob", column("b")).from("foo");
102120 assertEquals(select.toString(), query);
103121
104122 query = "SELECT * FROM foo WHERE k>42 LIMIT 42;";
105- select = select().all().from("foo").where(gt("k", 42)).limit(42);
123+ select = builder.select().all().from("foo").where(gt("k", 42)).limit(42);
106124 assertEquals(select.toString(), query);
107125
108126 query = "SELECT * FROM foo WHERE token(k)>token(42);";
109- select = select().all().from("foo").where(gt(token("k"), fcall("token", 42)));
127+ select = builder.select().all().from("foo").where(gt(token("k"), fcall("token", 42)));
110128 assertEquals(select.toString(), query);
111129
112130 query = "SELECT * FROM foo2 WHERE token(a,b)>token(42,101);";
113- select = select().all().from("foo2").where(gt(token("a", "b"), fcall("token", 42, 101)));
131+ select = builder.select().all().from("foo2").where(gt(token("a", "b"), fcall("token", 42, 101)));
114132 assertEquals(select.toString(), query);
115133
116134 query = "SELECT * FROM words WHERE w='):,ydL ;O,D';";
117- select = select().all().from("words").where(eq("w", "):,ydL ;O,D"));
135+ select = builder.select().all().from("words").where(eq("w", "):,ydL ;O,D"));
118136 assertEquals(select.toString(), query);
119137
120138 query = "SELECT * FROM words WHERE w='WA(!:gS)r(UfW';";
121- select = select().all().from("words").where(eq("w", "WA(!:gS)r(UfW"));
139+ select = builder.select().all().from("words").where(eq("w", "WA(!:gS)r(UfW"));
122140 assertEquals(select.toString(), query);
123141
124142 Date date = new Date();
125143 date.setTime(1234325);
126144 query = "SELECT * FROM foo WHERE d=1234325;";
127- select = select().all().from("foo").where(eq("d", date));
145+ select = builder.select().all().from("foo").where(eq("d", date));
128146 assertEquals(select.toString(), query);
129147
130148 query = "SELECT * FROM foo WHERE b=0xcafebabe;";
131- select = select().all().from("foo").where(eq("b", Bytes.fromHexString("0xCAFEBABE")));
149+ select = builder.select().all().from("foo").where(eq("b", Bytes.fromHexString("0xCAFEBABE")));
132150 assertEquals(select.toString(), query);
133151
134152 query = "SELECT * FROM foo WHERE e CONTAINS 'text';";
135- select = select().from("foo").where(contains("e", "text"));
153+ select = builder.select().from("foo").where(contains("e", "text"));
136154 assertEquals(select.toString(), query);
137155
138156 query = "SELECT * FROM foo WHERE e CONTAINS KEY 'key1';";
139- select = select().from("foo").where(containsKey("e", "key1"));
157+ select = builder.select().from("foo").where(containsKey("e", "key1"));
140158 assertEquals(select.toString(), query);
141159
142-
143160 try {
144- select().countAll().from("foo").orderBy(asc("a"), desc("b")).orderBy(asc("a"), desc("b"));
161+ builder.select().countAll().from("foo").orderBy(asc("a"), desc("b")).orderBy(asc("a"), desc("b"));
145162 fail();
146163 } catch (IllegalStateException e) {
147164 assertEquals(e.getMessage(), "An ORDER BY clause has already been provided");
148165 }
149166
150167 try {
151- select().column("a").all().from("foo");
168+ builder.select().column("a").all().from("foo");
152169 fail();
153170 } catch (IllegalStateException e) {
154171 assertEquals(e.getMessage(), "Some columns ([a]) have already been selected.");
155172 }
156173
157174 try {
158- select().column("a").countAll().from("foo");
175+ builder.select().column("a").countAll().from("foo");
159176 fail();
160177 } catch (IllegalStateException e) {
161178 assertEquals(e.getMessage(), "Some columns ([a]) have already been selected.");
162179 }
163180
164181 try {
165- select().all().from("foo").limit(-42);
182+ builder.select().all().from("foo").limit(-42);
166183 fail();
167184 } catch (IllegalArgumentException e) {
168185 assertEquals(e.getMessage(), "Invalid LIMIT value, must be strictly positive");
169186 }
170187
171188 try {
172- select().all().from("foo").limit(42).limit(42);
189+ builder.select().all().from("foo").limit(42).limit(42);
173190 fail();
174191 } catch (IllegalStateException e) {
175192 assertEquals(e.getMessage(), "A LIMIT value has already been provided");
@@ -177,14 +194,14 @@
177194 }
178195
179196 @Test(groups = "unit")
180- @SuppressWarnings("serial")
197+ @SuppressWarnings({ "serial", "deprecation" })
181198 public void insertTest() throws Exception {
182199
183200 String query;
184201 Statement insert;
185202
186203 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;";
187- insert = insertInto("foo")
204+ insert = builder.insertInto("foo")
188205 .value("a", 123)
189206 .value("b", InetAddress.getByName("127.0.0.1"))
190207 .value(quote("C"), "foo'bar")
@@ -196,13 +213,13 @@
196213 assertEquals(insert.toString(), query);
197214
198215 query = "INSERT INTO foo(a,b) VALUES (2,null);";
199- insert = insertInto("foo")
216+ insert = builder.insertInto("foo")
200217 .value("a", 2)
201218 .value("b", null);
202219 assertEquals(insert.toString(), query);
203220
204221 query = "INSERT INTO foo(a,b) VALUES ({2,3,4},3.4) USING TTL 24 AND TIMESTAMP 42;";
205- insert = insertInto("foo").values(new String[]{ "a", "b" }, new Object[]{ new TreeSet<Integer>() {{
222+ insert = builder.insertInto("foo").values(new String[]{ "a", "b" }, new Object[]{ new TreeSet<Integer>() {{
206223 add(2);
207224 add(3);
208225 add(4);
@@ -210,7 +227,7 @@
210227 assertEquals(insert.toString(), query);
211228
212229 query = "INSERT INTO foo.bar(a,b) VALUES ({2,3,4},3.4) USING TTL ? AND TIMESTAMP ?;";
213- insert = insertInto("foo", "bar")
230+ insert = builder.insertInto("foo", "bar")
214231 .values(new String[]{ "a", "b" }, new Object[]{ new TreeSet<Integer>() {{
215232 add(2);
216233 add(3);
@@ -222,7 +239,7 @@
222239
223240 // commutative result of TIMESTAMP
224241 query = "INSERT INTO foo.bar(a,b,c) VALUES ({2,3,4},3.4,123) USING TIMESTAMP 42;";
225- insert = insertInto("foo", "bar")
242+ insert = builder.insertInto("foo", "bar")
226243 .using(timestamp(42))
227244 .values(new String[]{ "a", "b" }, new Object[]{ new TreeSet<Integer>() {{
228245 add(2);
@@ -234,7 +251,7 @@
234251
235252 // commutative result of value() and values()
236253 query = "INSERT INTO foo(c,a,b) VALUES (123,{2,3,4},3.4) USING TIMESTAMP 42;";
237- insert = insertInto("foo")
254+ insert = builder.insertInto("foo")
238255 .using(timestamp(42))
239256 .value("c", 123)
240257 .values(new String[]{ "a", "b" }, new Object[]{ new TreeSet<Integer>() {{
@@ -245,7 +262,7 @@
245262 assertEquals(insert.toString(), query);
246263
247264 try {
248- insertInto("foo").values(new String[]{ "a", "b" }, new Object[]{ 1, 2, 3 });
265+ builder.insertInto("foo").values(new String[]{ "a", "b"}, new Object[]{ 1, 2, 3 });
249266 fail();
250267 } catch (IllegalArgumentException e) {
251268 assertEquals(e.getMessage(), "Got 2 names but 3 values");
@@ -253,13 +270,10 @@
253270
254271 // CAS test
255272 query = "INSERT INTO foo(k,x) VALUES (0,1) IF NOT EXISTS;";
256- insert = insertInto("foo").value("k", 0).value("x", 1).ifNotExists();
257- assertEquals(insert.toString(), query);
258-
259- query = "INSERT INTO foo(k,x) VALUES (0,(1));";
260- insert = insertInto("foo").value("k", 0).value("x", TupleType.of(cint()).newValue(1));
273+ insert = builder.insertInto("foo").value("k", 0).value("x", 1).ifNotExists();
261274 assertEquals(insert.toString(), query);
262275
276+ // Tuples: see QueryBuilderTupleExecutionTest
263277 // UDT: see QueryBuilderExecutionTest
264278 }
265279
@@ -271,23 +285,23 @@
271285 Statement update;
272286
273287 query = "UPDATE foo.bar USING TIMESTAMP 42 SET a=12,b=[3,2,1],c=c+3 WHERE k=2;";
274- 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));
288+ 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));
275289 assertEquals(update.toString(), query);
276290
277291 query = "UPDATE foo SET b=null WHERE k=2;";
278- update = update("foo").where().and(eq("k", 2)).with(set("b", null));
292+ update = builder.update("foo").where().and(eq("k", 2)).with(set("b", null));
279293 assertEquals(update.toString(), query);
280294
281295 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 = 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));
296+ 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));
283297 assertEquals(update.toString(), query);
284298
285299 query = "UPDATE foo SET b=[3]+b,c=c+['a'],d=d+[1,2,3],e=e-[1];";
286- update = update("foo").with().and(prepend("b", 3)).and(append("c", "a")).and(appendAll("d", Arrays.asList(1, 2, 3))).and(discard("e", 1));
300+ 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));
287301 assertEquals(update.toString(), query);
288302
289303 query = "UPDATE foo SET b=b-[1,2,3],c=c+{1},d=d+{2,3,4};";
290- update = update("foo").with(discardAll("b", Arrays.asList(1, 2, 3))).and(add("c", 1)).and(addAll("d", new TreeSet<Integer>() {{
304+ update = builder.update("foo").with(discardAll("b", Arrays.asList(1, 2, 3))).and(add("c", 1)).and(addAll("d", new TreeSet<Integer>() {{
291305 add(2);
292306 add(3);
293307 add(4);
@@ -295,7 +309,7 @@
295309 assertEquals(update.toString(), query);
296310
297311 query = "UPDATE foo SET b=b-{2,3,4},c['k']='v',d=d+{'x':3,'y':2};";
298- update = update("foo").with(removeAll("b", new TreeSet<Integer>() {{
312+ update = builder.update("foo").with(removeAll("b", new TreeSet<Integer>() {{
299313 add(2);
300314 add(3);
301315 add(4);
@@ -308,27 +322,27 @@
308322 assertEquals(update.toString(), query);
309323
310324 query = "UPDATE foo USING TTL 400;";
311- update = update("foo").using(ttl(400));
325+ update = builder.update("foo").using(ttl(400));
312326 assertEquals(update.toString(), query);
313327
314328 query = "UPDATE foo SET a=" + new BigDecimal(3.2) + ",b=42 WHERE k=2;";
315- update = update("foo").with(set("a", new BigDecimal(3.2))).and(set("b", new BigInteger("42"))).where(eq("k", 2));
329+ update = builder.update("foo").with(set("a", new BigDecimal(3.2))).and(set("b", new BigInteger("42"))).where(eq("k", 2));
316330 assertEquals(update.toString(), query);
317331
318332 query = "UPDATE foo USING TIMESTAMP 42 SET b=[3,2,1]+b WHERE k=2 AND l='foo';";
319- update = update("foo").where().and(eq("k", 2)).and(eq("l", "foo")).with(prependAll("b", Arrays.asList(3, 2, 1))).using(timestamp(42));
333+ update = builder.update("foo").where().and(eq("k", 2)).and(eq("l", "foo")).with(prependAll("b", Arrays.asList(3, 2, 1))).using(timestamp(42));
320334 assertEquals(update.toString(), query);
321335
322336 // Test commutative USING
323- update = update("foo").where().and(eq("k", 2)).and(eq("l", "foo")).using(timestamp(42)).with(prependAll("b", Arrays.asList(3, 2, 1)));
337+ update = builder.update("foo").where().and(eq("k", 2)).and(eq("l", "foo")).using(timestamp(42)).with(prependAll("b", Arrays.asList(3, 2, 1)));
324338 assertEquals(update.toString(), query);
325339
326340 // Test commutative USING
327- update = update("foo").using(timestamp(42)).where(eq("k", 2)).and(eq("l", "foo")).with(prependAll("b", Arrays.asList(3, 2, 1)));
341+ update = builder.update("foo").using(timestamp(42)).where(eq("k", 2)).and(eq("l", "foo")).with(prependAll("b", Arrays.asList(3, 2, 1)));
328342 assertEquals(update.toString(), query);
329343
330344 try {
331- update("foo").using(ttl(-400));
345+ builder.update("foo").using(ttl(-400));
332346 fail();
333347 } catch (IllegalArgumentException e) {
334348 assertEquals(e.getMessage(), "Invalid ttl, must be positive");
@@ -336,7 +350,7 @@
336350
337351 // CAS test
338352 query = "UPDATE foo SET x=4 WHERE k=0 IF x=1;";
339- update = update("foo").with(set("x", 4)).where(eq("k", 0)).onlyIf(eq("x", 1));
353+ update = builder.update("foo").with(set("x", 4)).where(eq("k", 0)).onlyIf(eq("x", 1));
340354 assertEquals(update.toString(), query);
341355 }
342356
@@ -347,60 +361,60 @@
347361 Statement delete;
348362
349363 query = "DELETE a,b,c FROM foo USING TIMESTAMP 0 WHERE k=1;";
350- delete = delete("a", "b", "c").from("foo").using(timestamp(0)).where(eq("k", 1));
364+ delete = builder.delete("a", "b", "c").from("foo").using(timestamp(0)).where(eq("k", 1));
351365 assertEquals(delete.toString(), query);
352366
353367 query = "DELETE a[3],b['foo'],c FROM foo WHERE k=1;";
354- delete = delete().listElt("a", 3).mapElt("b", "foo").column("c").from("foo").where(eq("k", 1));
368+ delete = builder.delete().listElt("a", 3).mapElt("b", "foo").column("c").from("foo").where(eq("k", 1));
355369 assertEquals(delete.toString(), query);
356370
357371 query = "DELETE a[?],b[?],c FROM foo WHERE k=1;";
358- delete = delete().listElt("a", bindMarker()).mapElt("b", bindMarker()).column("c").from("foo").where(eq("k", 1));
372+ delete = builder.delete().listElt("a", bindMarker()).mapElt("b", bindMarker()).column("c").from("foo").where(eq("k", 1));
359373 assertEquals(delete.toString(), query);
360374
361375 // Invalid CQL, testing edge case
362376 query = "DELETE a,b,c FROM foo;";
363- delete = delete("a", "b", "c").from("foo");
377+ delete = builder.delete("a", "b", "c").from("foo");
364378 assertEquals(delete.toString(), query);
365379
366380 query = "DELETE FROM foo USING TIMESTAMP 1240003134 WHERE k='value';";
367- delete = delete().all().from("foo").using(timestamp(1240003134L)).where(eq("k", "value"));
381+ delete = builder.delete().all().from("foo").using(timestamp(1240003134L)).where(eq("k", "value"));
368382 assertEquals(delete.toString(), query);
369- delete = delete().from("foo").using(timestamp(1240003134L)).where(eq("k", "value"));
383+ delete = builder.delete().from("foo").using(timestamp(1240003134L)).where(eq("k", "value"));
370384 assertEquals(delete.toString(), query);
371385
372386 query = "DELETE a,b,c FROM foo.bar USING TIMESTAMP 1240003134 WHERE k=1;";
373- delete = delete("a", "b", "c").from("foo", "bar").where().and(eq("k", 1)).using(timestamp(1240003134L));
387+ delete = builder.delete("a", "b", "c").from("foo", "bar").where().and(eq("k", 1)).using(timestamp(1240003134L));
374388 assertEquals(delete.toString(), query);
375389
376390 query = "DELETE FROM foo.bar WHERE k1='foo' AND k2=1;";
377- delete = delete().from("foo", "bar").where(eq("k1", "foo")).and(eq("k2", 1));
391+ delete = builder.delete().from("foo", "bar").where(eq("k1", "foo")).and(eq("k2", 1));
378392 assertEquals(delete.toString(), query);
379393
380394 try {
381- delete().column("a").all().from("foo");
395+ builder.delete().column("a").all().from("foo");
382396 fail();
383397 } catch (IllegalStateException e) {
384398 assertEquals(e.getMessage(), "Some columns ([a]) have already been selected.");
385399 }
386400
387401 try {
388- delete().from("foo").using(timestamp(-1240003134L));
402+ builder.delete().from("foo").using(timestamp(-1240003134L));
389403 fail();
390404 } catch (IllegalArgumentException e) {
391405 assertEquals(e.getMessage(), "Invalid timestamp, must be positive");
392406 }
393407
394408 query = "DELETE FROM foo.bar WHERE k1='foo' IF EXISTS;";
395- delete = delete().from("foo", "bar").where(eq("k1", "foo")).ifExists();
409+ delete = builder.delete().from("foo", "bar").where(eq("k1", "foo")).ifExists();
396410 assertEquals(delete.toString(), query);
397411
398412 query = "DELETE FROM foo.bar WHERE k1='foo' IF a=1 AND b=2;";
399- delete = delete().from("foo", "bar").where(eq("k1", "foo")).onlyIf(eq("a", 1)).and(eq("b", 2));
413+ delete = builder.delete().from("foo", "bar").where(eq("k1", "foo")).onlyIf(eq("a", 1)).and(eq("b", 2));
400414 assertEquals(delete.toString(), query);
401415
402416 query = "DELETE FROM foo WHERE k=:key;";
403- delete = delete().from("foo").where(eq("k", bindMarker("key")));
417+ delete = builder.delete().from("foo").where(eq("k", bindMarker("key")));
404418 assertEquals(delete.toString(), query);
405419 }
406420
@@ -415,14 +429,14 @@
415429 query += "UPDATE foo SET a[2]='foo',b=[3,2,1]+b,c=c-{'a'} WHERE k=2;";
416430 query += "DELETE a[3],b['foo'],c FROM foo WHERE k=1;";
417431 query += "APPLY BATCH;";
418- batch = batch()
419- .add(insertInto("foo").values(new String[]{ "a", "b" }, new Object[]{ new TreeSet<Integer>() {{
432+ batch = builder.batch()
433+ .add(builder.insertInto("foo").values(new String[]{ "a", "b" }, new Object[]{ new TreeSet<Integer>() {{
420434 add(2);
421435 add(3);
422436 add(4);
423437 }}, 3.4 }))
424- .add(update("foo").with(setIdx("a", 2, "foo")).and(prependAll("b", Arrays.asList(3, 2, 1))).and(remove("c", "a")).where(eq("k", 2)))
425- .add(delete().listElt("a", 3).mapElt("b", "foo").column("c").from("foo").where(eq("k", 1)))
438+ .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)))
439+ .add(builder.delete().listElt("a", 3).mapElt("b", "foo").column("c").from("foo").where(eq("k", 1)))
426440 .using(timestamp(42));
427441 assertEquals(batch.toString(), query);
428442
@@ -430,10 +444,10 @@
430444 query = "BEGIN BATCH ";
431445 query += "DELETE a[3] FROM foo WHERE k=1;";
432446 query += "APPLY BATCH;";
433- batch = batch(delete().listElt("a", 3).from("foo").where(eq("k", 1)));
447+ batch = builder.batch(builder.delete().listElt("a", 3).from("foo").where(eq("k", 1)));
434448 assertEquals(batch.toString(), query);
435449
436- assertEquals(batch().toString(), "BEGIN BATCH APPLY BATCH;");
450+ assertEquals(builder.batch().toString(), "BEGIN BATCH APPLY BATCH;");
437451 }
438452
439453 @Test(groups = "unit")
@@ -447,10 +461,10 @@
447461 query += "UPDATE foo SET b=b+2;";
448462 query += "UPDATE foo SET c=c+3;";
449463 query += "APPLY BATCH;";
450- batch = batch()
451- .add(update("foo").with(incr("a", 1)))
452- .add(update("foo").with(incr("b", 2)))
453- .add(update("foo").with(incr("c", 3)))
464+ batch = builder.batch()
465+ .add(builder.update("foo").with(incr("a", 1)))
466+ .add(builder.update("foo").with(incr("b", 2)))
467+ .add(builder.update("foo").with(incr("c", 3)))
454468 .using(timestamp(42));
455469 assertEquals(batch.toString(), query);
456470
@@ -460,10 +474,10 @@
460474 query += "UPDATE foo SET b=b+1;";
461475 query += "UPDATE foo SET c=c+1;";
462476 query += "APPLY BATCH;";
463- batch = batch()
464- .add(update("foo").with(incr("a")))
465- .add(update("foo").with(incr("b")))
466- .add(update("foo").with(incr("c")))
477+ batch = builder.batch()
478+ .add(builder.update("foo").with(incr("a")))
479+ .add(builder.update("foo").with(incr("b")))
480+ .add(builder.update("foo").with(incr("c")))
467481 .using(timestamp(42));
468482 assertEquals(batch.toString(), query);
469483
@@ -473,10 +487,10 @@
473487 query += "UPDATE foo SET b=b-2;";
474488 query += "UPDATE foo SET c=c-3;";
475489 query += "APPLY BATCH;";
476- batch = batch()
477- .add(update("foo").with(decr("a", 1)))
478- .add(update("foo").with(decr("b", 2)))
479- .add(update("foo").with(decr("c", 3)))
490+ batch = builder.batch()
491+ .add(builder.update("foo").with(decr("a", 1)))
492+ .add(builder.update("foo").with(decr("b", 2)))
493+ .add(builder.update("foo").with(decr("c", 3)))
480494 .using(timestamp(42));
481495 assertEquals(batch.toString(), query);
482496
@@ -486,10 +500,10 @@
486500 query += "UPDATE foo SET b=b-1;";
487501 query += "UPDATE foo SET c=c-1;";
488502 query += "APPLY BATCH;";
489- batch = batch()
490- .add(update("foo").with(decr("a")))
491- .add(update("foo").with(decr("b")))
492- .add(update("foo").with(decr("c")))
503+ batch = builder.batch()
504+ .add(builder.update("foo").with(decr("a")))
505+ .add(builder.update("foo").with(decr("b")))
506+ .add(builder.update("foo").with(decr("c")))
493507 .using(timestamp(42));
494508 assertEquals(batch.toString(), query);
495509
@@ -499,20 +513,20 @@
499513 query += "UPDATE foo SET b=b+-2;";
500514 query += "UPDATE foo SET c=c-3;";
501515 query += "APPLY BATCH;";
502- batch = batch()
503- .add(update("foo").with(decr("a", -1)))
504- .add(update("foo").with(incr("b", -2)))
505- .add(update("foo").with(decr("c", 3)))
516+ batch = builder.batch()
517+ .add(builder.update("foo").with(decr("a", -1)))
518+ .add(builder.update("foo").with(incr("b", -2)))
519+ .add(builder.update("foo").with(decr("c", 3)))
506520 .using(timestamp(42));
507521 assertEquals(batch.toString(), query);
508522 }
509523
510524 @Test(groups = "unit", expectedExceptions = { IllegalArgumentException.class })
511525 public void batchMixedCounterTest() throws Exception {
512- batch()
513- .add(update("foo").with(incr("a", 1)))
514- .add(update("foo").with(set("b", 2)))
515- .add(update("foo").with(incr("c", 3)))
526+ builder.batch()
527+ .add(builder.update("foo").with(incr("a", 1)))
528+ .add(builder.update("foo").with(set("b", 2)))
529+ .add(builder.update("foo").with(incr("c", 3)))
516530 .using(timestamp(42));
517531 }
518532
@@ -522,7 +536,7 @@
522536 Statement insert;
523537
524538 query = "INSERT INTO test(k,c) VALUES (0,?);";
525- insert = insertInto("test")
539+ insert = builder.insertInto("test")
526540 .value("k", 0)
527541 .value("c", bindMarker());
528542 assertEquals(insert.toString(), query);
@@ -535,19 +549,19 @@
535549 Statement select;
536550
537551 query = "SELECT * FROM t WHERE c='C''est la vie!';";
538- select = select().from("t").where(eq("c", "C'est la vie!"));
552+ select = builder.select().from("t").where(eq("c", "C'est la vie!"));
539553 assertEquals(select.toString(), query);
540554
541555 query = "SELECT * FROM t WHERE c=C'est la vie!;";
542- select = select().from("t").where(eq("c", raw("C'est la vie!")));
556+ select = builder.select().from("t").where(eq("c", raw("C'est la vie!")));
543557 assertEquals(select.toString(), query);
544558
545559 query = "SELECT * FROM t WHERE c=now();";
546- select = select().from("t").where(eq("c", fcall("now")));
560+ select = builder.select().from("t").where(eq("c", fcall("now")));
547561 assertEquals(select.toString(), query);
548562
549563 query = "SELECT * FROM t WHERE c='now()';";
550- select = select().from("t").where(eq("c", raw("'now()'")));
564+ select = builder.select().from("t").where(eq("c", raw("'now()'")));
551565 assertEquals(select.toString(), query);
552566 }
553567
@@ -558,52 +572,52 @@
558572 Statement select;
559573
560574 query = "SELECT * FROM \"foo WHERE k=4\";";
561- select = select().all().from("foo WHERE k=4");
575+ select = builder.select().all().from("foo WHERE k=4");
562576 assertEquals(select.toString(), query);
563577
564578 query = "SELECT * FROM foo WHERE k='4 AND c=5';";
565- select = select().all().from("foo").where(eq("k", "4 AND c=5"));
579+ select = builder.select().all().from("foo").where(eq("k", "4 AND c=5"));
566580 assertEquals(select.toString(), query);
567581
568582 query = "SELECT * FROM foo WHERE k='4'' AND c=''5';";
569- select = select().all().from("foo").where(eq("k", "4' AND c='5"));
583+ select = builder.select().all().from("foo").where(eq("k", "4' AND c='5"));
570584 assertEquals(select.toString(), query);
571585
572586 query = "SELECT * FROM foo WHERE k='4'' OR ''1''=''1';";
573- select = select().all().from("foo").where(eq("k", "4' OR '1'='1"));
587+ select = builder.select().all().from("foo").where(eq("k", "4' OR '1'='1"));
574588 assertEquals(select.toString(), query);
575589
576590 query = "SELECT * FROM foo WHERE k='4; --test comment;';";
577- select = select().all().from("foo").where(eq("k", "4; --test comment;"));
591+ select = builder.select().all().from("foo").where(eq("k", "4; --test comment;"));
578592 assertEquals(select.toString(), query);
579593
580594 query = "SELECT \"*\" FROM foo;";
581- select = select("*").from("foo");
595+ select = builder.select("*").from("foo");
582596 assertEquals(select.toString(), query);
583597
584598 query = "SELECT a,b FROM foo WHERE a IN ('b','c''); --comment');";
585- select = select("a", "b").from("foo").where(in("a", "b", "c'); --comment"));
599+ select = builder.select("a", "b").from("foo").where(in("a", "b", "c'); --comment"));
586600 assertEquals(select.toString(), query);
587601
588602 // User Injection?
589603 query = "SELECT * FROM bar; --(b) FROM foo;";
590- select = select().fcall("* FROM bar; --", column("b")).from("foo");
604+ select = builder.select().fcall("* FROM bar; --", column("b")).from("foo");
591605 assertEquals(select.toString(), query);
592606
593607 query = "SELECT writetime(\"a) FROM bar; --\"),ttl(a) FROM foo ALLOW FILTERING;";
594- select = select().writeTime("a) FROM bar; --").ttl("a").from("foo").allowFiltering();
608+ select = builder.select().writeTime("a) FROM bar; --").ttl("a").from("foo").allowFiltering();
595609 assertEquals(select.toString(), query);
596610
597611 query = "SELECT writetime(a),ttl(\"a) FROM bar; --\") FROM foo ALLOW FILTERING;";
598- select = select().writeTime("a").ttl("a) FROM bar; --").from("foo").allowFiltering();
612+ select = builder.select().writeTime("a").ttl("a) FROM bar; --").from("foo").allowFiltering();
599613 assertEquals(select.toString(), query);
600614
601615 query = "SELECT * FROM foo WHERE \"k=1 OR k\">42 LIMIT 42;";
602- select = select().all().from("foo").where(gt("k=1 OR k", 42)).limit(42);
616+ select = builder.select().all().from("foo").where(gt("k=1 OR k", 42)).limit(42);
603617 assertEquals(select.toString(), query);
604618
605619 query = "SELECT * FROM foo WHERE token(\"k)>0 OR token(k\")>token(42);";
606- select = select().all().from("foo").where(gt(token("k)>0 OR token(k"), fcall("token", 42)));
620+ select = builder.select().all().from("foo").where(gt(token("k)>0 OR token(k"), fcall("token", 42)));
607621 assertEquals(select.toString(), query);
608622 }
609623
@@ -615,15 +629,15 @@
615629 Statement insert;
616630
617631 query = "INSERT INTO foo(a) VALUES ('123); --comment');";
618- insert = insertInto("foo").value("a", "123); --comment");
632+ insert = builder.insertInto("foo").value("a", "123); --comment");
619633 assertEquals(insert.toString(), query);
620634
621635 query = "INSERT INTO foo(\"a,b\") VALUES (123);";
622- insert = insertInto("foo").value("a,b", 123);
636+ insert = builder.insertInto("foo").value("a,b", 123);
623637 assertEquals(insert.toString(), query);
624638
625639 query = "INSERT INTO foo(a,b) VALUES ({'2''} space','3','4'},3.4) USING TTL 24 AND TIMESTAMP 42;";
626- insert = insertInto("foo").values(new String[]{ "a", "b" }, new Object[]{ new TreeSet<String>() {{
640+ insert = builder.insertInto("foo").values(new String[]{ "a", "b" }, new Object[]{ new TreeSet<String>() {{
627641 add("2'} space");
628642 add("3");
629643 add("4");
@@ -638,15 +652,15 @@
638652 Statement update;
639653
640654 query = "UPDATE foo.bar USING TIMESTAMP 42 SET a=12 WHERE k='2 OR 1=1';";
641- update = update("foo", "bar").using(timestamp(42)).with(set("a", 12)).where(eq("k", "2 OR 1=1"));
655+ update = builder.update("foo", "bar").using(timestamp(42)).with(set("a", 12)).where(eq("k", "2 OR 1=1"));
642656 assertEquals(update.toString(), query);
643657
644658 query = "UPDATE foo SET b='null WHERE k=1; --comment' WHERE k=2;";
645- update = update("foo").where().and(eq("k", 2)).with(set("b", "null WHERE k=1; --comment"));
659+ update = builder.update("foo").where().and(eq("k", 2)).with(set("b", "null WHERE k=1; --comment"));
646660 assertEquals(update.toString(), query);
647661
648662 query = "UPDATE foo USING TIMESTAMP 42 SET \"b WHERE k=1; --comment\"=[3,2,1]+\"b WHERE k=1; --comment\" WHERE k=2;";
649- update = update("foo").where().and(eq("k", 2)).with(prependAll("b WHERE k=1; --comment", Arrays.asList(3, 2, 1))).using(timestamp(42));
663+ update = builder.update("foo").where().and(eq("k", 2)).with(prependAll("b WHERE k=1; --comment", Arrays.asList(3, 2, 1))).using(timestamp(42));
650664 assertEquals(update.toString(), query);
651665 }
652666
@@ -657,47 +671,47 @@
657671 Statement delete;
658672
659673 query = "DELETE FROM \"foo WHERE k=4\";";
660- delete = delete().from("foo WHERE k=4");
674+ delete = builder.delete().from("foo WHERE k=4");
661675 assertEquals(delete.toString(), query);
662676
663677 query = "DELETE FROM foo WHERE k='4 AND c=5';";
664- delete = delete().from("foo").where(eq("k", "4 AND c=5"));
678+ delete = builder.delete().from("foo").where(eq("k", "4 AND c=5"));
665679 assertEquals(delete.toString(), query);
666680
667681 query = "DELETE FROM foo WHERE k='4'' AND c=''5';";
668- delete = delete().from("foo").where(eq("k", "4' AND c='5"));
682+ delete = builder.delete().from("foo").where(eq("k", "4' AND c='5"));
669683 assertEquals(delete.toString(), query);
670684
671685 query = "DELETE FROM foo WHERE k='4'' OR ''1''=''1';";
672- delete = delete().from("foo").where(eq("k", "4' OR '1'='1"));
686+ delete = builder.delete().from("foo").where(eq("k", "4' OR '1'='1"));
673687 assertEquals(delete.toString(), query);
674688
675689 query = "DELETE FROM foo WHERE k='4; --test comment;';";
676- delete = delete().from("foo").where(eq("k", "4; --test comment;"));
690+ delete = builder.delete().from("foo").where(eq("k", "4; --test comment;"));
677691 assertEquals(delete.toString(), query);
678692
679693 query = "DELETE \"*\" FROM foo;";
680- delete = delete("*").from("foo");
694+ delete = builder.delete("*").from("foo");
681695 assertEquals(delete.toString(), query);
682696
683697 query = "DELETE a,b FROM foo WHERE a IN ('b','c''); --comment');";
684- delete = delete("a", "b").from("foo")
698+ delete = builder.delete("a", "b").from("foo")
685699 .where(in("a", "b", "c'); --comment"));
686700 assertEquals(delete.toString(), query);
687701
688702 query = "DELETE FROM foo WHERE \"k=1 OR k\">42;";
689- delete = delete().from("foo").where(gt("k=1 OR k", 42));
703+ delete = builder.delete().from("foo").where(gt("k=1 OR k", 42));
690704 assertEquals(delete.toString(), query);
691705
692706 query = "DELETE FROM foo WHERE token(\"k)>0 OR token(k\")>token(42);";
693- delete = delete().from("foo").where(gt(token("k)>0 OR token(k"), fcall("token", 42)));
707+ delete = builder.delete().from("foo").where(gt(token("k)>0 OR token(k"), fcall("token", 42)));
694708 assertEquals(delete.toString(), query);
695709 }
696710
697711 @Test(groups = "unit")
698712 public void statementForwardingTest() throws Exception {
699713
700- Update upd = update("foo");
714+ Update upd = builder.update("foo");
701715 upd.setConsistencyLevel(ConsistencyLevel.QUORUM);
702716 upd.enableTracing();
703717
@@ -709,40 +723,39 @@
709723
710724 @Test(groups = "unit")
711725 public void rejectUnknownValueTest() throws Exception {
712-
713726 try {
714727 //noinspection ResultOfMethodCallIgnored
715- update("foo").with(set("a", new byte[13])).where(eq("k", 2)).toString();
728+ builder.update("foo").with(set("a", new byte[13])).where(eq("k", 2)).toString();
716729 fail("Byte arrays should not be valid, ByteBuffer should be used instead");
717- } catch (IllegalArgumentException e) {
730+ } catch (CodecNotFoundException e) {
718731 // Ok, that's what we expect
719732 }
720733 }
721734
722735 @Test(groups = "unit")
723736 public void truncateTest() throws Exception {
724- assertEquals(truncate("foo").toString(), "TRUNCATE foo;");
725- assertEquals(truncate("foo", quote("Bar")).toString(), "TRUNCATE foo.\"Bar\";");
737+ assertEquals(builder.truncate("foo").toString(), "TRUNCATE foo;");
738+ assertEquals(builder.truncate("foo", quote("Bar")).toString(), "TRUNCATE foo.\"Bar\";");
726739 }
727740
728741 @Test(groups = "unit")
729742 public void quotingTest() {
730- assertEquals(QueryBuilder.select().from("Metrics", "epochs").getQueryString(),
743+ assertEquals(builder.select().from("Metrics", "epochs").toString(),
731744 "SELECT * FROM Metrics.epochs;");
732- assertEquals(QueryBuilder.select().from("Metrics", quote("epochs")).getQueryString(),
745+ assertEquals(builder.select().from("Metrics", quote("epochs")).toString(),
733746 "SELECT * FROM Metrics.\"epochs\";");
734- assertEquals(QueryBuilder.select().from(quote("Metrics"), "epochs").getQueryString(),
747+ assertEquals(builder.select().from(quote("Metrics"), "epochs").toString(),
735748 "SELECT * FROM \"Metrics\".epochs;");
736- assertEquals(QueryBuilder.select().from(quote("Metrics"), quote("epochs")).getQueryString(),
749+ assertEquals(builder.select().from(quote("Metrics"), quote("epochs")).toString(),
737750 "SELECT * FROM \"Metrics\".\"epochs\";");
738751
739- assertEquals(QueryBuilder.insertInto("Metrics", "epochs").getQueryString(),
752+ assertEquals(builder.insertInto("Metrics", "epochs").toString(),
740753 "INSERT INTO Metrics.epochs() VALUES ();");
741- assertEquals(QueryBuilder.insertInto("Metrics", quote("epochs")).getQueryString(),
754+ assertEquals(builder.insertInto("Metrics", quote("epochs")).toString(),
742755 "INSERT INTO Metrics.\"epochs\"() VALUES ();");
743- assertEquals(QueryBuilder.insertInto(quote("Metrics"), "epochs").getQueryString(),
756+ assertEquals(builder.insertInto(quote("Metrics"), "epochs").toString(),
744757 "INSERT INTO \"Metrics\".epochs() VALUES ();");
745- assertEquals(QueryBuilder.insertInto(quote("Metrics"), quote("epochs")).getQueryString(),
758+ assertEquals(builder.insertInto(quote("Metrics"), quote("epochs")).toString(),
746759 "INSERT INTO \"Metrics\".\"epochs\"() VALUES ();");
747760 }
748761
@@ -752,23 +765,23 @@
752765 Statement select;
753766
754767 query = "SELECT * FROM foo WHERE k=4 AND (c1,c2)>('a',2);";
755- select = select().all().from("foo").where(eq("k", 4)).and(gt(Arrays.asList("c1", "c2"), Arrays.<Object>asList("a", 2)));
768+ select = builder.select().all().from("foo").where(eq("k", 4)).and(gt(Arrays.asList("c1", "c2"), Arrays.<Object>asList("a", 2)));
756769 assertEquals(select.toString(), query);
757770
758771 query = "SELECT * FROM foo WHERE k=4 AND (c1,c2)>=('a',2) AND (c1,c2)<('b',0);";
759- select = select().all().from("foo").where(eq("k", 4)).and(gte(Arrays.asList("c1", "c2"), Arrays.<Object>asList("a", 2)))
772+ select = builder.select().all().from("foo").where(eq("k", 4)).and(gte(Arrays.asList("c1", "c2"), Arrays.<Object>asList("a", 2)))
760773 .and(lt(Arrays.asList("c1", "c2"), Arrays.<Object>asList("b", 0)));
761774 assertEquals(select.toString(), query);
762775
763776 query = "SELECT * FROM foo WHERE k=4 AND (c1,c2)<=('a',2);";
764- select = select().all().from("foo").where(eq("k", 4)).and(lte(Arrays.asList("c1", "c2"), Arrays.<Object>asList("a", 2)));
777+ select = builder.select().all().from("foo").where(eq("k", 4)).and(lte(Arrays.asList("c1", "c2"), Arrays.<Object>asList("a", 2)));
765778 assertEquals(select.toString(), query);
766779 }
767780
768781 @Test(groups = "unit", expectedExceptions = IllegalArgumentException.class)
769782 public void should_fail_if_in_clause_has_too_many_values() {
770783 List<Object> values = Collections.<Object>nCopies(65536, "a");
771- select().all().from("foo").where(in("bar", values.toArray()));
784+ builder.select().all().from("foo").where(in("bar", values.toArray()));
772785 }
773786
774787 @Test(groups = "unit", expectedExceptions = IllegalArgumentException.class)
@@ -776,24 +789,13 @@
776789 List<Object> values = Collections.<Object>nCopies(65535, "a");
777790
778791 // If the excessive count results from successive DSL calls, we don't check it on the fly so this statement works:
779- BuiltStatement statement = select().all().from("foo")
792+ BuiltStatement statement = builder.select().all().from("foo")
780793 .where(eq("bar", "a"))
781794 .and(in("baz", values.toArray()));
782795
783796 // But we still want to check it client-side, to fail fast instead of sending a bad query to Cassandra.
784797 // getValues() is called on any RegularStatement before we send it (see SessionManager.makeRequestMessage).
785- statement.getValues(ProtocolVersion.V3);
786- }
787-
788- @Test(groups = "unit")
789- public void should_handle_collections_of_tuples() {
790- String query;
791- Statement statement;
792-
793- query = "UPDATE foo SET l=[(1, 2)] WHERE k=1;";
794- List<TupleValue> list = ImmutableList.of(TupleType.of(cint(), cint()).newValue(1, 2));
795- statement = update("foo").with(set("l", list)).where(eq("k", 1));
796- assertThat(statement.toString()).isEqualTo(query);
798+ statement.getValues();
797799 }
798800
799801 @Test(groups = "unit")
@@ -804,57 +806,57 @@
804806
805807 query = "UPDATE foo SET l=[[1],[2]] WHERE k=1;";
806808 ImmutableList<ImmutableList<Integer>> list = ImmutableList.of(ImmutableList.of(1), ImmutableList.of(2));
807- statement = update("foo").with(set("l", list)).where(eq("k", 1));
809+ statement = builder.update("foo").with(set("l", list)).where(eq("k", 1));
808810 assertThat(statement.toString()).isEqualTo(query);
809811
810812 query = "UPDATE foo SET m={1:[[1],[2]],2:[[1],[2]]} WHERE k=1;";
811- statement = update("foo").with(set("m", ImmutableMap.of(1, list, 2, list))).where(eq("k", 1));
813+ statement = builder.update("foo").with(set("m", ImmutableMap.of(1, list, 2, list))).where(eq("k", 1));
812814 assertThat(statement.toString()).isEqualTo(query);
813815
814816 query = "UPDATE foo SET m=m+{1:[[1],[2]],2:[[1],[2]]} WHERE k=1;";
815- statement = update("foo").with(putAll("m", ImmutableMap.of(1, list, 2, list))).where(eq("k", 1));
817+ statement = builder.update("foo").with(putAll("m", ImmutableMap.of(1, list, 2, list))).where(eq("k", 1));
816818 assertThat(statement.toString()).isEqualTo(query);
817819
818820 query = "UPDATE foo SET l=[[1]]+l WHERE k=1;";
819- statement = update("foo").with(prepend("l", ImmutableList.of(1))).where(eq("k", 1));
821+ statement = builder.update("foo").with(prepend("l", ImmutableList.of(1))).where(eq("k", 1));
820822 assertThat(statement.toString()).isEqualTo(query);
821823
822824 query = "UPDATE foo SET l=[[1],[2]]+l WHERE k=1;";
823- statement = update("foo").with(prependAll("l", list)).where(eq("k", 1));
825+ statement = builder.update("foo").with(prependAll("l", list)).where(eq("k", 1));
824826 assertThat(statement.toString()).isEqualTo(query);
825827 }
826828
827829 @Test(groups = "unit", expectedExceptions = InvalidQueryException.class)
828830 public void should_not_allow_bind_marker_for_add() {
829831 // This generates the query "UPDATE foo SET s = s + {?} WHERE k = 1", which is invalid in Cassandra
830- update("foo").with(add("s", bindMarker())).where(eq("k", 1));
832+ builder.update("foo").with(add("s", bindMarker())).where(eq("k", 1));
831833 }
832834
833835 @Test(groups = "unit", expectedExceptions = InvalidQueryException.class)
834836 public void should_now_allow_bind_marker_for_prepend() {
835- update("foo").with(prepend("l", bindMarker())).where(eq("k", 1));
837+ builder.update("foo").with(prepend("l", bindMarker())).where(eq("k", 1));
836838 }
837839
838840 @Test(groups = "unit", expectedExceptions = InvalidQueryException.class)
839841 public void should_not_allow_bind_marker_for_append() {
840- update("foo").with(append("l", bindMarker())).where(eq("k", 1));
842+ builder.update("foo").with(append("l", bindMarker())).where(eq("k", 1));
841843 }
842844
843845 @Test(groups = "unit", expectedExceptions = InvalidQueryException.class)
844846 public void should_not_allow_bind_marker_for_remove() {
845- update("foo").with(remove("s", bindMarker())).where(eq("k", 1));
847+ builder.update("foo").with(remove("s", bindMarker())).where(eq("k", 1));
846848 }
847849
848850 @Test(groups = "unit", expectedExceptions = InvalidQueryException.class)
849851 public void should_not_allow_bind_marker_for_discard() {
850- update("foo").with(discard("l", bindMarker())).where(eq("k", 1));
852+ builder.update("foo").with(discard("l", bindMarker())).where(eq("k", 1));
851853 }
852854
853855 @Test(groups = "unit")
854856 public void should_quote_complex_column_names() {
855857 // A column name can be anything as long as it's quoted, so "foo.bar" is a valid name
856858 String query = "SELECT * FROM foo WHERE \"foo.bar\"=1;";
857- Statement statement = select().from("foo").where(eq(quote("foo.bar"), 1));
859+ Statement statement = builder.select().from("foo").where(eq(quote("foo.bar"), 1));
858860
859861 assertThat(statement.toString()).isEqualTo(query);
860862 }
@@ -863,15 +865,15 @@
863865 public void should_quote_column_names_with_escaped_quotes() {
864866 // A column name can include quotes as long as it is escaped with another set of quotes, so "foo""bar" is a valid name.
865867 String query = "SELECT * FROM foo WHERE \"foo \"\" bar\"=1;";
866- Statement statement = select().from("foo").where(eq(quote("foo \"\" bar"), 1));
868+ Statement statement = builder.select().from("foo").where(eq(quote("foo \"\" bar"), 1));
867869
868870 assertThat(statement.toString()).isEqualTo(query);
869871 }
870872
871873 @Test(groups = "unit")
872874 public void should_not_serialize_raw_query_values() {
873- RegularStatement select = select().from("test").where(gt("i", raw("1")));
875+ RegularStatement select = builder.select().from("test").where(gt("i", raw("1")));
874876 assertThat(select.getQueryString()).doesNotContain("?");
875- assertThat(select.getValues(ProtocolVersion.V3)).isNull();
877+ assertThat(select.getValues()).isNull();
876878 }
877879 }
added driver-core/src/test/java/com/datastax/driver/core/querybuilder/QueryBuilderTupleExecutionTest.java +65 −0
@@ -0,0 +1,65 @@
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.querybuilder;
17+
18+import java.util.Collection;
19+import java.util.Collections;
20+import java.util.List;
21+
22+import com.google.common.collect.ImmutableList;
23+import org.testng.annotations.Test;
24+
25+import static org.assertj.core.api.Assertions.assertThat;
26+import static org.testng.Assert.assertEquals;
27+
28+import com.datastax.driver.core.CCMBridge;
29+import com.datastax.driver.core.TupleType;
30+import com.datastax.driver.core.TupleValue;
31+import com.datastax.driver.core.utils.CassandraVersion;
32+
33+import static com.datastax.driver.core.DataType.cint;
34+import static com.datastax.driver.core.querybuilder.QueryBuilder.eq;
35+import static com.datastax.driver.core.querybuilder.QueryBuilder.set;
36+
37+@CassandraVersion(major=2.1, minor=3)
38+public class QueryBuilderTupleExecutionTest extends CCMBridge.PerClassSingleNodeCluster {
39+
40+ @Override
41+ protected Collection<String> getTableDefinitions() {
42+ return Collections.emptyList();
43+ }
44+
45+ @Test(groups = "short")
46+ public void should_handle_tuple() throws Exception {
47+ String query = "INSERT INTO foo(k,x) VALUES (0,(1));";
48+ TupleType tupleType = cluster.getMetadata().newTupleType(cint());
49+ BuiltStatement insert = new QueryBuilder(cluster).insertInto("foo").value("k", 0).value("x", tupleType.newValue(1));
50+ assertEquals(insert.toString(), query);
51+ }
52+
53+ @SuppressWarnings("deprecation")
54+ @Test(groups = "short")
55+ public void should_handle_collections_of_tuples() {
56+ String query;
57+ BuiltStatement statement;
58+ query = "UPDATE foo SET l=[(1, 2)] WHERE k=1;";
59+ TupleType tupleType = cluster.getMetadata().newTupleType(cint(), cint());
60+ List<TupleValue> list = ImmutableList.of(tupleType.newValue(1, 2));
61+ statement = new QueryBuilder(cluster).update("foo").with(set("l", list)).where(eq("k", 1));
62+ assertThat(statement.toString()).isEqualTo(query);
63+ }
64+
65+}
modified driver-core/src/test/java/com/datastax/driver/core/querybuilder/QueryBuilderUDTExecutionTest.java +9 −12
@@ -32,10 +32,7 @@
3232 import com.datastax.driver.core.utils.CassandraVersion;
3333
3434 import static com.datastax.driver.core.querybuilder.QueryBuilder.eq;
35-import static com.datastax.driver.core.querybuilder.QueryBuilder.insertInto;
3635 import static com.datastax.driver.core.querybuilder.QueryBuilder.putAll;
37-import static com.datastax.driver.core.querybuilder.QueryBuilder.select;
38-import static com.datastax.driver.core.querybuilder.QueryBuilder.update;
3936
4037 @CassandraVersion(major=2.1, minor=3)
4138 public class QueryBuilderUDTExecutionTest extends CCMBridge.PerClassSingleNodeCluster {
@@ -51,12 +48,12 @@
5148 UserType udtType = cluster.getMetadata().getKeyspace(keyspace).getUserType("udt");
5249 UDTValue udtValue = udtType.newValue().setInt("i", 2).setInet("a", InetAddress.getByName("localhost"));
5350
54- Statement insert = insertInto("udtTest").value("k", 1).value("t", udtValue);
55- assertEquals(insert.toString(), "INSERT INTO udtTest(k,t) VALUES (1,{i:2, a:'127.0.0.1'});");
51+ Statement insert = new QueryBuilder(cluster).insertInto("udtTest").value("k", 1).value("t", udtValue);
52+ assertEquals(insert.toString(), "INSERT INTO udtTest(k,t) VALUES (1,{i:2,a:'127.0.0.1'});");
5653
5754 session.execute(insert);
5855
59- List<Row> rows = session.execute(select().from("udtTest").where(eq("k", 1))).all();
56+ List<Row> rows = session.execute(new QueryBuilder(cluster).select().from("udtTest").where(eq("k", 1))).all();
6057
6158 assertEquals(rows.size(), 1);
6259
@@ -70,12 +67,12 @@
7067 UDTValue udtValue = udtType.newValue().setInt("i", 2).setInet("a", InetAddress.getByName("localhost"));
7168 UDTValue udtValue2 = udtType.newValue().setInt("i", 3).setInet("a", InetAddress.getByName("localhost"));
7269
73- Statement insert = insertInto("udtTest").value("k", 1).value("l", ImmutableList.of(udtValue));
74- assertThat(insert.toString()).isEqualTo("INSERT INTO udtTest(k,l) VALUES (1,[{i:2, a:'127.0.0.1'}]);");
70+ Statement insert = new QueryBuilder(cluster).insertInto("udtTest").value("k", 1).value("l", ImmutableList.of(udtValue));
71+ assertThat(insert.toString()).isEqualTo("INSERT INTO udtTest(k,l) VALUES (1,[{i:2,a:'127.0.0.1'}]);");
7572
7673 session.execute(insert);
7774
78- List<Row> rows = session.execute(select().from("udtTest").where(eq("k", 1))).all();
75+ List<Row> rows = session.execute(new QueryBuilder(cluster).select().from("udtTest").where(eq("k", 1))).all();
7976
8077 assertThat(rows.size()).isEqualTo(1);
8178
@@ -85,13 +82,13 @@
8582 Map<Integer, UDTValue> map = Maps.newHashMap();
8683 map.put(0, udtValue);
8784 map.put(2, udtValue2);
88- Statement updateMap = update("udtTest").with(putAll("m", map)).where(eq("k", 1));
85+ Statement updateMap = new QueryBuilder(cluster).update("udtTest").with(putAll("m", map)).where(eq("k", 1));
8986 assertThat(updateMap.toString())
90- .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;");
87+ .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;");
9188
9289 session.execute(updateMap);
9390
94- rows = session.execute(select().from("udtTest").where(eq("k", 1))).all();
91+ rows = session.execute(new QueryBuilder(cluster).select().from("udtTest").where(eq("k", 1))).all();
9592 r1 = rows.get(0);
9693 assertThat(r1.getMap("m", Integer.class, UDTValue.class)).isEqualTo(map);
9794 }
modified driver-core/src/test/java/com/datastax/driver/core/utils/UUIDsTest.java +4 −3
@@ -26,6 +26,7 @@
2626
2727 import com.datastax.driver.core.DataType;
2828 import com.datastax.driver.core.ProtocolVersion;
29+import com.datastax.driver.core.TypeCodec;
2930
3031 public class UUIDsTest {
3132
@@ -110,9 +111,9 @@
110111 }
111112
112113 private static void assertWithin(UUID uuid, UUID lowerBound, UUID upperBound) {
113- ByteBuffer uuidBytes = DataType.uuid().serialize(uuid, ProtocolVersion.V1);
114- ByteBuffer lb = DataType.uuid().serialize(lowerBound, ProtocolVersion.V1);
115- ByteBuffer ub = DataType.uuid().serialize(upperBound, ProtocolVersion.V1);
114+ ByteBuffer uuidBytes = TypeCodec.UUIDCodec.instance.serialize(uuid, ProtocolVersion.V1);
115+ ByteBuffer lb = TypeCodec.UUIDCodec.instance.serialize(lowerBound, ProtocolVersion.V1);
116+ ByteBuffer ub = TypeCodec.UUIDCodec.instance.serialize(upperBound, ProtocolVersion.V1);
116117 assertTrue(compareTimestampBytes(lb, uuidBytes) <= 0);
117118 assertTrue(compareTimestampBytes(ub, uuidBytes) >= 0);
118119 }
modified driver-examples/osgi/src/main/java/com/datastax/driver/osgi/impl/MailboxImpl.java +5 −6
@@ -22,16 +22,14 @@
2222
2323 import com.datastax.driver.core.*;
2424 import com.datastax.driver.core.exceptions.InvalidQueryException;
25+import com.datastax.driver.core.querybuilder.QueryBuilder;
2526 import com.datastax.driver.core.utils.UUIDs;
2627 import com.datastax.driver.osgi.api.MailboxException;
2728 import com.datastax.driver.osgi.api.MailboxMessage;
2829 import com.datastax.driver.osgi.api.MailboxService;
2930
3031 import static com.datastax.driver.core.querybuilder.QueryBuilder.bindMarker;
31-import static com.datastax.driver.core.querybuilder.QueryBuilder.delete;
3232 import static com.datastax.driver.core.querybuilder.QueryBuilder.eq;
33-import static com.datastax.driver.core.querybuilder.QueryBuilder.insertInto;
34-import static com.datastax.driver.core.querybuilder.QueryBuilder.select;
3533
3634 public class MailboxImpl implements MailboxService {
3735
@@ -73,17 +71,18 @@
7371 "PRIMARY KEY (recipient, time))");
7472 }
7573
76- retrieveStatement = session.prepare(select()
74+ QueryBuilder builder = new QueryBuilder(session.getCluster());
75+ retrieveStatement = session.prepare(builder.select()
7776 .from(keyspace, TABLE)
7877 .where(eq("recipient", bindMarker())));
7978
80- insertStatement = session.prepare(insertInto(keyspace, TABLE)
79+ insertStatement = session.prepare(builder.insertInto(keyspace, TABLE)
8180 .value("recipient", bindMarker())
8281 .value("time", bindMarker())
8382 .value("sender", bindMarker())
8483 .value("body", bindMarker()));
8584
86- deleteStatement = session.prepare(delete().from(keyspace, TABLE)
85+ deleteStatement = session.prepare(builder.delete().from(keyspace, TABLE)
8786 .where(eq("recipient", bindMarker())));
8887
8988 initialized = true;
modified driver-examples/stress/src/main/java/com/datastax/driver/stress/Generators.java +6 −6
@@ -104,11 +104,11 @@
104104 public QueryGenerator create(int id, int iterations, OptionSet options, Session session) {
105105
106106 return options.has("no-prepare")
107- ? createRegular(id, iterations, options)
107+ ? createRegular(id, iterations, options, session)
108108 : createPrepared(id, iterations, options, session);
109109 }
110110
111- public QueryGenerator createRegular(int id, int iterations, OptionSet options) {
111+ public QueryGenerator createRegular(int id, int iterations, OptionSet options, final Session session) {
112112 final int valueSize = (Integer)options.valueOf("value-size");
113113 final int columnsPerRow = (Integer)options.valueOf("columns-per-row");
114114 final long prefix = (long) id << 32;
@@ -124,7 +124,7 @@
124124 }
125125 sb.append(" WHERE key = ").append(prefix | iteration);
126126 ++iteration;
127- return new QueryGenerator.Request.SimpleQuery(new SimpleStatement(sb.toString()));
127+ return new QueryGenerator.Request.SimpleQuery(session.newSimpleStatement(sb.toString()));
128128 }
129129 };
130130 }
@@ -184,11 +184,11 @@
184184
185185 public QueryGenerator create(int id, int iterations, OptionSet options, Session session) {
186186 return options.has("no-prepare")
187- ? createRegular(id, iterations)
187+ ? createRegular(id, iterations, session)
188188 : createPrepared(id, iterations, session);
189189 }
190190
191- public QueryGenerator createRegular(long id, int iterations) {
191+ public QueryGenerator createRegular(long id, int iterations, final Session session) {
192192 final long prefix = (long) id << 32;
193193 return new AbstractGenerator(iterations) {
194194 @Override
@@ -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(new SimpleStatement(sb.toString()));
199+ return new QueryGenerator.Request.SimpleQuery(session.newSimpleStatement(sb.toString()));
200200 }
201201 };
202202 }
modified driver-mapping/src/main/java/com/datastax/driver/mapping/AnnotationParser.java +69 −34
@@ -25,12 +25,13 @@
2525 import java.util.concurrent.atomic.AtomicInteger;
2626
2727 import com.google.common.base.Strings;
28+import com.google.common.reflect.TypeToken;
2829
2930 import com.datastax.driver.core.ConsistencyLevel;
31+import com.datastax.driver.core.TypeCodec;
32+import com.datastax.driver.core.UserType;
3033 import com.datastax.driver.mapping.MethodMapper.EnumParamMapper;
31-import com.datastax.driver.mapping.MethodMapper.NestedUDTParamMapper;
3234 import com.datastax.driver.mapping.MethodMapper.ParamMapper;
33-import com.datastax.driver.mapping.MethodMapper.UDTParamMapper;
3435 import com.datastax.driver.mapping.annotations.*;
3536
3637 /**
@@ -112,7 +113,7 @@
112113 return mapper;
113114 }
114115
115- public static <T> EntityMapper<T> parseUDT(Class<T> udtClass, EntityMapper.Factory factory, MappingManager mappingManager) {
116+ public static <T> MappedUDTCodec<T> parseUDT(Class<T> udtClass, EntityMapper.Factory factory, MappingManager mappingManager) {
116117 UDT udt = AnnotationChecks.getTypeAnnotation(UDT.class, udtClass);
117118
118119 String ksName = udt.caseSensitiveKeyspace() ? udt.keyspace() : udt.keyspace().toLowerCase();
@@ -122,23 +123,23 @@
122123 ksName = mappingManager.getSession().getLoggedKeyspace();
123124 if (Strings.isNullOrEmpty(ksName))
124125 throw new IllegalArgumentException(String.format(
125- "Error creating UDT mapper for class %s, the @%s annotation declares no default keyspace, and the session is not currently logged to any keyspace",
126+ "Error creating UDT codec for class %s, the @%s annotation declares no default keyspace, and the session is not currently logged to any keyspace",
126127 udtClass.getSimpleName(),
127128 UDT.class.getSimpleName()
128129 ));
129130 }
130131
131- EntityMapper<T> mapper = factory.create(udtClass, ksName, udtName, null, null);
132+ UserType userType = mappingManager.getSession().getCluster().getMetadata().getKeyspace(ksName).getUserType(udtName);
132133
133134 List<Field> columns = new ArrayList<Field>();
134135
135136 for (Field field : udtClass.getDeclaredFields()) {
136137 if(field.isSynthetic() || (field.getModifiers() & Modifier.STATIC) == Modifier.STATIC)
137138 continue;
138-
139+
139140 AnnotationChecks.validateAnnotations(field, "UDT",
140- com.datastax.driver.mapping.annotations.Field.class, Frozen.class, FrozenKey.class,
141- FrozenValue.class, Enumerated.class, Transient.class);
141+ com.datastax.driver.mapping.annotations.Field.class, Frozen.class, FrozenKey.class,
142+ FrozenValue.class, Enumerated.class, Transient.class);
142143
143144 if (field.getAnnotation(Transient.class) != null)
144145 continue;
@@ -153,9 +154,8 @@
153154 break;
154155 }
155156 }
156-
157- mapper.addColumns(convert(columns, factory, udtClass, mappingManager, null));
158- return mapper;
157+ List<ColumnMapper<T>> columnMappers = convert(columns, factory, udtClass, mappingManager, null);
158+ return new MappedUDTCodec<T>(userType, udtClass, columnMappers, mappingManager);
159159 }
160160
161161 private static <T> List<ColumnMapper<T>> convert(List<Field> fields, EntityMapper.Factory factory, Class<T> klass, MappingManager mappingManager, AtomicInteger columnCounter) {
@@ -244,6 +244,36 @@
244244
245245 }
246246
247+ public static TypeCodec<Object> customCodec(Field field) {
248+ Class<? extends TypeCodec<?>> codecClass = getCodecClass(field);
249+
250+ if (codecClass.equals(Defaults.NoCodec.class))
251+ return null;
252+
253+ try {
254+ @SuppressWarnings("unchecked")
255+ TypeCodec<Object> instance = (TypeCodec<Object>)codecClass.newInstance();
256+ return instance;
257+ } catch (Exception e) {
258+ throw new IllegalArgumentException(String.format(
259+ "Cannot create an instance of custom codec %s for field %s",
260+ codecClass, field
261+ ), e);
262+ }
263+ }
264+
265+ private static Class<? extends TypeCodec<?>> getCodecClass(Field field) {
266+ Column column = field.getAnnotation(Column.class);
267+ if (column != null)
268+ return column.codec();
269+
270+ com.datastax.driver.mapping.annotations.Field udtField = field.getAnnotation(com.datastax.driver.mapping.annotations.Field.class);
271+ if (udtField != null)
272+ return udtField.codec();
273+
274+ return Defaults.NoCodec.class;
275+ }
276+
247277 public static <T> AccessorMapper<T> parseAccessor(Class<T> accClass, AccessorMapper.Factory factory, MappingManager mappingManager) {
248278 if (!accClass.isInterface())
249279 throw new IllegalArgumentException("@Accessor annotation is only allowed on interfaces");
@@ -261,21 +291,29 @@
261291 Annotation[][] paramAnnotations = m.getParameterAnnotations();
262292 Type[] paramTypes = m.getGenericParameterTypes();
263293 ParamMapper[] paramMappers = new ParamMapper[paramAnnotations.length];
264- Boolean hasParamAnnotation = null;
294+ Boolean allParamsNamed = null;
265295 for (int i = 0; i < paramMappers.length; i++) {
266296 String paramName = null;
297+ Class<? extends TypeCodec<?>> codecClass = null;
267298 for (Annotation a : paramAnnotations[i]) {
268299 if (a.annotationType().equals(Param.class)) {
269- paramName = ((Param) a).value();
300+ Param param = (Param)a;
301+ paramName = param.value();
302+ if (paramName.isEmpty())
303+ paramName = null;
304+ codecClass = param.codec();
305+ if (Defaults.NoCodec.class.equals(codecClass))
306+ codecClass = null;
270307 break;
271308 }
272309 }
273- if (hasParamAnnotation == null)
274- hasParamAnnotation = (paramName != null);
275- if (hasParamAnnotation != (paramName != null))
276- throw new IllegalArgumentException(String.format("For method '%s', either all or none of the paramaters of a method must have a @Param annotation", m.getName()));
277-
278- paramMappers[i] = newParamMapper(accClass.getName(), m.getName(), i, paramName, paramTypes[i], paramAnnotations[i], mappingManager);
310+ boolean thisParamNamed = (paramName != null);
311+ if (allParamsNamed == null)
312+ allParamsNamed = thisParamNamed;
313+ else if (allParamsNamed != thisParamNamed)
314+ throw new IllegalArgumentException(String.format("For method '%s', either all or none of the parameters must be named", m.getName()));
315+
316+ paramMappers[i] = newParamMapper(accClass.getName(), m.getName(), i, paramName, codecClass, paramTypes[i], paramAnnotations[i], mappingManager);
279317 }
280318
281319 ConsistencyLevel cl = null;
@@ -296,13 +334,10 @@
296334 }
297335
298336 @SuppressWarnings({ "unchecked", "rawtypes" })
299- private static ParamMapper newParamMapper(String className, String methodName, int idx, String paramName, Type paramType, Annotation[] paramAnnotations, MappingManager mappingManager) {
337+ private static ParamMapper newParamMapper(String className, String methodName, int idx, String paramName, Class<? extends TypeCodec<?>> codecClass, Type paramType, Annotation[] paramAnnotations, MappingManager mappingManager) {
300338 if (paramType instanceof Class) {
301339 Class<?> paramClass = (Class<?>) paramType;
302- if (paramClass.isAnnotationPresent(UDT.class)) {
303- UDTMapper<?> udtMapper = mappingManager.getUDTMapper(paramClass);
304- return new UDTParamMapper(paramName, idx, udtMapper);
305- } else if (paramClass.isEnum()) {
340+ if (paramClass.isEnum()) {
306341 EnumType enumType = EnumType.STRING;
307342 for (Annotation annotation : paramAnnotations) {
308343 if (annotation instanceof Enumerated) {
@@ -311,16 +346,16 @@
311346 }
312347 return new EnumParamMapper(paramName, idx, enumType);
313348 }
314- return new ParamMapper(paramName, idx);
315- } if (paramType instanceof ParameterizedType) {
316- InferredCQLType inferredCQLType = InferredCQLType.from(className, methodName, idx, paramName, paramType, mappingManager);
317- if (inferredCQLType.containsMappedUDT) {
318- // We need a specialized mapper to convert UDT instances in the hierarchy.
319- return new NestedUDTParamMapper(paramName, idx, inferredCQLType);
320- } else {
321- // Use the default mapper but provide the extracted type
322- return new ParamMapper(paramName, idx, inferredCQLType.dataType);
323- }
349+
350+ if (TypeMappings.isMappedUDT(paramClass))
351+ mappingManager.getUDTCodec(paramClass);
352+
353+ return new ParamMapper(paramName, idx, TypeToken.of(paramType), codecClass);
354+ } else if (paramType instanceof ParameterizedType) {
355+ for (Class<?> udt : TypeMappings.findUDTs(paramType))
356+ mappingManager.getUDTCodec(udt);
357+
358+ return new ParamMapper(paramName, idx, TypeToken.of(paramType), codecClass);
324359 } else {
325360 throw new IllegalArgumentException(String.format("Cannot map class %s for parameter %s of %s.%s", paramType, paramName, className, methodName));
326361 }
modified driver-mapping/src/main/java/com/datastax/driver/mapping/ColumnMapper.java +19 −11
@@ -18,7 +18,9 @@
1818 import java.lang.reflect.Field;
1919 import java.util.concurrent.atomic.AtomicInteger;
2020
21-import com.datastax.driver.core.DataType;
21+import com.google.common.reflect.TypeToken;
22+
23+import com.datastax.driver.core.TypeCodec;
2224
2325 import static com.datastax.driver.core.querybuilder.QueryBuilder.quote;
2426
@@ -29,24 +31,23 @@
2931 private final String columnName;
3032 private final String alias;
3133 protected final String fieldName;
32- protected final Class<?> javaType;
33- // Note: dataType is not guaranteed to be exact. Typically, it will be uuid even if the underlying
34- // type is timeuuid. Currently, this is not a problem, but we might allow some @Timeuuid annotation
35- // for the sake of validation (similarly, we'll always have text, never ascii).
36- protected final DataType dataType;
34+ /** The type of the Java field in the mapped class */
35+ protected final TypeToken<Object> fieldType;
3736 protected final Kind kind;
3837 protected final int position;
38+ protected final TypeCodec<Object> customCodec;
3939
40- protected ColumnMapper(Field field, DataType dataType, int position, AtomicInteger columnCounter) {
40+ @SuppressWarnings("unchecked")
41+ protected ColumnMapper(Field field, int position, AtomicInteger columnCounter) {
4142 this.columnName = AnnotationParser.columnName(field);
4243 this.alias = (columnCounter != null)
4344 ? AnnotationParser.newAlias(field, columnCounter.incrementAndGet())
4445 : null;
4546 this.fieldName = field.getName();
46- this.javaType = field.getType();
47- this.dataType = dataType;
47+ this.fieldType = (TypeToken<Object>)TypeToken.of(field.getGenericType());
4848 this.kind = AnnotationParser.kind(field);
4949 this.position = position;
50+ this.customCodec = AnnotationParser.customCodec(field);
5051 }
5152
5253 public abstract Object getValue(T entity);
@@ -63,8 +64,15 @@
6364 return alias;
6465 }
6566
66- public DataType getDataType() {
67- return dataType;
67+ public TypeCodec<Object> getCustomCodec() {
68+ return customCodec;
6869 }
6970
71+ /**
72+ * The Java type that will get passed to the codec.
73+ * This might be different from the field type if the column mapper does a transformation.
74+ */
75+ public TypeToken<Object> getPivotType() {
76+ return fieldType;
77+ }
7078 }
modified driver-mapping/src/main/java/com/datastax/driver/mapping/EnumType.java +12 −2
@@ -15,6 +15,8 @@
1515 */
1616 package com.datastax.driver.mapping;
1717
18+import com.google.common.reflect.TypeToken;
19+
1820 /**
1921 * The types of way to persist a JAVA Enum.
2022 */
@@ -25,7 +27,15 @@
2527 * Note that this relies on the order of the values in source code, and will change
2628 * if values are added/removed before existing ones.
2729 */
28- ORDINAL,
30+ ORDINAL(Integer.class),
2931 /** Persists enumeration values using the string they have been declared with. */
30- STRING
32+ STRING(String.class);
33+
34+ @SuppressWarnings("unchecked")
35+ EnumType(Class<?> klass) {
36+ this.pivotType = (TypeToken<Object>)TypeToken.of(klass);
37+ }
38+
39+ /** The type enum constants will be turned into before being saved */
40+ final TypeToken<Object> pivotType;
3141 }
deleted driver-mapping/src/main/java/com/datastax/driver/mapping/InferredCQLType.java +0 −101
@@ -1,101 +0,0 @@
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.mapping;
17-
18-import java.lang.reflect.Field;
19-import java.lang.reflect.ParameterizedType;
20-import java.lang.reflect.Type;
21-import java.util.Collections;
22-import java.util.List;
23-
24-import com.google.common.collect.Lists;
25-
26-import com.datastax.driver.core.DataType;
27-
28-/**
29- * Describes the CQL type inferred from a generic Java field (which will always map
30- * to a collection, possibly with various levels of nesting).
31- *
32- * The reason we wrap {@code DataType} is because we also want to remember if there are mapped UDT
33- * types somewhere in the hierarchy.
34- */
35-class InferredCQLType {
36- final DataType dataType;
37- final boolean containsMappedUDT;
38- final UDTMapper udtMapper;
39- final List<InferredCQLType> childTypes;
40-
41- static InferredCQLType from(Field field, MappingManager mappingManager) {
42- String name = String.format("field %s of class %s", field.getName(), field.getDeclaringClass().getName());
43- return new InferredCQLType(field.getGenericType(), name, field.getGenericType(), mappingManager);
44- }
45-
46- static InferredCQLType from(String className, String methodName, int idx, String paramName, Type paramType, MappingManager mappingManager) {
47- String name = String.format("parameter %s of %s.%s", paramName == null ? idx : paramName, className, methodName);
48- return new InferredCQLType(paramType, name, paramType, mappingManager);
49- }
50-
51- private InferredCQLType(Type javaType, String rootName, Type rootType, MappingManager mappingManager) {
52- if (javaType instanceof ParameterizedType) {
53- ParameterizedType pt = (ParameterizedType)javaType;
54- Type raw = pt.getRawType();
55- if (!(raw instanceof Class))
56- throw fail(rootName, rootType);
57-
58- Class<?> klass = (Class<?>)raw;
59- if (!TypeMappings.mapsToCollection(klass))
60- throw fail(rootName, rootType);
61-
62- childTypes = Lists.newArrayList();
63- boolean childrenContainMappedUDT = false;
64- for (Type childJavaType : pt.getActualTypeArguments()) {
65- InferredCQLType child = new InferredCQLType(childJavaType, rootName, rootType, mappingManager);
66- childrenContainMappedUDT |= child.containsMappedUDT;
67- childTypes.add(child);
68- }
69- containsMappedUDT = childrenContainMappedUDT;
70- udtMapper = null;
71-
72- if (TypeMappings.mapsToList(klass)) {
73- dataType = DataType.list(childTypes.get(0).dataType);
74- } else if (TypeMappings.mapsToSet(klass)) {
75- dataType = DataType.set(childTypes.get(0).dataType);
76- } else if (TypeMappings.mapsToMap(klass)) {
77- dataType = DataType.map(childTypes.get(0).dataType, childTypes.get(1).dataType);
78- } else
79- throw fail(rootName, rootType);
80- } else if (javaType instanceof Class) {
81- Class<?> klass = (Class<?>)javaType;
82- if (TypeMappings.isMappedUDT(klass)) {
83- containsMappedUDT = true;
84- udtMapper = mappingManager.udtMapper(klass);
85- dataType = udtMapper.getUserType();
86- childTypes = Collections.emptyList();
87- } else {
88- containsMappedUDT = false;
89- udtMapper = null;
90- dataType = TypeMappings.getSimpleType(klass, rootName);
91- childTypes = Collections.emptyList();
92- }
93- } else {
94- throw fail(rootName, rootType);
95- }
96- }
97-
98- private IllegalArgumentException fail(String rootName, Type rootType) {
99- return new IllegalArgumentException(String.format("Cannot map class %s for %s", rootType, rootName));
100- }
101-}
added driver-mapping/src/main/java/com/datastax/driver/mapping/MappedUDTCodec.java +110 −0
@@ -0,0 +1,110 @@
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.mapping;
17+
18+import java.nio.ByteBuffer;
19+import java.util.List;
20+
21+import com.google.common.collect.Lists;
22+
23+import com.datastax.driver.core.*;
24+import com.datastax.driver.core.exceptions.InvalidTypeException;
25+
26+/**
27+ * Serializes a class annotated with {@code @UDT} to the corresponding CQL user-defined type.
28+ */
29+class MappedUDTCodec<T> extends TypeCodec<T> {
30+ private final UserType cqlUserType;
31+ private final Class<T> udtClass;
32+ private final List<ColumnMapper<T>> columnMappers;
33+ private final CodecRegistry codecRegistry;
34+
35+ public MappedUDTCodec(UserType cqlUserType, Class<T> udtClass, List<ColumnMapper<T>> columnMappers, MappingManager mappingManager) {
36+ super(cqlUserType, udtClass);
37+ this.cqlUserType = cqlUserType;
38+ this.udtClass = udtClass;
39+ this.columnMappers = columnMappers;
40+ this.codecRegistry = mappingManager.getSession().getCluster().getConfiguration().getCodecRegistry();
41+ }
42+
43+ @Override
44+ public ByteBuffer serialize(T sourceObject, ProtocolVersion protocolVersion) throws InvalidTypeException {
45+ if (sourceObject == null)
46+ return null;
47+
48+ int size = 0;
49+
50+ List<ByteBuffer> serializedFields = Lists.newArrayList();
51+ for (ColumnMapper<T> cm : columnMappers) {
52+ Object value = cm.getValue(sourceObject);
53+ TypeCodec<Object> codec = cm.getCustomCodec();
54+ if (codec == null)
55+ codec = codecRegistry.codecFor(cqlUserType.getFieldType(cm.getColumnName()), cm.getPivotType());
56+ ByteBuffer serializedField = codec.serialize(value, protocolVersion);
57+ size += 4 + (serializedField == null ? 0 : serializedField.remaining());
58+ serializedFields.add(serializedField);
59+ }
60+
61+ ByteBuffer result = ByteBuffer.allocate(size);
62+ for (ByteBuffer bb : serializedFields) {
63+ if (bb == null) {
64+ result.putInt(-1);
65+ } else {
66+ result.putInt(bb.remaining());
67+ result.put(bb.duplicate());
68+ }
69+ }
70+ return (ByteBuffer)result.flip();
71+ }
72+
73+ @Override
74+ public T deserialize(ByteBuffer bytes, ProtocolVersion protocolVersion) throws InvalidTypeException {
75+ if (bytes == null || bytes.remaining() == 0)
76+ return null;
77+ ByteBuffer input = bytes.duplicate();
78+
79+ T targetObject = newInstance();
80+
81+ for (ColumnMapper<T> cm : columnMappers) {
82+ int size = input.getInt();
83+ ByteBuffer serialized = (size < 0) ? null : CodecUtils.readBytes(input, size);
84+ TypeCodec<Object> codec = cm.getCustomCodec();
85+ if (codec == null)
86+ codec = codecRegistry.codecFor(cqlUserType.getFieldType(cm.getColumnName()), cm.getPivotType());
87+ cm.setValue(targetObject, codec.deserialize(serialized, protocolVersion));
88+ }
89+
90+ return targetObject;
91+ }
92+
93+ private T newInstance() {
94+ try {
95+ return udtClass.newInstance();
96+ } catch (Exception e) {
97+ throw new IllegalArgumentException("Error creating instance of @UDT-annotated class " + udtClass, e);
98+ }
99+ }
100+
101+ @Override
102+ public T parse(String value) throws InvalidTypeException {
103+ throw new UnsupportedOperationException();
104+ }
105+
106+ @Override
107+ public String format(T value) throws InvalidTypeException {
108+ throw new UnsupportedOperationException();
109+ }
110+}
modified driver-mapping/src/main/java/com/datastax/driver/mapping/Mapper.java +12 −4
@@ -200,9 +200,9 @@
200200 BoundStatement bs = getPreparedQuery(QueryType.SAVE, values.keySet(), options).bind();
201201 int i = 0;
202202 for (Map.Entry<ColumnMapper<?>, Object> entry : values.entrySet()) {
203- DataType type = entry.getKey().getDataType();
203+ ColumnMapper<?> mapper = entry.getKey();
204204 Object value = entry.getValue();
205- bs.setBytesUnsafe(i++, value == null ? null : type.serialize(value, protocolVersion));
205+ setObject(bs, i++, value, mapper);
206206 }
207207
208208 if (mapper.writeConsistency != null)
@@ -221,6 +221,14 @@
221221 return option == null || option.saveNullFields;
222222 }
223223
224+ private static void setObject(BoundStatement bs, int i, Object value, ColumnMapper<?> mapper) {
225+ TypeCodec<Object> customCodec = mapper.getCustomCodec();
226+ if (customCodec != null)
227+ bs.set(i, value, customCodec);
228+ else
229+ bs.set(i, value, mapper.getPivotType());
230+ }
231+
224232 /**
225233 * Save an entity mapped by this mapper.
226234 * <p>
@@ -328,7 +336,7 @@
328336 if (value == null) {
329337 throw new IllegalArgumentException(String.format("Invalid null value for PRIMARY KEY column %s (argument %d)", column.getColumnName(), i));
330338 }
331- bs.setBytesUnsafe(i++, column.getDataType().serialize(value, protocolVersion));
339+ setObject(bs, i++, value, column);
332340 }
333341
334342 if (mapper.readConsistency != null)
@@ -510,7 +518,7 @@
510518 if (value == null) {
511519 throw new IllegalArgumentException(String.format("Invalid null value for PRIMARY KEY column %s (argument %d)", column.getColumnName(), i));
512520 }
513- bs.setBytesUnsafe(i++, column.getDataType().serialize(value, protocolVersion));
521+ setObject(bs, i++, value, column);
514522 columnNumber++;
515523 }
516524 return bs;
modified driver-mapping/src/main/java/com/datastax/driver/mapping/MappingManager.java +42 −27
@@ -18,11 +18,16 @@
1818 import java.util.Collections;
1919 import java.util.HashMap;
2020 import java.util.Map;
21+import java.util.Set;
22+
23+import com.google.common.collect.Sets;
2124
2225 import com.datastax.driver.core.ProtocolVersion;
2326 import com.datastax.driver.core.Session;
27+import com.datastax.driver.core.TypeCodec;
2428 import com.datastax.driver.mapping.annotations.Accessor;
2529 import com.datastax.driver.mapping.annotations.Table;
30+import com.datastax.driver.mapping.annotations.UDT;
2631
2732 /**
2833 * Mapping manager from which to obtain entity mappers.
@@ -30,11 +35,14 @@
3035 public class MappingManager {
3136
3237 private final Session session;
38+ private final ProtocolVersion protocolVersion;
3339 final boolean isCassandraV1;
3440
35- private volatile Map<Class<?>, Mapper<?>> mappers = Collections.<Class<?>, Mapper<?>>emptyMap();
36- private volatile Map<Class<?>, UDTMapper<?>> udtMappers = Collections.<Class<?>, UDTMapper<?>>emptyMap();
37- private volatile Map<Class<?>, Object> accessors = Collections.<Class<?>, Object>emptyMap();
41+ private volatile Map<Class<?>, Mapper<?>> mappers = Collections.emptyMap();
42+ private volatile Map<Class<?>, MappedUDTCodec<?>> udtCodecs = Collections.emptyMap();
43+ private volatile Map<Class<?>, Object> accessors = Collections.emptyMap();
44+
45+ private final Set<Class<?>> registeredUDTs = Sets.newConcurrentHashSet();
3846
3947 /**
4048 * Creates a new {@code MappingManager} using the provided {@code Session}.
@@ -45,11 +53,12 @@
4553 */
4654 public MappingManager(Session session) {
4755 this.session = session;
56+ this.protocolVersion = getProtocolVersion(session);
4857 // This is not strictly correct because we could connect to C* 2.0 with the v1 protocol.
4958 // But mappers need to make a decision early so that generated queries are compatible, and we don't know in advance
5059 // which nodes might join the cluster later.
5160 // At least if protocol >=2 we know there won't be any 1.2 nodes ever.
52- this.isCassandraV1 = (getProtocolVersion(session) == ProtocolVersion.V1);
61+ this.isCassandraV1 = protocolVersion == ProtocolVersion.V1;
5362 }
5463
5564 private static ProtocolVersion getProtocolVersion(Session session) {
@@ -78,6 +87,10 @@
7887 * <p>
7988 * The {@code MappingManager} only ever keeps one Mapper for each class, and so calling this
8089 * method multiple times on the same class will always return the same object.
90+ * <p>
91+ * If the type of any field in the class is an {@link UDT}-annotated classes, a codec for that
92+ * class will automatically be created and registered with the underlying {@code Cluster}.
93+ * This works recursively with UDTs nested in other UDTs or in collections.
8194 *
8295 * @param <T> the type of the class to map.
8396 * @param klass the (annotated) class for which to return the mapper.
@@ -88,21 +101,22 @@
88101 }
89102
90103 /**
91- * Creates a {@code UDTMapper} for the provided class (that must be
92- * annotated by a {@link com.datastax.driver.mapping.annotations.UDT} annotation).
93- *
104+ * Creates a {@code TypeCodec} for the provided class (that must be annotated by
105+ * a {@link UDT} annotation).
106+ * <p>
107+ * This method also registers the codec against the underlying {@code Cluster}.
108+ * In addition, the codecs for any nested UDTs will also be created and registered.
94109 * <p>
95- * The {@code MappingManager} only ever keeps one {@code UDTMapper} for each
96- * class, and so calling this method multiple times on the same class will
97- * always return the same object.
98- * </p>
110+ * You don't need to call this method explicitly if you already call {@link #mapper(Class)}
111+ * for a class that references this UDT class (creating a mapper will automatically
112+ * process all UDTs that it uses).
99113 *
100114 * @param <T> the type of the class to map.
101- * @param klass the (annotated) class for which to return the mapper.
102- * @return the {@code UDTMapper} object for class {@code klass}.
115+ * @param klass the (annotated) class for which to return the codec.
116+ * @return the codec that maps the provided class to the corresponding user-defined type.
103117 */
104- public <T> UDTMapper<T> udtMapper(Class<T> klass) {
105- return getUDTMapper(klass);
118+ public <T> TypeCodec<T> udtCodec(Class<T> klass) {
119+ return getUDTCodec(klass);
106120 }
107121
108122 /**
@@ -139,21 +153,22 @@
139153 }
140154
141155 @SuppressWarnings("unchecked")
142- <T> UDTMapper<T> getUDTMapper(Class<T> klass) {
143- UDTMapper<T> mapper = (UDTMapper<T>)udtMappers.get(klass);
144- if (mapper == null) {
145- synchronized (udtMappers) {
146- mapper = (UDTMapper<T>)udtMappers.get(klass);
147- if (mapper == null) {
148- EntityMapper<T> entityMapper = AnnotationParser.parseUDT(klass, ReflectionMapper.factory(), this);
149- mapper = new UDTMapper<T>(entityMapper, session);
150- Map<Class<?>, UDTMapper<?>> newMappers = new HashMap<Class<?>, UDTMapper<?>>(udtMappers);
151- newMappers.put(klass, mapper);
152- udtMappers = newMappers;
156+ <T> TypeCodec<T> getUDTCodec(Class<T> mappedClass) {
157+ MappedUDTCodec<T> codec = (MappedUDTCodec<T>)udtCodecs.get(mappedClass);
158+ if (codec == null) {
159+ synchronized (udtCodecs) {
160+ codec = (MappedUDTCodec<T>)udtCodecs.get(mappedClass);
161+ if (codec == null) {
162+ codec = AnnotationParser.parseUDT(mappedClass, ReflectionMapper.factory(), this);
163+ session.getCluster().getConfiguration().getCodecRegistry().register(codec);
164+
165+ HashMap<Class<?>, MappedUDTCodec<?>> newCodecs = new HashMap<Class<?>, MappedUDTCodec<?>>(udtCodecs);
166+ newCodecs.put(mappedClass, codec);
167+ udtCodecs = newCodecs;
153168 }
154169 }
155170 }
156- return mapper;
171+ return codec;
157172 }
158173
159174 @SuppressWarnings("unchecked")
modified driver-mapping/src/main/java/com/datastax/driver/mapping/MethodMapper.java +23 −56
@@ -18,10 +18,10 @@
1818 import java.lang.reflect.Method;
1919 import java.lang.reflect.ParameterizedType;
2020 import java.lang.reflect.Type;
21-import java.nio.ByteBuffer;
2221 import java.util.Set;
2322
2423 import com.google.common.collect.Sets;
24+import com.google.common.reflect.TypeToken;
2525 import com.google.common.util.concurrent.Futures;
2626 import com.google.common.util.concurrent.ListenableFuture;
2727
@@ -175,81 +175,48 @@
175175 }
176176
177177 static class ParamMapper {
178- // We'll only set one of the other. If paramName is null, then paramIdx is used.
178+ // We'll only set one or the other. If paramName is null, then paramIdx is used.
179179 private final String paramName;
180180 private final int paramIdx;
181- private final DataType dataType;
182-
183- public ParamMapper(String paramName, int paramIdx, DataType dataType) {
181+ private final TypeToken<Object> paramType;
182+ private final TypeCodec<Object> codec;
183+
184+ @SuppressWarnings("unchecked")
185+ public ParamMapper(String paramName, int paramIdx, TypeToken<?> paramType, Class<? extends TypeCodec<?>> codecClass) {
184186 this.paramName = paramName;
185187 this.paramIdx = paramIdx;
186- this.dataType = dataType;
187- }
188-
189- public ParamMapper(String paramName, int paramIdx) {
190- this(paramName, paramIdx, null);
188+ this.paramType = (TypeToken<Object>)paramType;
189+ try {
190+ this.codec = (codecClass == null) ? null : (TypeCodec<Object>)codecClass.newInstance();
191+ } catch (Exception e) {
192+ throw new IllegalArgumentException(String.format(
193+ "Cannot create instance of codec %s for parameter %s",
194+ codecClass, (paramName == null) ? paramIdx : paramName
195+ ), e);
196+ }
191197 }
192198
193199 void setValue(BoundStatement boundStatement, Object arg, ProtocolVersion protocolVersion) {
194- ByteBuffer serializedArg = (dataType == null)
195- ? DataType.serializeValue(arg, protocolVersion)
196- : dataType.serialize(arg, protocolVersion);
197200 if (paramName == null) {
198- if (arg == null)
199- boundStatement.setToNull(paramIdx);
201+ if (codec == null)
202+ boundStatement.set(paramIdx, arg, paramType);
200203 else
201- boundStatement.setBytesUnsafe(paramIdx, serializedArg);
204+ boundStatement.set(paramIdx, arg, codec);
202205 } else {
203- if (arg == null)
204- boundStatement.setToNull(paramName);
206+ if (codec == null)
207+ boundStatement.set(paramName, arg, paramType);
205208 else
206- boundStatement.setBytesUnsafe(paramName, serializedArg);
209+ boundStatement.set(paramName, arg, codec);
207210 }
208211 }
209212 }
210213
211- static class UDTParamMapper<V> extends ParamMapper {
212- private final UDTMapper<V> udtMapper;
213-
214- UDTParamMapper(String paramName, int paramIdx, UDTMapper<V> udtMapper) {
215- super(paramName, paramIdx);
216- this.udtMapper = udtMapper;
217- }
218-
219- @Override
220- void setValue(BoundStatement boundStatement, Object arg, ProtocolVersion protocolVersion) {
221- @SuppressWarnings("unchecked")
222- V entity = (V) arg;
223- UDTValue udtArg = arg != null ? udtMapper.toUDT(entity) : null;
224- super.setValue(boundStatement, udtArg, protocolVersion);
225- }
226- }
227-
228- /**
229- * Maps a nested collection which has a mapped UDT somewhere in the hierarchy.
230- */
231- static class NestedUDTParamMapper extends ParamMapper {
232- private final InferredCQLType inferredCQLType;
233-
234- NestedUDTParamMapper(String paramName, int paramIdx, InferredCQLType inferredCQLType) {
235- super(paramName, paramIdx);
236- this.inferredCQLType = inferredCQLType;
237- }
238-
239- @Override
240- void setValue(BoundStatement boundStatement, Object arg, ProtocolVersion protocolVersion) {
241- super.setValue(boundStatement,
242- UDTMapper.convertEntitiesToUDTs(arg, inferredCQLType),
243- protocolVersion);
244- }
245- }
246-
247214 static class EnumParamMapper extends ParamMapper {
248215
249216 private final EnumType enumType;
250217
251218 public EnumParamMapper(String paramName, int paramIdx, EnumType enumType) {
252- super(paramName, paramIdx);
219+ super(paramName, paramIdx, enumType.pivotType, null);
253220 this.enumType = enumType;
254221 }
255222
modified driver-mapping/src/main/java/com/datastax/driver/mapping/QueryType.java +9 −7
@@ -25,6 +25,7 @@
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;
2829 import com.datastax.driver.core.querybuilder.Select;
2930
3031 import static com.datastax.driver.core.querybuilder.QueryBuilder.*;
@@ -62,11 +63,12 @@
6263 }
6364
6465 String makePreparedQueryString(TableMetadata table, EntityMapper<?> mapper, MappingManager manager, Set<ColumnMapper<?>> columns, Collection<Mapper.Option> options) {
66+ QueryBuilder builder = new QueryBuilder(manager.getSession().getCluster());
6567 switch (kind) {
6668 case SAVE: {
6769 Insert insert = table == null
68- ? insertInto(mapper.getKeyspace(), mapper.getTable())
69- : insertInto(table);
70+ ? builder.insertInto(mapper.getKeyspace(), mapper.getTable())
71+ : builder.insertInto(table);
7072 for (ColumnMapper<?> cm : columns)
7173 if (cm.kind != ColumnMapper.Kind.COMPUTED)
7274 insert.value(cm.getColumnName(), bindMarker());
@@ -80,7 +82,7 @@
8082 return insert.toString();
8183 }
8284 case GET: {
83- Select.Selection selection = select();
85+ Select.Selection selection = builder.select();
8486 for (ColumnMapper cm : mapper.allColumns()) {
8587 Select.SelectionOrAlias column = (cm.kind == ColumnMapper.Kind.COMPUTED)
8688 ? ((Select.SelectionOrAlias)selection).raw(cm.getColumnName())
@@ -108,8 +110,8 @@
108110 }
109111 case DEL: {
110112 Delete delete = table == null
111- ? delete().all().from(mapper.getKeyspace(), mapper.getTable())
112- : delete().all().from(table);
113+ ? builder.delete().all().from(mapper.getKeyspace(), mapper.getTable())
114+ : builder.delete().all().from(table);
113115 Delete.Where where = delete.where();
114116 for (int i = 0; i < mapper.primaryKeySize(); i++)
115117 where.and(eq(mapper.getPrimaryKeyColumn(i).getColumnName(), bindMarker()));
@@ -124,8 +126,8 @@
124126 case SLICE:
125127 case REVERSED_SLICE: {
126128 Select select = table == null
127- ? select().all().from(mapper.getKeyspace(), mapper.getTable())
128- : select().all().from(table);
129+ ? builder.select().all().from(mapper.getKeyspace(), mapper.getTable())
130+ : builder.select().all().from(table);
129131 Select.Where where = select.where();
130132 for (int i = 0; i < mapper.partitionKeys.size(); i++)
131133 where.and(eq(mapper.partitionKeys.get(i).getColumnName(), bindMarker()));
modified driver-mapping/src/main/java/com/datastax/driver/mapping/ReflectionMapper.java +12 −83
@@ -19,15 +19,13 @@
1919 import java.beans.PropertyDescriptor;
2020 import java.lang.reflect.Field;
2121 import java.lang.reflect.Method;
22-import java.lang.reflect.ParameterizedType;
23-import java.lang.reflect.Type;
2422 import java.util.HashMap;
2523 import java.util.Map;
2624 import java.util.concurrent.atomic.AtomicInteger;
2725
26+import com.google.common.reflect.TypeToken;
27+
2828 import com.datastax.driver.core.ConsistencyLevel;
29-import com.datastax.driver.core.DataType;
30-import com.datastax.driver.core.UDTValue;
3129
3230 /**
3331 * An {@link EntityMapper} implementation that use reflection to read and write fields
@@ -59,12 +57,8 @@
5957 private final Method readMethod;
6058 private final Method writeMethod;
6159
62- private LiteralMapper(Field field, int position, PropertyDescriptor pd, AtomicInteger columnNumber) {
63- this(field, extractSimpleType(field), position, pd, columnNumber);
64- }
65-
66- private LiteralMapper(Field field, DataType type, int position, PropertyDescriptor pd, AtomicInteger columnCounter) {
67- super(field, type, position, columnCounter);
60+ private LiteralMapper(Field field, int position, PropertyDescriptor pd, AtomicInteger columnCounter) {
61+ super(field, position, columnCounter);
6862 this.readMethod = pd.getReadMethod();
6963 this.writeMethod = pd.getWriteMethod();
7064 }
@@ -98,12 +92,12 @@
9892 private final Map<String, Object> fromString;
9993
10094 private EnumMapper(Field field, int position, PropertyDescriptor pd, EnumType enumType, AtomicInteger columnCounter) {
101- super(field, enumType == EnumType.STRING ? DataType.text() : DataType.cint(), position, pd, columnCounter);
95+ super(field, position, pd, columnCounter);
10296 this.enumType = enumType;
10397
10498 if (enumType == EnumType.STRING) {
105- fromString = new HashMap<String, Object>(javaType.getEnumConstants().length);
106- for (Object constant : javaType.getEnumConstants())
99+ fromString = new HashMap<String, Object>(fieldType.getRawType().getEnumConstants().length);
100+ for (Object constant : fieldType.getRawType().getEnumConstants())
107101 fromString.put(constant.toString().toLowerCase(), constant);
108102
109103 } else {
@@ -132,70 +126,18 @@
132126 converted = fromString.get(value.toString().toLowerCase());
133127 break;
134128 case ORDINAL:
135- converted = javaType.getEnumConstants()[(Integer)value];
129+ converted = fieldType.getRawType().getEnumConstants()[(Integer)value];
136130 break;
137131 }
138132 super.setValue(entity, converted);
139133 }
140- }
141-
142- private static class UDTColumnMapper<T, U> extends LiteralMapper<T> {
143- private final UDTMapper<U> udtMapper;
144-
145- private UDTColumnMapper(Field field, int position, PropertyDescriptor pd, UDTMapper<U> udtMapper, AtomicInteger columnCounter) {
146- super(field, udtMapper.getUserType(), position, pd, columnCounter);
147- this.udtMapper = udtMapper;
148- }
149-
150- @Override
151- public Object getValue(T entity) {
152- @SuppressWarnings("unchecked")
153- U udtEntity = (U)super.getValue(entity);
154- return udtEntity == null ? null : udtMapper.toUDT(udtEntity);
155- }
156-
157- @Override
158- public void setValue(Object entity, Object value) {
159- assert value instanceof UDTValue;
160- UDTValue udtValue = (UDTValue)value;
161- assert udtValue.getType().equals(udtMapper.getUserType());
162-
163- super.setValue(entity, udtMapper.toEntity((udtValue)));
164- }
165- }
166-
167- private static class NestedUDTMapper<T> extends LiteralMapper<T> {
168- private final InferredCQLType inferredCQLType;
169-
170- public NestedUDTMapper(Field field, int position, PropertyDescriptor pd, InferredCQLType inferredCQLType, AtomicInteger columnCounter) {
171- super(field, inferredCQLType.dataType, position, pd, columnCounter);
172- this.inferredCQLType = inferredCQLType;
173- }
174-
175- @Override
176- @SuppressWarnings("unchecked")
177- public Object getValue(T entity) {
178- Object valueWithEntities = super.getValue(entity);
179- return (T)UDTMapper.convertEntitiesToUDTs(valueWithEntities, inferredCQLType);
180- }
181134
182135 @Override
183- public void setValue(Object entity, Object valueWithUDTValues) {
184- super.setValue(entity, UDTMapper.convertUDTsToEntities(valueWithUDTValues, inferredCQLType));
136+ public TypeToken<Object> getPivotType() {
137+ return enumType.pivotType;
185138 }
186139 }
187140
188- static DataType extractSimpleType(Field f) {
189- Type type = f.getGenericType();
190-
191- assert !(type instanceof ParameterizedType);
192-
193- if (!(type instanceof Class))
194- throw new IllegalArgumentException(String.format("Cannot map class %s for field %s", type, f.getName()));
195-
196- return TypeMappings.getSimpleType((Class<?>)type, f.getName());
197- }
198-
199141 private static class ReflectionFactory implements Factory {
200142
201143 public <T> EntityMapper<T> create(Class<T> entityClass, String keyspace, String table, ConsistencyLevel writeConsistency, ConsistencyLevel readConsistency) {
@@ -212,21 +154,8 @@
212154 return new EnumMapper<T>(field, position, pd, AnnotationParser.enumType(field), columnCounter);
213155 }
214156
215- if (TypeMappings.isMappedUDT(field.getType())) {
216- UDTMapper<?> udtMapper = mappingManager.getUDTMapper(field.getType());
217- return (ColumnMapper<T>) new UDTColumnMapper(field, position, pd, udtMapper, columnCounter);
218- }
219-
220- if (field.getGenericType() instanceof ParameterizedType) {
221- InferredCQLType inferredCQLType = InferredCQLType.from(field, mappingManager);
222- if (inferredCQLType.containsMappedUDT) {
223- // We need a specialized mapper to convert UDT instances in the hierarchy.
224- return (ColumnMapper<T>)new NestedUDTMapper(field, position, pd, inferredCQLType, columnCounter);
225- } else {
226- // The default codecs will know how to handle the extracted datatype.
227- return new LiteralMapper<T>(field, inferredCQLType.dataType, position, pd, columnCounter);
228- }
229- }
157+ for (Class<?> udt : TypeMappings.findUDTs(field.getGenericType()))
158+ mappingManager.getUDTCodec(udt);
230159
231160 return new LiteralMapper<T>(field, position, pd, columnCounter);
232161
modified driver-mapping/src/main/java/com/datastax/driver/mapping/Result.java +21 −4
@@ -15,7 +15,6 @@
1515 */
1616 package com.datastax.driver.mapping;
1717
18-import java.nio.ByteBuffer;
1918 import java.util.*;
2019
2120 import com.datastax.driver.core.*;
@@ -47,13 +46,31 @@
4746 String name = cm.getAlias() != null && this.useAlias ? cm.getAlias() : cm.getColumnName();
4847 if (!row.getColumnDefinitions().contains(name))
4948 continue;
50- ByteBuffer bytes = row.getBytesUnsafe(name);
51- if (bytes != null)
52- cm.setValue(entity, cm.getDataType().deserialize(bytes, protocolVersion));
49+
50+ Object value;
51+ TypeCodec<Object> customCodec = cm.getCustomCodec();
52+ if (customCodec != null)
53+ value = row.get(name, customCodec);
54+ else
55+ value = row.get(name, cm.getPivotType());
56+
57+ if (shouldSetValue(value)) {
58+ cm.setValue(entity, value);
59+ }
5360 }
5461 return entity;
5562 }
5663
64+ private static boolean shouldSetValue(Object value) {
65+ if (value == null)
66+ return false;
67+ if(value instanceof Collection)
68+ return !((Collection)value).isEmpty();
69+ if(value instanceof Map)
70+ return !((Map)value).isEmpty();
71+ return true;
72+ }
73+
5774 /**
5875 * Test whether this mapped result set has more results.
5976 *
modified driver-mapping/src/main/java/com/datastax/driver/mapping/TypeMappings.java +50 −54
@@ -15,14 +15,15 @@
1515 */
1616 package com.datastax.driver.mapping;
1717
18-import java.math.BigDecimal;
19-import java.math.BigInteger;
20-import java.net.InetAddress;
21-import java.nio.ByteBuffer;
22-import java.util.*;
23-
24-import com.datastax.driver.core.DataType;
25-import com.datastax.driver.core.LocalDate;
18+import java.lang.reflect.ParameterizedType;
19+import java.lang.reflect.Type;
20+import java.util.Collections;
21+import java.util.List;
22+import java.util.Map;
23+import java.util.Set;
24+
25+import com.google.common.collect.Sets;
26+
2627 import com.datastax.driver.core.TupleValue;
2728 import com.datastax.driver.core.UDTValue;
2829 import com.datastax.driver.mapping.annotations.UDT;
@@ -32,63 +33,22 @@
3233 */
3334 class TypeMappings {
3435
35- static DataType getSimpleType(Class<?> klass, String fieldName) {
36- if (ByteBuffer.class.isAssignableFrom(klass))
37- return DataType.blob();
38-
39- if (klass == byte.class || Byte.class.isAssignableFrom(klass))
40- return DataType.tinyint();
41- if (klass == short.class || Short.class.isAssignableFrom(klass))
42- return DataType.smallint();
43- if (klass == int.class || Integer.class.isAssignableFrom(klass))
44- return DataType.cint();
45- if (klass == long.class || Long.class.isAssignableFrom(klass))
46- return DataType.bigint();
47- if (klass == float.class || Float.class.isAssignableFrom(klass))
48- return DataType.cfloat();
49- if (klass == double.class || Double.class.isAssignableFrom(klass))
50- return DataType.cdouble();
51- if (klass == boolean.class || Boolean.class.isAssignableFrom(klass))
52- return DataType.cboolean();
53-
54- if (BigDecimal.class.isAssignableFrom(klass))
55- return DataType.decimal();
56- if (BigInteger.class.isAssignableFrom(klass))
57- return DataType.varint();
58-
59- if (String.class.isAssignableFrom(klass))
60- return DataType.text();
61- if (InetAddress.class.isAssignableFrom(klass))
62- return DataType.inet();
63- if (Date.class.isAssignableFrom(klass))
64- return DataType.timestamp();
65- if (UUID.class.isAssignableFrom(klass))
66- return DataType.uuid();
67- if (LocalDate.class.isAssignableFrom(klass))
68- return DataType.date();
69-
70- if (Collection.class.isAssignableFrom(klass))
71- throw new IllegalArgumentException(String.format("Cannot map non-parametrized collection type %s for field %s; Please use a concrete type parameter", klass.getName(), fieldName));
72-
73- throw new IllegalArgumentException(String.format("Cannot map unknown class %s for field %s", klass.getName(), fieldName));
36+ static boolean mapsToCollection(Class<?> klass) {
37+ return mapsToList(klass) || mapsToSet(klass) || mapsToMap(klass);
7438 }
7539
76- static boolean mapsToList(Class<?> klass) {
40+ private static boolean mapsToList(Class<?> klass) {
7741 return List.class.equals(klass);
7842 }
7943
80- static boolean mapsToSet(Class<?> klass) {
44+ private static boolean mapsToSet(Class<?> klass) {
8145 return Set.class.equals(klass);
8246 }
8347
84- static boolean mapsToMap(Class<?> klass) {
48+ private static boolean mapsToMap(Class<?> klass) {
8549 return Map.class.equals(klass);
8650 }
8751
88- static boolean mapsToCollection(Class<?> klass) {
89- return mapsToList(klass) || mapsToSet(klass) || mapsToMap(klass);
90- }
91-
9252 static boolean isMappedUDT(Class<?> klass) {
9353 return klass.isAnnotationPresent(UDT.class);
9454 }
@@ -98,4 +58,40 @@
9858 klass.equals(UDTValue.class) ||
9959 klass.equals(TupleValue.class);
10060 }
61+
62+ /**
63+ * Traverses the type of a Java field or parameter to find classes annotated with @UDT.
64+ * This will recurse into nested collections, e.g. List<Set<TheMappedUDT>>
65+ */
66+ static Set<Class<?>> findUDTs(Type type) {
67+ Set<Class<?>> udts = findUDTs(type, null);
68+ return (udts == null)
69+ ? Collections.<Class<?>>emptySet()
70+ : udts;
71+ }
72+
73+ private static Set<Class<?>> findUDTs(Type type, Set<Class<?>> udts) {
74+ if (type instanceof ParameterizedType) {
75+ ParameterizedType pt = (ParameterizedType)type;
76+ Type raw = pt.getRawType();
77+ if ((raw instanceof Class)) {
78+ Class<?> klass = (Class<?>)raw;
79+ if (mapsToCollection(klass)) {
80+ Type[] childTypes = pt.getActualTypeArguments();
81+ udts = findUDTs(childTypes[0], udts);
82+
83+ if (mapsToMap(klass))
84+ udts = findUDTs(childTypes[1], udts);
85+ }
86+ }
87+ } else if (type instanceof Class) {
88+ Class<?> klass = (Class<?>)type;
89+ if (isMappedUDT(klass)) {
90+ if (udts == null)
91+ udts = Sets.newHashSet();
92+ udts.add(klass);
93+ }
94+ }
95+ return udts;
96+ }
10197 }
deleted driver-mapping/src/main/java/com/datastax/driver/mapping/UDTMapper.java +0 −187
@@ -1,187 +0,0 @@
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.mapping;
17-
18-import java.nio.ByteBuffer;
19-import java.util.*;
20-import java.util.Map.Entry;
21-
22-import com.datastax.driver.core.*;
23-
24-/**
25- * An object handling the mapping of a particular class to a UDT.
26- * <p>
27- * A {@code UDTMapper} object is obtained from a {@code MappingManager} using the
28- * {@link MappingManager#udtMapper} method.
29- * </p>
30- */
31-public class UDTMapper<T> {
32- // UDTs are always serialized with the v3 protocol
33- private static final ProtocolVersion UDT_PROTOCOL_VERSION = ProtocolVersion.V3;
34-
35- private final EntityMapper<T> entityMapper;
36- private final UserType userType;
37-
38- UDTMapper(EntityMapper<T> entityMapper, Session session) {
39- this.entityMapper = entityMapper;
40-
41- String keyspace = entityMapper.getKeyspace();
42- String udt = entityMapper.getTable();
43- userType = session.getCluster().getMetadata().getKeyspace(keyspace).getUserType(udt);
44- if (userType == null) {
45- throw new IllegalArgumentException(String.format("Type \"%s\" does not exist in keyspace \"%s\"", udt, keyspace));
46- }
47- }
48-
49- /**
50- * Converts a {@link UDTValue} (returned by the core API) to the mapped
51- * class.
52- *
53- * @param v the {@code UDTValue}.
54- * @return an instance of the mapped class.
55- *
56- * @throws IllegalArgumentException if the {@code UDTValue} is not of the
57- * type indicated in the mapped class's {@code @UDT} annotation.
58- */
59- public T fromUDT(UDTValue v) {
60- if (!v.getType().equals(userType)) {
61- String message = String.format("UDT conversion mismatch: expected type %s, got %s",
62- userType, v.getType());
63- throw new IllegalArgumentException(message);
64- }
65- return toEntity(v);
66- }
67-
68- /**
69- * Converts a mapped class to a {@link UDTValue}.
70- *
71- * @param entity an instance of the mapped class.
72- *
73- * @return the corresponding {@code UDTValue}.
74- */
75- public UDTValue toUDT(T entity) {
76- UDTValue udtValue = userType.newValue();
77- for (ColumnMapper<T> cm : entityMapper.allColumns()) {
78- Object value = cm.getValue(entity);
79- udtValue.setBytesUnsafe(cm.getColumnName(), value == null ? null : cm.getDataType().serialize(value, UDT_PROTOCOL_VERSION));
80- }
81- return udtValue;
82- }
83-
84- UserType getUserType() {
85- return userType;
86- }
87-
88- T toEntity(UDTValue udtValue) {
89- T entity = entityMapper.newEntity();
90- for (ColumnMapper<T> cm : entityMapper.allColumns()) {
91- ByteBuffer bytes = udtValue.getBytesUnsafe(cm.getColumnName());
92- if (bytes != null)
93- cm.setValue(entity, cm.getDataType().deserialize(bytes, UDT_PROTOCOL_VERSION));
94- }
95- return entity;
96- }
97-
98- /**
99- * Handles a (possibly nested) collection where some of the elements are domain classes that
100- * must be converted to {@code UDTValue} instances.
101- */
102- @SuppressWarnings("unchecked")
103- static Object convertEntitiesToUDTs(Object value, InferredCQLType type) {
104- if (value == null)
105- return null;
106-
107- if (!type.containsMappedUDT)
108- return value;
109-
110- if (type.udtMapper != null)
111- return type.udtMapper.toUDT(value);
112-
113- if (type.dataType.getName() == DataType.Name.LIST) {
114- InferredCQLType elementType = type.childTypes.get(0);
115- List<Object> result = new ArrayList<Object>();
116- for (Object element : (List<Object>)value)
117- result.add(convertEntitiesToUDTs(element, elementType));
118- return result;
119- }
120-
121- if (type.dataType.getName() == DataType.Name.SET) {
122- InferredCQLType elementType = type.childTypes.get(0);
123- Set<Object> result = new LinkedHashSet<Object>();
124- for (Object element : (Set<Object>)value)
125- result.add(convertEntitiesToUDTs(element, elementType));
126- return result;
127- }
128-
129- if (type.dataType.getName() == DataType.Name.MAP) {
130- InferredCQLType keyType = type.childTypes.get(0);
131- InferredCQLType valueType = type.childTypes.get(1);
132- Map<Object, Object> result = new LinkedHashMap<Object, Object>();
133- for (Entry<Object, Object> entry : ((Map<Object, Object>)value).entrySet())
134- result.put(
135- convertEntitiesToUDTs(entry.getKey(), keyType),
136- convertEntitiesToUDTs(entry.getValue(), valueType)
137- );
138- return result;
139- }
140- throw new IllegalArgumentException("Error converting " + value);
141- }
142-
143- /**
144- * Handles a (possibly nested) collection where some of the elements are {@code UDTValue}
145- * instances that must be converted to domain classes.
146- */
147- @SuppressWarnings("unchecked")
148- static Object convertUDTsToEntities(Object value, InferredCQLType type) {
149- if (value == null)
150- return null;
151-
152- if (!type.containsMappedUDT)
153- return value;
154-
155- if (type.udtMapper != null)
156- return type.udtMapper.toEntity((UDTValue)value);
157-
158- if (type.dataType.getName() == DataType.Name.LIST) {
159- InferredCQLType elementType = type.childTypes.get(0);
160- List<Object> result = new ArrayList<Object>();
161- for (Object element : (List<Object>)value)
162- result.add(convertUDTsToEntities(element, elementType));
163- return result;
164- }
165-
166- if (type.dataType.getName() == DataType.Name.SET) {
167- InferredCQLType elementType = type.childTypes.get(0);
168- Set<Object> result = new LinkedHashSet<Object>();
169- for (Object element : (Set<Object>)value)
170- result.add(convertUDTsToEntities(element, elementType));
171- return result;
172- }
173-
174- if (type.dataType.getName() == DataType.Name.MAP) {
175- InferredCQLType keyType = type.childTypes.get(0);
176- InferredCQLType valueType = type.childTypes.get(1);
177- Map<Object, Object> result = new LinkedHashMap<Object, Object>();
178- for (Entry<Object, Object> entry : ((Map<Object, Object>)value).entrySet())
179- result.put(
180- convertUDTsToEntities(entry.getKey(), keyType),
181- convertUDTsToEntities(entry.getValue(), valueType)
182- );
183- return result;
184- }
185- throw new IllegalArgumentException("Error converting " + value);
186- }
187-}
modified driver-mapping/src/main/java/com/datastax/driver/mapping/annotations/Column.java +10 −0
@@ -20,6 +20,8 @@
2020 import java.lang.annotation.RetentionPolicy;
2121 import java.lang.annotation.Target;
2222
23+import com.datastax.driver.core.TypeCodec;
24+
2325 /**
2426 * Annotation that allows to specify the name of the CQL column to which the
2527 * field should be mapped.
@@ -49,4 +51,12 @@
4951 * @return whether the column name is a case sensitive one.
5052 */
5153 boolean caseSensitive() default false;
54+
55+ /**
56+ * A custom codec that will be used to serialize and deserialize the column.
57+ *
58+ * @return the codec's class. It must have a no-argument constructor (the mapper
59+ * will create an instance and cache it).
60+ */
61+ Class<? extends TypeCodec<?>> codec() default Defaults.NoCodec.class;
5262 }
added driver-mapping/src/main/java/com/datastax/driver/mapping/annotations/Defaults.java +34 −0
@@ -0,0 +1,34 @@
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.mapping.annotations;
17+
18+import com.datastax.driver.core.DataType;
19+import com.datastax.driver.core.TypeCodec;
20+
21+/**
22+ * Holds common defaults for the mapping annotations.
23+ */
24+public class Defaults {
25+
26+ /**
27+ * A fake codec implementation to use as the default in mapping annotations.
28+ */
29+ public static abstract class NoCodec extends TypeCodec<String> {
30+ private NoCodec() {
31+ super(DataType.cint(), String.class);
32+ }
33+ }
34+}
modified driver-mapping/src/main/java/com/datastax/driver/mapping/annotations/Field.java +10 −0
@@ -20,6 +20,8 @@
2020 import java.lang.annotation.RetentionPolicy;
2121 import java.lang.annotation.Target;
2222
23+import com.datastax.driver.core.TypeCodec;
24+
2325 /**
2426 * Annotation that allows to specify the name of the CQL UDT field to which the
2527 * Java field should be mapped.
@@ -49,4 +51,12 @@
4951 * @return whether the column name is a case sensitive one.
5052 */
5153 boolean caseSensitive() default false;
54+
55+ /**
56+ * A custom codec that will be used to serialize and deserialize the column.
57+ *
58+ * @return the codec's class. It must have a no-argument constructor (the mapper
59+ * will create an instance and cache it).
60+ */
61+ Class<? extends TypeCodec<?>> codec() default Defaults.NoCodec.class;
5262 }
modified driver-mapping/src/main/java/com/datastax/driver/mapping/annotations/Param.java +11 −1
@@ -20,6 +20,8 @@
2020 import java.lang.annotation.RetentionPolicy;
2121 import java.lang.annotation.Target;
2222
23+import com.datastax.driver.core.TypeCodec;
24+
2325 /**
2426 * Provides a name for a parameter of a method in an {@link Accessor} interface that
2527 * can be used to reference to that parameter in method {@link Query}.
@@ -32,5 +34,13 @@
3234 *
3335 * @return the name of the parameter.
3436 */
35- String value();
37+ String value() default "";
38+
39+ /**
40+ * A custom codec that will be used to serialize the parameter.
41+ *
42+ * @return the codec's class. It must have a no-argument constructor (the mapper
43+ * will create an instance and cache it).
44+ */
45+ Class<? extends TypeCodec<?>> codec() default Defaults.NoCodec.class;
3646 }
modified driver-mapping/src/test/java/com/datastax/driver/core/CoreHooks.java +1 −1
@@ -21,5 +21,5 @@
2121 * Provides access to package-private members of the core module.
2222 */
2323 public class CoreHooks {
24- public static UserType MOCK_USER_TYPE = new UserType("mockKs", "mockUDT", Collections.<UserType.Field>emptyList());
24+ public static UserType MOCK_USER_TYPE = new UserType("mockKs", "mockUDT", Collections.<UserType.Field>emptyList(), TestUtils.getDesiredProtocolVersion(), new CodecRegistry());
2525 }
deleted driver-mapping/src/test/java/com/datastax/driver/mapping/InferredCQLTypeTest.java +0 −109
@@ -1,109 +0,0 @@
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.mapping;
17-
18-import java.lang.reflect.Field;
19-import java.util.List;
20-import java.util.Map;
21-import java.util.Set;
22-
23-import org.testng.annotations.BeforeClass;
24-import org.testng.annotations.Test;
25-
26-import static org.mockito.Mockito.mock;
27-import static org.mockito.Mockito.when;
28-
29-import com.datastax.driver.core.CoreHooks;
30-import com.datastax.driver.core.DataType;
31-import com.datastax.driver.core.UserType;
32-import com.datastax.driver.mapping.annotations.UDT;
33-
34-import static com.datastax.driver.core.Assertions.assertThat;
35-
36-public class InferredCQLTypeTest {
37- MappingManager manager;
38- UDTMapper mockMapper;
39- UserType mockUDTType = CoreHooks.MOCK_USER_TYPE;
40-
41- @BeforeClass(groups = "unit")
42- @SuppressWarnings("unchecked")
43- public void setup() {
44- mockMapper = mock(UDTMapper.class);
45- when(mockMapper.getUserType()).thenReturn(mockUDTType);
46-
47- manager = mock(MappingManager.class);
48- when(manager.udtMapper(MockUDT.class)).thenReturn(mockMapper);
49- }
50-
51- @Test(groups = "unit")
52- public void should_parse_collections_of_primitives() throws Exception {
53- InferredCQLType instance = newInstanceForField("listOfIntegers");
54- assertThat(instance.dataType).isEqualTo(DataType.list(DataType.cint()));
55- assertThat(instance.containsMappedUDT).isFalse();
56- assertThat(instance.udtMapper).isNull();
57-
58- instance = newInstanceForField("setOfStrings");
59- assertThat(instance.dataType).isEqualTo(DataType.set(DataType.text()));
60- assertThat(instance.containsMappedUDT).isFalse();
61- assertThat(instance.udtMapper).isNull();
62-
63- instance = newInstanceForField("mapOfIntegerToString");
64- assertThat(instance.dataType).isEqualTo(DataType.map(DataType.cint(), DataType.text()));
65- assertThat(instance.containsMappedUDT).isFalse();
66- assertThat(instance.udtMapper).isNull();
67- }
68-
69- @Test(groups = "unit")
70- public void should_parse_collection_containing_UDT() throws Exception {
71- InferredCQLType instance = newInstanceForField("listOfUDT");
72- assertThat(instance.dataType).isEqualTo(DataType.list(mockUDTType));
73- assertThat(instance.containsMappedUDT).isTrue();
74- assertThat(instance.udtMapper).isNull();
75- assertThat(instance.childTypes.get(0).udtMapper).isEqualTo(mockMapper);
76-
77- instance = newInstanceForField("complexMap");
78- assertThat(instance.dataType).isEqualTo(DataType.map(
79- DataType.list(DataType.cint()),
80- DataType.map(DataType.text(), DataType.set(mockUDTType))
81- ));
82- assertThat(instance.containsMappedUDT).isTrue();
83- assertThat(instance.udtMapper).isNull();
84- InferredCQLType key = instance.childTypes.get(0);
85- assertThat(key.containsMappedUDT).isFalse();
86- assertThat(key.udtMapper).isNull();
87- InferredCQLType value = instance.childTypes.get(1);
88- assertThat(value.containsMappedUDT).isTrue();
89- assertThat(value.udtMapper).isNull();
90- assertThat(value.childTypes.get(0).containsMappedUDT).isFalse();
91- assertThat(value.childTypes.get(1).containsMappedUDT).isTrue();
92- assertThat(value.childTypes.get(1).childTypes.get(0).udtMapper).isEqualTo(mockMapper);
93- }
94-
95- private InferredCQLType newInstanceForField(String name) throws NoSuchFieldException {
96- Field field = InferredCQLTypeTest.class.getDeclaredField(name);
97- return InferredCQLType.from(field, manager);
98- }
99-
100- @UDT(name = "mock")
101- static class MockUDT {
102- }
103-
104- List<Integer> listOfIntegers;
105- Set<String> setOfStrings;
106- Map<Integer, String> mapOfIntegerToString;
107- List<MockUDT> listOfUDT;
108- Map<List<Integer>, Map<String, Set<MockUDT>>> complexMap;
109-}
No newline at the end of the file
modified driver-mapping/src/test/java/com/datastax/driver/mapping/MapperComputedFieldsTest.java +9 −6
@@ -26,6 +26,7 @@
2626 import static org.assertj.core.api.Assertions.fail;
2727
2828 import com.datastax.driver.core.*;
29+import com.datastax.driver.core.exceptions.CodecNotFoundException;
2930 import com.datastax.driver.core.exceptions.InvalidQueryException;
3031 import com.datastax.driver.core.utils.CassandraVersion;
3132 import com.datastax.driver.mapping.annotations.*;
@@ -125,10 +126,12 @@
125126 assertThat(user.getWriteTime()).isEqualTo(0);
126127 }
127128
128- @Test(groups = "short", expectedExceptions = IllegalArgumentException.class)
129+ @Test(groups = "short", expectedExceptions = CodecNotFoundException.class)
129130 @CassandraVersion(major = 2.0)
130131 void should_fail_if_computed_field_is_not_right_type() {
131- mappingManager.mapper(User_WrongComputedType.class);
132+ Mapper<User_WrongComputedType> mapper = mappingManager.mapper(User_WrongComputedType.class);
133+
134+ User_WrongComputedType user = mapper.get("testlogin");
132135 }
133136
134137 @Test(groups = "short")
@@ -213,8 +216,8 @@
213216 private String login;
214217 private String name;
215218
216- @Column(name = "writetime(v)")
217- byte writeTime;
219+ @Computed(value = "writetime(name)")
220+ String writeTime;
218221
219222 public String getLogin() {
220223 return login;
@@ -232,11 +235,11 @@
232235 this.name = name;
233236 }
234237
235- public byte getWriteTime() {
238+ public String getWriteTime() {
236239 return writeTime;
237240 }
238241
239- public void setWriteTime(byte writeTime) {
242+ public void setWriteTime(String writeTime) {
240243 this.writeTime = writeTime;
241244 }
242245 }
added driver-mapping/src/test/java/com/datastax/driver/mapping/MapperCustomCodecTest.java +558 −0
@@ -0,0 +1,558 @@
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.mapping;
17+
18+import java.nio.ByteBuffer;
19+import java.util.Collection;
20+import java.util.Map;
21+
22+import com.datastax.driver.core.utils.CassandraVersion;
23+import com.google.common.base.Optional;
24+import com.google.common.collect.ImmutableMap;
25+import com.google.common.collect.Lists;
26+import org.testng.annotations.Test;
27+
28+import static org.assertj.core.api.Assertions.assertThat;
29+import static org.assertj.core.api.Assertions.fail;
30+
31+import com.datastax.driver.core.*;
32+import com.datastax.driver.core.exceptions.InvalidTypeException;
33+import com.datastax.driver.mapping.annotations.*;
34+
35+@CassandraVersion(major=2.1)
36+public class MapperCustomCodecTest extends CCMBridge.PerClassSingleNodeCluster {
37+
38+ @Override
39+ protected Collection<String> getTableDefinitions() {
40+ return Lists.newArrayList(
41+ // Columns mapped to custom types
42+ "CREATE TABLE data1 (i int PRIMARY KEY, l bigint)",
43+ "INSERT INTO data1 (i, l) VALUES (1, 11)",
44+
45+ // UDT fields mapped to custom types
46+ "CREATE TYPE holder(i int, l bigint)",
47+ "CREATE TABLE data2(i int primary key, data frozen<holder>)",
48+ "INSERT INTO data2 (i, data) values (1, {i: 1, l: 11})",
49+
50+ // nested UDT
51+ // both UDT fields and non-UDT elements in the collection are mapped to custom types
52+ "CREATE TABLE data3(i int primary key, data map<int, frozen<holder>>)",
53+ "INSERT INTO data3 (i, data) values (1, {1: {i: 1, l: 11}})"
54+ );
55+ }
56+
57+ @Override
58+ protected Cluster.Builder configure(Cluster.Builder builder) {
59+ return builder.withCodecRegistry(new CodecRegistry()
60+ .register(new CustomInt.Codec()));
61+ }
62+
63+ @Test(groups = "short")
64+ public void should_use_custom_codecs_with_basic_operations() {
65+ Mapper<Data1> mapper = new MappingManager(session).mapper(Data1.class);
66+
67+ // Get
68+ Data1 data11 = mapper.get(new CustomInt(1));
69+ assertThat(data11.getI()).isEqualTo(new CustomInt(1));
70+ assertThat(data11.getL()).isEqualTo(new CustomLong(11));
71+
72+ // Save
73+ Data1 data12 = new Data1();
74+ data12.setI(new CustomInt(2));
75+ data12.setL(new CustomLong(12));
76+ mapper.save(data12);
77+
78+ Row row = session.execute("select * from data1 where i = 2").one();
79+ assertThat(row.getInt(0)).isEqualTo(2);
80+ assertThat(row.getLong(1)).isEqualTo(12);
81+
82+ // Delete
83+ mapper.delete(new CustomInt(2));
84+ row = session.execute("select * from data1 where i = 2").one();
85+ assertThat(row).isNull();
86+ }
87+
88+ @Test(groups = "short")
89+ public void should_use_custom_codecs_with_accessors() {
90+ Data1Accessor accessor = new MappingManager(session).createAccessor(Data1Accessor.class);
91+ Data1 data1 = accessor.get(new CustomInt(1));
92+ assertThat(data1.getI()).isEqualTo(new CustomInt(1));
93+ assertThat(data1.getL()).isEqualTo(new CustomLong(11));
94+
95+ accessor.setL(1, new CustomLong(12));
96+ Row row = session.execute("select l from data1 where i = 1").one();
97+ assertThat(row.getLong(0)).isEqualTo(12);
98+
99+ accessor.setL(1, new CustomLong(11));
100+ }
101+
102+ @Test(groups = "short")
103+ public void should_use_custom_codecs_in_UDTs() {
104+ Mapper<Data2> mapper = new MappingManager(session).mapper(Data2.class);
105+
106+ // Get
107+ Data2 data21 = mapper.get(1);
108+ assertThat(data21.getData().getI()).isEqualTo(new CustomInt(1));
109+ assertThat(data21.getData().getL()).isEqualTo(new CustomLong(11));
110+
111+ // Save
112+ Data2 data22 = new Data2();
113+ data22.setI(2);
114+ data22.setData(new Holder(2, 22));
115+ mapper.save(data22);
116+
117+ Row row = session.execute("select * from data2 where i = 2").one();
118+ assertThat(row.getUDTValue(1).getInt("i")).isEqualTo(2);
119+ assertThat(row.getUDTValue(1).getLong("l")).isEqualTo(22);
120+
121+ // cleanup
122+ mapper.delete(2);
123+ }
124+
125+ @Test(groups = "short")
126+ public void should_use_custom_codecs_in_nested_structures() {
127+ Mapper<Data3> mapper = new MappingManager(session).mapper(Data3.class);
128+
129+ // Get
130+ Data3 data31 = mapper.get(1);
131+ assertThat(data31.getData().containsKey(new CustomInt(1)));
132+ assertThat(data31.getData().get(new CustomInt(1)).getI()).isEqualTo(new CustomInt(1));
133+
134+ // Save
135+ Data3 data32 = new Data3();
136+ data32.setI(2);
137+ data32.setData(ImmutableMap.of(new CustomInt(2), new Holder(2, 22)));
138+ mapper.save(data32);
139+
140+ Row row = session.execute("select * from data3 where i = 2").one();
141+ Map<Integer, UDTValue> data = row.getMap(1, Integer.class, UDTValue.class);
142+ assertThat(data.containsKey(2));
143+ assertThat(data.get(2).getInt("i")).isEqualTo(2);
144+ assertThat(data.get(2).getLong("l")).isEqualTo(22);
145+
146+ // cleanup
147+ mapper.delete(2);
148+ }
149+
150+ @Test(groups="short", expectedExceptions = IllegalArgumentException.class)
151+ public void should_fail_when_invalid_codec_with_no_default_ctor_provided() {
152+ new MappingManager(session).mapper(Data1InvalidCodecNoDefaultConstructor.class);
153+ }
154+
155+ @Test(groups="short", expectedExceptions = InvalidTypeException.class)
156+ public void should_fail_when_invalid_codec_type_mapping() {
157+ Mapper<Data1InvalidCodecTypeMapping> mapper = new MappingManager(session).mapper(Data1InvalidCodecTypeMapping.class);
158+
159+ // Get should return an InvalidTypeException.
160+ try {
161+ Data1InvalidCodecTypeMapping data1 = mapper.get(1);
162+ fail("Should not have been able to retrieve.");
163+ } catch (InvalidTypeException e) {
164+ // expected.
165+ }
166+
167+ // Set should also return an InvalidTypeException.
168+ Data1InvalidCodecTypeMapping data12 = new Data1InvalidCodecTypeMapping();
169+ data12.setI(2);
170+ data12.setL(Optional.of(1L));
171+ mapper.save(data12);
172+ }
173+
174+ @Test(groups="short", expectedExceptions = IllegalArgumentException.class)
175+ public void should_fail_when_invalid_codec_with_no_default_ctor_provided_in_accessor() {
176+ new MappingManager(session).createAccessor(Data1AccessorNoDefaultConstructor.class);
177+ }
178+
179+ @Test(groups="short", expectedExceptions = InvalidTypeException.class)
180+ public void should_fail_when_invalid_codec_type_mapping_in_accessor() {
181+ Data1AccessorInvalidCodecTypeMapping accessor = new MappingManager(session).createAccessor(Data1AccessorInvalidCodecTypeMapping.class);
182+
183+ // Get should return an InvalidTypeException.
184+ try {
185+ Data1InvalidCodecTypeMapping data1 = accessor.get(1);
186+ fail("Should not have been able to retrieve.");
187+ } catch (InvalidTypeException e) {
188+ // expected.
189+ }
190+
191+ accessor.setL(1, Optional.of(2L));
192+ }
193+
194+ @Test(groups="short")
195+ public void should_be_able_to_use_parameterized_type() {
196+ Mapper<Data1ParameterizedType> mapper = new MappingManager(session).mapper(Data1ParameterizedType.class);
197+
198+ Data1ParameterizedType data1 = mapper.get(1);
199+ assertThat(data1.getL()).isEqualTo(Optional.of(11L));
200+
201+ // Set with an absent ('null') value.
202+ Data1ParameterizedType empty1 = new Data1ParameterizedType();
203+ empty1.setI(1000);
204+ empty1.setL(Optional.<Long>absent());
205+ mapper.save(empty1);
206+
207+ // Value should come back absent.
208+ Data1ParameterizedType empty1r = mapper.get(1000);
209+ assertThat(empty1r.getL()).isEqualTo(Optional.<Long>absent());
210+
211+ // Value should come back absent with codec, otherwise null with getObject, 0 with getLong.
212+ Row row = session.execute("select l from data1 where i=1000").one();
213+ assertThat(row.getObject(0)).isEqualTo(null); // should map to long codec and return null.
214+ assertThat(row.getLong(0)).isEqualTo(0L); // default boxed primitive value.
215+ assertThat(row.get(0, new OptionalOfLong())).isEqualTo(Optional.<Long>absent());
216+
217+ // Set with a present value.
218+ Data1ParameterizedType present1 = new Data1ParameterizedType();
219+ present1.setI(1001);
220+ present1.setL(Optional.of(20L));
221+ mapper.save(present1);
222+
223+ // Value should come back present with codec, otherwise 20L.
224+ row = session.execute("select l from data1 where i=1001").one();
225+ assertThat(row.getObject(0)).isEqualTo(20L); // should map to long codec.
226+ assertThat(row.getLong(0)).isEqualTo(20L);
227+ assertThat(row.get(0, new OptionalOfLong())).isEqualTo(Optional.of(20L));
228+ }
229+
230+ @Table(name = "data1")
231+ public static class Data1 {
232+ @PartitionKey
233+ private CustomInt i;
234+
235+ @Column(codec = CustomLong.Codec.class)
236+ private CustomLong l;
237+
238+ public CustomInt getI() {
239+ return i;
240+ }
241+
242+ public void setI(CustomInt i) {
243+ this.i = i;
244+ }
245+
246+ public CustomLong getL() {
247+ return l;
248+ }
249+
250+ public void setL(CustomLong l) {
251+ this.l = l;
252+ }
253+ }
254+
255+ @Table(name = "data1")
256+ public static class Data1InvalidCodecNoDefaultConstructor {
257+
258+ @PartitionKey
259+ private int i;
260+
261+ @Column(codec = TypeCodec.StringCodec.class)
262+ private long l;
263+
264+ public int getI() {
265+ return i;
266+ }
267+
268+ public void setI(int i) {
269+ this.i = i;
270+ }
271+
272+ public long getL() {
273+ return l;
274+ }
275+
276+ public void setL(long l) {
277+ this.l = l;
278+ }
279+ }
280+
281+ @Table(name = "data1")
282+ public static class Data1InvalidCodecTypeMapping {
283+
284+ @PartitionKey
285+ private int i;
286+
287+ @Column(codec = OptionalOfString.class)
288+ private Optional<Long> l;
289+
290+ public int getI() {
291+ return i;
292+ }
293+
294+ public void setI(int i) {
295+ this.i = i;
296+ }
297+
298+ public Optional<Long> getL() {
299+ return l;
300+ }
301+
302+ public void setL(Optional<Long> l) {
303+ this.l = l;
304+ }
305+ }
306+
307+ @Table(name = "data1")
308+ public static class Data1ParameterizedType {
309+
310+ @PartitionKey
311+ private int i;
312+
313+ @Column(codec = OptionalOfLong.class)
314+ private Optional<Long> l;
315+
316+ public int getI() {
317+ return i;
318+ }
319+
320+ public void setI(int i) {
321+ this.i = i;
322+ }
323+
324+ public Optional<Long> getL() {
325+ return l;
326+ }
327+
328+ public void setL(Optional<Long> l) {
329+ this.l = l;
330+ }
331+ }
332+
333+ @Accessor
334+ public interface Data1Accessor {
335+ @Query("select * from data1 where i = :i")
336+ Data1 get(@Param("i") CustomInt i);
337+
338+ @Query("update data1 set l = :l where i = :i")
339+ void setL(@Param("i") int i,
340+ @Param(value = "l", codec = CustomLong.Codec.class) CustomLong l);
341+ }
342+
343+ @Accessor
344+ public interface Data1AccessorNoDefaultConstructor {
345+
346+ @Query("update data1 set l = :l where i = :i")
347+ void setL(@Param("i") int i,
348+ @Param(value = "l", codec = TypeCodec.StringCodec.class) long l);
349+ }
350+
351+ @Accessor
352+ public interface Data1AccessorInvalidCodecTypeMapping {
353+
354+ @Query("select * from data1 where i = :i")
355+ Data1InvalidCodecTypeMapping get(@Param("i") int i);
356+
357+ @Query("update data1 set l = :l where i = :i")
358+ void setL(@Param("i") int i,
359+ @Param(value = "l", codec = OptionalOfString.class) Optional<Long> l);
360+ }
361+
362+ @UDT(name = "holder")
363+ public static class Holder {
364+ private CustomInt i;
365+
366+ @Field(codec = CustomLong.Codec.class)
367+ private CustomLong l;
368+
369+ public Holder() {
370+ }
371+
372+ public Holder(int i, long l) {
373+ this.i = new CustomInt(i);
374+ this.l = new CustomLong(l);
375+ }
376+
377+ public CustomInt getI() {
378+ return i;
379+ }
380+
381+ public void setI(CustomInt i) {
382+ this.i = i;
383+ }
384+
385+ public CustomLong getL() {
386+ return l;
387+ }
388+
389+ public void setL(CustomLong l) {
390+ this.l = l;
391+ }
392+ }
393+
394+ @Table(name = "data2")
395+ public static class Data2 {
396+ @PartitionKey
397+ private int i;
398+
399+ @Frozen
400+ private Holder data;
401+
402+ public int getI() {
403+ return i;
404+ }
405+
406+ public void setI(int i) {
407+ this.i = i;
408+ }
409+
410+ public Holder getData() {
411+ return data;
412+ }
413+
414+ public void setData(Holder data) {
415+ this.data = data;
416+ }
417+ }
418+
419+ @Table(name = "data3")
420+ public static class Data3 {
421+ @PartitionKey
422+ private int i;
423+
424+ @FrozenValue
425+ private Map<CustomInt, Holder> data;
426+
427+ public int getI() {
428+ return i;
429+ }
430+
431+ public void setI(int i) {
432+ this.i = i;
433+ }
434+
435+ public Map<CustomInt, Holder> getData() {
436+ return data;
437+ }
438+
439+ public void setData(Map<CustomInt, Holder> data) {
440+ this.data = data;
441+ }
442+ }
443+
444+ public static class CustomInt {
445+ public final int value;
446+
447+ public CustomInt(int value) {
448+ this.value = value;
449+ }
450+
451+ @Override
452+ public boolean equals(Object other) {
453+ if (other instanceof CustomInt) {
454+ CustomInt that = (CustomInt)other;
455+ return this.value == that.value;
456+ }
457+ return false;
458+ }
459+
460+ @Override
461+ public int hashCode() {
462+ return value;
463+ }
464+
465+ public static class Codec extends TypeCodec<CustomInt> {
466+ public Codec() {
467+ super(DataType.cint(), CustomInt.class);
468+ }
469+
470+ @Override
471+ public ByteBuffer serialize(CustomInt value, ProtocolVersion protocolVersion) throws InvalidTypeException {
472+ return TypeCodec.IntCodec.instance.serialize(value.value, protocolVersion);
473+ }
474+
475+ @Override
476+ public CustomInt deserialize(ByteBuffer bytes, ProtocolVersion protocolVersion) throws InvalidTypeException {
477+ Integer i = TypeCodec.IntCodec.instance.deserialize(bytes, protocolVersion);
478+ return new CustomInt(i);
479+ }
480+
481+ @Override
482+ public CustomInt parse(String value) throws InvalidTypeException {
483+ throw new UnsupportedOperationException();
484+ }
485+
486+ @Override
487+ public String format(CustomInt value) throws InvalidTypeException {
488+ throw new UnsupportedOperationException();
489+ }
490+ }
491+ }
492+
493+ public static class CustomLong {
494+ public final long value;
495+
496+ public CustomLong(long value) {
497+ this.value = value;
498+ }
499+
500+ @Override
501+ public boolean equals(Object other) {
502+ if (other instanceof CustomLong) {
503+ CustomLong that = (CustomLong)other;
504+ return this.value == that.value;
505+ }
506+ return false;
507+ }
508+
509+ @Override
510+ public int hashCode() {
511+ return (int)(value ^ (value >>> 32));
512+ }
513+
514+ public static class Codec extends TypeCodec<CustomLong> {
515+ public Codec() {
516+ super(DataType.bigint(), CustomLong.class);
517+ }
518+
519+ @Override
520+ public ByteBuffer serialize(CustomLong value, ProtocolVersion protocolVersion) throws InvalidTypeException {
521+ return TypeCodec.BigintCodec.instance.serialize(value.value, protocolVersion);
522+ }
523+
524+ @Override
525+ public CustomLong deserialize(ByteBuffer bytes, ProtocolVersion protocolVersion) throws InvalidTypeException {
526+ Long l = TypeCodec.BigintCodec.instance.deserialize(bytes, protocolVersion);
527+ return new CustomLong(l);
528+ }
529+
530+ @Override
531+ public CustomLong parse(String value) throws InvalidTypeException {
532+ throw new UnsupportedOperationException();
533+ }
534+
535+ @Override
536+ public String format(CustomLong value) throws InvalidTypeException {
537+ throw new UnsupportedOperationException();
538+ }
539+ }
540+ }
541+
542+ public static class OptionalOfLong extends OptionalCodec<Long> {
543+ private static final CodecRegistry registry = new CodecRegistry();
544+
545+ public OptionalOfLong() {
546+ super(registry.codecFor(DataType.bigint(), Long.class));
547+ }
548+ }
549+
550+ public static class OptionalOfString extends OptionalCodec<String> {
551+
552+ private static final CodecRegistry registry = new CodecRegistry();
553+
554+ public OptionalOfString() {
555+ super(registry.codecFor(DataType.text(), String.class));
556+ }
557+ }
558+}
modified driver-mapping/src/test/java/com/datastax/driver/mapping/MapperDefaultKeyspaceTest.java +74 −72
@@ -15,20 +15,21 @@
1515 */
1616 package com.datastax.driver.mapping;
1717
18-import java.util.*;
18+import java.util.Arrays;
19+import java.util.Collection;
20+import java.util.UUID;
1921
20-import com.datastax.driver.core.Session;
21-import com.datastax.driver.core.utils.CassandraVersion;
22-import com.datastax.driver.mapping.annotations.*;
2322 import com.google.common.base.Objects;
2423 import org.testng.annotations.Test;
2524
26-import static com.datastax.driver.core.TestUtils.CREATE_KEYSPACE_SIMPLE_FORMAT;
2725 import static org.testng.Assert.assertEquals;
2826 import static org.testng.Assert.assertNull;
2927
3028 import com.datastax.driver.core.CCMBridge;
29+import com.datastax.driver.core.Session;
30+import com.datastax.driver.core.utils.CassandraVersion;
3131 import com.datastax.driver.core.utils.UUIDs;
32+import com.datastax.driver.mapping.annotations.*;
3233
3334 /**
3435 * Tests usage of mapping annotations without specifying a keyspace.
@@ -39,10 +40,76 @@
3940 private static final String KEYSPACE = "mapper_default_keyspace_test_ks";
4041
4142 protected Collection<String> getTableDefinitions() {
42- return Arrays.asList("CREATE TABLE groups (group_id uuid PRIMARY KEY, name text)",
43- "CREATE TYPE IF NOT EXISTS group_name (name text)");
43+ return Arrays.asList(
44+ String.format("CREATE KEYSPACE IF NOT EXISTS %s WITH replication = { 'class' : 'SimpleStrategy', 'replication_factor' : 1 }", KEYSPACE),
45+ String.format("CREATE TYPE IF NOT EXISTS %s.group_name (name text)", KEYSPACE),
46+ String.format("CREATE TABLE IF NOT EXISTS %s.groups (group_id uuid PRIMARY KEY, name text)", KEYSPACE),
47+ String.format("CREATE TABLE IF NOT EXISTS %s.groups2 (group_id uuid PRIMARY KEY, name frozen<group_name>)", KEYSPACE));
48+ }
49+
50+ @Test(groups = "short")
51+ public void testTableWithDefaultKeyspace() throws Exception {
52+ // Ensure that the test session is logged into the keyspace.
53+ session.execute("USE " + KEYSPACE);
54+
55+ MappingManager manager = new MappingManager(session);
56+ Mapper<Group> m = manager.mapper(Group.class);
57+ Group group = new Group("testGroup");
58+ UUID groupId = group.getGroupId();
59+
60+ // Check the save operation.
61+ m.save(group);
62+
63+ // Check the select operation.
64+ Group selectedGroup = m.get(groupId);
65+ assertEquals(selectedGroup.getGroupId(), groupId);
66+
67+ // Check the delete operation.
68+ m.delete(group);
69+ assertNull(m.get(groupId));
70+ }
71+
72+ @Test(groups = "short")
73+ public void testUDTWithDefaultKeyspace() throws Exception {
74+ // Ensure that the test session is logged into the keyspace.
75+ session.execute("USE " + KEYSPACE);
76+
77+ MappingManager manager = new MappingManager(session);
78+ Mapper<Group2> m = manager.mapper(Group2.class);
79+ Group2 group = new Group2(new GroupName("testGroup"));
80+ UUID groupId = group.getGroupId();
81+
82+ // Check the save operation.
83+ m.save(group);
84+
85+ // Check the select operation.
86+ Group2 selectedGroup = m.get(groupId);
87+ assertEquals(selectedGroup.getGroupId(), groupId);
88+
89+ // Check the delete operation.
90+ m.delete(group);
91+ assertNull(m.get(groupId));
92+ }
93+
94+ @Test(groups = "short",
95+ expectedExceptions = IllegalArgumentException.class,
96+ expectedExceptionsMessageRegExp = "Error creating mapper for class Group, the @Table annotation declares no default keyspace, and the session is not currently logged to any keyspace")
97+ public void should_throw_a_meaningful_error_message_when_no_default_table_keyspace_and_session_not_logged() {
98+ Session session2 = cluster.connect();
99+ MappingManager manager = new MappingManager(session2);
100+ manager.mapper(Group.class);
101+ }
102+
103+ @Test(groups = "short",
104+ expectedExceptions = IllegalArgumentException.class,
105+ expectedExceptionsMessageRegExp = "Error creating UDT codec for class GroupName, the @UDT annotation declares no default keyspace, and the session is not currently logged to any keyspace")
106+ public void should_throw_a_meaningful_error_message_when_no_default_udt_keyspace_and_session_not_logged() {
107+ Session session2 = cluster.connect();
108+ MappingManager manager = new MappingManager(session2);
109+ manager.udtCodec(GroupName.class);
44110 }
45111
112+
46113 /*
47114 * An entity that does not specify a keyspace in its @Table annotation. When a keyspace is
48115 * not specified, the mapper uses the session's logged in keyspace.
@@ -95,28 +162,6 @@
95162 }
96163 }
97164
98- @Test(groups = "short")
99- public void testTableWithDefaultKeyspace() throws Exception {
100- // Ensure that the test session is logged into the "ks" keyspace.
101- session.execute("USE " + keyspace);
102-
103- MappingManager manager = new MappingManager(session);
104- Mapper<Group> m = manager.mapper(Group.class);
105- Group group = new Group("testGroup");
106- UUID groupId = group.getGroupId();
107-
108- // Check the save operation.
109- m.save(group);
110-
111- // Check the select operation.
112- Group selectedGroup = m.get(groupId);
113- assertEquals(selectedGroup.getGroupId(), groupId);
114-
115- // Check the delete operation.
116- m.delete(group);
117- assertNull(m.get(groupId));
118- }
119-
120165 @Table(keyspace = KEYSPACE, name = "groups2")
121166 public static class Group2 {
122167
@@ -204,47 +249,4 @@
204249 }
205250 }
206251
207- @Test(groups = "short")
208- public void testUDTWithDefaultKeyspace() throws Exception {
209- // Create test specific keyspace and table.
210- session.execute(String.format("CREATE KEYSPACE IF NOT EXISTS %s WITH replication = { 'class' : 'SimpleStrategy', 'replication_factor' : 1 }", KEYSPACE));
211- session.execute(String.format("CREATE TYPE IF NOT EXISTS %s.group_name (name text)", KEYSPACE));
212- session.execute(String.format("CREATE TABLE IF NOT EXISTS %s.groups2 (group_id uuid PRIMARY KEY, name frozen<group_name>)", KEYSPACE));
213- // Ensure that the test session is logged into the keyspace.
214- session.execute("USE " + keyspace);
215-
216- MappingManager manager = new MappingManager(session);
217- Mapper<Group2> m = manager.mapper(Group2.class);
218- Group2 group = new Group2(new GroupName("testGroup"));
219- UUID groupId = group.getGroupId();
220-
221- // Check the save operation.
222- m.save(group);
223-
224- // Check the select operation.
225- Group2 selectedGroup = m.get(groupId);
226- assertEquals(selectedGroup.getGroupId(), groupId);
227-
228- // Check the delete operation.
229- m.delete(group);
230- assertNull(m.get(groupId));
231- }
232-
233- @Test(groups = "short",
234- expectedExceptions = IllegalArgumentException.class,
235- expectedExceptionsMessageRegExp = "Error creating mapper for class Group, the @Table annotation declares no default keyspace, and the session is not currently logged to any keyspace")
236- public void should_throw_a_meaningful_error_message_when_no_default_table_keyspace_and_session_not_logged() {
237- Session session2 = cluster.connect();
238- MappingManager manager = new MappingManager(session2);
239- manager.mapper(Group.class);
240- }
241-
242- @Test(groups = "short",
243- expectedExceptions = IllegalArgumentException.class,
244- expectedExceptionsMessageRegExp = "Error creating UDT mapper for class GroupName, the @UDT annotation declares no default keyspace, and the session is not currently logged to any keyspace")
245- public void should_throw_a_meaningful_error_message_when_no_default_udt_keyspace_and_session_not_logged() {
246- Session session2 = cluster.connect();
247- MappingManager manager = new MappingManager(session2);
248- manager.udtMapper(GroupName.class);
249- }
250252 }
deleted driver-mapping/src/test/java/com/datastax/driver/mapping/MapperInvalidCollectionTypesTest.java +0 −120
@@ -1,120 +0,0 @@
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.mapping;
17-
18-import java.util.*;
19-
20-import org.testng.annotations.Test;
21-
22-import com.datastax.driver.core.CCMBridge;
23-import com.datastax.driver.mapping.annotations.PartitionKey;
24-import com.datastax.driver.mapping.annotations.Table;
25-
26-public class MapperInvalidCollectionTypesTest extends CCMBridge.PerClassSingleNodeCluster {
27- protected Collection<String> getTableDefinitions() {
28- return Arrays.asList(
29- "CREATE TABLE table_list (id int PRIMARY KEY, l list<int>)",
30- "CREATE TABLE table_set (id int PRIMARY KEY, s set<int>)",
31- "CREATE TABLE table_map (id int PRIMARY KEY, m map<int, int>)");
32- }
33-
34- @Table(keyspace="ks", name="table_list")
35- public class InvalidList {
36- @PartitionKey
37- private int id;
38-
39- private ArrayList<Integer> l;
40-
41- public int getId() {
42- return id;
43- }
44-
45- public void setId(int id) {
46- this.id = id;
47- }
48-
49- public ArrayList<Integer> getL() {
50- return l;
51- }
52-
53- public void setL(ArrayList<Integer> l) {
54- this.l = l;
55- }
56- }
57-
58- @Table(keyspace="ks", name="table_set")
59- public class InvalidSet {
60- @PartitionKey
61- private int id;
62-
63- private HashSet<Integer> s;
64-
65- public int getId() {
66- return id;
67- }
68-
69- public void setId(int id) {
70- this.id = id;
71- }
72-
73- public HashSet<Integer> getS() {
74- return s;
75- }
76-
77- public void setS(HashSet<Integer> s) {
78- this.s = s;
79- }
80- }
81-
82- @Table(keyspace="ks", name="table_map")
83- public class InvalidMap {
84- @PartitionKey
85- private int id;
86-
87- private TreeMap<Integer, Integer> m;
88-
89- public TreeMap<Integer, Integer> getM() {
90- return m;
91- }
92-
93- public void setM(TreeMap<Integer, Integer> m) {
94- this.m = m;
95- }
96-
97- public int getId() {
98- return id;
99- }
100-
101- public void setId(int id) {
102- this.id = id;
103- }
104- }
105-
106- @Test(groups="short", expectedExceptions = IllegalArgumentException.class)
107- public void list_type_is_enforced() {
108- new MappingManager(session).mapper(InvalidList.class);
109- }
110-
111- @Test(groups="short", expectedExceptions = IllegalArgumentException.class)
112- public void map_type_is_enforced() {
113- new MappingManager(session).mapper(InvalidMap.class);
114- }
115-
116- @Test(groups="short", expectedExceptions = IllegalArgumentException.class)
117- public void set_type_is_enforced() {
118- new MappingManager(session).mapper(InvalidSet.class);
119- }
120-}
modified driver-mapping/src/test/java/com/datastax/driver/mapping/MapperUDTTest.java +70 −3
@@ -17,20 +17,21 @@
1717
1818 import java.util.*;
1919
20+import com.datastax.driver.core.*;
21+import com.datastax.driver.core.exceptions.CodecNotFoundException;
2022 import com.google.common.collect.Maps;
23+import org.assertj.core.data.MapEntry;
2124 import org.testng.annotations.BeforeMethod;
2225
2326 import com.google.common.base.Objects;
2427 import org.testng.annotations.Test;
2528
2629 import static org.assertj.core.api.Assertions.assertThat;
30+import static org.assertj.core.api.Assertions.fail;
2731 import static org.testng.Assert.assertEquals;
2832 import static org.testng.Assert.assertNull;
2933 import static org.testng.Assert.assertTrue;
3034
31-import com.datastax.driver.core.CCMBridge;
32-import com.datastax.driver.core.ResultSet;
33-import com.datastax.driver.core.Row;
3435 import com.datastax.driver.core.utils.UUIDs;
3536
3637 import com.datastax.driver.mapping.annotations.*;
@@ -273,4 +274,70 @@
273274 assertEquals(u.one(), u5);
274275 assertTrue(u.isExhausted());
275276 }
277+
278+ @Test(groups = "short")
279+ public void should_be_able_to_use_udtCodec_standalone() {
280+ // Create a separate Cluster/Session to start with a CodecRegistry from scratch (so not already registered).
281+ Cluster cluster = Cluster.builder().addContactPointsWithPorts(Collections.singleton(hostAddress)).build();
282+ try {
283+ CodecRegistry registry = cluster.getConfiguration().getCodecRegistry();
284+ Session session = cluster.connect(keyspace);
285+
286+ UUID userId = UUIDs.random();
287+
288+ // Create a user.
289+ session.execute("update users SET other_addresses['condo']={street: '101 Ocean Ln', city: 'Jacksonville, FL', zip_code: 89898, phones: {'8675309'}} " +
290+ " WHERE user_id=" + TypeCodec.UUIDCodec.instance.format(userId));
291+ session.execute("update users SET mainaddress={street: '42 Middle of Nowhere', city: 'Lake of the Woods', zip_code: 49553, phones: {'8675039'}} " +
292+ " WHERE user_Id=" + TypeCodec.UUIDCodec.instance.format(userId));
293+
294+ // Get the user.
295+ Row row = session.execute("select * from users where user_id=?", userId).one();
296+
297+ UDTValue udtValue = row.getUDTValue("mainaddress");
298+ assertThat(udtValue.getString("street")).isEqualTo("42 Middle of Nowhere");
299+
300+ Object udtObject = row.getObject("mainaddress");
301+ assertThat(udtObject).isEqualTo(udtValue);
302+
303+ // There shouldn't be a codec for address.
304+ try {
305+ assertThat(registry.codecFor(udtValue.getType(), Address.class));
306+ fail("Didn't expect to find codec for udtType <-> Address");
307+ } catch (CodecNotFoundException e) {
308+ // expected.
309+ }
310+
311+ // Expect a this_udt <-> UDTValue codec to exist. This is a pretty safe bet or else we wouldn't get
312+ // this value back.
313+ TypeCodec<UDTValue> udtCodec = registry.codecFor(udtValue.getType());
314+ assertThat(udtCodec.getCqlType()).isEqualTo(udtValue.getType());
315+ assertThat(udtCodec.getJavaType().getRawType()).isEqualTo(UDTValue.class);
316+
317+ // Retrieve codec for Address, if it can be mapped it will be created, if already registered it'll be used.
318+ TypeCodec<Address> codec = new MappingManager(session).udtCodec(Address.class);
319+
320+ // The codec should be registered after we call udtCodec.
321+ assertThat(registry.codecFor(udtValue.getType(), Address.class)).isEqualTo(codec);
322+
323+ // Should be able to retrieve as an Address.
324+ Address mainAddress = row.get("mainaddress", Address.class);
325+ assertThat(mainAddress.getCity()).isEqualTo("Lake of the Woods");
326+ assertThat(mainAddress.getStreet()).isEqualTo("42 Middle of Nowhere");
327+ assertThat(mainAddress.getZipCode()).isEqualTo(49553);
328+ assertThat(mainAddress.getPhones()).containsExactly("8675039");
329+
330+ // Should be able to retrieve within a Map.
331+ Address expectedOtherAddress = new Address();
332+ expectedOtherAddress.setStreet("101 Ocean Ln");
333+ expectedOtherAddress.setCity("Jacksonville, FL");
334+ expectedOtherAddress.setZipCode(89898);
335+ expectedOtherAddress.setPhones(Collections.singleton("8675309"));
336+
337+ Map<String, Address> otherAddresses = row.getMap("other_addresses", String.class, Address.class);
338+ assertThat(otherAddresses).containsOnly(MapEntry.entry("condo", expectedOtherAddress));
339+ } finally {
340+ cluster.close();
341+ }
342+ }
276343 }
added features/custom_codecs/README.md +419 −0
@@ -0,0 +1,419 @@
1+## Custom Codecs
2+
3+Custom codecs support transparent, user-configurable mapping of CQL types to arbitrary Java objects.
4+
5+Practical use cases that justify such a feature are numerous:
6+
7+* Ability to map CQL timestamp, date and time columns to Java 8 or Joda Time classes (rather than the built-in mappings for Date, [LocalDate] and Long);
8+* Ability to map CQL varchar columns directly to JSON or XML mapped objects (i.e. using frameworks such as Jackson);
9+* Ability to map CQL user-defined types to Java objects;
10+* Ability to map CQL lists directly to Java arrays;
11+* Ability to map CQL collections directly to Scala collections;
12+* etc.
13+
14+### Overview of the serialization mechanism
15+
16+The central piece in the serialization mechanism is [TypeCodec].
17+
18+Each `TypeCodec` supports a bidirectional mapping between a Java type and a CQL type. A `TypeCodec` is thus capable of 4 basic operations:
19+
20+* [Serialize][serialize] a Java object into a CQL value;
21+* [Deserialize][deserialize] a CQL value into a Java object;
22+* [Format][TypeCodec.format] a Java object into a CQL literal;
23+* [Parse][TypeCodec.parse] a CQL literal into a Java object.
24+
25+Additionally, it implements inspection methods that verify if the codec is suitable for a specific
26+CQL type and/or Java object.
27+
28+`TypeCodec` can be freely subclassed by users willing to implement their own serialization logic.
29+However, users are only required to do so when they want to extend
30+the driver's default set of codecs by registering additional codecs that handle
31+Java types that the driver is otherwise unable to process. For all other users,
32+the built-in set of codecs that is bundled with the driver provides
33+exactly the same functionality that the driver used to offer so far,
34+with out-of-the-box conversion from all CQL types to standard Java equivalents.
35+
36+Refer to the [javadocs][TypeCodec] of `TypeCodec` for more information.
37+
38+`TypeCodec`s are centralized in a [CodecRegistry] instance.
39+Whenever the driver needs to perform one of the aforementioned operations,
40+it will lookup for an appropriate codec in a `CodecRegistry`.
41+`CodecRegistry` is also used to manually register user-created codecs (see below for detailed instructions).
42+It also caches codec lookup results for faster execution whenever possible.
43+
44+Refer to the [javadocs][CodecRegistry] of User `CodecRegistry` for more information.
45+
46+### Implementing and using custom codecs
47+
48+Let's consider the following scenario: a user has JSON documents stored in a varchar column, and wants
49+the driver to automatically map that column to a Java object using the [Jackson] library,
50+instead of returning the raw JSON string.
51+
52+The (admittedly simplistic) table structure is as follows:
53+
54+```sql
55+CREATE TABLE t (id int PRIMARY KEY, json VARCHAR);
56+```
57+
58+The first step is to implement a suitable codec. Using Jackson, here is what a Json codec could like like:
59+
60+```java
61+/**
62+ * A simple Json codec.
63+ */
64+public class JsonCodec<T> extends TypeCodec.StringParsingCodec<T> {
65+
66+ private final ObjectMapper objectMapper;
67+
68+ public JsonCodec(Class<T> javaType, ObjectMapper objectMapper) {
69+ super(javaType);
70+ this.objectMapper = objectMapper;
71+ }
72+
73+ @Override
74+ @SuppressWarnings("unchecked")
75+ public T fromString(String value) {
76+ if (value == null)
77+ return null;
78+ try {
79+ return (T) objectMapper.readValue(value, getJavaType().getRawType());
80+ } catch (IOException e) {
81+ throw new InvalidTypeException(e.getMessage(), e);
82+ }
83+ }
84+
85+ @Override
86+ public String toString(T value) {
87+ if (value == null)
88+ return null;
89+ try {
90+ return objectMapper.writeValueAsString(value);
91+ } catch (JsonProcessingException e) {
92+ throw new InvalidTypeException(e.getMessage(), e);
93+ }
94+ }
95+}
96+```
97+
98+As you can see, the driver already provides a convenient base class: [StringParsingCodec][StringParsingCodec].
99+
100+A few implementation guidelines:
101+
102+* Your codecs should be thread-safe, or better yet, immutable;
103+* Your codecs should be fast: do not forget that codecs are executed often and are usually very "hot" pieces of code;
104+* Your codecs should never block.
105+
106+Note: the code above is an example and is not particularly efficient;
107+it suffers from the overhead of deserializing raw bytes into a String,
108+to only then parse the String into an object.
109+More advanced solutions that read the underlying byte stream directly are possible.
110+
111+The second step is to register your codec:
112+
113+```java
114+ObjectMapper objectMapper = ...
115+JsonCodec<MyPojo> myJsonCodec = new JsonCodec<MyPojo>(MyPojo.class, objectMapper);
116+CodecRegistry myCodecRegistry = new CodecRegistry().register(myJsonCodec);
117+```
118+
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*.
122+
123+The third step is to associate your `CodecRegistry` instance with your `Cluster` instance:
124+
125+```java
126+Cluster cluster = new Cluster.builder().withCodecRegistry(myCodecRegistry).build();
127+```
128+
129+From now on, your codec is fully operational. It will be used every time the driver encounters
130+a `MyPojo` instance when executing queries, or when you ask it to retrieve a `MyPojo` instance from a `ResultSet`.
131+
132+For example, here is how to save a `MyPojo` object:
133+
134+```java
135+Cluster cluster = ...
136+Session session = ...
137+MyPojo myPojo = ...
138+// Using SimpleStatement
139+Statement stmt = session.newSimpleStatement("INSERT INTO t (id, json) VALUES (?, ?)", 42, myPojo));
140+// Using the Query Builder
141+BuiltStatement insertStmt = new QueryBuilder(cluster).insertInto("t")
142+ .value("id", 42)
143+ .value("json", myPojo);
144+// Using BoundStatements
145+PreparedStatement ps = session.prepare("INSERT INTO t (id, json) VALUES (?, ?)");
146+BoundStatement bs1 = ps.bind(42, myPojo); // or alternatively...
147+BoundStatement bs2 = ps.bind()
148+ .setInt(0, 42)
149+ .set(1, myPojo, MyPojo.class);
150+```
151+
152+And here is how to retrieve a `MyPojo` object converted from a JSON document:
153+
154+```java
155+ResultSet rows = session.execute(...);
156+Row row = one();
157+// Let the driver convert the string for you...
158+MyPojo myPojo = row.get(1, MyPojo.class);
159+// ... or retrieve the raw string if you need it
160+String json = row.get(1, String.class); // row.getString(1) would have worked too
161+```
162+
163+Tip: `Row` and `BoundStatement` have several methods to set and retrieve values.
164+But if you plan to use custom codecs,
165+make sure that you use preferably the `get()` and `set()` methods: they
166+avoid any ambiguity by requiring the user to explicitly specify the desired Java type,
167+thus forcing the driver to pick the right codec for the right task.
168+
169+### Support for parameterized types
170+
171+`get()` and `set()` can even be used to retrieve collections or other
172+user-defined parameterized types; simply use the `get()` and `set()` variants that
173+take Guava's [TypeToken] parameter:
174+
175+```java
176+Row row = ...
177+List<MyPojo> myPojos = row.get("jsonList", new TypeToken<List<MyPojo>>(){});
178+// or alternatively, the following also works for collections:
179+List<MyPojo> myPojos = row.getList("jsonList", MyPojo.class);
180+```
181+
182+### Support for collections, user types, tuples and Java Enums
183+
184+`CodecRegistry` instances not only store default codecs and user-defined codecs;
185+they can also create new codecs on the fly, based on the set of codecs they currently hold.
186+
187+* Codecs for [UserType] instances are created on the fly using [UDTCodec];
188+* Codecs for [TupleType] instances are created on the fly using [TupleCodec];
189+* Codecs for Java Enums are created on the fly using [EnumStringCodec];
190+* Codecs for collections are created on the fly using [ListCodec],
191+ [SetCodec] and [MapCodec], if their element types can be handled by
192+ existing codecs (or codecs that can themselves be generated).
193+
194+This way, the user does not have to manually register all derived codecs for a given "base" codec.
195+However, other combinations of Java and CQL types not listed above cannot have their codecs created on the fly;
196+such codecs must be manually registered.
197+
198+The driver also provides another codec for Enums that converts Enum instances to CQL ints
199+representing their ordinal position: [EnumIntCodec]. If you plan to use this codec, make sure to register it
200+manually, otherwise Enums would be converted using [EnumStringCodec].
201+_It is not possible to mix both codecs in the same `CodecRegistry`_.
202+
203+Note that the default set of codecs has no support for
204+[Cassandra custom types][AbstractType];
205+to be able to deserialize values of such types, you need to manually register an appropriate codec.
206+
207+### Using custom codecs with user types and tuples
208+
209+By default, the driver maps user-defined type values and tuple values to [UDTValue] and [TupleValue],
210+using the built-in codecs [UDTCodec] and [TupleCodec] respectively.
211+
212+If you want to register a custom codec for a specific user type, follow these steps:
213+
214+Let's suppose you have a keyspace containing the following type and table:
215+
216+```sql
217+CREATE TYPE address (street VARCHAR, zipcode INT);
218+CREATE TABLE users (id UUID PRIMARY KEY, name VARCHAR, address frozen<address>);
219+```
220+
221+And let's suppose that you want to map the type `address` to an `Address` class:
222+
223+```java
224+public class Address {
225+
226+ private final String street;
227+
228+ private final int zipcode;
229+
230+ public Address(String street, int zipcode) {
231+ this.street = street;
232+ this.zipcode = zipcode;
233+ }
234+
235+ // getters, setters, equals() and hashcode() omitted
236+}
237+```
238+
239+First of all, create a codec for this class:
240+
241+```java
242+public class AddressCodec extends TypeCodec.MappingCodec<Address, UDTValue> {
243+
244+ private final UserType userType;
245+
246+ public AddressCodec(TypeCodec<UDTValue> innerCodec, Class<Address> javaType) {
247+ super(innerCodec, javaType);
248+ userType = (UserType) innerCodec.getCqlType();
249+ }
250+
251+ @Override
252+ protected Address deserialize(UDTValue value) {
253+ return value == null ? null : new Address(value.getString("street"), value.getInt("zipcode"));
254+ }
255+
256+ @Override
257+ protected UDTValue serialize(Address address) {
258+ return address == null ? null : userType.newValue().setString("street", address.getStreet()).setInt("zipcode", address.getZipcode());
259+ }
260+}
261+```
262+
263+Again, the driver provides a convenient base class: [MappingCodec].
264+
265+Now, create your `CodecRegistry` and `Cluster` instances the usual way:
266+
267+```java
268+CodecRegistry codecRegistry = new CodecRegistry();
269+Cluster cluster = Cluster.builder()
270+ .addContactPoints(...)
271+ .withCodecRegistry(codecRegistry)
272+ .build();
273+```
274+
275+Now, retrieve the metadata for type `address`:
276+
277+```java
278+UserType addressType = cluster.getMetadata().getKeyspace(...).getUserType("address");
279+```
280+
281+And finally, register your `AddressCodec` with the `CodecRegistry`. Note that
282+your codec simply delegates the hard work to an inner codec that knows how to deal with
283+user type values:
284+
285+```java
286+AddressCodec addressCodec = new AddressCodec(new TypeCodec.UDTCodec(addressType), Address.class);
287+codecRegistry.register(addressCodec);
288+```
289+
290+And voilà! You can now retrieve `address` values as `Address` instances:
291+
292+```java
293+ResultSet rows = session.execute(...);
294+Row row = rows.one();
295+// let the driver convert it for you...
296+Address address = row.get("address", Address.class);
297+// ...or access the low-level UDTValue, if you need
298+UDTValue addressUdt = row.get("address", UDTValue.class); // row.getUDTValue("address") would have worked too
299+```
300+
301+Note that this solution creates an intermediary `UDTValue` object when
302+serializing and deserializing. It's possible to bypass this step with a
303+lower-level implementation that manipulates the binary stream directly.
304+That's also how the object mapper handles UDTs, and you can rely on the
305+mapper to generate UDT codecs for you; see
306+[this page](object_mapper/custom_codecs/#implicit-udt-codecs) for more
307+information.
308+
309+### Limitations
310+
311+#### Generics
312+
313+Java generic types are fully supported, through Guava's [TypeToken] API.
314+Be sure to only use `get()` and `set()` methods
315+that take a `TypeToken` argument:
316+
317+```java
318+// this works
319+Foo<Bar> foo = row.get(0, new TypeToken<Foo<Bar>>(){})
320+// this does not work due to type erasure
321+Foo<Bar> foo = row.get(0, Foo.class);
322+```
323+
324+#### Type inheritance
325+
326+If a codec accepts a Java type that is assignable to the
327+desired Java type, that codec may be returned if it is found first
328+in the registry, *even if another codec is a better match*.
329+
330+As a consequence, type inheritance and interfaces should be used with care.
331+Let's consider an example and assume that class `B` extends class `A`:
332+
333+1) If you register a codec for `A`, you can pass `B` as the target type,
334+because `B` instances are assignable to `A`, and the driver is capable
335+of detecting that:
336+
337+```java
338+codecRegistry.register(new ACodec());
339+// all work
340+A a1 = row.get(0, A.class);
341+B b = row.get(0, B.class);
342+A a2 = row.get(0, B.class);
343+```
344+
345+However, because `List<B>` is *not* assignable to `List<A>`:
346+
347+```java
348+codecRegistry.register(new ACodec());
349+// this works
350+List<A> as1 = row.getList(0, A.class);
351+// but this throws CodecNotFoundException
352+List<B> bs = row.getList(0, B.class);
353+List<? extends A> as2 = row.getList(0, B.class);
354+```
355+
356+2) If you register a codec for `B`, you can't pass `A` as the target type,
357+because no codec matches `A.class` exactly:
358+
359+```java
360+codecRegistry.register(new BCodec());
361+// this works
362+A a1 = row.get(0, B.class);
363+B b = row.get(0, B.class);
364+// but this throws CodecNotFoundException
365+A a2 = row.get(0, A.class);
366+// and with collections, this works
367+List<B> bs = row.getList(0, B.class);
368+// but this throws CodecNotFoundException
369+List<A> as = row.getList(0, A.class);
370+```
371+
372+The same apply for interfaces.
373+
374+### Performance considerations
375+
376+A codec lookup operation may be costly; to mitigate this, the `CodecRegistry` caches lookup results whenever possible.
377+
378+The following situations are exceptions where it is not possible to cache lookup results:
379+
380+* With [SimpleStatement] and [BuiltStatement] (Query Builder) instances; in these places, the driver has
381+ no way to determine the right CQL type to use, so it performs a best-effort heuristic to guess which codec to use.
382+* When using "ambiguous" methods of `BoundStatement` and `Row`, such as [setList()][setList],
383+ [setSet()][setSet], [setMap()][setMap], [setObject()][setObject];
384+ these methods are "ambiguous" because they do not convey enough compile-time information about the object
385+ to serialize, so the driver performs the same heuristic to guess which codec to use.
386+
387+Beware that in these cases the lookup performs in average 10x worse. If performance is a key factor for your application,
388+consider using prepared statements all the time, and avoid calling ambiguous methods (prefer `get()` and `set()`).
389+
390+[JAVA-721]: https://datastax-oss.atlassian.net/browse/JAVA-721
391+[TypeCodec]: http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/core/TypeCodec.html
392+[LocalDate]: http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/core/LocalDate.html
393+[serialize]: http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/core/TypeCodec.html#serialize(T,%20com.datastax.driver.core.ProtocolVersion)
394+[deserialize]: http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/core/TypeCodec.html#deserialize(java.nio.ByteBuffer,%20com.datastax.driver.core.ProtocolVersion)
395+[TypeCodec.format]: http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/core/TypeCodec.html#format(T)
396+[TypeCodec.parse]: http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/core/TypeCodec.html#parse(java.lang.String)
397+[CodecRegistry]: http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/core/CodecRegistry.html
398+[Jackson]: http://wiki.fasterxml.com/JacksonHome
399+[AbstractType]: https://github.com/apache/cassandra/blob/trunk/src/java/org/apache/cassandra/db/marshal/AbstractType.java
400+[EnumStringCodec]: http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/core/TypeCodec.EnumStringCodec.html
401+[EnumIntCodec]: http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/core/TypeCodec.EnumIntCodec.html
402+[UserType]: http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/core/UserType.html
403+[UDTValue]: http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/core/UDTValue.html
404+[UDTCodec]: http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/core/TypeCodec.UDTCodec.html
405+[TupleType]: http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/core/TupleType.html
406+[TupleValue]: http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/core/TupleValue.html
407+[TupleCodec]: http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/core/TypeCodec.TupleCodec.html
408+[ListCodec]: http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/core/TypeCodec.ListCodec.html
409+[SetCodec]: http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/core/TypeCodec.SetCodec.html
410+[MapCodec]: http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/core/TypeCodec.MapCodec.html
411+[TypeToken]: http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/reflect/TypeToken.html
412+[MappingCodec]: http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/core/TypeCodec.MappingCodec.html
413+[StringParsingCodec]: http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/core/TypeCodec.StringParsingCodec.html
414+[SimpleStatement]: http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/core/SimpleStatement.html
415+[BuiltStatement]: http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/core/BuiltStatement.html
416+[setList]: http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/core/SettableByIndexData.html#setList(int,%20java.util.List)
417+[setSet]: http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/core/SettableByIndexData.html#setSet(int,%20java.util.Set)
418+[setMap]: http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/core/SettableByIndexData.html#setMap(int,%20java.util.Map)
419+[setObject]: http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/core/SettableByIndexData.html#setObject(int,%20V)
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 = new SimpleStatement("SELECT foo FROM bar WHERE qix = 1");
74+Statement statement = session.newSimpleStatement("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 = new SimpleStatement("INSERT INTO t1 (c1, c2) values ('foo', 'bar')")
91+Statement statement = session.newSimpleStatement("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 = new SimpleStatement("...");
107+Statement statement = session.newSimpleStatement("...");
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 = new SimpleStatement("...");
151+Statement statement = session.newSimpleStatement("...");
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 = new SimpleStatement("...");
163+Statement statement = session.newSimpleStatement("...");
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 = new SimpleStatement("...");
186+Statement statement = session.newSimpleStatement("...");
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 = new SimpleStatement("...");
197+Statement statement = session.newSimpleStatement("...");
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 = new SimpleStatement("...");
221+Statement statement = session.newSimpleStatement("...");
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
added features/object_mapper/.nav +3 −0
@@ -0,0 +1,3 @@
1+creating
2+using
3+custom_codecs
No newline at the end of the file
added features/object_mapper/custom_codecs/README.md +147 −0
@@ -0,0 +1,147 @@
1+# Using custom codecs
2+
3+The mapper can take advantage of [custom codecs](../../custom_codecs/)
4+to apply custom conversions to mapped columns and fields.
5+
6+## Declaring codecs
7+
8+Let's assume you have a table containing a timestamp column:
9+
10+```
11+create table user(id int primary key, birth timestamp);
12+```
13+
14+You've created a custom class, and the codec to convert it:
15+
16+```java
17+public class MyCustomDate { ... }
18+
19+public class MyCustomDateCodec extends TypeCodec<MyCustomDate> {
20+ public MyCustomDate() {
21+ super(DataType.timestamp(), MyCustomDate.class);
22+ }
23+ ...
24+}
25+```
26+
27+### Pre-registered codecs
28+
29+If you register your codec with the mapper's underlying `Cluster`, it
30+will be automatically available to the mapper:
31+
32+```java
33+Cluster cluster = Cluster.builder()
34+ .addContactPoint("127.0.0.1")
35+ .withCodecRegistry(
36+ new CodecRegistry().register(new MyCustomDateCodec())
37+ ).build();
38+
39+MappingManager mappingManager = new MappingManager(cluster.connect());
40+```
41+
42+You can normally create your mapped classes using your custom type,
43+without any additional configuration:
44+
45+```java
46+@Table(name = "user")
47+public class User {
48+ @PartitionKey
49+ private int id;
50+ private MyCustomDate birth;
51+
52+ ... // getters and setters
53+}
54+```
55+
56+This also works in accessors:
57+
58+```java
59+@Accessor
60+interface UserAccessor {
61+ @Query("update user set birth = :b where id = :i)
62+ void updateBirth(@Param("i") int id,
63+ @Param("b") MyCustomDate birth);
64+}
65+```
66+
67+### One-time declaration
68+
69+Sometimes you might want to use your codec only for one particular
70+column/field. In that case you won't register it when initializing the
71+`Cluster`:
72+
73+```java
74+Cluster cluster = Cluster.builder()
75+ .addContactPoint("127.0.0.1")
76+ .build();
77+
78+MappingManager mappingManager = new MappingManager(cluster.connect());
79+```
80+
81+Instead, reference the codec's class in the [@Column][column]
82+annotation:
83+
84+```java
85+@Table(name = "user")
86+public class User {
87+ @PartitionKey
88+ private int id;
89+ @Column(codec = MyCustomDateCodec.class)
90+ private MyCustomDate birth;
91+
92+ ... // getters and setters
93+}
94+```
95+
96+The class must have a no-arg constructor. The mapper will create an
97+instance (one per column) and cache it for future use.
98+
99+This also works with [@Field][field] and [@Param][param] annotations.
100+
101+[column]:http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/mapping/annotations/Column.html
102+[field]:http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/mapping/annotations/Field.html
103+[param]:http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/mapping/annotations/Param.html
104+
105+
106+## Implicit UDT codecs
107+
108+The mapper uses custom codecs internally to handle UDT conversions: when
109+you register an [entity](../using/#entity-mappers), the mapper inspects
110+the type of all fields to find classes annotated with
111+[@UDT](../creating/#mapping-user-types) (this works recursively with
112+nested UDTs and collections). For each class, the mapper creates a codec
113+and registers it with the underlying `Cluster`.
114+
115+```java
116+@UDT(name = "address")
117+public class Address { ... }
118+
119+@Entity(name = "user")
120+public class User {
121+ ...
122+ private Address address;
123+ ...
124+}
125+
126+Mapper<User> userMapper = mappingManager.mapper(User.class);
127+
128+// Codec is now registered for Address <-> CQL address
129+```
130+
131+A nice side-effect is that you can now use the `@UDT`-annotated class
132+with any driver method, not just mapper methods:
133+
134+```java
135+Row row = session.execute("select address from user where id = 1").one();
136+Address address = row.get("address", Address.class);
137+```
138+
139+If you don't use entity mappers but still want the convenience of the
140+UDT codec for core driver methods, the mapper provides a way to create
141+it independently:
142+
143+```java
144+mappingManager.udtCodec(Address.class);
145+
146+// Codec is now registered
147+```
modified features/object_mapper/using/README.md +0 −18
@@ -175,24 +175,6 @@
175175
176176 [Result]: http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/mapping/Result.html
177177
178-### UDT Mappers
179-
180-A UDT will be automatically mapped when it is part of a table-level
181-class (as shown [here](../creating/#mapping-user-types)).
182-
183-However, there might be cases where it is useful to convert a mapped
184-instance to the corresponding [UDTValue][UDTValue] (and back). The
185-mapper provides an [UDTMapper] for that purpose:
186-
187-```java
188-UDTMapper<Address> addressMapper = manager.getUDTMapper(Address.class);
189-Address address = addressMapper.fromUDT(udtValue);
190-UDTValue value = addressMapper.toUDT(address);
191-```
192-
193-[UDTValue]: http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/core/UDTValue.html
194-[UDTMapper]: http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/mapping/UDTMapper.html
195-
196178 ### Accessors
197179
198180 `Accessor`s provide a way to map custom queries not supported by the
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 = new SimpleStatement("your query");
28+Statement statement = session.newSimpleStatement("your query");
2929 statement.setFetchSize(2000);
3030 ```
3131
@@ -125,7 +125,7 @@
125125
126126 ```java
127127 PagingState pagingState = PagingState.fromString(string);
128-Statement st = new SimpleStatement("your query");
128+Statement st = session.newSimpleStatement("your query");
129129 st.setPagingState(pagingState);
130130 ResultSet rs = session.execute(st);
131131 ```
@@ -142,7 +142,7 @@
142142 ```java
143143 final int RESULTS_PER_PAGE = 100;
144144
145-Statement st = new SimpleStatement("your query");
145+Statement st = session.newSimpleStatement("your query");
146146 st.setFetchSize(RESULTS_PER_PAGE);
147147
148148 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 = new SimpleStatement(
39+Statement statement = session.newSimpleStatement(
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 = new SimpleStatement("SELECT * FROM users WHERE id = 1");
95+Statement s = session.newSimpleStatement("SELECT * FROM users WHERE id = 1");
9696 s.setIdempotent(true);
9797 ```
9898
modified pom.xml +2 −6
@@ -43,15 +43,11 @@
4343
4444 <properties>
4545 <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
46- <cassandra.version>2.2.0-rc2</cassandra.version>
46+ <cassandra.version>2.2.0</cassandra.version>
4747 <java.version>1.6</java.version>
4848 <log4j.version>1.2.17</log4j.version>
4949 <slf4j-log4j12.version>1.7.6</slf4j-log4j12.version>
50- <!--
51- We use an old version of Guava to be compatible with Spark 1.1.
52- Check with the spark-cassandra-connector team before upgrading this.
53- -->
54- <guava.version>14.0.1</guava.version>
50+ <guava.version>16.0.1</guava.version>
5551 <netty.version>4.0.27.Final</netty.version>
5652 <metrics.version>3.0.2</metrics.version>
5753 <snappy.version>1.0.5</snappy.version>
modified upgrade_guide/README.md +87 −27
@@ -5,45 +5,105 @@
55
66 ### 2.2.0
77
8-This version brings parity with Cassandra 2.2. We've also seized the
9-opportunity to clean up the API.
10-
11-1. All methods that took the protocol version as an `int` or assumed a
8+This version brings parity with Cassandra 2.2.
9+
10+It is **not binary compatible** with the driver's 2.1 branch.
11+The main changes were introduced by the custom codecs feature (see below).
12+We've also seized the opportunity to remove code that was deprecated in 2.1.
13+
14+1. [Custom codecs](../features/custom_codecs/README.md)
15+ ([JAVA-721](https://datastax-oss.atlassian.net/browse/JAVA-721))
16+ introduce several breaking changes and also modify a few runtime behaviors.
17+
18+ Here is a detailed list of breaking API changes:
19+ * `TypeCodec` was package-private before and is now public.
20+ * `DataType` has no more references to `TypeCodec`, so most methods that dealt with serialization and deserialization of data types have been removed:
21+ * `ByteBuffer serialize(Object value, ProtocolVersion protocolVersion)`
22+ * `ByteBuffer serializeValue(Object value, ProtocolVersion protocolVersion)`
23+ * `Object deserialize(ByteBuffer bytes, ProtocolVersion protocolVersion)`
24+ * `Object deserialize(ByteBuffer bytes, int protocolVersion)`
25+ * `Object parse(String value)`
26+ * `String format(Object value)`
27+ * `Class<?> asJavaClass()`
28+ * `GettableByIndexData` (affects `Row`, `BoundStatement`, `TupleValue` and `UDTValue`). The following public methods were added:
29+ * `<T> T get(int i, Class<T> targetClass)`
30+ * `<T> T get(int i, TypeToken<T> targetType)`
31+ * `<T> T get(int i, TypeCodec<T> codec)`
32+ * `GettableByNameData` (affects `Row`, `BoundStatement` and `UDTValue`). The following public methods were added:
33+ * `<T> T get(String name, Class<T> targetClass)`
34+ * `<T> T get(String name, TypeToken<T> targetType)`
35+ * `<T> T get(String name, TypeCodec<T> codec)`
36+ * `SettableByIndexData` (affects `Row`, `BoundStatement`, `TupleValue` and `UDTValue`). The following public methods were added:
37+ * `<V> T set(int i, V v, Class<V> targetClass)`
38+ * `<V> T set(int i, V v, TypeToken<V> targetType)`
39+ * `<V> T set(int i, V v, TypeCodec<V> codec)`
40+ * `SettableByNameData` (affects `Row`, `BoundStatement` and `UDTValue`). The following public methods were added:
41+ * `<V> T set(String name, V v, Class<V> targetClass)`
42+ * `<V> T set(String name, V v, TypeToken<V> targetType)`
43+ * `<V> T set(String name, V v, TypeCodec<V> codec)`
44+ * `Session`. The following methods were added:
45+ * `newSimpleStatement(String query)`
46+ * `newSimpleStatement(String query, Object... values)`
47+ * `RegularStatement`. The following public methods were modified:
48+ * `getValues()`
49+ * `hasValues()`
50+ * `SimpleStatement`. Public constructors were removed; users are required to call either:
51+ * `Session.newSimpleStatement(String query)` or
52+ * `Session.newSimpleStatement(String query, Object... values)`
53+ * `QueryBuilder`. This class now has a single, public constructor: `QueryBuilder(Cluster cluster)`.
54+ Its fluent API has also changed; instead of e.g.: `QueryBuilder.select(...)`,
55+ users should now use the following idiom: `new QueryBuilder(cluster).select(...)`
56+ All methods that start a query are now instance methods instead of static ones.
57+ * `PreparedStatement`. The following public method was added:
58+ * `CodecRegistry getCodecRegistry()`.
59+ * `TupleType`. The following public method was deleted:
60+ * `TupleType of(DataType... types)`; users should now use `Metadata.newTupleType(DataType...)`.
61+
62+ <p>The driver runtime behavior changes in the following situations:</p>
63+ * `RuntimeException`s thrown during serialization or deserialization might not be
64+ the same ones as before, due to the newly-introduced `CodecNotFoundException`
65+ and to the dynamic nature of codec search introduced by JAVA-721.
66+ * `TypeCodec.format(Object)` now returns the CQL keyword `"NULL"` instead of a `null` reference
67+ for `null` inputs.
68+
69+2. The driver now depends on Guava 16.0.1 (instead of 14.0.1).
70+ This update has been mainly motivated by Guava's [Issue #1635](https://code.google.com/p/guava-libraries/issues/detail?id=1635),
71+ which affects `TypeToken`, and hence all `TypeCodec` implementations handling parameterized types.
72+
73+3. `UDTMapper` (the type previously used to convert `@UDT`-annotated
74+ classes to their CQL counterpart) was removed, as well as the
75+ corresponding method `MappingManager#udtMapper`.
76+
77+ The mapper now uses custom codecs to convert UDTs. See more
78+ explanations [here](../features/object_mapper/custom_codecs/#implicit-udt-codecs).
79+
80+4. All methods that took the protocol version as an `int` or assumed a
1281 default version have been removed (they were already deprecated in
1382 2.1):
1483 * `AbstractGettableData(int)`
1584 * `Cluster.Builder#withProtocolVersion(int)`
16- * in `DataType`:
17- * `serialize(Object, int)`
18- * `serialize(Object)`
19- * `deserialize(ByteBuffer)`
20- * `serializeValue(Object, int)`
21- * `serializeValue(Object)`
2285 * in `ProtocolOptions`:
2386 * `NEWEST_SUPPORTED_PROTOCOL_VERSION` (replaced by
2487 `ProtocolVersion#NEWEST_SUPPORTED`)
2588 * `int getProtocolVersion()`
26- * in `RegularStatement`:
27- * `getValues(int)`
28- * `getValues()`
2989
3090 There are now variants of these methods using the `ProtocolVersion`
3191 enum. In addition, `ProtocolOptions#getProtocolVersionEnum` has been
3292 renamed to `ProtocolOptions#getProtocolVersion`.
3393
34-2. All methods related to the "suspected" host state have been removed
94+5. All methods related to the "suspected" host state have been removed
3595 (they had been deprecated in 2.1.6 when the suspicion mechanism was
3696 removed):
3797 * `Host.StateListener#onSuspected()` (was inherited by
3898 `LoadBalancingPolicy`)
3999 * `Host#getInitialReconnectionAttemptFuture()`
40100
41-3. `PoolingOptions#setMinSimultaneousRequestsPerConnectionThreshold(HostDistance,
101+6. `PoolingOptions#setMinSimultaneousRequestsPerConnectionThreshold(HostDistance,
42102 int)` has been removed. The new connection pool resizing algorithm introduced by
43103 [JAVA-419](https://datastax-oss.atlassian.net/browse/JAVA-419) does not need this
44104 threshold anymore.
45105
46-4. `AddressTranslater` has been renamed to `AddressTranslator`. All
106+7. `AddressTranslater` has been renamed to `AddressTranslator`. All
47107 related methods and classes have also been renamed.
48108
49109 In addition, the `close()` method has been pulled up into
@@ -51,12 +111,12 @@
51111 Existing third-party `AddressTranslator` implementations only need
52112 to add an empty `close()` method.
53113
54-5. The `close()` method has been pulled up into `LoadBalancingPolicy`,
114+8. The `close()` method has been pulled up into `LoadBalancingPolicy`,
55115 and `CloseableLoadBalancingPolicy` has been removed. Existing third-party
56116 `LoadBalancingPolicy` implementations only need to add an empty
57117 `close()` method.
58118
59-6. All pluggable components now have callbacks to detect when they get
119+9. All pluggable components now have callbacks to detect when they get
60120 associated with a `Cluster` instance:
61121 * `ReconnectionPolicy`, `RetryPolicy`, `AddressTranslator`,
62122 and `TimestampGenerator`:
@@ -70,22 +130,22 @@
70130 initialization / cleanup tasks. Existing third-party implementations
71131 only need to add empty methods.
72132
73-7. `LoadBalancingPolicy` does not extend `Host.StateListener` anymore:
133+10. `LoadBalancingPolicy` does not extend `Host.StateListener` anymore:
74134 callback methods (`onUp`, `onDown`, etc.) have been duplicated. This
75135 is unlikely to affect clients.
76136
77-8. [Client-side timestamp generation](../features/query_timestamps/) is
137+11. [Client-side timestamp generation](../features/query_timestamps/) is
78138 now the default (provided that [native
79139 protocol](../features/native_protocol) v3 or higher is in use). The
80140 generator used is `AtomicMonotonicTimestampGenerator`.
81141
82-9. If a DNS name resolves to multiple A-records,
142+12. If a DNS name resolves to multiple A-records,
83143 `Cluster.Builder#addContactPoint(String)` will now use all of these
84144 addresses as contact points. This gives you the possibility of
85145 maintaining contact points in DNS configuration, and having a single,
86146 static contact point in your Java code.
87147
88-10. The following methods were added for [Custom payloads](../features/custom_payloads):
148+13. The following methods were added for [Custom payloads](../features/custom_payloads):
89149 * in `PreparedStatement`: `getIncomingPayload()`,
90150 `getOutgoingPayload()` and
91151 `setOutgoingPayload(Map<String,ByteBuffer>)`
@@ -98,7 +158,7 @@
98158 This breaks binary compatibility for these two classes; if you have
99159 custom implementations, you will have to adapt them accordingly.
100160
101-11. Getters and setters have been added to "data-container" classes for
161+14. Getters and setters have been added to "data-container" classes for
102162 new CQL types:
103163 * `getByte`/`setByte` for the `TINYINT` type
104164 * `getShort`/`setShort` for the `SMALLINT` type
@@ -110,7 +170,7 @@
110170
111171 This affects `Row`, `BoundStatement`, `TupleValue` and `UDTValue`.
112172
113-12. New exception types have been added to handle additional server-side
173+15. New exception types have been added to handle additional server-side
114174 errors introduced in Cassandra 2.2:
115175 * `ReadFailureException`
116176 * `WriteFailureException`
@@ -125,13 +185,13 @@
125185 exception hierarchy, it now has new child classes that are not
126186 related to timeouts).
127187
128-13. `ResultSet#fetchMoreResults()` now returns a `ListenableFuture<ResultSet>`.
188+16. `ResultSet#fetchMoreResults()` now returns a `ListenableFuture<ResultSet>`.
129189 This makes the API more friendly if you chain transformations on an async
130190 query to process all pages (see `AsyncResultSetTest` in the sources for an
131191 example).
132192
133-14. `Frozen` annotations in the mapper are no longer checked at runtime (see
134- [JAVA-843|https://datastax-oss.atlassian.net/browse/JAVA-843] for more
193+17. `Frozen` annotations in the mapper are no longer checked at runtime (see
194+ [JAVA-843](https://datastax-oss.atlassian.net/browse/JAVA-843) for more
135195 explanations). So they become purely informational at this stage.
136196 However it is a good idea to keep using these annotations and make sure
137197 they match the schema, in anticipation for the schema generation features