kikocis/java-driver public
Changesets · Branches · Tags · Compare
| Changeset | f80a71e5968b8faef90c01e157c04ffce713a3b1ea1978f1d4b879940f6b1df3 |
|---|---|
| Author | Alexandre Dutra <alexdut@gmail.com> · 2015-07-28 10:37 +02:00 |
| Committer | Alexandre Dutra <alexdut@gmail.com> · 2015-07-28 10:37 +02:00 |
| Parents | bcf9101430f7, f083a19ab3b5 |
160 files changed
modified changelog/README.md +2 −0
| @@ -9,6 +9,8 @@ | ||
| 9 | 9 | - [improvement] Make ResultSet#fetchMoreResult return a |
| 10 | 10 | ListenableFuture<ResultSet> (JAVA-836) |
| 11 | 11 | - [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) | |
| 12 | 14 | |
| 13 | 15 | Merged from 2.1 branch: |
| 14 | 16 |
modified driver-core/pom.xml +14 −0
| @@ -125,6 +125,20 @@ | ||
| 125 | 125 | <scope>test</scope> |
| 126 | 126 | </dependency> |
| 127 | 127 | |
| 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 | + | |
| 128 | 142 | </dependencies> |
| 129 | 143 | |
| 130 | 144 | <build> |
modified driver-core/src/main/java/com/datastax/driver/core/AbstractAddressableByIndexData.java +179 −122
| @@ -21,7 +21,13 @@ | ||
| 21 | 21 | import java.nio.ByteBuffer; |
| 22 | 22 | import java.util.*; |
| 23 | 23 | |
| 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.*; | |
| 25 | 31 | |
| 26 | 32 | abstract class AbstractAddressableByIndexData<T extends SettableByIndexData<T>> extends AbstractGettableByIndexData implements SettableByIndexData<T> { |
| 27 | 33 | |
| @@ -43,75 +49,111 @@ | ||
| 43 | 49 | } |
| 44 | 50 | |
| 45 | 51 | 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); | |
| 48 | 60 | } |
| 49 | 61 | |
| 50 | 62 | 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); | |
| 53 | 71 | } |
| 54 | 72 | |
| 55 | 73 | 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); | |
| 58 | 82 | } |
| 59 | 83 | |
| 60 | 84 | 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); | |
| 63 | 93 | } |
| 64 | 94 | |
| 65 | 95 | 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); | |
| 72 | 104 | } |
| 73 | 105 | |
| 74 | 106 | 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)); | |
| 77 | 109 | } |
| 78 | 110 | |
| 79 | 111 | 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)); | |
| 82 | 114 | } |
| 83 | 115 | |
| 84 | 116 | 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); | |
| 87 | 125 | } |
| 88 | 126 | |
| 89 | 127 | 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); | |
| 92 | 136 | } |
| 93 | 137 | |
| 94 | 138 | 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); | |
| 97 | 147 | } |
| 98 | 148 | |
| 99 | 149 | 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)); | |
| 110 | 152 | } |
| 111 | 153 | |
| 112 | 154 | 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)); | |
| 115 | 157 | } |
| 116 | 158 | |
| 117 | 159 | public T setBytesUnsafe(int i, ByteBuffer v) { |
| @@ -119,117 +161,130 @@ | ||
| 119 | 161 | } |
| 120 | 162 | |
| 121 | 163 | 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)); | |
| 124 | 166 | } |
| 125 | 167 | |
| 126 | 168 | 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)); | |
| 129 | 171 | } |
| 130 | 172 | |
| 131 | 173 | 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)); | |
| 143 | 176 | } |
| 144 | 177 | |
| 145 | 178 | 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)); | |
| 148 | 181 | } |
| 149 | 182 | |
| 183 | + @SuppressWarnings("unchecked") | |
| 150 | 184 | 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)); | |
| 166 | 194 | } |
| 167 | - return setValue(i, type.codec(protocolVersion).serialize(v)); | |
| 168 | 195 | } |
| 169 | 196 | |
| 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") | |
| 170 | 208 | 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); | |
| 180 | 217 | 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)); | |
| 188 | 221 | } |
| 189 | - return setValue(i, type.codec(protocolVersion).serialize(v)); | |
| 190 | 222 | } |
| 191 | 223 | |
| 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") | |
| 192 | 235 | 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)); | |
| 207 | 245 | } |
| 208 | - return setValue(i, type.codec(protocolVersion).serialize(v)); | |
| 209 | 246 | } |
| 210 | 247 | |
| 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 | + } | |
| 215 | 252 | |
| 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 | + } | |
| 218 | 257 | |
| 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)); | |
| 221 | 261 | } |
| 222 | 262 | |
| 223 | 263 | 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 | + } | |
| 227 | 278 | |
| 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 | + } | |
| 230 | 283 | |
| 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)); | |
| 233 | 288 | } |
| 234 | 289 | |
| 235 | 290 | public T setToNull(int i) { |
| @@ -245,6 +300,9 @@ | ||
| 245 | 300 | if (values.length != that.values.length) |
| 246 | 301 | return false; |
| 247 | 302 | |
| 303 | + if(this.protocolVersion != that.protocolVersion) | |
| 304 | + return false; | |
| 305 | + | |
| 248 | 306 | // Deserializing each value is slightly inefficient, but comparing |
| 249 | 307 | // the bytes could in theory be wrong (for varint for instance, 2 values |
| 250 | 308 | // can have different binary representation but be the same value due to |
| @@ -255,10 +313,9 @@ | ||
| 255 | 313 | if (!thisType.equals(thatType)) |
| 256 | 314 | return false; |
| 257 | 315 | |
| 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)) | |
| 262 | 319 | return false; |
| 263 | 320 | } |
| 264 | 321 | return true; |
| @@ -269,7 +326,7 @@ | ||
| 269 | 326 | // Same as equals |
| 270 | 327 | int hash = 31; |
| 271 | 328 | 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(); | |
| 273 | 330 | return hash; |
| 274 | 331 | } |
| 275 | 332 | } |
modified driver-core/src/main/java/com/datastax/driver/core/AbstractData.java +319 −222
| @@ -21,7 +21,13 @@ | ||
| 21 | 21 | import java.nio.ByteBuffer; |
| 22 | 22 | import java.util.*; |
| 23 | 23 | |
| 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.*; | |
| 25 | 31 | |
| 26 | 32 | // 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). |
| 27 | 33 | abstract class AbstractData<T extends SettableData<T>> extends AbstractGettableData implements SettableData<T> { |
| @@ -29,7 +35,7 @@ | ||
| 29 | 35 | final T wrapped; |
| 30 | 36 | final ByteBuffer[] values; |
| 31 | 37 | |
| 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 | |
| 33 | 39 | // want wrapped to be 'this' (UDTValue), and sometimes some other object (in BoundStatement). |
| 34 | 40 | @SuppressWarnings("unchecked") |
| 35 | 41 | protected AbstractData(ProtocolVersion protocolVersion, int size) { |
| @@ -64,186 +70,193 @@ | ||
| 64 | 70 | } |
| 65 | 71 | |
| 66 | 72 | 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); | |
| 69 | 81 | } |
| 70 | 82 | |
| 71 | 83 | 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); | |
| 77 | 86 | } |
| 78 | 87 | return wrapped; |
| 79 | 88 | } |
| 80 | 89 | |
| 81 | 90 | 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); | |
| 84 | 99 | } |
| 85 | 100 | |
| 86 | 101 | 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); | |
| 92 | 104 | } |
| 93 | 105 | return wrapped; |
| 94 | 106 | } |
| 95 | 107 | |
| 96 | 108 | 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); | |
| 99 | 117 | } |
| 100 | 118 | |
| 101 | 119 | 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); | |
| 107 | 122 | } |
| 108 | 123 | return wrapped; |
| 109 | 124 | } |
| 110 | 125 | |
| 111 | 126 | 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); | |
| 114 | 135 | } |
| 115 | 136 | |
| 116 | 137 | 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); | |
| 122 | 140 | } |
| 123 | 141 | return wrapped; |
| 124 | 142 | } |
| 125 | 143 | |
| 126 | 144 | 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); | |
| 129 | 153 | } |
| 130 | 154 | |
| 131 | 155 | 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); | |
| 137 | 158 | } |
| 138 | 159 | return wrapped; |
| 139 | 160 | } |
| 140 | 161 | |
| 141 | 162 | 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)); | |
| 144 | 165 | } |
| 145 | 166 | |
| 146 | 167 | 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); | |
| 152 | 170 | } |
| 153 | 171 | return wrapped; |
| 154 | 172 | } |
| 155 | 173 | |
| 156 | 174 | 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)); | |
| 159 | 177 | } |
| 160 | 178 | |
| 161 | 179 | 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); | |
| 167 | 182 | } |
| 168 | 183 | return wrapped; |
| 169 | 184 | } |
| 170 | 185 | |
| 171 | 186 | 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); | |
| 174 | 195 | } |
| 175 | 196 | |
| 176 | 197 | 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); | |
| 182 | 200 | } |
| 183 | 201 | return wrapped; |
| 184 | 202 | } |
| 185 | 203 | |
| 186 | 204 | 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); | |
| 189 | 213 | } |
| 190 | 214 | |
| 191 | 215 | 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); | |
| 197 | 218 | } |
| 198 | 219 | return wrapped; |
| 199 | 220 | } |
| 200 | 221 | |
| 201 | 222 | 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); | |
| 204 | 231 | } |
| 205 | 232 | |
| 206 | 233 | 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); | |
| 212 | 236 | } |
| 213 | 237 | return wrapped; |
| 214 | 238 | } |
| 215 | 239 | |
| 216 | 240 | 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)); | |
| 227 | 243 | } |
| 228 | 244 | |
| 229 | 245 | 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 | + } | |
| 233 | 249 | return wrapped; |
| 234 | 250 | } |
| 235 | 251 | |
| 236 | 252 | 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)); | |
| 239 | 255 | } |
| 240 | 256 | |
| 241 | 257 | 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); | |
| 247 | 260 | } |
| 248 | 261 | return wrapped; |
| 249 | 262 | } |
| @@ -253,80 +266,57 @@ | ||
| 253 | 266 | } |
| 254 | 267 | |
| 255 | 268 | public T setBytesUnsafe(String name, ByteBuffer v) { |
| 256 | - int[] indexes = getAllIndexesOf(name); | |
| 257 | 269 | 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 | + } | |
| 260 | 273 | return wrapped; |
| 261 | 274 | } |
| 262 | 275 | |
| 263 | 276 | 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)); | |
| 266 | 279 | } |
| 267 | 280 | |
| 268 | 281 | 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); | |
| 274 | 284 | } |
| 275 | 285 | return wrapped; |
| 276 | 286 | } |
| 277 | 287 | |
| 278 | 288 | 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)); | |
| 281 | 291 | } |
| 282 | 292 | |
| 283 | 293 | 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); | |
| 289 | 296 | } |
| 290 | 297 | return wrapped; |
| 291 | 298 | } |
| 292 | 299 | |
| 293 | 300 | 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)); | |
| 305 | 303 | } |
| 306 | 304 | |
| 307 | 305 | 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); | |
| 315 | 308 | } |
| 316 | 309 | return wrapped; |
| 317 | 310 | } |
| 318 | 311 | |
| 319 | 312 | 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)); | |
| 322 | 315 | } |
| 323 | 316 | |
| 324 | 317 | 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); | |
| 330 | 320 | } |
| 331 | 321 | return wrapped; |
| 332 | 322 | } |
| @@ -336,135 +326,240 @@ | ||
| 336 | 326 | if (v == null) |
| 337 | 327 | throw new NullPointerException(String.format("Cannot set a null token for column %s", getName(i))); |
| 338 | 328 | 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)); | |
| 340 | 331 | } |
| 341 | 332 | |
| 342 | 333 | 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 | + } | |
| 346 | 337 | return wrapped; |
| 347 | 338 | } |
| 348 | 339 | |
| 340 | + @SuppressWarnings("unchecked") | |
| 349 | 341 | 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 | + } | |
| 353 | 353 | |
| 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 | + } | |
| 356 | 358 | |
| 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 | + } | |
| 362 | 371 | |
| 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); | |
| 365 | 376 | } |
| 366 | - return setValue(i, type.codec(protocolVersion).serialize(v)); | |
| 377 | + return wrapped; | |
| 367 | 378 | } |
| 368 | 379 | |
| 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 | + } | |
| 373 | 385 | return wrapped; |
| 374 | 386 | } |
| 375 | 387 | |
| 388 | + @SuppressWarnings("unchecked") | |
| 389 | + @Override | |
| 376 | 390 | 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 | + } | |
| 380 | 410 | |
| 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 | + } | |
| 383 | 415 | |
| 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 | + } | |
| 389 | 423 | |
| 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); | |
| 394 | 428 | } |
| 395 | - return setValue(i, type.codec(protocolVersion).serialize(v)); | |
| 429 | + return wrapped; | |
| 396 | 430 | } |
| 397 | 431 | |
| 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 | + } | |
| 402 | 437 | return wrapped; |
| 403 | 438 | } |
| 404 | 439 | |
| 440 | + @SuppressWarnings("unchecked") | |
| 405 | 441 | 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 | + } | |
| 412 | 458 | |
| 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 | + } | |
| 417 | 463 | |
| 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); | |
| 420 | 468 | } |
| 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; | |
| 422 | 478 | } |
| 423 | 479 | |
| 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 | + } | |
| 428 | 485 | return wrapped; |
| 429 | 486 | } |
| 430 | 487 | |
| 431 | 488 | 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 | + } | |
| 435 | 492 | |
| 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 | + } | |
| 438 | 499 | |
| 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 | + } | |
| 441 | 509 | return wrapped; |
| 442 | 510 | } |
| 443 | 511 | |
| 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 | + } | |
| 448 | 523 | return wrapped; |
| 449 | 524 | } |
| 450 | 525 | |
| 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 | + } | |
| 455 | 530 | |
| 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 | + } | |
| 458 | 543 | |
| 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 | + } | |
| 461 | 549 | return wrapped; |
| 462 | 550 | } |
| 463 | 551 | |
| 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 | + } | |
| 468 | 563 | return wrapped; |
| 469 | 564 | } |
| 470 | 565 | |
| @@ -475,9 +570,9 @@ | ||
| 475 | 570 | |
| 476 | 571 | @Override |
| 477 | 572 | 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 | + } | |
| 481 | 576 | return wrapped; |
| 482 | 577 | } |
| 483 | 578 | |
| @@ -490,6 +585,9 @@ | ||
| 490 | 585 | if (values.length != that.values.length) |
| 491 | 586 | return false; |
| 492 | 587 | |
| 588 | + if(this.protocolVersion != that.protocolVersion) | |
| 589 | + return false; | |
| 590 | + | |
| 493 | 591 | // Deserializing each value is slightly inefficient, but comparing |
| 494 | 592 | // the bytes could in theory be wrong (for varint for instance, 2 values |
| 495 | 593 | // can have different binary representation but be the same value due to |
| @@ -500,10 +598,9 @@ | ||
| 500 | 598 | if (!thisType.equals(thatType)) |
| 501 | 599 | return false; |
| 502 | 600 | |
| 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)) | |
| 507 | 604 | return false; |
| 508 | 605 | } |
| 509 | 606 | return true; |
| @@ -514,7 +611,7 @@ | ||
| 514 | 611 | // Same as equals |
| 515 | 612 | int hash = 31; |
| 516 | 613 | 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(); | |
| 518 | 615 | return hash; |
| 519 | 616 | } |
| 520 | 617 | } |
modified driver-core/src/main/java/com/datastax/driver/core/AbstractGettableByIndexData.java +144 −228
| @@ -19,7 +19,6 @@ | ||
| 19 | 19 | import java.math.BigInteger; |
| 20 | 20 | import java.net.InetAddress; |
| 21 | 21 | import java.nio.ByteBuffer; |
| 22 | -import java.util.Collections; | |
| 23 | 22 | import java.util.Date; |
| 24 | 23 | import java.util.List; |
| 25 | 24 | import java.util.Map; |
| @@ -28,8 +27,16 @@ | ||
| 28 | 27 | |
| 29 | 28 | import com.google.common.reflect.TypeToken; |
| 30 | 29 | |
| 30 | +import static com.google.common.collect.Sets.newHashSet; | |
| 31 | +import static com.google.common.collect.Sets.newLinkedHashSet; | |
| 32 | + | |
| 31 | 33 | import com.datastax.driver.core.exceptions.InvalidTypeException; |
| 32 | 34 | |
| 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 | + | |
| 33 | 40 | abstract class AbstractGettableByIndexData implements GettableByIndexData { |
| 34 | 41 | |
| 35 | 42 | protected final ProtocolVersion protocolVersion; |
| @@ -68,27 +75,41 @@ | ||
| 68 | 75 | */ |
| 69 | 76 | protected abstract ByteBuffer getValue(int i); |
| 70 | 77 | |
| 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); | |
| 76 | 90 | } |
| 77 | 91 | |
| 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 | + } | |
| 82 | 95 | |
| 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)); | |
| 84 | 101 | } |
| 85 | 102 | |
| 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 | + } | |
| 90 | 108 | |
| 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)); | |
| 92 | 113 | } |
| 93 | 114 | |
| 94 | 115 | /** |
| @@ -104,13 +125,17 @@ | ||
| 104 | 125 | */ |
| 105 | 126 | @Override |
| 106 | 127 | public boolean getBool(int i) { |
| 107 | - checkType(i, DataType.Name.BOOLEAN); | |
| 128 | + checkType(i, BOOLEAN); | |
| 108 | 129 | |
| 109 | 130 | ByteBuffer value = getValue(i); |
| 110 | 131 | if (value == null || value.remaining() == 0) |
| 111 | 132 | return false; |
| 112 | 133 | |
| 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); | |
| 114 | 139 | } |
| 115 | 140 | |
| 116 | 141 | /** |
| @@ -118,13 +143,13 @@ | ||
| 118 | 143 | */ |
| 119 | 144 | @Override |
| 120 | 145 | 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); | |
| 128 | 153 | } |
| 129 | 154 | |
| 130 | 155 | /** |
| @@ -132,13 +157,13 @@ | ||
| 132 | 157 | */ |
| 133 | 158 | @Override |
| 134 | 159 | 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); | |
| 142 | 167 | } |
| 143 | 168 | |
| 144 | 169 | /** |
| @@ -146,13 +171,13 @@ | ||
| 146 | 171 | */ |
| 147 | 172 | @Override |
| 148 | 173 | 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); | |
| 156 | 181 | } |
| 157 | 182 | |
| 158 | 183 | /** |
| @@ -160,28 +185,23 @@ | ||
| 160 | 185 | */ |
| 161 | 186 | @Override |
| 162 | 187 | 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); | |
| 170 | 195 | } |
| 171 | 196 | |
| 172 | 197 | /** |
| 173 | 198 | * {@inheritDoc} |
| 174 | 199 | */ |
| 175 | 200 | @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); | |
| 180 | 203 | 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); | |
| 185 | 205 | } |
| 186 | 206 | |
| 187 | 207 | /** |
| @@ -189,13 +209,9 @@ | ||
| 189 | 209 | */ |
| 190 | 210 | @Override |
| 191 | 211 | public LocalDate getDate(int i) { |
| 192 | - checkType(i, DataType.Name.DATE); | |
| 193 | - | |
| 212 | + checkType(i, DATE); | |
| 194 | 213 | 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); | |
| 199 | 215 | } |
| 200 | 216 | |
| 201 | 217 | /** |
| @@ -203,13 +219,13 @@ | ||
| 203 | 219 | */ |
| 204 | 220 | @Override |
| 205 | 221 | 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); | |
| 213 | 229 | } |
| 214 | 230 | |
| 215 | 231 | /** |
| @@ -217,13 +233,13 @@ | ||
| 217 | 233 | */ |
| 218 | 234 | @Override |
| 219 | 235 | 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); | |
| 227 | 243 | } |
| 228 | 244 | |
| 229 | 245 | /** |
| @@ -231,13 +247,13 @@ | ||
| 231 | 247 | */ |
| 232 | 248 | @Override |
| 233 | 249 | 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); | |
| 241 | 257 | } |
| 242 | 258 | |
| 243 | 259 | /** |
| @@ -248,7 +264,6 @@ | ||
| 248 | 264 | ByteBuffer value = getValue(i); |
| 249 | 265 | if (value == null) |
| 250 | 266 | return null; |
| 251 | - | |
| 252 | 267 | return value.duplicate(); |
| 253 | 268 | } |
| 254 | 269 | |
| @@ -257,8 +272,9 @@ | ||
| 257 | 272 | */ |
| 258 | 273 | @Override |
| 259 | 274 | 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); | |
| 262 | 278 | } |
| 263 | 279 | |
| 264 | 280 | /** |
| @@ -266,17 +282,9 @@ | ||
| 266 | 282 | */ |
| 267 | 283 | @Override |
| 268 | 284 | 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); | |
| 273 | 286 | 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); | |
| 280 | 288 | } |
| 281 | 289 | |
| 282 | 290 | /** |
| @@ -284,13 +292,9 @@ | ||
| 284 | 292 | */ |
| 285 | 293 | @Override |
| 286 | 294 | public BigInteger getVarint(int i) { |
| 287 | - checkType(i, DataType.Name.VARINT); | |
| 288 | - | |
| 295 | + checkType(i, VARINT); | |
| 289 | 296 | 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); | |
| 294 | 298 | } |
| 295 | 299 | |
| 296 | 300 | /** |
| @@ -298,13 +302,9 @@ | ||
| 298 | 302 | */ |
| 299 | 303 | @Override |
| 300 | 304 | public BigDecimal getDecimal(int i) { |
| 301 | - checkType(i, DataType.Name.DECIMAL); | |
| 302 | - | |
| 305 | + checkType(i, DECIMAL); | |
| 303 | 306 | 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); | |
| 308 | 308 | } |
| 309 | 309 | |
| 310 | 310 | /** |
| @@ -312,15 +312,9 @@ | ||
| 312 | 312 | */ |
| 313 | 313 | @Override |
| 314 | 314 | public UUID getUUID(int i) { |
| 315 | - DataType.Name type = checkType(i, DataType.Name.UUID, DataType.Name.TIMEUUID); | |
| 316 | - | |
| 315 | + checkType(i, UUID, TIMEUUID); | |
| 317 | 316 | 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); | |
| 324 | 318 | } |
| 325 | 319 | |
| 326 | 320 | /** |
| @@ -328,13 +322,9 @@ | ||
| 328 | 322 | */ |
| 329 | 323 | @Override |
| 330 | 324 | public InetAddress getInet(int i) { |
| 331 | - checkType(i, DataType.Name.INET); | |
| 332 | - | |
| 325 | + checkType(i, INET); | |
| 333 | 326 | 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); | |
| 338 | 328 | } |
| 339 | 329 | |
| 340 | 330 | /** |
| @@ -343,19 +333,7 @@ | ||
| 343 | 333 | @Override |
| 344 | 334 | @SuppressWarnings("unchecked") |
| 345 | 335 | 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)); | |
| 359 | 337 | } |
| 360 | 338 | |
| 361 | 339 | /** |
| @@ -364,19 +342,10 @@ | ||
| 364 | 342 | @Override |
| 365 | 343 | @SuppressWarnings("unchecked") |
| 366 | 344 | 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); | |
| 375 | 346 | 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); | |
| 380 | 349 | } |
| 381 | 350 | |
| 382 | 351 | /** |
| @@ -385,19 +354,7 @@ | ||
| 385 | 354 | @Override |
| 386 | 355 | @SuppressWarnings("unchecked") |
| 387 | 356 | 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)); | |
| 401 | 358 | } |
| 402 | 359 | |
| 403 | 360 | /** |
| @@ -406,19 +363,10 @@ | ||
| 406 | 363 | @Override |
| 407 | 364 | @SuppressWarnings("unchecked") |
| 408 | 365 | 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); | |
| 417 | 367 | 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); | |
| 422 | 370 | } |
| 423 | 371 | |
| 424 | 372 | /** |
| @@ -427,20 +375,7 @@ | ||
| 427 | 375 | @Override |
| 428 | 376 | @SuppressWarnings("unchecked") |
| 429 | 377 | 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)); | |
| 444 | 379 | } |
| 445 | 380 | |
| 446 | 381 | /** |
| @@ -449,20 +384,10 @@ | ||
| 449 | 384 | @Override |
| 450 | 385 | @SuppressWarnings("unchecked") |
| 451 | 386 | 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); | |
| 461 | 388 | 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); | |
| 466 | 391 | } |
| 467 | 392 | |
| 468 | 393 | /** |
| @@ -471,15 +396,9 @@ | ||
| 471 | 396 | @Override |
| 472 | 397 | @SuppressWarnings("unchecked") |
| 473 | 398 | 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); | |
| 478 | 400 | 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); | |
| 483 | 402 | } |
| 484 | 403 | |
| 485 | 404 | /** |
| @@ -488,15 +407,9 @@ | ||
| 488 | 407 | @Override |
| 489 | 408 | @SuppressWarnings("unchecked") |
| 490 | 409 | 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); | |
| 495 | 411 | 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); | |
| 500 | 413 | } |
| 501 | 414 | |
| 502 | 415 | /** |
| @@ -504,20 +417,23 @@ | ||
| 504 | 417 | */ |
| 505 | 418 | @Override |
| 506 | 419 | 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); | |
| 522 | 438 | } |
| 523 | 439 | } |
modified driver-core/src/main/java/com/datastax/driver/core/AbstractGettableData.java +24 −0
| @@ -264,4 +264,28 @@ | ||
| 264 | 264 | public Object getObject(String name) { |
| 265 | 265 | return getObject(getIndexOf(name)); |
| 266 | 266 | } |
| 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 | + } | |
| 267 | 291 | } |
modified driver-core/src/main/java/com/datastax/driver/core/AbstractSession.java +22 −5
| @@ -36,7 +36,7 @@ | ||
| 36 | 36 | */ |
| 37 | 37 | @Override |
| 38 | 38 | public ResultSet execute(String query) { |
| 39 | - return execute(new SimpleStatement(query)); | |
| 39 | + return execute(newSimpleStatement(query)); | |
| 40 | 40 | } |
| 41 | 41 | |
| 42 | 42 | /** |
| @@ -44,7 +44,7 @@ | ||
| 44 | 44 | */ |
| 45 | 45 | @Override |
| 46 | 46 | public ResultSet execute(String query, Object... values) { |
| 47 | - return execute(new SimpleStatement(query, values)); | |
| 47 | + return execute(newSimpleStatement(query, values)); | |
| 48 | 48 | } |
| 49 | 49 | |
| 50 | 50 | /** |
| @@ -60,7 +60,7 @@ | ||
| 60 | 60 | */ |
| 61 | 61 | @Override |
| 62 | 62 | public ResultSetFuture executeAsync(String query) { |
| 63 | - return executeAsync(new SimpleStatement(query)); | |
| 63 | + return executeAsync(newSimpleStatement(query)); | |
| 64 | 64 | } |
| 65 | 65 | |
| 66 | 66 | /** |
| @@ -68,7 +68,23 @@ | ||
| 68 | 68 | */ |
| 69 | 69 | @Override |
| 70 | 70 | 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); | |
| 72 | 88 | } |
| 73 | 89 | |
| 74 | 90 | /** |
| @@ -108,10 +124,11 @@ | ||
| 108 | 124 | */ |
| 109 | 125 | @Override |
| 110 | 126 | public ListenableFuture<PreparedStatement> prepareAsync(final RegularStatement statement) { |
| 127 | + | |
| 111 | 128 | if (statement.hasValues()) |
| 112 | 129 | throw new IllegalArgumentException("A statement to prepare should not have values"); |
| 113 | 130 | |
| 114 | - ListenableFuture<PreparedStatement> prepared = prepareAsync(statement.toString(), statement.getOutgoingPayload()); | |
| 131 | + ListenableFuture<PreparedStatement> prepared = prepareAsync(statement.getQueryString(), statement.getOutgoingPayload()); | |
| 115 | 132 | return Futures.transform(prepared, new Function<PreparedStatement, PreparedStatement>() { |
| 116 | 133 | @Override |
| 117 | 134 | public PreparedStatement apply(PreparedStatement prepared) { |
modified driver-core/src/main/java/com/datastax/driver/core/AggregateMetadata.java +15 −11
| @@ -38,10 +38,11 @@ | ||
| 38 | 38 | private final String stateFuncSimpleName; |
| 39 | 39 | private final String stateFuncFullName; |
| 40 | 40 | private final DataType stateType; |
| 41 | + private final TypeCodec<Object> stateTypeCodec; | |
| 41 | 42 | |
| 42 | 43 | public AggregateMetadata(KeyspaceMetadata keyspace, String fullName, String simpleName, List<DataType> argumentTypes, |
| 43 | 44 | 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) { | |
| 45 | 46 | this.keyspace = keyspace; |
| 46 | 47 | this.fullName = fullName; |
| 47 | 48 | this.simpleName = simpleName; |
| @@ -53,6 +54,7 @@ | ||
| 53 | 54 | this.stateFuncSimpleName = stateFuncSimpleName; |
| 54 | 55 | this.stateFuncFullName = stateFuncFullName; |
| 55 | 56 | this.stateType = stateType; |
| 57 | + this.stateTypeCodec = stateTypeCodec; | |
| 56 | 58 | } |
| 57 | 59 | |
| 58 | 60 | // CREATE TABLE system.schema_aggregates ( |
| @@ -67,25 +69,25 @@ | ||
| 67 | 69 | // state_type text, |
| 68 | 70 | // PRIMARY KEY (keyspace_name, aggregate_name, signature) |
| 69 | 71 | // ) 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) { | |
| 71 | 73 | String simpleName = row.getString("aggregate_name"); |
| 72 | 74 | List<String> signature = row.getList("signature", String.class); |
| 73 | 75 | 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); | |
| 75 | 77 | 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); | |
| 77 | 79 | String stateFuncSimpleName = row.getString("state_func"); |
| 78 | 80 | String stateTypeName = row.getString("state_type"); |
| 79 | - DataType stateType = CassandraTypeParser.parseOne(stateTypeName); | |
| 81 | + DataType stateType = CassandraTypeParser.parseOne(stateTypeName, protocolVersion, codecRegistry); | |
| 80 | 82 | 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); | |
| 82 | 84 | |
| 83 | 85 | String finalFuncFullName = finalFuncSimpleName == null ? null : String.format("%s(%s)", finalFuncSimpleName, stateType); |
| 84 | 86 | String stateFuncFullName = makeStateFuncFullName(stateFuncSimpleName, stateType.toString(), signature); |
| 85 | 87 | |
| 86 | 88 | AggregateMetadata aggregate = new AggregateMetadata(ksm, fullName, simpleName, argumentTypes, |
| 87 | 89 | finalFuncSimpleName, finalFuncFullName, initCond, returnType, stateFuncSimpleName, |
| 88 | - stateFuncFullName, stateType); | |
| 90 | + stateFuncFullName, stateType, codecRegistry.codecFor(stateType)); | |
| 89 | 91 | ksm.add(aggregate); |
| 90 | 92 | return aggregate; |
| 91 | 93 | } |
| @@ -96,13 +98,15 @@ | ||
| 96 | 98 | return Metadata.fullFunctionName(stateFuncSimpleName, args); |
| 97 | 99 | } |
| 98 | 100 | |
| 99 | - private static List<DataType> parseTypes(List<String> names) { | |
| 101 | + private static List<DataType> parseTypes(List<String> names, ProtocolVersion protocolVersion, CodecRegistry codecRegistry) { | |
| 100 | 102 | if (names.isEmpty()) |
| 101 | 103 | return Collections.emptyList(); |
| 102 | 104 | |
| 103 | 105 | 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 | + } | |
| 106 | 110 | return builder.build(); |
| 107 | 111 | } |
| 108 | 112 | |
| @@ -170,7 +174,7 @@ | ||
| 170 | 174 | if (initCond != null) |
| 171 | 175 | TableMetadata.spaceOrNewLine(sb, formatted) |
| 172 | 176 | .append("INITCOND ") |
| 173 | - .append(stateType.format(initCond)); | |
| 177 | + .append(stateTypeCodec.format(initCond)); | |
| 174 | 178 | |
| 175 | 179 | sb.append(';'); |
| 176 | 180 |
modified driver-core/src/main/java/com/datastax/driver/core/ArrayBackedResultSet.java +11 −5
| @@ -29,7 +29,6 @@ | ||
| 29 | 29 | import org.slf4j.LoggerFactory; |
| 30 | 30 | |
| 31 | 31 | import com.datastax.driver.core.exceptions.DriverInternalError; |
| 32 | -import com.datastax.driver.core.utils.MoreFutures; | |
| 33 | 32 | |
| 34 | 33 | /** |
| 35 | 34 | * Default implementation of a result set, backed by an ArrayDeque of ArrayList. |
| @@ -50,7 +49,7 @@ | ||
| 50 | 49 | this.metadata = metadata; |
| 51 | 50 | this.protocolVersion = protocolVersion; |
| 52 | 51 | this.tokenFactory = tokenFactory; |
| 53 | - this.wasApplied = checkWasApplied(firstRow, metadata); | |
| 52 | + this.wasApplied = checkWasApplied(firstRow, metadata, protocolVersion); | |
| 54 | 53 | } |
| 55 | 54 | |
| 56 | 55 | static ArrayBackedResultSet fromMessage(Responses.Result msg, SessionManager session, ProtocolVersion protocolVersion, ExecutionInfo info, Statement statement) { |
| @@ -77,6 +76,13 @@ | ||
| 77 | 76 | // info can be null only for internal calls, but we don't page those. We assert |
| 78 | 77 | // this explicitly because MultiPage implementation don't support info == null. |
| 79 | 78 | 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 | + | |
| 80 | 86 | return r.metadata.pagingState == null |
| 81 | 87 | ? new SinglePage(columnDefs, tokenFactory, protocolVersion, r.data, info) |
| 82 | 88 | : new MultiPage(columnDefs, tokenFactory, protocolVersion, r.data, info, r.metadata.pagingState, session, statement); |
| @@ -419,7 +425,7 @@ | ||
| 419 | 425 | |
| 420 | 426 | // This method checks the value of the "[applied]" column manually, to avoid instantiating an ArrayBackedRow |
| 421 | 427 | // 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) { | |
| 423 | 429 | // If the column is not present or not a boolean, we assume the query |
| 424 | 430 | // was not a conditional statement, and therefore return true. |
| 425 | 431 | if (firstRow == null) |
| @@ -436,6 +442,6 @@ | ||
| 436 | 442 | if (value == null || value.remaining() == 0) |
| 437 | 443 | return false; |
| 438 | 444 | |
| 439 | - return TypeCodec.BooleanCodec.instance.deserializeNoBoxing(value); | |
| 445 | + return TypeCodec.BooleanCodec.instance.deserializeNoBoxing(value, protocolVersion); | |
| 440 | 446 | } |
| 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 @@ | ||
| 19 | 19 | import java.util.*; |
| 20 | 20 | import java.util.regex.Pattern; |
| 21 | 21 | |
| 22 | +import com.google.common.base.Joiner; | |
| 23 | + | |
| 22 | 24 | import com.datastax.driver.core.exceptions.DriverInternalError; |
| 23 | 25 | |
| 24 | 26 | /** |
| @@ -71,6 +73,11 @@ | ||
| 71 | 73 | return data.get(i); |
| 72 | 74 | } |
| 73 | 75 | |
| 76 | + @Override | |
| 77 | + protected CodecRegistry getCodecRegistry() { | |
| 78 | + return metadata.getCodecRegistry(); | |
| 79 | + } | |
| 80 | + | |
| 74 | 81 | @Override |
| 75 | 82 | protected int getIndexOf(String name) { |
| 76 | 83 | return metadata.getFirstIdx(name); |
| @@ -81,7 +88,7 @@ | ||
| 81 | 88 | if (tokenFactory == null) |
| 82 | 89 | throw new DriverInternalError("Token factory not set. This should only happen at initialization time"); |
| 83 | 90 | |
| 84 | - metadata.checkType(i, tokenFactory.getTokenType().getName()); | |
| 91 | + checkType(i, tokenFactory.getTokenType().getName()); | |
| 85 | 92 | |
| 86 | 93 | ByteBuffer value = data.get(i); |
| 87 | 94 | if (value == null || value.remaining() == 0) |
| @@ -116,9 +123,9 @@ | ||
| 116 | 123 | if (bb == null) |
| 117 | 124 | sb.append("NULL"); |
| 118 | 125 | else |
| 119 | - sb.append(metadata.getType(i).codec(protocolVersion).deserialize(bb).toString()); | |
| 126 | + sb.append(getCodecRegistry().codecFor(metadata.getType(i)).deserialize(bb, protocolVersion).toString()); | |
| 120 | 127 | } |
| 121 | 128 | sb.append(']'); |
| 122 | 129 | return sb.toString(); |
| 123 | 130 | } |
| 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 @@ | ||
| 16 | 16 | package com.datastax.driver.core; |
| 17 | 17 | |
| 18 | 18 | 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.*; | |
| 24 | 20 | |
| 25 | 21 | import com.google.common.collect.ImmutableList; |
| 26 | 22 | |
| @@ -85,13 +81,16 @@ | ||
| 85 | 81 | this.batchType = batchType; |
| 86 | 82 | } |
| 87 | 83 | |
| 88 | - IdAndValues getIdAndValues(ProtocolVersion protocolVersion) { | |
| 84 | + IdAndValues getIdAndValues() { | |
| 89 | 85 | IdAndValues idAndVals = new IdAndValues(statements.size()); |
| 90 | 86 | for (Statement statement : statements) { |
| 87 | + if(statement instanceof StatementWrapper) | |
| 88 | + statement = ((StatementWrapper) statement).getWrappedStatement(); | |
| 91 | 89 | if (statement instanceof RegularStatement) { |
| 92 | 90 | 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); | |
| 95 | 94 | idAndVals.values.add(vals == null ? Collections.<ByteBuffer>emptyList() : Arrays.asList(vals)); |
| 96 | 95 | } else { |
| 97 | 96 | // We handle BatchStatement in add() so ... |
| @@ -133,7 +132,7 @@ | ||
| 133 | 132 | public BatchStatement add(Statement statement) { |
| 134 | 133 | |
| 135 | 134 | // 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 | |
| 137 | 136 | // object (or this directly). |
| 138 | 137 | if (statement instanceof BatchStatement) { |
| 139 | 138 | for (Statement subStatements : ((BatchStatement)statement).statements) { |
| @@ -216,6 +215,8 @@ | ||
| 216 | 215 | @Override |
| 217 | 216 | public ByteBuffer getRoutingKey() { |
| 218 | 217 | for (Statement statement : statements) { |
| 218 | + if(statement instanceof StatementWrapper) | |
| 219 | + statement = ((StatementWrapper) statement).getWrappedStatement(); | |
| 219 | 220 | ByteBuffer rk = statement.getRoutingKey(); |
| 220 | 221 | if (rk != null) |
| 221 | 222 | return rk; |
modified driver-core/src/main/java/com/datastax/driver/core/BoundStatement.java +404 −618
| @@ -52,6 +52,8 @@ | ||
| 52 | 52 | // we still want to avoid duplicating too much code so we wrap. |
| 53 | 53 | final DataWrapper wrapper; |
| 54 | 54 | |
| 55 | + private final CodecRegistry codecRegistry; | |
| 56 | + | |
| 55 | 57 | private ByteBuffer routingKey; |
| 56 | 58 | |
| 57 | 59 | /** |
| @@ -79,6 +81,7 @@ | ||
| 79 | 81 | else |
| 80 | 82 | // propagate incoming payload as outgoing payload, if no outgoing payload has been explicitly set |
| 81 | 83 | this.setOutgoingPayload(statement.getIncomingPayload()); |
| 84 | + this.codecRegistry = statement.getCodecRegistry(); | |
| 82 | 85 | } |
| 83 | 86 | |
| 84 | 87 | /** |
| @@ -144,95 +147,22 @@ | ||
| 144 | 147 | if (values.length > statement.getVariables().size()) |
| 145 | 148 | throw new IllegalArgumentException(String.format("Prepared statement has only %d variables, %d values provided", statement.getVariables().size(), values.length)); |
| 146 | 149 | |
| 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) { | |
| 152 | 153 | 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); | |
| 213 | 161 | } |
| 214 | - wrapper.values[i] = columnType.codec(statement.getPreparedId().protocolVersion).serialize(toSet); | |
| 215 | 162 | } |
| 216 | 163 | return this; |
| 217 | 164 | } |
| 218 | 165 | |
| 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 | - | |
| 236 | 166 | /** |
| 237 | 167 | * The routing key for this bound query. |
| 238 | 168 | * <p> |
| @@ -253,7 +183,6 @@ | ||
| 253 | 183 | * |
| 254 | 184 | * @return the routing key for this statement or {@code null}. |
| 255 | 185 | */ |
| 256 | - @Override | |
| 257 | 186 | public ByteBuffer getRoutingKey() { |
| 258 | 187 | if (this.routingKey != null) { |
| 259 | 188 | return this.routingKey; |
| @@ -275,24 +204,31 @@ | ||
| 275 | 204 | return null; |
| 276 | 205 | components[i] = value; |
| 277 | 206 | } |
| 278 | - return SimpleStatement.compose(components); | |
| 207 | + return CodecUtils.compose(components); | |
| 279 | 208 | } |
| 280 | 209 | } |
| 281 | 210 | return null; |
| 282 | 211 | } |
| 283 | 212 | |
| 284 | 213 | /** |
| 285 | - * Returns the keyspace this query operates on. | |
| 214 | + * Sets the routing key for this bound statement. | |
| 286 | 215 | * <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. | |
| 293 | 222 | * |
| 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} | |
| 296 | 232 | */ |
| 297 | 233 | @Override |
| 298 | 234 | public String getKeyspace() { |
| @@ -300,157 +236,81 @@ | ||
| 300 | 236 | } |
| 301 | 237 | |
| 302 | 238 | /** |
| 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} | |
| 311 | 240 | */ |
| 241 | + @Override | |
| 312 | 242 | public BoundStatement setBool(int i, boolean v) { |
| 313 | 243 | return wrapper.setBool(i, v); |
| 314 | 244 | } |
| 315 | 245 | |
| 316 | 246 | /** |
| 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} | |
| 328 | 248 | */ |
| 249 | + @Override | |
| 329 | 250 | public BoundStatement setBool(String name, boolean v) { |
| 330 | 251 | return wrapper.setBool(name, v); |
| 331 | 252 | } |
| 332 | 253 | |
| 333 | 254 | /** |
| 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} | |
| 342 | 256 | */ |
| 257 | + @Override | |
| 343 | 258 | public BoundStatement setByte(int i, byte v) { |
| 344 | 259 | return wrapper.setByte(i, v); |
| 345 | 260 | } |
| 346 | 261 | |
| 347 | 262 | /** |
| 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} | |
| 359 | 264 | */ |
| 265 | + @Override | |
| 360 | 266 | public BoundStatement setByte(String name, byte v) { |
| 361 | 267 | return wrapper.setByte(name, v); |
| 362 | 268 | } |
| 363 | 269 | |
| 364 | 270 | /** |
| 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} | |
| 373 | 272 | */ |
| 273 | + @Override | |
| 374 | 274 | public BoundStatement setShort(int i, short v) { |
| 375 | 275 | return wrapper.setShort(i, v); |
| 376 | 276 | } |
| 377 | 277 | |
| 378 | 278 | /** |
| 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} | |
| 390 | 280 | */ |
| 281 | + @Override | |
| 391 | 282 | public BoundStatement setShort(String name, short v) { |
| 392 | 283 | return wrapper.setShort(name, v); |
| 393 | 284 | } |
| 394 | 285 | |
| 395 | 286 | /** |
| 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} | |
| 404 | 288 | */ |
| 289 | + @Override | |
| 405 | 290 | public BoundStatement setInt(int i, int v) { |
| 406 | 291 | return wrapper.setInt(i, v); |
| 407 | 292 | } |
| 408 | 293 | |
| 409 | 294 | /** |
| 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} | |
| 421 | 296 | */ |
| 297 | + @Override | |
| 422 | 298 | public BoundStatement setInt(String name, int v) { |
| 423 | 299 | return wrapper.setInt(name, v); |
| 424 | 300 | } |
| 425 | 301 | |
| 426 | 302 | /** |
| 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} | |
| 435 | 304 | */ |
| 305 | + @Override | |
| 436 | 306 | public BoundStatement setLong(int i, long v) { |
| 437 | 307 | return wrapper.setLong(i, v); |
| 438 | 308 | } |
| 439 | 309 | |
| 440 | 310 | /** |
| 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} | |
| 453 | 312 | */ |
| 313 | + @Override | |
| 454 | 314 | public BoundStatement setLong(String name, long v) { |
| 455 | 315 | return wrapper.setLong(name, v); |
| 456 | 316 | } |
| @@ -492,401 +352,193 @@ | ||
| 492 | 352 | } |
| 493 | 353 | |
| 494 | 354 | /** |
| 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} | |
| 503 | 356 | */ |
| 357 | + @Override | |
| 504 | 358 | public BoundStatement setTimestamp(int i, Date v) { |
| 505 | 359 | return wrapper.setTimestamp(i, v); |
| 506 | 360 | } |
| 507 | 361 | |
| 508 | 362 | /** |
| 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} | |
| 521 | 364 | */ |
| 365 | + @Override | |
| 522 | 366 | public BoundStatement setTimestamp(String name, Date v) { |
| 523 | 367 | return wrapper.setTimestamp(name, v); |
| 524 | 368 | } |
| 525 | 369 | |
| 526 | 370 | /** |
| 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} | |
| 535 | 372 | */ |
| 373 | + @Override | |
| 536 | 374 | public BoundStatement setDate(int i, LocalDate v) { |
| 537 | 375 | return wrapper.setDate(i, v); |
| 538 | 376 | } |
| 539 | 377 | |
| 540 | 378 | /** |
| 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} | |
| 552 | 380 | */ |
| 381 | + @Override | |
| 553 | 382 | public BoundStatement setDate(String name, LocalDate v) { |
| 554 | 383 | return wrapper.setDate(name, v); |
| 555 | 384 | } |
| 556 | 385 | |
| 557 | 386 | /** |
| 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} | |
| 566 | 388 | */ |
| 389 | + @Override | |
| 567 | 390 | public BoundStatement setTime(int i, long v) { |
| 568 | 391 | return wrapper.setTime(i, v); |
| 569 | 392 | } |
| 570 | 393 | |
| 571 | 394 | /** |
| 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} | |
| 583 | 396 | */ |
| 397 | + @Override | |
| 584 | 398 | public BoundStatement setTime(String name, long v) { |
| 585 | 399 | return wrapper.setTime(name, v); |
| 586 | 400 | } |
| 587 | 401 | |
| 588 | 402 | /** |
| 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} | |
| 597 | 404 | */ |
| 405 | + @Override | |
| 598 | 406 | public BoundStatement setFloat(int i, float v) { |
| 599 | 407 | return wrapper.setFloat(i, v); |
| 600 | 408 | } |
| 601 | 409 | |
| 602 | 410 | /** |
| 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} | |
| 615 | 412 | */ |
| 413 | + @Override | |
| 616 | 414 | public BoundStatement setFloat(String name, float v) { |
| 617 | 415 | return wrapper.setFloat(name, v); |
| 618 | 416 | } |
| 619 | 417 | |
| 620 | 418 | /** |
| 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} | |
| 629 | 420 | */ |
| 421 | + @Override | |
| 630 | 422 | public BoundStatement setDouble(int i, double v) { |
| 631 | 423 | return wrapper.setDouble(i, v); |
| 632 | 424 | } |
| 633 | 425 | |
| 634 | 426 | /** |
| 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} | |
| 647 | 428 | */ |
| 429 | + @Override | |
| 648 | 430 | public BoundStatement setDouble(String name, double v) { |
| 649 | 431 | return wrapper.setDouble(name, v); |
| 650 | 432 | } |
| 651 | 433 | |
| 652 | 434 | /** |
| 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} | |
| 662 | 436 | */ |
| 437 | + @Override | |
| 663 | 438 | public BoundStatement setString(int i, String v) { |
| 664 | 439 | return wrapper.setString(i, v); |
| 665 | 440 | } |
| 666 | 441 | |
| 667 | 442 | /** |
| 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} | |
| 680 | 444 | */ |
| 445 | + @Override | |
| 681 | 446 | public BoundStatement setString(String name, String v) { |
| 682 | 447 | return wrapper.setString(name, v); |
| 683 | 448 | } |
| 684 | 449 | |
| 685 | 450 | /** |
| 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} | |
| 698 | 452 | */ |
| 453 | + @Override | |
| 699 | 454 | public BoundStatement setBytes(int i, ByteBuffer v) { |
| 700 | 455 | return wrapper.setBytes(i, v); |
| 701 | 456 | } |
| 702 | 457 | |
| 703 | 458 | /** |
| 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} | |
| 719 | 460 | */ |
| 461 | + @Override | |
| 720 | 462 | public BoundStatement setBytes(String name, ByteBuffer v) { |
| 721 | 463 | return wrapper.setBytes(name, v); |
| 722 | 464 | } |
| 723 | 465 | |
| 724 | 466 | /** |
| 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} | |
| 737 | 468 | */ |
| 469 | + @Override | |
| 738 | 470 | public BoundStatement setBytesUnsafe(int i, ByteBuffer v) { |
| 739 | 471 | return wrapper.setBytesUnsafe(i, v); |
| 740 | 472 | } |
| 741 | 473 | |
| 742 | 474 | /** |
| 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} | |
| 758 | 476 | */ |
| 477 | + @Override | |
| 759 | 478 | public BoundStatement setBytesUnsafe(String name, ByteBuffer v) { |
| 760 | 479 | return wrapper.setBytesUnsafe(name, v); |
| 761 | 480 | } |
| 762 | 481 | |
| 763 | 482 | /** |
| 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} | |
| 772 | 484 | */ |
| 485 | + @Override | |
| 773 | 486 | public BoundStatement setVarint(int i, BigInteger v) { |
| 774 | 487 | return wrapper.setVarint(i, v); |
| 775 | 488 | } |
| 776 | 489 | |
| 777 | 490 | /** |
| 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} | |
| 790 | 492 | */ |
| 493 | + @Override | |
| 791 | 494 | public BoundStatement setVarint(String name, BigInteger v) { |
| 792 | 495 | return wrapper.setVarint(name, v); |
| 793 | 496 | } |
| 794 | 497 | |
| 795 | 498 | /** |
| 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} | |
| 804 | 500 | */ |
| 501 | + @Override | |
| 805 | 502 | public BoundStatement setDecimal(int i, BigDecimal v) { |
| 806 | 503 | return wrapper.setDecimal(i, v); |
| 807 | 504 | } |
| 808 | 505 | |
| 809 | 506 | /** |
| 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} | |
| 822 | 508 | */ |
| 509 | + @Override | |
| 823 | 510 | public BoundStatement setDecimal(String name, BigDecimal v) { |
| 824 | 511 | return wrapper.setDecimal(name, v); |
| 825 | 512 | } |
| 826 | 513 | |
| 827 | 514 | /** |
| 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} | |
| 838 | 516 | */ |
| 517 | + @Override | |
| 839 | 518 | public BoundStatement setUUID(int i, UUID v) { |
| 840 | 519 | return wrapper.setUUID(i, v); |
| 841 | 520 | } |
| 842 | 521 | |
| 843 | 522 | /** |
| 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} | |
| 857 | 524 | */ |
| 525 | + @Override | |
| 858 | 526 | public BoundStatement setUUID(String name, UUID v) { |
| 859 | 527 | return wrapper.setUUID(name, v); |
| 860 | 528 | } |
| 861 | 529 | |
| 862 | 530 | /** |
| 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} | |
| 871 | 532 | */ |
| 533 | + @Override | |
| 872 | 534 | public BoundStatement setInet(int i, InetAddress v) { |
| 873 | 535 | return wrapper.setInet(i, v); |
| 874 | 536 | } |
| 875 | 537 | |
| 876 | 538 | /** |
| 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} | |
| 889 | 540 | */ |
| 541 | + @Override | |
| 890 | 542 | public BoundStatement setInet(String name, InetAddress v) { |
| 891 | 543 | return wrapper.setInet(name, v); |
| 892 | 544 | } |
| @@ -973,231 +625,257 @@ | ||
| 973 | 625 | } |
| 974 | 626 | |
| 975 | 627 | /** |
| 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} | |
| 991 | 629 | */ |
| 630 | + @Override | |
| 992 | 631 | public <T> BoundStatement setList(int i, List<T> v) { |
| 993 | 632 | return wrapper.setList(i, v); |
| 994 | 633 | } |
| 995 | 634 | |
| 996 | 635 | /** |
| 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} | |
| 1015 | 645 | */ |
| 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 | |
| 1016 | 655 | public <T> BoundStatement setList(String name, List<T> v) { |
| 1017 | 656 | return wrapper.setList(name, v); |
| 1018 | 657 | } |
| 1019 | 658 | |
| 1020 | 659 | /** |
| 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} | |
| 1037 | 725 | */ |
| 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); | |
| 1040 | 729 | } |
| 1041 | 730 | |
| 1042 | 731 | /** |
| 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} | |
| 1062 | 733 | */ |
| 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); | |
| 1065 | 737 | } |
| 1066 | 738 | |
| 1067 | 739 | /** |
| 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} | |
| 1083 | 741 | */ |
| 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); | |
| 1086 | 745 | } |
| 1087 | 746 | |
| 1088 | 747 | /** |
| 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} | |
| 1107 | 749 | */ |
| 750 | + @Override | |
| 1108 | 751 | public <T> BoundStatement setSet(String name, Set<T> v) { |
| 1109 | 752 | return wrapper.setSet(name, v); |
| 1110 | 753 | } |
| 1111 | 754 | |
| 1112 | 755 | /** |
| 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} | |
| 1122 | 765 | */ |
| 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 | |
| 1123 | 775 | public BoundStatement setUDTValue(int i, UDTValue v) { |
| 1124 | 776 | return wrapper.setUDTValue(i, v); |
| 1125 | 777 | } |
| 1126 | 778 | |
| 1127 | 779 | /** |
| 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} | |
| 1140 | 781 | */ |
| 782 | + @Override | |
| 1141 | 783 | public BoundStatement setUDTValue(String name, UDTValue v) { |
| 1142 | 784 | return wrapper.setUDTValue(name, v); |
| 1143 | 785 | } |
| 1144 | 786 | |
| 1145 | 787 | /** |
| 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} | |
| 1155 | 789 | */ |
| 790 | + @Override | |
| 1156 | 791 | public BoundStatement setTupleValue(int i, TupleValue v) { |
| 1157 | 792 | return wrapper.setTupleValue(i, v); |
| 1158 | 793 | } |
| 1159 | 794 | |
| 1160 | 795 | /** |
| 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} | |
| 1173 | 797 | */ |
| 798 | + @Override | |
| 1174 | 799 | public BoundStatement setTupleValue(String name, TupleValue v) { |
| 1175 | 800 | return wrapper.setTupleValue(name, v); |
| 1176 | 801 | } |
| 1177 | 802 | |
| 1178 | 803 | /** |
| 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} | |
| 1186 | 869 | */ |
| 870 | + @Override | |
| 1187 | 871 | public BoundStatement setToNull(int i) { |
| 1188 | 872 | return wrapper.setToNull(i); |
| 1189 | 873 | } |
| 1190 | 874 | |
| 1191 | 875 | /** |
| 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} | |
| 1200 | 877 | */ |
| 878 | + @Override | |
| 1201 | 879 | public BoundStatement setToNull(String name) { |
| 1202 | 880 | return wrapper.setToNull(name); |
| 1203 | 881 | } |
| @@ -1205,6 +883,7 @@ | ||
| 1205 | 883 | /** |
| 1206 | 884 | * {@inheritDoc} |
| 1207 | 885 | */ |
| 886 | + @Override | |
| 1208 | 887 | public boolean isNull(int i) { |
| 1209 | 888 | return wrapper.isNull(i); |
| 1210 | 889 | } |
| @@ -1212,6 +891,7 @@ | ||
| 1212 | 891 | /** |
| 1213 | 892 | * {@inheritDoc} |
| 1214 | 893 | */ |
| 894 | + @Override | |
| 1215 | 895 | public boolean isNull(String name) { |
| 1216 | 896 | return wrapper.isNull(name); |
| 1217 | 897 | } |
| @@ -1219,6 +899,7 @@ | ||
| 1219 | 899 | /** |
| 1220 | 900 | * {@inheritDoc} |
| 1221 | 901 | */ |
| 902 | + @Override | |
| 1222 | 903 | public boolean getBool(int i) { |
| 1223 | 904 | return wrapper.getBool(i); |
| 1224 | 905 | } |
| @@ -1226,6 +907,7 @@ | ||
| 1226 | 907 | /** |
| 1227 | 908 | * {@inheritDoc} |
| 1228 | 909 | */ |
| 910 | + @Override | |
| 1229 | 911 | public boolean getBool(String name) { |
| 1230 | 912 | return wrapper.getBool(name); |
| 1231 | 913 | } |
| @@ -1233,6 +915,7 @@ | ||
| 1233 | 915 | /** |
| 1234 | 916 | * {@inheritDoc} |
| 1235 | 917 | */ |
| 918 | + @Override | |
| 1236 | 919 | public byte getByte(int i) { |
| 1237 | 920 | return wrapper.getByte(i); |
| 1238 | 921 | } |
| @@ -1240,6 +923,7 @@ | ||
| 1240 | 923 | /** |
| 1241 | 924 | * {@inheritDoc} |
| 1242 | 925 | */ |
| 926 | + @Override | |
| 1243 | 927 | public byte getByte(String name) { |
| 1244 | 928 | return wrapper.getByte(name); |
| 1245 | 929 | } |
| @@ -1247,6 +931,7 @@ | ||
| 1247 | 931 | /** |
| 1248 | 932 | * {@inheritDoc} |
| 1249 | 933 | */ |
| 934 | + @Override | |
| 1250 | 935 | public short getShort(int i) { |
| 1251 | 936 | return wrapper.getShort(i); |
| 1252 | 937 | } |
| @@ -1254,6 +939,7 @@ | ||
| 1254 | 939 | /** |
| 1255 | 940 | * {@inheritDoc} |
| 1256 | 941 | */ |
| 942 | + @Override | |
| 1257 | 943 | public short getShort(String name) { |
| 1258 | 944 | return wrapper.getShort(name); |
| 1259 | 945 | } |
| @@ -1261,6 +947,7 @@ | ||
| 1261 | 947 | /** |
| 1262 | 948 | * {@inheritDoc} |
| 1263 | 949 | */ |
| 950 | + @Override | |
| 1264 | 951 | public int getInt(int i) { |
| 1265 | 952 | return wrapper.getInt(i); |
| 1266 | 953 | } |
| @@ -1268,6 +955,7 @@ | ||
| 1268 | 955 | /** |
| 1269 | 956 | * {@inheritDoc} |
| 1270 | 957 | */ |
| 958 | + @Override | |
| 1271 | 959 | public int getInt(String name) { |
| 1272 | 960 | return wrapper.getInt(name); |
| 1273 | 961 | } |
| @@ -1275,6 +963,7 @@ | ||
| 1275 | 963 | /** |
| 1276 | 964 | * {@inheritDoc} |
| 1277 | 965 | */ |
| 966 | + @Override | |
| 1278 | 967 | public long getLong(int i) { |
| 1279 | 968 | return wrapper.getLong(i); |
| 1280 | 969 | } |
| @@ -1282,6 +971,7 @@ | ||
| 1282 | 971 | /** |
| 1283 | 972 | * {@inheritDoc} |
| 1284 | 973 | */ |
| 974 | + @Override | |
| 1285 | 975 | public long getLong(String name) { |
| 1286 | 976 | return wrapper.getLong(name); |
| 1287 | 977 | } |
| @@ -1289,6 +979,7 @@ | ||
| 1289 | 979 | /** |
| 1290 | 980 | * {@inheritDoc} |
| 1291 | 981 | */ |
| 982 | + @Override | |
| 1292 | 983 | public Date getTimestamp(int i) { |
| 1293 | 984 | return wrapper.getTimestamp(i); |
| 1294 | 985 | } |
| @@ -1296,6 +987,7 @@ | ||
| 1296 | 987 | /** |
| 1297 | 988 | * {@inheritDoc} |
| 1298 | 989 | */ |
| 990 | + @Override | |
| 1299 | 991 | public Date getTimestamp(String name) { |
| 1300 | 992 | return wrapper.getTimestamp(name); |
| 1301 | 993 | } |
| @@ -1303,6 +995,7 @@ | ||
| 1303 | 995 | /** |
| 1304 | 996 | * {@inheritDoc} |
| 1305 | 997 | */ |
| 998 | + @Override | |
| 1306 | 999 | public LocalDate getDate(int i) { |
| 1307 | 1000 | return wrapper.getDate(i); |
| 1308 | 1001 | } |
| @@ -1310,6 +1003,7 @@ | ||
| 1310 | 1003 | /** |
| 1311 | 1004 | * {@inheritDoc} |
| 1312 | 1005 | */ |
| 1006 | + @Override | |
| 1313 | 1007 | public LocalDate getDate(String name) { |
| 1314 | 1008 | return wrapper.getDate(name); |
| 1315 | 1009 | } |
| @@ -1317,6 +1011,7 @@ | ||
| 1317 | 1011 | /** |
| 1318 | 1012 | * {@inheritDoc} |
| 1319 | 1013 | */ |
| 1014 | + @Override | |
| 1320 | 1015 | public long getTime(int i) { |
| 1321 | 1016 | return wrapper.getTime(i); |
| 1322 | 1017 | } |
| @@ -1324,6 +1019,7 @@ | ||
| 1324 | 1019 | /** |
| 1325 | 1020 | * {@inheritDoc} |
| 1326 | 1021 | */ |
| 1022 | + @Override | |
| 1327 | 1023 | public long getTime(String name) { |
| 1328 | 1024 | return wrapper.getTime(name); |
| 1329 | 1025 | } |
| @@ -1331,6 +1027,7 @@ | ||
| 1331 | 1027 | /** |
| 1332 | 1028 | * {@inheritDoc} |
| 1333 | 1029 | */ |
| 1030 | + @Override | |
| 1334 | 1031 | public float getFloat(int i) { |
| 1335 | 1032 | return wrapper.getFloat(i); |
| 1336 | 1033 | } |
| @@ -1338,6 +1035,7 @@ | ||
| 1338 | 1035 | /** |
| 1339 | 1036 | * {@inheritDoc} |
| 1340 | 1037 | */ |
| 1038 | + @Override | |
| 1341 | 1039 | public float getFloat(String name) { |
| 1342 | 1040 | return wrapper.getFloat(name); |
| 1343 | 1041 | } |
| @@ -1345,6 +1043,7 @@ | ||
| 1345 | 1043 | /** |
| 1346 | 1044 | * {@inheritDoc} |
| 1347 | 1045 | */ |
| 1046 | + @Override | |
| 1348 | 1047 | public double getDouble(int i) { |
| 1349 | 1048 | return wrapper.getDouble(i); |
| 1350 | 1049 | } |
| @@ -1352,6 +1051,7 @@ | ||
| 1352 | 1051 | /** |
| 1353 | 1052 | * {@inheritDoc} |
| 1354 | 1053 | */ |
| 1054 | + @Override | |
| 1355 | 1055 | public double getDouble(String name) { |
| 1356 | 1056 | return wrapper.getDouble(name); |
| 1357 | 1057 | } |
| @@ -1359,6 +1059,7 @@ | ||
| 1359 | 1059 | /** |
| 1360 | 1060 | * {@inheritDoc} |
| 1361 | 1061 | */ |
| 1062 | + @Override | |
| 1362 | 1063 | public ByteBuffer getBytesUnsafe(int i) { |
| 1363 | 1064 | return wrapper.getBytesUnsafe(i); |
| 1364 | 1065 | } |
| @@ -1366,6 +1067,7 @@ | ||
| 1366 | 1067 | /** |
| 1367 | 1068 | * {@inheritDoc} |
| 1368 | 1069 | */ |
| 1070 | + @Override | |
| 1369 | 1071 | public ByteBuffer getBytesUnsafe(String name) { |
| 1370 | 1072 | return wrapper.getBytesUnsafe(name); |
| 1371 | 1073 | } |
| @@ -1373,6 +1075,7 @@ | ||
| 1373 | 1075 | /** |
| 1374 | 1076 | * {@inheritDoc} |
| 1375 | 1077 | */ |
| 1078 | + @Override | |
| 1376 | 1079 | public ByteBuffer getBytes(int i) { |
| 1377 | 1080 | return wrapper.getBytes(i); |
| 1378 | 1081 | } |
| @@ -1380,6 +1083,7 @@ | ||
| 1380 | 1083 | /** |
| 1381 | 1084 | * {@inheritDoc} |
| 1382 | 1085 | */ |
| 1086 | + @Override | |
| 1383 | 1087 | public ByteBuffer getBytes(String name) { |
| 1384 | 1088 | return wrapper.getBytes(name); |
| 1385 | 1089 | } |
| @@ -1387,6 +1091,7 @@ | ||
| 1387 | 1091 | /** |
| 1388 | 1092 | * {@inheritDoc} |
| 1389 | 1093 | */ |
| 1094 | + @Override | |
| 1390 | 1095 | public String getString(int i) { |
| 1391 | 1096 | return wrapper.getString(i); |
| 1392 | 1097 | } |
| @@ -1394,6 +1099,7 @@ | ||
| 1394 | 1099 | /** |
| 1395 | 1100 | * {@inheritDoc} |
| 1396 | 1101 | */ |
| 1102 | + @Override | |
| 1397 | 1103 | public String getString(String name) { |
| 1398 | 1104 | return wrapper.getString(name); |
| 1399 | 1105 | } |
| @@ -1401,6 +1107,7 @@ | ||
| 1401 | 1107 | /** |
| 1402 | 1108 | * {@inheritDoc} |
| 1403 | 1109 | */ |
| 1110 | + @Override | |
| 1404 | 1111 | public BigInteger getVarint(int i) { |
| 1405 | 1112 | return wrapper.getVarint(i); |
| 1406 | 1113 | } |
| @@ -1408,6 +1115,7 @@ | ||
| 1408 | 1115 | /** |
| 1409 | 1116 | * {@inheritDoc} |
| 1410 | 1117 | */ |
| 1118 | + @Override | |
| 1411 | 1119 | public BigInteger getVarint(String name) { |
| 1412 | 1120 | return wrapper.getVarint(name); |
| 1413 | 1121 | } |
| @@ -1415,6 +1123,7 @@ | ||
| 1415 | 1123 | /** |
| 1416 | 1124 | * {@inheritDoc} |
| 1417 | 1125 | */ |
| 1126 | + @Override | |
| 1418 | 1127 | public BigDecimal getDecimal(int i) { |
| 1419 | 1128 | return wrapper.getDecimal(i); |
| 1420 | 1129 | } |
| @@ -1422,6 +1131,7 @@ | ||
| 1422 | 1131 | /** |
| 1423 | 1132 | * {@inheritDoc} |
| 1424 | 1133 | */ |
| 1134 | + @Override | |
| 1425 | 1135 | public BigDecimal getDecimal(String name) { |
| 1426 | 1136 | return wrapper.getDecimal(name); |
| 1427 | 1137 | } |
| @@ -1429,6 +1139,7 @@ | ||
| 1429 | 1139 | /** |
| 1430 | 1140 | * {@inheritDoc} |
| 1431 | 1141 | */ |
| 1142 | + @Override | |
| 1432 | 1143 | public UUID getUUID(int i) { |
| 1433 | 1144 | return wrapper.getUUID(i); |
| 1434 | 1145 | } |
| @@ -1436,6 +1147,7 @@ | ||
| 1436 | 1147 | /** |
| 1437 | 1148 | * {@inheritDoc} |
| 1438 | 1149 | */ |
| 1150 | + @Override | |
| 1439 | 1151 | public UUID getUUID(String name) { |
| 1440 | 1152 | return wrapper.getUUID(name); |
| 1441 | 1153 | } |
| @@ -1443,6 +1155,7 @@ | ||
| 1443 | 1155 | /** |
| 1444 | 1156 | * {@inheritDoc} |
| 1445 | 1157 | */ |
| 1158 | + @Override | |
| 1446 | 1159 | public InetAddress getInet(int i) { |
| 1447 | 1160 | return wrapper.getInet(i); |
| 1448 | 1161 | } |
| @@ -1450,6 +1163,7 @@ | ||
| 1450 | 1163 | /** |
| 1451 | 1164 | * {@inheritDoc} |
| 1452 | 1165 | */ |
| 1166 | + @Override | |
| 1453 | 1167 | public InetAddress getInet(String name) { |
| 1454 | 1168 | return wrapper.getInet(name); |
| 1455 | 1169 | } |
| @@ -1457,6 +1171,7 @@ | ||
| 1457 | 1171 | /** |
| 1458 | 1172 | * {@inheritDoc} |
| 1459 | 1173 | */ |
| 1174 | + @Override | |
| 1460 | 1175 | public <T> List<T> getList(int i, Class<T> elementsClass) { |
| 1461 | 1176 | return wrapper.getList(i, elementsClass); |
| 1462 | 1177 | } |
| @@ -1464,6 +1179,7 @@ | ||
| 1464 | 1179 | /** |
| 1465 | 1180 | * {@inheritDoc} |
| 1466 | 1181 | */ |
| 1182 | + @Override | |
| 1467 | 1183 | public <T> List<T> getList(int i, TypeToken<T> elementsType) { |
| 1468 | 1184 | return wrapper.getList(i, elementsType); |
| 1469 | 1185 | } |
| @@ -1471,6 +1187,7 @@ | ||
| 1471 | 1187 | /** |
| 1472 | 1188 | * {@inheritDoc} |
| 1473 | 1189 | */ |
| 1190 | + @Override | |
| 1474 | 1191 | public <T> List<T> getList(String name, Class<T> elementsClass) { |
| 1475 | 1192 | return wrapper.getList(name, elementsClass); |
| 1476 | 1193 | } |
| @@ -1478,6 +1195,7 @@ | ||
| 1478 | 1195 | /** |
| 1479 | 1196 | * {@inheritDoc} |
| 1480 | 1197 | */ |
| 1198 | + @Override | |
| 1481 | 1199 | public <T> List<T> getList(String name, TypeToken<T> elementsType) { |
| 1482 | 1200 | return wrapper.getList(name, elementsType); |
| 1483 | 1201 | } |
| @@ -1485,6 +1203,7 @@ | ||
| 1485 | 1203 | /** |
| 1486 | 1204 | * {@inheritDoc} |
| 1487 | 1205 | */ |
| 1206 | + @Override | |
| 1488 | 1207 | public <T> Set<T> getSet(int i, Class<T> elementsClass) { |
| 1489 | 1208 | return wrapper.getSet(i, elementsClass); |
| 1490 | 1209 | } |
| @@ -1492,6 +1211,7 @@ | ||
| 1492 | 1211 | /** |
| 1493 | 1212 | * {@inheritDoc} |
| 1494 | 1213 | */ |
| 1214 | + @Override | |
| 1495 | 1215 | public <T> Set<T> getSet(int i, TypeToken<T> elementsType) { |
| 1496 | 1216 | return wrapper.getSet(i, elementsType); |
| 1497 | 1217 | } |
| @@ -1499,6 +1219,7 @@ | ||
| 1499 | 1219 | /** |
| 1500 | 1220 | * {@inheritDoc} |
| 1501 | 1221 | */ |
| 1222 | + @Override | |
| 1502 | 1223 | public <T> Set<T> getSet(String name, Class<T> elementsClass) { |
| 1503 | 1224 | return wrapper.getSet(name, elementsClass); |
| 1504 | 1225 | } |
| @@ -1506,6 +1227,7 @@ | ||
| 1506 | 1227 | /** |
| 1507 | 1228 | * {@inheritDoc} |
| 1508 | 1229 | */ |
| 1230 | + @Override | |
| 1509 | 1231 | public <T> Set<T> getSet(String name, TypeToken<T> elementsType) { |
| 1510 | 1232 | return wrapper.getSet(name, elementsType); |
| 1511 | 1233 | } |
| @@ -1513,6 +1235,7 @@ | ||
| 1513 | 1235 | /** |
| 1514 | 1236 | * {@inheritDoc} |
| 1515 | 1237 | */ |
| 1238 | + @Override | |
| 1516 | 1239 | public <K, V> Map<K, V> getMap(int i, Class<K> keysClass, Class<V> valuesClass) { |
| 1517 | 1240 | return wrapper.getMap(i, keysClass, valuesClass); |
| 1518 | 1241 | } |
| @@ -1520,6 +1243,7 @@ | ||
| 1520 | 1243 | /** |
| 1521 | 1244 | * {@inheritDoc} |
| 1522 | 1245 | */ |
| 1246 | + @Override | |
| 1523 | 1247 | public <K, V> Map<K, V> getMap(int i, TypeToken<K> keysType, TypeToken<V> valuesType) { |
| 1524 | 1248 | return wrapper.getMap(i, keysType, valuesType); |
| 1525 | 1249 | } |
| @@ -1527,6 +1251,7 @@ | ||
| 1527 | 1251 | /** |
| 1528 | 1252 | * {@inheritDoc} |
| 1529 | 1253 | */ |
| 1254 | + @Override | |
| 1530 | 1255 | public <K, V> Map<K, V> getMap(String name, Class<K> keysClass, Class<V> valuesClass) { |
| 1531 | 1256 | return wrapper.getMap(name, keysClass, valuesClass); |
| 1532 | 1257 | } |
| @@ -1534,6 +1259,7 @@ | ||
| 1534 | 1259 | /** |
| 1535 | 1260 | * {@inheritDoc} |
| 1536 | 1261 | */ |
| 1262 | + @Override | |
| 1537 | 1263 | public <K, V> Map<K, V> getMap(String name, TypeToken<K> keysType, TypeToken<V> valuesType) { |
| 1538 | 1264 | return wrapper.getMap(name, keysType, valuesType); |
| 1539 | 1265 | } |
| @@ -1541,6 +1267,7 @@ | ||
| 1541 | 1267 | /** |
| 1542 | 1268 | * {@inheritDoc} |
| 1543 | 1269 | */ |
| 1270 | + @Override | |
| 1544 | 1271 | public UDTValue getUDTValue(int i) { |
| 1545 | 1272 | return wrapper.getUDTValue(i); |
| 1546 | 1273 | } |
| @@ -1548,6 +1275,7 @@ | ||
| 1548 | 1275 | /** |
| 1549 | 1276 | * {@inheritDoc} |
| 1550 | 1277 | */ |
| 1278 | + @Override | |
| 1551 | 1279 | public UDTValue getUDTValue(String name) { |
| 1552 | 1280 | return wrapper.getUDTValue(name); |
| 1553 | 1281 | } |
| @@ -1555,6 +1283,7 @@ | ||
| 1555 | 1283 | /** |
| 1556 | 1284 | * {@inheritDoc} |
| 1557 | 1285 | */ |
| 1286 | + @Override | |
| 1558 | 1287 | public TupleValue getTupleValue(int i) { |
| 1559 | 1288 | return wrapper.getTupleValue(i); |
| 1560 | 1289 | } |
| @@ -1562,6 +1291,7 @@ | ||
| 1562 | 1291 | /** |
| 1563 | 1292 | * {@inheritDoc} |
| 1564 | 1293 | */ |
| 1294 | + @Override | |
| 1565 | 1295 | public TupleValue getTupleValue(String name) { |
| 1566 | 1296 | return wrapper.getTupleValue(name); |
| 1567 | 1297 | } |
| @@ -1569,6 +1299,7 @@ | ||
| 1569 | 1299 | /** |
| 1570 | 1300 | * {@inheritDoc} |
| 1571 | 1301 | */ |
| 1302 | + @Override | |
| 1572 | 1303 | public Object getObject(int i) { |
| 1573 | 1304 | return wrapper.getObject(i); |
| 1574 | 1305 | } |
| @@ -1576,10 +1307,70 @@ | ||
| 1576 | 1307 | /** |
| 1577 | 1308 | * {@inheritDoc} |
| 1578 | 1309 | */ |
| 1310 | + @Override | |
| 1579 | 1311 | public Object getObject(String name) { |
| 1580 | 1312 | return wrapper.getObject(name); |
| 1581 | 1313 | } |
| 1582 | 1314 | |
| 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 | + | |
| 1583 | 1374 | static class DataWrapper extends AbstractData<BoundStatement> { |
| 1584 | 1375 | |
| 1585 | 1376 | DataWrapper(BoundStatement wrapped, int size) { |
| @@ -1597,15 +1388,10 @@ | ||
| 1597 | 1388 | protected String getName(int i) { |
| 1598 | 1389 | return wrapped.statement.getVariables().getName(i); |
| 1599 | 1390 | } |
| 1600 | - } | |
| 1601 | 1391 | |
| 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; | |
| 1609 | 1395 | } |
| 1610 | 1396 | } |
| 1611 | 1397 | } |
modified driver-core/src/main/java/com/datastax/driver/core/CassandraTypeParser.java +14 −14
| @@ -72,7 +72,7 @@ | ||
| 72 | 72 | .put("org.apache.cassandra.db.marshal.ShortType", DataType.smallint()) |
| 73 | 73 | .build(); |
| 74 | 74 | |
| 75 | - static DataType parseOne(String className) { | |
| 75 | + static DataType parseOne(String className, ProtocolVersion protocolVersion, CodecRegistry codecRegistry) { | |
| 76 | 76 | boolean frozen = false; |
| 77 | 77 | if (isReversed(className)) { |
| 78 | 78 | // Just skip the ReversedType part, we don't care |
| @@ -86,14 +86,14 @@ | ||
| 86 | 86 | String next = parser.parseNextName(); |
| 87 | 87 | |
| 88 | 88 | 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); | |
| 90 | 90 | |
| 91 | 91 | 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); | |
| 93 | 93 | |
| 94 | 94 | if (next.startsWith(MAP_TYPE)) { |
| 95 | 95 | 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); | |
| 97 | 97 | } |
| 98 | 98 | |
| 99 | 99 | if (frozen) |
| @@ -105,22 +105,22 @@ | ||
| 105 | 105 | |
| 106 | 106 | String keyspace = parser.readOne(); |
| 107 | 107 | 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); | |
| 109 | 109 | parser.skipBlankAndComma(); |
| 110 | 110 | Map<String, String> rawFields = parser.getNameAndTypeParameters(); |
| 111 | 111 | List<UserType.Field> fields = new ArrayList<UserType.Field>(rawFields.size()); |
| 112 | 112 | 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); | |
| 115 | 115 | } |
| 116 | 116 | |
| 117 | 117 | if (isTupleType(next)) { |
| 118 | 118 | List<String> rawTypes = parser.getTypeParameters(); |
| 119 | 119 | List<DataType> types = new ArrayList<DataType>(rawTypes.size()); |
| 120 | 120 | for (String rawType : rawTypes) { |
| 121 | - types.add(parseOne(rawType)); | |
| 121 | + types.add(parseOne(rawType, protocolVersion, codecRegistry)); | |
| 122 | 122 | } |
| 123 | - return new TupleType(types); | |
| 123 | + return new TupleType(types, protocolVersion, codecRegistry); | |
| 124 | 124 | } |
| 125 | 125 | |
| 126 | 126 | DataType type = cassTypeToDataType.get(next); |
| @@ -161,12 +161,12 @@ | ||
| 161 | 161 | return className.startsWith(COLLECTION_TYPE); |
| 162 | 162 | } |
| 163 | 163 | |
| 164 | - static ParseResult parseWithComposite(String className) { | |
| 164 | + static ParseResult parseWithComposite(String className, ProtocolVersion protocolVersion, CodecRegistry codecRegistry) { | |
| 165 | 165 | Parser parser = new Parser(className, 0); |
| 166 | 166 | |
| 167 | 167 | String next = parser.parseNextName(); |
| 168 | 168 | if (!isComposite(next)) |
| 169 | - return new ParseResult(parseOne(className), isReversed(next)); | |
| 169 | + return new ParseResult(parseOne(className, protocolVersion, codecRegistry), isReversed(next)); | |
| 170 | 170 | |
| 171 | 171 | List<String> subClassNames = parser.getTypeParameters(); |
| 172 | 172 | int count = subClassNames.size(); |
| @@ -178,13 +178,13 @@ | ||
| 178 | 178 | collectionParser.parseNextName(); // skips columnToCollectionType |
| 179 | 179 | Map<String, String> params = collectionParser.getCollectionsParameters(); |
| 180 | 180 | 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)); | |
| 182 | 182 | } |
| 183 | 183 | |
| 184 | 184 | List<DataType> types = new ArrayList<DataType>(count); |
| 185 | 185 | List<Boolean> reversed = new ArrayList<Boolean>(count); |
| 186 | 186 | for (int i = 0; i < count; i++) { |
| 187 | - types.add(parseOne(subClassNames.get(i))); | |
| 187 | + types.add(parseOne(subClassNames.get(i), protocolVersion, codecRegistry)); | |
| 188 | 188 | reversed.add(isReversed(subClassNames.get(i))); |
| 189 | 189 | } |
| 190 | 190 | |
| @@ -319,7 +319,7 @@ | ||
| 319 | 319 | String bbHex = readNextIdentifier(); |
| 320 | 320 | String name = null; |
| 321 | 321 | try { |
| 322 | - name = TypeCodec.StringCodec.utf8Instance.deserialize(Bytes.fromHexString("0x" + bbHex)); | |
| 322 | + name = TypeCodec.VarcharCodec.instance.deserialize(Bytes.fromHexString("0x" + bbHex), ProtocolVersion.NEWEST_SUPPORTED); | |
| 323 | 323 | } catch (NumberFormatException e) { |
| 324 | 324 | throwSyntaxError(e.getMessage()); |
| 325 | 325 | } |
modified driver-core/src/main/java/com/datastax/driver/core/Cluster.java +35 −38
| @@ -26,7 +26,6 @@ | ||
| 26 | 26 | import java.util.concurrent.atomic.AtomicReference; |
| 27 | 27 | |
| 28 | 28 | import com.google.common.annotations.VisibleForTesting; |
| 29 | -import com.google.common.base.Objects; | |
| 30 | 29 | import com.google.common.base.Predicates; |
| 31 | 30 | import com.google.common.collect.*; |
| 32 | 31 | import com.google.common.util.concurrent.*; |
| @@ -575,27 +574,16 @@ | ||
| 575 | 574 | private ProtocolVersion protocolVersion; |
| 576 | 575 | private AuthProvider authProvider = AuthProvider.NONE; |
| 577 | 576 | |
| 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(); | |
| 584 | 579 | |
| 585 | 580 | private ProtocolOptions.Compression compression = ProtocolOptions.Compression.NONE; |
| 586 | 581 | private SSLOptions sslOptions = null; |
| 587 | 582 | private boolean metricsEnabled = true; |
| 588 | 583 | private boolean jmxEnabled = true; |
| 589 | 584 | |
| 590 | - private PoolingOptions poolingOptions; | |
| 591 | - private SocketOptions socketOptions; | |
| 592 | - private QueryOptions queryOptions; | |
| 593 | - | |
| 594 | - private NettyOptions nettyOptions = NettyOptions.DEFAULT_INSTANCE; | |
| 595 | - | |
| 596 | 585 | private Collection<Host.StateListener> listeners; |
| 597 | 586 | |
| 598 | - | |
| 599 | 587 | @Override |
| 600 | 588 | public String getClusterName() { |
| 601 | 589 | return clusterName; |
| @@ -852,7 +840,7 @@ | ||
| 852 | 840 | * @return this Builder. |
| 853 | 841 | */ |
| 854 | 842 | public Builder withLoadBalancingPolicy(LoadBalancingPolicy policy) { |
| 855 | - this.loadBalancingPolicy = policy; | |
| 843 | + policiesBuilder.withLoadBalancingPolicy(policy); | |
| 856 | 844 | return this; |
| 857 | 845 | } |
| 858 | 846 | |
| @@ -866,7 +854,7 @@ | ||
| 866 | 854 | * @return this Builder. |
| 867 | 855 | */ |
| 868 | 856 | public Builder withReconnectionPolicy(ReconnectionPolicy policy) { |
| 869 | - this.reconnectionPolicy = policy; | |
| 857 | + policiesBuilder.withReconnectionPolicy(policy); | |
| 870 | 858 | return this; |
| 871 | 859 | } |
| 872 | 860 | |
| @@ -880,7 +868,7 @@ | ||
| 880 | 868 | * @return this Builder. |
| 881 | 869 | */ |
| 882 | 870 | public Builder withRetryPolicy(RetryPolicy policy) { |
| 883 | - this.retryPolicy = policy; | |
| 871 | + policiesBuilder.withRetryPolicy(policy); | |
| 884 | 872 | return this; |
| 885 | 873 | } |
| 886 | 874 | |
| @@ -895,7 +883,7 @@ | ||
| 895 | 883 | * @return this Builder. |
| 896 | 884 | */ |
| 897 | 885 | public Builder withAddressTranslator(AddressTranslator translator) { |
| 898 | - this.addressTranslator = translator; | |
| 886 | + policiesBuilder.withAddressTranslator(translator); | |
| 899 | 887 | return this; |
| 900 | 888 | } |
| 901 | 889 | |
| @@ -915,7 +903,7 @@ | ||
| 915 | 903 | * @return this Builder. |
| 916 | 904 | */ |
| 917 | 905 | public Builder withTimestampGenerator(TimestampGenerator timestampGenerator) { |
| 918 | - this.timestampGenerator = timestampGenerator; | |
| 906 | + policiesBuilder.withTimestampGenerator(timestampGenerator); | |
| 919 | 907 | return this; |
| 920 | 908 | } |
| 921 | 909 | |
| @@ -929,7 +917,22 @@ | ||
| 929 | 917 | * @return this Builder. |
| 930 | 918 | */ |
| 931 | 919 | 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); | |
| 933 | 936 | return this; |
| 934 | 937 | } |
| 935 | 938 | |
| @@ -1059,7 +1062,7 @@ | ||
| 1059 | 1062 | * @return this builder. |
| 1060 | 1063 | */ |
| 1061 | 1064 | public Builder withPoolingOptions(PoolingOptions options) { |
| 1062 | - this.poolingOptions = options; | |
| 1065 | + configurationBuilder.withPoolingOptions(options); | |
| 1063 | 1066 | return this; |
| 1064 | 1067 | } |
| 1065 | 1068 | |
| @@ -1073,7 +1076,7 @@ | ||
| 1073 | 1076 | * @return this builder. |
| 1074 | 1077 | */ |
| 1075 | 1078 | public Builder withSocketOptions(SocketOptions options) { |
| 1076 | - this.socketOptions = options; | |
| 1079 | + configurationBuilder.withSocketOptions(options); | |
| 1077 | 1080 | return this; |
| 1078 | 1081 | } |
| 1079 | 1082 | |
| @@ -1087,7 +1090,7 @@ | ||
| 1087 | 1090 | * @return this builder. |
| 1088 | 1091 | */ |
| 1089 | 1092 | public Builder withQueryOptions(QueryOptions options) { |
| 1090 | - this.queryOptions = options; | |
| 1093 | + configurationBuilder.withQueryOptions(options); | |
| 1091 | 1094 | return this; |
| 1092 | 1095 | } |
| 1093 | 1096 | |
| @@ -1101,7 +1104,7 @@ | ||
| 1101 | 1104 | * @return this builder. |
| 1102 | 1105 | */ |
| 1103 | 1106 | public Builder withNettyOptions(NettyOptions nettyOptions) { |
| 1104 | - this.nettyOptions = nettyOptions; | |
| 1107 | + configurationBuilder.withNettyOptions(nettyOptions); | |
| 1105 | 1108 | return this; |
| 1106 | 1109 | } |
| 1107 | 1110 | |
| @@ -1116,21 +1119,15 @@ | ||
| 1116 | 1119 | */ |
| 1117 | 1120 | @Override |
| 1118 | 1121 | 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()) | |
| 1126 | 1130 | .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); | |
| 1134 | 1131 | } |
| 1135 | 1132 | |
| 1136 | 1133 | @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<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 @@ | ||
| 17 | 17 | |
| 18 | 18 | import java.util.*; |
| 19 | 19 | |
| 20 | -import com.datastax.driver.core.exceptions.InvalidTypeException; | |
| 21 | - | |
| 22 | 20 | /** |
| 23 | 21 | * Metadata describing the columns returned in a {@link ResultSet} or a |
| 24 | 22 | * {@link PreparedStatement}. |
| @@ -61,6 +59,7 @@ | ||
| 61 | 59 | |
| 62 | 60 | private final Definition[] byIdx; |
| 63 | 61 | private final Map<String, int[]> byName; |
| 62 | + private volatile CodecRegistry codecRegistry; | |
| 64 | 63 | |
| 65 | 64 | ColumnDefinitions(Definition[] defs) { |
| 66 | 65 | |
| @@ -279,32 +278,34 @@ | ||
| 279 | 278 | return getAllIdx(name)[0]; |
| 280 | 279 | } |
| 281 | 280 | |
| 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; | |
| 300 | 285 | } |
| 301 | 286 | |
| 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 | + } | |
| 308 | 309 | } |
| 309 | 310 | |
| 310 | 311 | /** |
modified driver-core/src/main/java/com/datastax/driver/core/ColumnMetadata.java +4 −4
| @@ -190,7 +190,7 @@ | ||
| 190 | 190 | */ |
| 191 | 191 | return !isKeys() |
| 192 | 192 | && !isEntries() |
| 193 | - && column.getType().isCollection() | |
| 193 | + && column.getType() instanceof DataType.CollectionType | |
| 194 | 194 | && column.getType().isFrozen(); |
| 195 | 195 | } |
| 196 | 196 | |
| @@ -299,6 +299,7 @@ | ||
| 299 | 299 | // Temporary class that is used to make building the schema easier. Not meant to be |
| 300 | 300 | // exposed publicly at all. |
| 301 | 301 | static class Raw { |
| 302 | + | |
| 302 | 303 | public enum Kind { PARTITION_KEY, CLUSTERING_KEY, REGULAR, COMPACT_VALUE, STATIC } |
| 303 | 304 | |
| 304 | 305 | public final String name; |
| @@ -317,7 +318,7 @@ | ||
| 317 | 318 | this.isReversed = isReversed; |
| 318 | 319 | } |
| 319 | 320 | |
| 320 | - static Raw fromRow(Row row, VersionNumber version) { | |
| 321 | + static Raw fromRow(Row row, VersionNumber version, ProtocolVersion protocolVersion, CodecRegistry codecRegistry) { | |
| 321 | 322 | |
| 322 | 323 | String name = row.getString(COLUMN_NAME); |
| 323 | 324 | Kind kind = version.getMajor() < 2 || row.isNull(KIND) |
| @@ -326,8 +327,7 @@ | ||
| 326 | 327 | int componentIndex = row.isNull(COMPONENT_INDEX) ? 0 : row.getInt(COMPONENT_INDEX); |
| 327 | 328 | String validatorStr = row.getString(VALIDATOR); |
| 328 | 329 | boolean reversed = CassandraTypeParser.isReversed(validatorStr); |
| 329 | - DataType dataType = CassandraTypeParser.parseOne(validatorStr); | |
| 330 | - | |
| 330 | + DataType dataType = CassandraTypeParser.parseOne(validatorStr, protocolVersion, codecRegistry); | |
| 331 | 331 | Raw c = new Raw(name, kind, componentIndex, dataType, reversed); |
| 332 | 332 | |
| 333 | 333 | 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 @@ | ||
| 33 | 33 | */ |
| 34 | 34 | public class Configuration { |
| 35 | 35 | |
| 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 | + } | |
| 37 | 44 | |
| 45 | + private final Policies policies; | |
| 38 | 46 | private final ProtocolOptions protocolOptions; |
| 39 | 47 | private final PoolingOptions poolingOptions; |
| 40 | 48 | private final SocketOptions socketOptions; |
| 41 | 49 | private final MetricsOptions metricsOptions; |
| 42 | 50 | private final QueryOptions queryOptions; |
| 43 | 51 | private final NettyOptions nettyOptions; |
| 52 | + private final CodecRegistry codecRegistry; | |
| 44 | 53 | |
| 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, | |
| 70 | 55 | ProtocolOptions protocolOptions, |
| 71 | 56 | PoolingOptions poolingOptions, |
| 72 | 57 | SocketOptions socketOptions, |
| 73 | 58 | MetricsOptions metricsOptions, |
| 74 | 59 | QueryOptions queryOptions, |
| 75 | - NettyOptions nettyOptions) { | |
| 60 | + NettyOptions nettyOptions, | |
| 61 | + CodecRegistry codecRegistry) { | |
| 76 | 62 | this.policies = policies; |
| 77 | 63 | this.protocolOptions = protocolOptions; |
| 78 | 64 | this.poolingOptions = poolingOptions; |
| @@ -80,6 +66,7 @@ | ||
| 80 | 66 | this.metricsOptions = metricsOptions; |
| 81 | 67 | this.queryOptions = queryOptions; |
| 82 | 68 | this.nettyOptions = nettyOptions; |
| 69 | + this.codecRegistry = codecRegistry; | |
| 83 | 70 | } |
| 84 | 71 | |
| 85 | 72 | void register(Cluster.Manager manager) { |
| @@ -152,4 +139,125 @@ | ||
| 152 | 139 | public NettyOptions getNettyOptions() { |
| 153 | 140 | return nettyOptions; |
| 154 | 141 | } |
| 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 | + } | |
| 155 | 263 | } |
modified driver-core/src/main/java/com/datastax/driver/core/ControlConnection.java +4 −2
| @@ -38,6 +38,8 @@ | ||
| 38 | 38 | |
| 39 | 39 | private static final Logger logger = LoggerFactory.getLogger(ControlConnection.class); |
| 40 | 40 | |
| 41 | + private static final TypeCodec.ListCodec<String> LIST_OF_TEXT_CODEC = new TypeCodec.ListCodec<String>(TypeCodec.VarcharCodec.instance); | |
| 42 | + | |
| 41 | 43 | private static final InetAddress bindAllAddress; |
| 42 | 44 | static |
| 43 | 45 | { |
| @@ -335,9 +337,9 @@ | ||
| 335 | 337 | else if (targetType == TYPE) |
| 336 | 338 | whereClause += " AND type_name = '" + targetName + '\''; |
| 337 | 339 | 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); | |
| 339 | 341 | 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); | |
| 341 | 343 | } |
| 342 | 344 | |
| 343 | 345 | boolean isSchemaOrKeyspace = (targetType == null || targetType == KEYSPACE); |
modified driver-core/src/main/java/com/datastax/driver/core/DataType.java +116 −374
| @@ -15,10 +15,6 @@ | ||
| 15 | 15 | */ |
| 16 | 16 | package com.datastax.driver.core; |
| 17 | 17 | |
| 18 | -import java.math.BigDecimal; | |
| 19 | -import java.math.BigInteger; | |
| 20 | -import java.net.InetAddress; | |
| 21 | -import java.nio.ByteBuffer; | |
| 22 | 18 | import java.util.*; |
| 23 | 19 | |
| 24 | 20 | import com.google.common.base.Objects; |
| @@ -26,11 +22,9 @@ | ||
| 26 | 22 | import com.google.common.collect.ImmutableList; |
| 27 | 23 | import com.google.common.collect.ImmutableSet; |
| 28 | 24 | import com.google.common.collect.Sets; |
| 29 | -import com.google.common.reflect.TypeToken; | |
| 30 | 25 | import io.netty.buffer.ByteBuf; |
| 31 | 26 | |
| 32 | 27 | import com.datastax.driver.core.exceptions.DriverInternalError; |
| 33 | -import com.datastax.driver.core.exceptions.InvalidTypeException; | |
| 34 | 28 | |
| 35 | 29 | /** |
| 36 | 30 | * Data types supported by cassandra. |
| @@ -42,35 +36,44 @@ | ||
| 42 | 36 | */ |
| 43 | 37 | public enum Name { |
| 44 | 38 | |
| 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 | + ; | |
| 71 | 74 | |
| 72 | 75 | final int protocolId; |
| 73 | - final Class<?> javaType; | |
| 76 | + | |
| 74 | 77 | final ProtocolVersion minProtocolVersion; |
| 75 | 78 | |
| 76 | 79 | private static final Name[] nameToIds; |
| @@ -86,15 +89,12 @@ | ||
| 86 | 89 | } |
| 87 | 90 | } |
| 88 | 91 | |
| 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); | |
| 93 | 94 | } |
| 94 | 95 | |
| 95 | - private Name(int protocolId, Class<?> javaType, ProtocolVersion minProtocolVersion) { | |
| 96 | + private Name(int protocolId, ProtocolVersion minProtocolVersion) { | |
| 96 | 97 | this.protocolId = protocolId; |
| 97 | - this.javaType = javaType; | |
| 98 | 98 | this.minProtocolVersion = minProtocolVersion; |
| 99 | 99 | } |
| 100 | 100 | |
| @@ -106,59 +106,15 @@ | ||
| 106 | 106 | } |
| 107 | 107 | |
| 108 | 108 | /** |
| 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. | |
| 127 | 111 | * |
| 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. | |
| 159 | 115 | */ |
| 160 | - public Class<?> asJavaClass() { | |
| 161 | - return javaType; | |
| 116 | + public boolean isCompatibleWith(Name that) { | |
| 117 | + return this == that; | |
| 162 | 118 | } |
| 163 | 119 | |
| 164 | 120 | @Override |
| @@ -167,38 +123,53 @@ | ||
| 167 | 123 | } |
| 168 | 124 | } |
| 169 | 125 | |
| 170 | - protected final DataType.Name name; | |
| 171 | - | |
| 172 | 126 | private static final Map<Name, DataType> primitiveTypeMap = new EnumMap<Name, DataType>(Name.class); |
| 173 | 127 | 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)); | |
| 178 | 148 | } |
| 149 | + | |
| 179 | 150 | private static final Set<DataType> primitiveTypeSet = ImmutableSet.copyOf(primitiveTypeMap.values()); |
| 180 | 151 | |
| 181 | - static final DataType LIST_OF_TEXT = DataType.list(DataType.text()); | |
| 152 | + protected final DataType.Name name; | |
| 182 | 153 | |
| 183 | 154 | protected DataType(DataType.Name name) { |
| 184 | 155 | this.name = name; |
| 185 | 156 | } |
| 186 | 157 | |
| 187 | - static DataType decode(ByteBuf buffer) { | |
| 158 | + static DataType decode(ByteBuf buffer, ProtocolVersion protocolVersion, CodecRegistry codecRegistry) { | |
| 188 | 159 | Name name = Name.fromProtocolId(buffer.readUnsignedShort()); |
| 189 | 160 | switch (name) { |
| 190 | 161 | case CUSTOM: |
| 191 | 162 | String className = CBUtil.readString(buffer); |
| 192 | 163 | return CassandraTypeParser.isUserType(className) || CassandraTypeParser.isTupleType(className) |
| 193 | - ? CassandraTypeParser.parseOne(className) | |
| 164 | + ? CassandraTypeParser.parseOne(className, protocolVersion, codecRegistry) | |
| 194 | 165 | : custom(className); |
| 195 | 166 | case LIST: |
| 196 | - return list(decode(buffer)); | |
| 167 | + return list(decode(buffer, protocolVersion, codecRegistry)); | |
| 197 | 168 | case SET: |
| 198 | - return set(decode(buffer)); | |
| 169 | + return set(decode(buffer, protocolVersion, codecRegistry)); | |
| 199 | 170 | 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); | |
| 202 | 173 | return map(keys, values); |
| 203 | 174 | case UDT: |
| 204 | 175 | String keyspace = CBUtil.readString(buffer); |
| @@ -207,24 +178,22 @@ | ||
| 207 | 178 | List<UserType.Field> fields = new ArrayList<UserType.Field>(nFields); |
| 208 | 179 | for (int i = 0; i < nFields; i++) { |
| 209 | 180 | String fieldName = CBUtil.readString(buffer); |
| 210 | - DataType fieldType = decode(buffer); | |
| 181 | + DataType fieldType = decode(buffer, protocolVersion, codecRegistry); | |
| 211 | 182 | fields.add(new UserType.Field(fieldName, fieldType)); |
| 212 | 183 | } |
| 213 | - return new UserType(keyspace, type, fields); | |
| 184 | + return new UserType(keyspace, type, fields, protocolVersion, codecRegistry); | |
| 214 | 185 | case TUPLE: |
| 215 | 186 | nFields = buffer.readShort() & 0xffff; |
| 216 | 187 | List<DataType> types = new ArrayList<DataType>(nFields); |
| 217 | 188 | for (int i = 0; i < nFields; i++) { |
| 218 | - types.add(decode(buffer)); | |
| 189 | + types.add(decode(buffer, protocolVersion, codecRegistry)); | |
| 219 | 190 | } |
| 220 | - return new TupleType(types); | |
| 191 | + return new TupleType(types, protocolVersion, codecRegistry); | |
| 221 | 192 | default: |
| 222 | 193 | return primitiveTypeMap.get(name); |
| 223 | 194 | } |
| 224 | 195 | } |
| 225 | 196 | |
| 226 | - abstract TypeCodec<Object> codec(ProtocolVersion protocolVersion); | |
| 227 | - | |
| 228 | 197 | /** |
| 229 | 198 | * Returns the ASCII type. |
| 230 | 199 | * |
| @@ -412,8 +381,8 @@ | ||
| 412 | 381 | * @param frozen whether the list is frozen. |
| 413 | 382 | * @return the type of lists of {@code elementType} elements. |
| 414 | 383 | */ |
| 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); | |
| 417 | 386 | } |
| 418 | 387 | |
| 419 | 388 | /** |
| @@ -424,7 +393,7 @@ | ||
| 424 | 393 | * @param elementType the type of the list elements. |
| 425 | 394 | * @return the type of "not frozen" lists of {@code elementType} elements. |
| 426 | 395 | */ |
| 427 | - public static DataType list(DataType elementType) { | |
| 396 | + public static CollectionType list(DataType elementType) { | |
| 428 | 397 | return list(elementType, false); |
| 429 | 398 | } |
| 430 | 399 | |
| @@ -436,7 +405,7 @@ | ||
| 436 | 405 | * @param elementType the type of the list elements. |
| 437 | 406 | * @return the type of frozen lists of {@code elementType} elements. |
| 438 | 407 | */ |
| 439 | - public static DataType frozenList(DataType elementType) { | |
| 408 | + public static CollectionType frozenList(DataType elementType) { | |
| 440 | 409 | return list(elementType, true); |
| 441 | 410 | } |
| 442 | 411 | |
| @@ -447,8 +416,8 @@ | ||
| 447 | 416 | * @param frozen whether the set is frozen. |
| 448 | 417 | * @return the type of sets of {@code elementType} elements. |
| 449 | 418 | */ |
| 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); | |
| 452 | 421 | } |
| 453 | 422 | |
| 454 | 423 | /** |
| @@ -459,7 +428,7 @@ | ||
| 459 | 428 | * @param elementType the type of the set elements. |
| 460 | 429 | * @return the type of "not frozen" sets of {@code elementType} elements. |
| 461 | 430 | */ |
| 462 | - public static DataType set(DataType elementType) { | |
| 431 | + public static CollectionType set(DataType elementType) { | |
| 463 | 432 | return set(elementType, false); |
| 464 | 433 | } |
| 465 | 434 | |
| @@ -471,7 +440,7 @@ | ||
| 471 | 440 | * @param elementType the type of the set elements. |
| 472 | 441 | * @return the type of frozen sets of {@code elementType} elements. |
| 473 | 442 | */ |
| 474 | - public static DataType frozenSet(DataType elementType) { | |
| 443 | + public static CollectionType frozenSet(DataType elementType) { | |
| 475 | 444 | return set(elementType, true); |
| 476 | 445 | } |
| 477 | 446 | |
| @@ -483,8 +452,8 @@ | ||
| 483 | 452 | * @param frozen whether the map is frozen. |
| 484 | 453 | * @return the type of maps of {@code keyType} to {@code valueType} elements. |
| 485 | 454 | */ |
| 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); | |
| 488 | 457 | } |
| 489 | 458 | |
| 490 | 459 | /** |
| @@ -496,7 +465,7 @@ | ||
| 496 | 465 | * @param valueType the type of the map values. |
| 497 | 466 | * @return the type of "not frozen" maps of {@code keyType} to {@code valueType} elements. |
| 498 | 467 | */ |
| 499 | - public static DataType map(DataType keyType, DataType valueType) { | |
| 468 | + public static CollectionType map(DataType keyType, DataType valueType) { | |
| 500 | 469 | return map(keyType, valueType, false); |
| 501 | 470 | } |
| 502 | 471 | |
| @@ -509,7 +478,7 @@ | ||
| 509 | 478 | * @param valueType the type of the map values. |
| 510 | 479 | * @return the type of frozen maps of {@code keyType} to {@code valueType} elements. |
| 511 | 480 | */ |
| 512 | - public static DataType frozenMap(DataType keyType, DataType valueType) { | |
| 481 | + public static CollectionType frozenMap(DataType keyType, DataType valueType) { | |
| 513 | 482 | return map(keyType, valueType, true); |
| 514 | 483 | } |
| 515 | 484 | |
| @@ -518,9 +487,7 @@ | ||
| 518 | 487 | * <p> |
| 519 | 488 | * A custom type is defined by the name of the class used on the Cassandra |
| 520 | 489 | * 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. | |
| 524 | 491 | * <p> |
| 525 | 492 | * The use of custom types is rarely useful and is thus not encouraged. |
| 526 | 493 | * |
| @@ -530,7 +497,7 @@ | ||
| 530 | 497 | public static DataType custom(String typeClassName) { |
| 531 | 498 | if (typeClassName == null) |
| 532 | 499 | throw new NullPointerException(); |
| 533 | - return new DataType.Custom(Name.CUSTOM, typeClassName); | |
| 500 | + return new DataType.CustomType(Name.CUSTOM, typeClassName); | |
| 534 | 501 | } |
| 535 | 502 | |
| 536 | 503 | /** |
| @@ -552,6 +519,16 @@ | ||
| 552 | 519 | */ |
| 553 | 520 | public abstract boolean isFrozen(); |
| 554 | 521 | |
| 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 | + | |
| 555 | 532 | /** |
| 556 | 533 | * Returns the type arguments of this type. |
| 557 | 534 | * <p> |
| @@ -570,73 +547,7 @@ | ||
| 570 | 547 | * @return an immutable list containing the type arguments of this type. |
| 571 | 548 | */ |
| 572 | 549 | 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(); | |
| 640 | 551 | } |
| 641 | 552 | |
| 642 | 553 | /** |
| @@ -670,114 +581,9 @@ | ||
| 670 | 581 | }); |
| 671 | 582 | } |
| 672 | 583 | |
| 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 { | |
| 778 | 585 | |
| 779 | - private static class Native extends DataType { | |
| 780 | - private Native(DataType.Name name) { | |
| 586 | + private NativeType(DataType.Name name) { | |
| 781 | 587 | super(name); |
| 782 | 588 | } |
| 783 | 589 | |
| @@ -786,16 +592,6 @@ | ||
| 786 | 592 | return false; |
| 787 | 593 | } |
| 788 | 594 | |
| 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 | - | |
| 799 | 595 | @Override |
| 800 | 596 | public final int hashCode() { |
| 801 | 597 | return (name == Name.TEXT) |
| @@ -805,13 +601,11 @@ | ||
| 805 | 601 | |
| 806 | 602 | @Override |
| 807 | 603 | public final boolean equals(Object o) { |
| 808 | - if(!(o instanceof DataType.Native)) | |
| 604 | + if(!(o instanceof DataType.NativeType)) | |
| 809 | 605 | return false; |
| 810 | 606 | |
| 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); | |
| 815 | 609 | } |
| 816 | 610 | |
| 817 | 611 | @Override |
| @@ -820,12 +614,12 @@ | ||
| 820 | 614 | } |
| 821 | 615 | } |
| 822 | 616 | |
| 823 | - private static class Collection extends DataType { | |
| 617 | + public static class CollectionType extends DataType { | |
| 824 | 618 | |
| 825 | 619 | private final List<DataType> typeArguments; |
| 826 | 620 | private boolean frozen; |
| 827 | 621 | |
| 828 | - private Collection(DataType.Name name, List<DataType> typeArguments, boolean frozen) { | |
| 622 | + private CollectionType(DataType.Name name, List<DataType> typeArguments, boolean frozen) { | |
| 829 | 623 | super(name); |
| 830 | 624 | this.typeArguments = typeArguments; |
| 831 | 625 | this.frozen = frozen; |
| @@ -836,36 +630,6 @@ | ||
| 836 | 630 | return frozen; |
| 837 | 631 | } |
| 838 | 632 | |
| 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 | - | |
| 869 | 633 | @Override |
| 870 | 634 | public List<DataType> getTypeArguments() { |
| 871 | 635 | return typeArguments; |
| @@ -878,10 +642,10 @@ | ||
| 878 | 642 | |
| 879 | 643 | @Override |
| 880 | 644 | public final boolean equals(Object o) { |
| 881 | - if(!(o instanceof DataType.Collection)) | |
| 645 | + if(!(o instanceof DataType.CollectionType)) | |
| 882 | 646 | return false; |
| 883 | 647 | |
| 884 | - DataType.Collection d = (DataType.Collection)o; | |
| 648 | + DataType.CollectionType d = (DataType.CollectionType)o; | |
| 885 | 649 | return name == d.name && typeArguments.equals(d.typeArguments); |
| 886 | 650 | } |
| 887 | 651 | |
| @@ -898,11 +662,11 @@ | ||
| 898 | 662 | } |
| 899 | 663 | } |
| 900 | 664 | |
| 901 | - private static class Custom extends DataType { | |
| 665 | + public static class CustomType extends DataType { | |
| 902 | 666 | |
| 903 | 667 | private final String customClassName; |
| 904 | 668 | |
| 905 | - private Custom(DataType.Name name, String className) { | |
| 669 | + private CustomType(DataType.Name name, String className) { | |
| 906 | 670 | super(name); |
| 907 | 671 | this.customClassName = className; |
| 908 | 672 | } |
| @@ -912,32 +676,10 @@ | ||
| 912 | 676 | return false; |
| 913 | 677 | } |
| 914 | 678 | |
| 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 | |
| 927 | 679 | public String getCustomTypeClassName() { |
| 928 | 680 | return customClassName; |
| 929 | 681 | } |
| 930 | 682 | |
| 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 | - | |
| 941 | 683 | @Override |
| 942 | 684 | public final int hashCode() { |
| 943 | 685 | return Arrays.hashCode(new Object[]{ name, customClassName }); |
| @@ -945,10 +687,10 @@ | ||
| 945 | 687 | |
| 946 | 688 | @Override |
| 947 | 689 | public final boolean equals(Object o) { |
| 948 | - if(!(o instanceof DataType.Custom)) | |
| 690 | + if(!(o instanceof DataType.CustomType)) | |
| 949 | 691 | return false; |
| 950 | 692 | |
| 951 | - DataType.Custom d = (DataType.Custom)o; | |
| 693 | + DataType.CustomType d = (DataType.CustomType)o; | |
| 952 | 694 | return name == d.name && Objects.equal(customClassName, d.customClassName); |
| 953 | 695 | } |
| 954 | 696 |
modified driver-core/src/main/java/com/datastax/driver/core/DefaultPreparedStatement.java +19 −7
| @@ -32,6 +32,7 @@ | ||
| 32 | 32 | final String query; |
| 33 | 33 | final String queryKeyspace; |
| 34 | 34 | final Map<String, ByteBuffer> incomingPayload; |
| 35 | + final Cluster cluster; | |
| 35 | 36 | |
| 36 | 37 | volatile ByteBuffer routingKey; |
| 37 | 38 | |
| @@ -41,28 +42,34 @@ | ||
| 41 | 42 | volatile RetryPolicy retryPolicy; |
| 42 | 43 | volatile ImmutableMap<String, ByteBuffer> outgoingPayload; |
| 43 | 44 | |
| 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) { | |
| 45 | 46 | this.preparedId = id; |
| 46 | 47 | this.query = query; |
| 47 | 48 | this.queryKeyspace = queryKeyspace; |
| 48 | 49 | this.incomingPayload = incomingPayload; |
| 50 | + this.cluster = cluster; | |
| 49 | 51 | } |
| 50 | 52 | |
| 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) { | |
| 52 | 54 | assert msg.metadata.columns != null; |
| 53 | 55 | |
| 54 | 56 | ColumnDefinitions defs = msg.metadata.columns; |
| 55 | 57 | |
| 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 | + } | |
| 58 | 65 | |
| 59 | 66 | int[] pkIndices = (protocolVersion.compareTo(V4) >= 0) |
| 60 | 67 | ? msg.metadata.pkIndices |
| 61 | - : computePkIndices(clusterMetadata, defs); | |
| 68 | + : computePkIndices(cluster.getMetadata(), defs); | |
| 62 | 69 | |
| 63 | 70 | PreparedId prepId = new PreparedId(msg.statementId, defs, msg.resultMetadata.columns, pkIndices, protocolVersion); |
| 64 | 71 | |
| 65 | - return new DefaultPreparedStatement(prepId, query, queryKeyspace, msg.getCustomPayload()); | |
| 72 | + return new DefaultPreparedStatement(prepId, query, queryKeyspace, msg.getCustomPayload(), cluster); | |
| 66 | 73 | } |
| 67 | 74 | |
| 68 | 75 | private static int[] computePkIndices(Metadata clusterMetadata, ColumnDefinitions boundColumns) { |
| @@ -129,7 +136,7 @@ | ||
| 129 | 136 | } |
| 130 | 137 | |
| 131 | 138 | public PreparedStatement setRoutingKey(ByteBuffer... routingKeyComponents) { |
| 132 | - this.routingKey = SimpleStatement.compose(routingKeyComponents); | |
| 139 | + this.routingKey = CodecUtils.compose(routingKeyComponents); | |
| 133 | 140 | return this; |
| 134 | 141 | } |
| 135 | 142 | |
| @@ -207,4 +214,9 @@ | ||
| 207 | 214 | this.outgoingPayload = payload == null ? null : ImmutableMap.copyOf(payload); |
| 208 | 215 | return this; |
| 209 | 216 | } |
| 217 | + | |
| 218 | + @Override | |
| 219 | + public CodecRegistry getCodecRegistry() { | |
| 220 | + return cluster.getConfiguration().getCodecRegistry(); | |
| 221 | + } | |
| 210 | 222 | } |
modified driver-core/src/main/java/com/datastax/driver/core/FunctionMetadata.java +5 −6
| @@ -20,7 +20,6 @@ | ||
| 20 | 20 | import java.util.List; |
| 21 | 21 | import java.util.Map; |
| 22 | 22 | |
| 23 | -import com.google.common.base.Joiner; | |
| 24 | 23 | import com.google.common.collect.ImmutableMap; |
| 25 | 24 | import org.slf4j.Logger; |
| 26 | 25 | import org.slf4j.LoggerFactory; |
| @@ -70,7 +69,7 @@ | ||
| 70 | 69 | // return_type text, |
| 71 | 70 | // PRIMARY KEY (keyspace_name, function_name, signature) |
| 72 | 71 | // ) 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) { | |
| 74 | 73 | String simpleName = row.getString("function_name"); |
| 75 | 74 | List<String> signature = row.getList("signature", String.class); |
| 76 | 75 | String fullName = Metadata.fullFunctionName(simpleName, signature); |
| @@ -83,12 +82,12 @@ | ||
| 83 | 82 | ksm.getName(), fullName)); |
| 84 | 83 | return null; |
| 85 | 84 | } |
| 86 | - Map<String, DataType> arguments = buildArguments(argumentNames, argumentTypes); | |
| 85 | + Map<String, DataType> arguments = buildArguments(argumentNames, argumentTypes, protocolVersion, codecRegistry); | |
| 87 | 86 | |
| 88 | 87 | String body = row.getString("body"); |
| 89 | 88 | boolean calledOnNullInput = row.getBool("called_on_null_input"); |
| 90 | 89 | 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); | |
| 92 | 91 | |
| 93 | 92 | FunctionMetadata function = new FunctionMetadata(ksm, fullName, simpleName, arguments, body, |
| 94 | 93 | calledOnNullInput, language, returnType); |
| @@ -97,14 +96,14 @@ | ||
| 97 | 96 | } |
| 98 | 97 | |
| 99 | 98 | // 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) { | |
| 101 | 100 | if (names.isEmpty()) |
| 102 | 101 | return Collections.emptyMap(); |
| 103 | 102 | |
| 104 | 103 | ImmutableMap.Builder<String, DataType> builder = ImmutableMap.builder(); |
| 105 | 104 | Iterator<String> iterTypes = types.iterator(); |
| 106 | 105 | for (String name : names) { |
| 107 | - DataType type = CassandraTypeParser.parseOne(iterTypes.next()); | |
| 106 | + DataType type = CassandraTypeParser.parseOne(iterTypes.next(), protocolVersion, codecRegistry); | |
| 108 | 107 | builder.put(name, type); |
| 109 | 108 | } |
| 110 | 109 | return builder.build(); |
modified driver-core/src/main/java/com/datastax/driver/core/GettableByIndexData.java +68 −0
| @@ -404,6 +404,10 @@ | ||
| 404 | 404 | |
| 405 | 405 | /** |
| 406 | 406 | * 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. | |
| 407 | 411 | * |
| 408 | 412 | * @param i the index to retrieve. |
| 409 | 413 | * @return the value of the {@code i}th value as the Java type matching its CQL type. |
| @@ -413,4 +417,68 @@ | ||
| 413 | 417 | * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object. |
| 414 | 418 | */ |
| 415 | 419 | 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 | + | |
| 416 | 484 | } |
modified driver-core/src/main/java/com/datastax/driver/core/GettableByNameData.java +66 −0
| @@ -403,6 +403,10 @@ | ||
| 403 | 403 | |
| 404 | 404 | /** |
| 405 | 405 | * 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. | |
| 406 | 410 | * |
| 407 | 411 | * @param name the name to retrieve. |
| 408 | 412 | * @return the value of the {@code i}th value as the Java type matching its CQL type. |
| @@ -412,4 +416,66 @@ | ||
| 412 | 416 | * @throws IllegalArgumentException if {@code name} is not a valid name for this object. |
| 413 | 417 | */ |
| 414 | 418 | 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 | + | |
| 415 | 481 | } |
modified driver-core/src/main/java/com/datastax/driver/core/Host.java +0 −1
| @@ -22,7 +22,6 @@ | ||
| 22 | 22 | import java.util.concurrent.locks.ReentrantLock; |
| 23 | 23 | |
| 24 | 24 | import com.google.common.collect.ImmutableList; |
| 25 | -import com.google.common.util.concurrent.Futures; | |
| 26 | 25 | import com.google.common.util.concurrent.ListenableFuture; |
| 27 | 26 | import org.slf4j.Logger; |
| 28 | 27 | import org.slf4j.LoggerFactory; |
modified driver-core/src/main/java/com/datastax/driver/core/KeyspaceMetadata.java +4 −4
| @@ -50,7 +50,7 @@ | ||
| 50 | 50 | this.strategy = ReplicationStrategy.create(replication); |
| 51 | 51 | } |
| 52 | 52 | |
| 53 | - static KeyspaceMetadata build(Row row, List<Row> udtRows) { | |
| 53 | + static KeyspaceMetadata build(Row row, List<Row> udtRows, ProtocolVersion protocolVersion, CodecRegistry codecRegistry) { | |
| 54 | 54 | |
| 55 | 55 | String name = row.getString(KS_NAME); |
| 56 | 56 | boolean durableWrites = row.getBool(DURABLE_WRITES); |
| @@ -64,7 +64,7 @@ | ||
| 64 | 64 | if (udtRows == null) |
| 65 | 65 | return ksm; |
| 66 | 66 | |
| 67 | - ksm.addUserTypes(udtRows); | |
| 67 | + ksm.addUserTypes(udtRows, protocolVersion, codecRegistry); | |
| 68 | 68 | |
| 69 | 69 | return ksm; |
| 70 | 70 | } |
| @@ -143,9 +143,9 @@ | ||
| 143 | 143 | return Collections.unmodifiableCollection(userTypes.values()); |
| 144 | 144 | } |
| 145 | 145 | |
| 146 | - void addUserTypes(List<Row> udtRows) { | |
| 146 | + void addUserTypes(List<Row> udtRows, ProtocolVersion protocolVersion, CodecRegistry codecRegistry) { | |
| 147 | 147 | for (Row r : udtRows) { |
| 148 | - UserType def = UserType.build(r); | |
| 148 | + UserType def = UserType.build(r, protocolVersion, codecRegistry); | |
| 149 | 149 | userTypes.put(def.getTypeName(), def); |
| 150 | 150 | } |
| 151 | 151 | } |
modified driver-core/src/main/java/com/datastax/driver/core/Metadata.java +22 −12
| @@ -82,7 +82,7 @@ | ||
| 82 | 82 | l = new HashMap<String, ColumnMetadata.Raw>(); |
| 83 | 83 | colsByCf.put(cfName, l); |
| 84 | 84 | } |
| 85 | - ColumnMetadata.Raw c = ColumnMetadata.Raw.fromRow(row, cassandraVersion); | |
| 85 | + ColumnMetadata.Raw c = ColumnMetadata.Raw.fromRow(row, cassandraVersion, cluster.protocolVersion(), cluster.configuration.getCodecRegistry()); | |
| 86 | 86 | l.put(c.name, c); |
| 87 | 87 | } |
| 88 | 88 | } |
| @@ -92,16 +92,16 @@ | ||
| 92 | 92 | Set<String> addedKs = new HashSet<String>(); |
| 93 | 93 | for (Row ksRow : ks) { |
| 94 | 94 | 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()); | |
| 96 | 96 | |
| 97 | 97 | if (cfDefs.containsKey(ksName)) { |
| 98 | 98 | buildTableMetadata(ksm, cfDefs.get(ksName), colsDefs.get(ksName), cassandraVersion); |
| 99 | 99 | } |
| 100 | 100 | if (functionDefs.containsKey(ksName)) { |
| 101 | - buildFunctionMetadata(ksm, functionDefs.get(ksName)); | |
| 101 | + buildFunctionMetadata(ksm, functionDefs.get(ksName), cluster.protocolVersion(), cluster.configuration.getCodecRegistry()); | |
| 102 | 102 | } |
| 103 | 103 | if (aggregateDefs.containsKey(ksName)) { |
| 104 | - buildAggregateMetadata(ksm, aggregateDefs.get(ksName), cluster.protocolVersion()); | |
| 104 | + buildAggregateMetadata(ksm, aggregateDefs.get(ksName), cluster.protocolVersion(), cluster.configuration.getCodecRegistry()); | |
| 105 | 105 | } |
| 106 | 106 | addedKs.add(ksName); |
| 107 | 107 | keyspaces.put(ksName, ksm); |
| @@ -135,15 +135,15 @@ | ||
| 135 | 135 | break; |
| 136 | 136 | case TYPE: |
| 137 | 137 | if (udtDefs.containsKey(targetKeyspace)) |
| 138 | - ksm.addUserTypes(udtDefs.get(targetKeyspace)); | |
| 138 | + ksm.addUserTypes(udtDefs.get(targetKeyspace), cluster.protocolVersion(), cluster.configuration.getCodecRegistry()); | |
| 139 | 139 | break; |
| 140 | 140 | case FUNCTION: |
| 141 | 141 | if (functionDefs.containsKey(targetKeyspace)) |
| 142 | - buildFunctionMetadata(ksm, functionDefs.get(targetKeyspace)); | |
| 142 | + buildFunctionMetadata(ksm, functionDefs.get(targetKeyspace), cluster.protocolVersion(), cluster.configuration.getCodecRegistry()); | |
| 143 | 143 | break; |
| 144 | 144 | case AGGREGATE: |
| 145 | 145 | if (functionDefs.containsKey(targetKeyspace)) |
| 146 | - buildAggregateMetadata(ksm, aggregateDefs.get(targetKeyspace), cluster.protocolVersion()); | |
| 146 | + buildAggregateMetadata(ksm, aggregateDefs.get(targetKeyspace), cluster.protocolVersion(), cluster.configuration.getCodecRegistry()); | |
| 147 | 147 | break; |
| 148 | 148 | default: |
| 149 | 149 | logger.warn("Unexpected element type to rebuild: {}", targetType); |
| @@ -192,7 +192,7 @@ | ||
| 192 | 192 | cols = Collections.<String, ColumnMetadata.Raw>emptyMap(); |
| 193 | 193 | } |
| 194 | 194 | } |
| 195 | - TableMetadata.build(ksm, cfRow, cols, cassandraVersion); | |
| 195 | + TableMetadata.build(ksm, cfRow, cols, cassandraVersion, cluster.protocolVersion(), cluster.configuration.getCodecRegistry()); | |
| 196 | 196 | } catch (RuntimeException e) { |
| 197 | 197 | // See ControlConnection#refreshSchema for why we'd rather not probably this further |
| 198 | 198 | logger.error(String.format("Error parsing schema for table %s.%s: " |
| @@ -202,14 +202,14 @@ | ||
| 202 | 202 | } |
| 203 | 203 | } |
| 204 | 204 | |
| 205 | - private void buildFunctionMetadata(KeyspaceMetadata ksm, List<Row> rows) { | |
| 205 | + private void buildFunctionMetadata(KeyspaceMetadata ksm, List<Row> rows, ProtocolVersion protocolVersion, CodecRegistry codecRegistry) { | |
| 206 | 206 | for (Row row : rows) |
| 207 | - FunctionMetadata.build(ksm, row); | |
| 207 | + FunctionMetadata.build(ksm, row, protocolVersion, codecRegistry); | |
| 208 | 208 | } |
| 209 | 209 | |
| 210 | - private void buildAggregateMetadata(KeyspaceMetadata ksm, List<Row> rows, ProtocolVersion protocolVersion) { | |
| 210 | + private void buildAggregateMetadata(KeyspaceMetadata ksm, List<Row> rows, ProtocolVersion protocolVersion, CodecRegistry codecRegistry) { | |
| 211 | 211 | for (Row row : rows) |
| 212 | - AggregateMetadata.build(ksm, row, protocolVersion); | |
| 212 | + AggregateMetadata.build(ksm, row, protocolVersion, codecRegistry); | |
| 213 | 213 | } |
| 214 | 214 | |
| 215 | 215 | |
| @@ -485,6 +485,16 @@ | ||
| 485 | 485 | return sb.toString(); |
| 486 | 486 | } |
| 487 | 487 | |
| 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 | + | |
| 488 | 498 | /** |
| 489 | 499 | * Builds a new {@link Token} from its string representation, according to the partitioner |
| 490 | 500 | * reported by the Cassandra nodes. |
modified driver-core/src/main/java/com/datastax/driver/core/PagingState.java +7 −7
| @@ -37,13 +37,13 @@ | ||
| 37 | 37 | */ |
| 38 | 38 | public class PagingState { |
| 39 | 39 | |
| 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; | |
| 43 | 43 | |
| 44 | 44 | PagingState(ByteBuffer pagingState, Statement statement, ProtocolVersion protocolVersion) { |
| 45 | 45 | this.pagingState = Bytes.getArray(pagingState); |
| 46 | - this.hash = hash(statement, protocolVersion); | |
| 46 | + this.hash = hash(statement); | |
| 47 | 47 | this.protocolVersion = protocolVersion; |
| 48 | 48 | } |
| 49 | 49 | |
| @@ -70,7 +70,7 @@ | ||
| 70 | 70 | : ProtocolVersion.V2; |
| 71 | 71 | } |
| 72 | 72 | |
| 73 | - private byte[] hash(Statement statement, ProtocolVersion protocolVersion) { | |
| 73 | + private byte[] hash(Statement statement) { | |
| 74 | 74 | byte[] digest; |
| 75 | 75 | ByteBuffer[] values; |
| 76 | 76 | MessageDigest md; |
| @@ -85,7 +85,7 @@ | ||
| 85 | 85 | //it is a RegularStatement since Batch statements are not allowed |
| 86 | 86 | RegularStatement rs = (RegularStatement)statement; |
| 87 | 87 | md.update(rs.getQueryString().getBytes()); |
| 88 | - values = rs.getValues(protocolVersion); | |
| 88 | + values = rs.getValues(); | |
| 89 | 89 | } |
| 90 | 90 | if (values != null) { |
| 91 | 91 | for (ByteBuffer value : values) { |
| @@ -102,7 +102,7 @@ | ||
| 102 | 102 | } |
| 103 | 103 | |
| 104 | 104 | boolean matches(Statement statement) { |
| 105 | - byte[] toTest = hash(statement, protocolVersion); | |
| 105 | + byte[] toTest = hash(statement); | |
| 106 | 106 | return Arrays.equals(toTest, this.hash); |
| 107 | 107 | } |
| 108 | 108 |
modified driver-core/src/main/java/com/datastax/driver/core/PreparedStatement.java +11 −1
| @@ -337,4 +337,14 @@ | ||
| 337 | 337 | */ |
| 338 | 338 | public PreparedStatement setOutgoingPayload(Map<String, ByteBuffer> payload); |
| 339 | 339 | |
| 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 @@ | ||
| 36 | 36 | /** |
| 37 | 37 | * The most recent protocol version supported by the driver. |
| 38 | 38 | */ |
| 39 | - public static ProtocolVersion NEWEST_SUPPORTED = V4; | |
| 39 | + public static final ProtocolVersion NEWEST_SUPPORTED = V4; | |
| 40 | 40 | |
| 41 | 41 | private final VersionNumber minCassandraVersion; |
| 42 | 42 | private final int asInt; |
modified driver-core/src/main/java/com/datastax/driver/core/QueryLogger.java +11 −7
| @@ -206,7 +206,7 @@ | ||
| 206 | 206 | protected volatile int maxLoggedParameters; |
| 207 | 207 | |
| 208 | 208 | /** |
| 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. | |
| 210 | 210 | */ |
| 211 | 211 | private QueryLogger(int maxQueryStringLength, int maxParameterValueLength, int maxLoggedParameters) { |
| 212 | 212 | this.maxQueryStringLength = maxQueryStringLength; |
| @@ -725,6 +725,8 @@ | ||
| 725 | 725 | valueStr = "NULL"; |
| 726 | 726 | } else { |
| 727 | 727 | DataType type = definition.getType(); |
| 728 | + CodecRegistry codecRegistry = cluster.getConfiguration().getCodecRegistry(); | |
| 729 | + TypeCodec<Object> codec = codecRegistry.codecFor(type); | |
| 728 | 730 | int maxParameterValueLength = this.maxParameterValueLength; |
| 729 | 731 | if (type.equals(DataType.blob()) && maxParameterValueLength != -1) { |
| 730 | 732 | // prevent large blobs from being converted to strings |
| @@ -733,14 +735,14 @@ | ||
| 733 | 735 | if (bufferTooLarge) { |
| 734 | 736 | raw = (ByteBuffer)raw.duplicate().limit(maxBufferLength); |
| 735 | 737 | } |
| 736 | - Object value = type.deserialize(raw, protocolVersion()); | |
| 737 | - valueStr = type.format(value); | |
| 738 | + Object value = codec.deserialize(raw, protocolVersion()); | |
| 739 | + valueStr = codec.format(value); | |
| 738 | 740 | if (bufferTooLarge) { |
| 739 | 741 | valueStr = valueStr + TRUNCATED_OUTPUT; |
| 740 | 742 | } |
| 741 | 743 | } 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); | |
| 744 | 746 | if (maxParameterValueLength != -1 && valueStr.length() > maxParameterValueLength) { |
| 745 | 747 | valueStr = valueStr.substring(0, maxParameterValueLength) + TRUNCATED_OUTPUT; |
| 746 | 748 | } |
| @@ -766,7 +768,9 @@ | ||
| 766 | 768 | statement = ((StatementWrapper)statement).getWrappedStatement(); |
| 767 | 769 | |
| 768 | 770 | 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); | |
| 770 | 774 | } else if (statement instanceof BoundStatement) { |
| 771 | 775 | remaining = append(((BoundStatement)statement).preparedStatement().getQueryString().trim(), buffer, remaining); |
| 772 | 776 | } else if (statement instanceof BatchStatement) { |
| @@ -813,4 +817,4 @@ | ||
| 813 | 817 | return remaining; |
| 814 | 818 | } |
| 815 | 819 | |
| 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 @@ | ||
| 17 | 17 | |
| 18 | 18 | import java.nio.ByteBuffer; |
| 19 | 19 | |
| 20 | +import com.datastax.driver.core.exceptions.InvalidTypeException; | |
| 21 | + | |
| 20 | 22 | /** |
| 21 | 23 | * A regular (non-prepared and non batched) CQL statement. |
| 22 | 24 | * <p> |
| @@ -49,14 +51,11 @@ | ||
| 49 | 51 | * 1 through {@link Cluster.Builder#withProtocolVersion} or you use |
| 50 | 52 | * Cassandra 1.2). |
| 51 | 53 | * |
| 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...) | |
| 58 | 57 | */ |
| 59 | - public abstract ByteBuffer[] getValues(ProtocolVersion protocolVersion); | |
| 58 | + public abstract ByteBuffer[] getValues(); | |
| 60 | 59 | |
| 61 | 60 | /** |
| 62 | 61 | * 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 @@ | ||
| 19 | 19 | import java.nio.ByteBuffer; |
| 20 | 20 | import java.util.*; |
| 21 | 21 | |
| 22 | -import com.google.common.collect.ImmutableList; | |
| 23 | 22 | import io.netty.buffer.ByteBuf; |
| 24 | 23 | |
| 25 | 24 | import com.datastax.driver.core.Responses.Result.Rows.Metadata; |
| @@ -348,11 +347,11 @@ | ||
| 348 | 347 | this.pkIndices = pkIndices; |
| 349 | 348 | } |
| 350 | 349 | |
| 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); | |
| 353 | 352 | } |
| 354 | 353 | |
| 355 | - public static Metadata decode(ByteBuf body, boolean withPkIndices) { | |
| 354 | + public static Metadata decode(ByteBuf body, boolean withPkIndices, ProtocolVersion protocolVersion) { | |
| 356 | 355 | |
| 357 | 356 | // flags & column count |
| 358 | 357 | EnumSet<Flag> flags = Flag.deserialize(body.readInt()); |
| @@ -388,7 +387,9 @@ | ||
| 388 | 387 | String ksName = globalTablesSpec ? globalKsName : CBUtil.readString(body); |
| 389 | 388 | String cfName = globalTablesSpec ? globalCfName : CBUtil.readString(body); |
| 390 | 389 | 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); | |
| 392 | 393 | defs[i] = new ColumnDefinitions.Definition(ksName, cfName, name, type); |
| 393 | 394 | } |
| 394 | 395 | |
| @@ -416,7 +417,7 @@ | ||
| 416 | 417 | public static final Message.Decoder<Result> subcodec = new Message.Decoder<Result>() { |
| 417 | 418 | public Result decode(ByteBuf body, ProtocolVersion version) { |
| 418 | 419 | |
| 419 | - Metadata metadata = Metadata.decode(body); | |
| 420 | + Metadata metadata = Metadata.decode(body, version); | |
| 420 | 421 | |
| 421 | 422 | int rowCount = body.readInt(); |
| 422 | 423 | int columnCount = metadata.columnCount; |
| @@ -455,11 +456,12 @@ | ||
| 455 | 456 | sb.append(" | null"); |
| 456 | 457 | } else { |
| 457 | 458 | 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(" "); | |
| 462 | 462 | } |
| 463 | + // cannot deserialize without the right CodecRegistry instance | |
| 464 | + sb.append(Bytes.toHexString(v)); | |
| 463 | 465 | } |
| 464 | 466 | } |
| 465 | 467 | sb.append('\n'); |
| @@ -475,7 +477,7 @@ | ||
| 475 | 477 | public Result decode(ByteBuf body, ProtocolVersion version) { |
| 476 | 478 | MD5Digest id = MD5Digest.wrap(CBUtil.readBytes(body)); |
| 477 | 479 | 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); | |
| 479 | 481 | Rows.Metadata resultMetadata = decodeResultMetadata(body, version); |
| 480 | 482 | return new Prepared(id, metadata, resultMetadata); |
| 481 | 483 | } |
| @@ -487,7 +489,7 @@ | ||
| 487 | 489 | case V2: |
| 488 | 490 | case V3: |
| 489 | 491 | case V4: |
| 490 | - return Rows.Metadata.decode(body); | |
| 492 | + return Rows.Metadata.decode(body, version); | |
| 491 | 493 | default: |
| 492 | 494 | throw version.unsupported(); |
| 493 | 495 | } |
modified driver-core/src/main/java/com/datastax/driver/core/Session.java +64 −2
| @@ -110,7 +110,7 @@ | ||
| 110 | 110 | * |
| 111 | 111 | * @param query the CQL query to execute. |
| 112 | 112 | * @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. | |
| 114 | 114 | * @return the result of the query. That result will never be null but can |
| 115 | 115 | * be empty (and will be for any non SELECT query). |
| 116 | 116 | * |
| @@ -172,7 +172,7 @@ | ||
| 172 | 172 | * |
| 173 | 173 | * @param query the CQL query to execute. |
| 174 | 174 | * @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. | |
| 176 | 176 | * @return a future on the result of the query. |
| 177 | 177 | * |
| 178 | 178 | * @throws UnsupportedFeatureException if version 1 of the protocol |
| @@ -181,6 +181,68 @@ | ||
| 181 | 181 | */ |
| 182 | 182 | public ResultSetFuture executeAsync(String query, Object... values); |
| 183 | 183 | |
| 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 | + | |
| 184 | 246 | /** |
| 185 | 247 | * Executes the provided query asynchronously. |
| 186 | 248 | * |
modified driver-core/src/main/java/com/datastax/driver/core/SessionManager.java +6 −3
| @@ -147,7 +147,7 @@ | ||
| 147 | 147 | switch (rm.kind) { |
| 148 | 148 | case PREPARED: |
| 149 | 149 | 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); | |
| 151 | 151 | stmt = cluster.manager.addPrepared(stmt); |
| 152 | 152 | try { |
| 153 | 153 | // All Sessions are connected to the same nodes so it's enough to prepare only the nodes of this session. |
| @@ -499,6 +499,7 @@ | ||
| 499 | 499 | statement = ((StatementWrapper)statement).getWrappedStatement(); |
| 500 | 500 | |
| 501 | 501 | Message.Request request; |
| 502 | + | |
| 502 | 503 | if (statement instanceof RegularStatement) { |
| 503 | 504 | RegularStatement rs = (RegularStatement)statement; |
| 504 | 505 | |
| @@ -508,13 +509,15 @@ | ||
| 508 | 509 | if (version == ProtocolVersion.V1 && rs instanceof com.datastax.driver.core.querybuilder.BuiltStatement) |
| 509 | 510 | ((com.datastax.driver.core.querybuilder.BuiltStatement)rs).setForceNoValues(true); |
| 510 | 511 | |
| 511 | - ByteBuffer[] rawValues = rs.getValues(version); | |
| 512 | + ByteBuffer[] rawValues = rs.getValues(); | |
| 512 | 513 | |
| 513 | 514 | if (version == ProtocolVersion.V1 && rawValues != null) |
| 514 | 515 | throw new UnsupportedFeatureException(version, "Binary values are not supported"); |
| 515 | 516 | |
| 516 | 517 | List<ByteBuffer> values = rawValues == null ? Collections.<ByteBuffer>emptyList() : Arrays.asList(rawValues); |
| 518 | + | |
| 517 | 519 | String qString = rs.getQueryString(); |
| 520 | + | |
| 518 | 521 | Requests.QueryProtocolOptions options = new Requests.QueryProtocolOptions(consistency, values, false, |
| 519 | 522 | fetchSize, usedPagingState, serialConsistency, defaultTimestamp); |
| 520 | 523 | request = new Requests.Query(qString, options, statement.isTracing()); |
| @@ -540,7 +543,7 @@ | ||
| 540 | 543 | BatchStatement bs = (BatchStatement)statement; |
| 541 | 544 | if (version.compareTo(ProtocolVersion.V4) < 0) |
| 542 | 545 | bs.ensureAllSet(); |
| 543 | - BatchStatement.IdAndValues idAndVals = bs.getIdAndValues(version); | |
| 546 | + BatchStatement.IdAndValues idAndVals = bs.getIdAndValues(); | |
| 544 | 547 | Requests.BatchProtocolOptions options = new Requests.BatchProtocolOptions(consistency, serialConsistency, defaultTimestamp); |
| 545 | 548 | request = new Requests.Batch(bs.batchType, idAndVals.ids, idAndVals.values, options, statement.isTracing()); |
| 546 | 549 | } |
modified driver-core/src/main/java/com/datastax/driver/core/SettableByIndexData.java +241 −1
| @@ -21,6 +21,8 @@ | ||
| 21 | 21 | import java.nio.ByteBuffer; |
| 22 | 22 | import java.util.*; |
| 23 | 23 | |
| 24 | +import com.google.common.reflect.TypeToken; | |
| 25 | + | |
| 24 | 26 | import com.datastax.driver.core.exceptions.InvalidTypeException; |
| 25 | 27 | |
| 26 | 28 | /** |
| @@ -246,7 +248,14 @@ | ||
| 246 | 248 | /** |
| 247 | 249 | * Sets the {@code i}th value to the provided list. |
| 248 | 250 | * <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. | |
| 250 | 259 | * |
| 251 | 260 | * @param i the index of the value to set. |
| 252 | 261 | * @param v the value to set. |
| @@ -261,10 +270,65 @@ | ||
| 261 | 270 | */ |
| 262 | 271 | public <E> T setList(int i, List<E> v); |
| 263 | 272 | |
| 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 | + | |
| 264 | 321 | /** |
| 265 | 322 | * Sets the {@code i}th value to the provided map. |
| 266 | 323 | * <p> |
| 267 | 324 | * 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. | |
| 268 | 332 | * |
| 269 | 333 | * @param i the index of the value to set. |
| 270 | 334 | * @param v the value to set. |
| @@ -279,10 +343,67 @@ | ||
| 279 | 343 | */ |
| 280 | 344 | public <K, V> T setMap(int i, Map<K, V> v); |
| 281 | 345 | |
| 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 | + | |
| 282 | 396 | /** |
| 283 | 397 | * Sets the {@code i}th value to the provided set. |
| 284 | 398 | * <p> |
| 285 | 399 | * 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. | |
| 286 | 407 | * |
| 287 | 408 | * @param i the index of the value to set. |
| 288 | 409 | * @param v the value to set. |
| @@ -297,6 +418,54 @@ | ||
| 297 | 418 | */ |
| 298 | 419 | public <E> T setSet(int i, Set<E> v); |
| 299 | 420 | |
| 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 | + | |
| 300 | 469 | /** |
| 301 | 470 | * Sets the {@code i}th value to the provided UDT value. |
| 302 | 471 | * |
| @@ -333,4 +502,75 @@ | ||
| 333 | 502 | * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object. |
| 334 | 503 | */ |
| 335 | 504 | 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 | + | |
| 336 | 576 | } |
modified driver-core/src/main/java/com/datastax/driver/core/SettableByNameData.java +249 −1
| @@ -21,6 +21,8 @@ | ||
| 21 | 21 | import java.nio.ByteBuffer; |
| 22 | 22 | import java.util.*; |
| 23 | 23 | |
| 24 | +import com.google.common.reflect.TypeToken; | |
| 25 | + | |
| 24 | 26 | import com.datastax.driver.core.exceptions.InvalidTypeException; |
| 25 | 27 | |
| 26 | 28 | /** |
| @@ -290,7 +292,14 @@ | ||
| 290 | 292 | * Sets the value for (all occurrences of) variable {@code name} to the |
| 291 | 293 | * provided list. |
| 292 | 294 | * <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. | |
| 294 | 303 | * |
| 295 | 304 | * @param name the name of the value to set; if {@code name} is present multiple |
| 296 | 305 | * times, all its values are set. |
| @@ -306,11 +315,66 @@ | ||
| 306 | 315 | */ |
| 307 | 316 | public <E> T setList(String name, List<E> v); |
| 308 | 317 | |
| 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 | + | |
| 309 | 366 | /** |
| 310 | 367 | * Sets the value for (all occurrences of) variable {@code name} to the |
| 311 | 368 | * provided map. |
| 312 | 369 | * <p> |
| 313 | 370 | * 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. | |
| 314 | 378 | * |
| 315 | 379 | * @param name the name of the value to set; if {@code name} is present multiple |
| 316 | 380 | * times, all its values are set. |
| @@ -326,11 +390,70 @@ | ||
| 326 | 390 | */ |
| 327 | 391 | public <K, V> T setMap(String name, Map<K, V> v); |
| 328 | 392 | |
| 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 | + | |
| 329 | 445 | /** |
| 330 | 446 | * Sets the value for (all occurrences of) variable {@code name} to the |
| 331 | 447 | * provided set. |
| 332 | 448 | * <p> |
| 333 | 449 | * 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. | |
| 334 | 457 | * |
| 335 | 458 | * @param name the name of the value to set; if {@code name} is present multiple |
| 336 | 459 | * times, all its values are set. |
| @@ -346,6 +469,54 @@ | ||
| 346 | 469 | */ |
| 347 | 470 | public <E> T setSet(String name, Set<E> v); |
| 348 | 471 | |
| 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 | + | |
| 349 | 520 | /** |
| 350 | 521 | * Sets the value for (all occurrences of) variable {@code name} to the |
| 351 | 522 | * provided UDT value. |
| @@ -391,4 +562,81 @@ | ||
| 391 | 562 | * @throws IllegalArgumentException if {@code name} is not a valid name for this object. |
| 392 | 563 | */ |
| 393 | 564 | 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 | + | |
| 394 | 642 | } |
modified driver-core/src/main/java/com/datastax/driver/core/SimpleStatement.java +24 −100
| @@ -17,6 +17,9 @@ | ||
| 17 | 17 | |
| 18 | 18 | import java.nio.ByteBuffer; |
| 19 | 19 | |
| 20 | +import static com.datastax.driver.core.CodecUtils.compose; | |
| 21 | +import static com.datastax.driver.core.CodecUtils.convert; | |
| 22 | + | |
| 20 | 23 | /** |
| 21 | 24 | * A simple {@code RegularStatement} implementation built directly from a query |
| 22 | 25 | * string. |
| @@ -25,99 +28,42 @@ | ||
| 25 | 28 | |
| 26 | 29 | private final String query; |
| 27 | 30 | private final Object[] values; |
| 31 | + private final Cluster cluster; | |
| 28 | 32 | |
| 29 | 33 | private volatile ByteBuffer routingKey; |
| 30 | 34 | 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); | |
| 40 | 38 | } |
| 41 | 39 | |
| 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) | |
| 87 | 42 | throw new IllegalArgumentException("Too many values, the maximum allowed is 65535"); |
| 88 | 43 | this.query = query; |
| 89 | 44 | this.values = values; |
| 45 | + this.cluster = cluster; | |
| 90 | 46 | } |
| 91 | 47 | |
| 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 | - */ | |
| 113 | 48 | @Override |
| 114 | 49 | public String getQueryString() { |
| 115 | 50 | return query; |
| 116 | 51 | } |
| 117 | 52 | |
| 53 | + /** | |
| 54 | + * {@inheritDoc} | |
| 55 | + * <p> | |
| 56 | + * Note: Calling this method may trigger the underlying {@link Cluster} initialization. | |
| 57 | + */ | |
| 118 | 58 | @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); | |
| 121 | 67 | } |
| 122 | 68 | |
| 123 | 69 | /** |
| @@ -229,26 +175,4 @@ | ||
| 229 | 175 | return this; |
| 230 | 176 | } |
| 231 | 177 | |
| 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 @@ | ||
| 484 | 484 | this.outgoingPayload = payload == null ? null : ImmutableMap.copyOf(payload); |
| 485 | 485 | return this; |
| 486 | 486 | } |
| 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 @@ | ||
| 98 | 98 | this.cassandraVersion = cassandraVersion; |
| 99 | 99 | } |
| 100 | 100 | |
| 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) { | |
| 102 | 102 | |
| 103 | 103 | String name = row.getString(CF_NAME); |
| 104 | 104 | UUID id = (cassandraVersion.getMajor() > 2 || (cassandraVersion.getMajor() == 2 && cassandraVersion.getMinor() >= 1)) |
| 105 | 105 | ? row.getUUID(CF_ID) |
| 106 | 106 | : null; |
| 107 | 107 | |
| 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); | |
| 110 | 110 | List<String> columnAliases = cassandraVersion.getMajor() >= 2 || row.getString(COLUMN_ALIASES) == null |
| 111 | 111 | ? Collections.<String>emptyList() |
| 112 | 112 | : SimpleJSONParser.parseStringList(row.getString(COLUMN_ALIASES)); |
| @@ -159,7 +159,7 @@ | ||
| 159 | 159 | // We have a value alias if we're dense |
| 160 | 160 | if (isDense) { |
| 161 | 161 | 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); | |
| 163 | 163 | otherColumns.add(ColumnMetadata.forAlias(tm, alias, type)); |
| 164 | 164 | } |
| 165 | 165 | } |
modified driver-core/src/main/java/com/datastax/driver/core/Token.java +28 −3
| @@ -19,7 +19,6 @@ | ||
| 19 | 19 | import java.nio.ByteBuffer; |
| 20 | 20 | import java.security.MessageDigest; |
| 21 | 21 | import java.security.NoSuchAlgorithmException; |
| 22 | -import java.util.Arrays; | |
| 23 | 22 | import java.util.List; |
| 24 | 23 | |
| 25 | 24 | import com.google.common.annotations.VisibleForTesting; |
| @@ -47,6 +46,17 @@ | ||
| 47 | 46 | */ |
| 48 | 47 | public abstract Object getValue(); |
| 49 | 48 | |
| 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 | + | |
| 50 | 60 | static Token.Factory getFactory(String partitionerName) { |
| 51 | 61 | if (partitionerName.endsWith("Murmur3Partitioner")) |
| 52 | 62 | return M3PToken.FACTORY; |
| @@ -213,7 +223,7 @@ | ||
| 213 | 223 | |
| 214 | 224 | @Override |
| 215 | 225 | 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)); | |
| 217 | 227 | } |
| 218 | 228 | |
| 219 | 229 | @Override |
| @@ -264,6 +274,11 @@ | ||
| 264 | 274 | return value; |
| 265 | 275 | } |
| 266 | 276 | |
| 277 | + @Override | |
| 278 | + public ByteBuffer serialize(ProtocolVersion protocolVersion) { | |
| 279 | + return TypeCodec.BigintCodec.instance.serialize(value, protocolVersion); | |
| 280 | + } | |
| 281 | + | |
| 267 | 282 | @Override |
| 268 | 283 | public int compareTo(Token other) { |
| 269 | 284 | assert other instanceof M3PToken; |
| @@ -466,6 +481,11 @@ | ||
| 466 | 481 | return value; |
| 467 | 482 | } |
| 468 | 483 | |
| 484 | + @Override | |
| 485 | + public ByteBuffer serialize(ProtocolVersion protocolVersion) { | |
| 486 | + return TypeCodec.BlobCodec.instance.serialize(value, protocolVersion); | |
| 487 | + } | |
| 488 | + | |
| 469 | 489 | @Override |
| 470 | 490 | public int compareTo(Token other) { |
| 471 | 491 | assert other instanceof OPPToken; |
| @@ -532,7 +552,7 @@ | ||
| 532 | 552 | |
| 533 | 553 | @Override |
| 534 | 554 | 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)); | |
| 536 | 556 | } |
| 537 | 557 | |
| 538 | 558 | @Override |
| @@ -582,6 +602,11 @@ | ||
| 582 | 602 | return value; |
| 583 | 603 | } |
| 584 | 604 | |
| 605 | + @Override | |
| 606 | + public ByteBuffer serialize(ProtocolVersion protocolVersion) { | |
| 607 | + return TypeCodec.VarintCodec.instance.serialize(value, protocolVersion); | |
| 608 | + } | |
| 609 | + | |
| 585 | 610 | @Override |
| 586 | 611 | public int compareTo(Token other) { |
| 587 | 612 | assert other instanceof RPToken; |
modified driver-core/src/main/java/com/datastax/driver/core/TupleType.java +63 −24
| @@ -15,10 +15,10 @@ | ||
| 15 | 15 | */ |
| 16 | 16 | package com.datastax.driver.core; |
| 17 | 17 | |
| 18 | -import java.util.*; | |
| 18 | +import java.util.Arrays; | |
| 19 | +import java.util.List; | |
| 19 | 20 | |
| 20 | 21 | import com.google.common.collect.ImmutableList; |
| 21 | -import com.google.common.reflect.TypeToken; | |
| 22 | 22 | |
| 23 | 23 | import com.datastax.driver.core.exceptions.InvalidTypeException; |
| 24 | 24 | |
| @@ -30,26 +30,14 @@ | ||
| 30 | 30 | public class TupleType extends DataType { |
| 31 | 31 | |
| 32 | 32 | private final List<DataType> types; |
| 33 | + private final ProtocolVersion protocolVersion; | |
| 34 | + private volatile CodecRegistry codecRegistry; | |
| 33 | 35 | |
| 34 | - TupleType(List<DataType> types) { | |
| 36 | + TupleType(List<DataType> types, ProtocolVersion protocolVersion, CodecRegistry codecRegistry) { | |
| 35 | 37 | super(DataType.Name.TUPLE); |
| 36 | 38 | 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; | |
| 53 | 41 | } |
| 54 | 42 | |
| 55 | 43 | /** |
| @@ -95,8 +83,13 @@ | ||
| 95 | 83 | throw new IllegalArgumentException(String.format("Invalid number of values. Expecting %d but got %d", types.size(), values.length)); |
| 96 | 84 | |
| 97 | 85 | 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 | + } | |
| 100 | 93 | return t; |
| 101 | 94 | } |
| 102 | 95 | |
| @@ -105,11 +98,30 @@ | ||
| 105 | 98 | return true; |
| 106 | 99 | } |
| 107 | 100 | |
| 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; | |
| 111 | 114 | } |
| 112 | 115 | |
| 116 | + CodecRegistry getCodecRegistry() { | |
| 117 | + return codecRegistry; | |
| 118 | + } | |
| 119 | + | |
| 120 | + void setCodecRegistry(CodecRegistry codecRegistry) { | |
| 121 | + this.codecRegistry = codecRegistry; | |
| 122 | + } | |
| 123 | + | |
| 124 | + | |
| 113 | 125 | @Override |
| 114 | 126 | public int hashCode() { |
| 115 | 127 | return Arrays.hashCode(new Object[]{ name, types }); |
| @@ -124,6 +136,32 @@ | ||
| 124 | 136 | return name == d.name && types.equals(d.types); |
| 125 | 137 | } |
| 126 | 138 | |
| 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 | + | |
| 127 | 165 | @Override |
| 128 | 166 | public String toString() { |
| 129 | 167 | StringBuilder sb = new StringBuilder(); |
| @@ -133,4 +171,5 @@ | ||
| 133 | 171 | } |
| 134 | 172 | return sb.append(">>").toString(); |
| 135 | 173 | } |
| 174 | + | |
| 136 | 175 | } |
modified driver-core/src/main/java/com/datastax/driver/core/TupleValue.java +14 −8
| @@ -15,9 +15,6 @@ | ||
| 15 | 15 | */ |
| 16 | 16 | package com.datastax.driver.core; |
| 17 | 17 | |
| 18 | -import java.util.Arrays; | |
| 19 | -import java.util.List; | |
| 20 | - | |
| 21 | 18 | /** |
| 22 | 19 | * A value for a Tuple. |
| 23 | 20 | */ |
| @@ -28,11 +25,10 @@ | ||
| 28 | 25 | /** |
| 29 | 26 | * Builds a new value for a tuple. |
| 30 | 27 | * |
| 31 | - * @param types the types of the tuple's components. | |
| 28 | + * @param type the {@link TupleType} instance defining this tuple's components. | |
| 32 | 29 | */ |
| 33 | 30 | 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()); | |
| 36 | 32 | this.type = type; |
| 37 | 33 | } |
| 38 | 34 | |
| @@ -46,6 +42,11 @@ | ||
| 46 | 42 | return "component " + i; |
| 47 | 43 | } |
| 48 | 44 | |
| 45 | + @Override | |
| 46 | + protected CodecRegistry getCodecRegistry() { | |
| 47 | + return type.getCodecRegistry(); | |
| 48 | + } | |
| 49 | + | |
| 49 | 50 | /** |
| 50 | 51 | * The tuple type this is a value of. |
| 51 | 52 | * |
| @@ -80,8 +81,13 @@ | ||
| 80 | 81 | if (i > 0) |
| 81 | 82 | sb.append(", "); |
| 82 | 83 | |
| 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 | + } | |
| 85 | 91 | } |
| 86 | 92 | sb.append(")"); |
| 87 | 93 | return sb.toString(); |
modified driver-core/src/main/java/com/datastax/driver/core/TypeCodec.java +1290 −597
| @@ -29,366 +29,401 @@ | ||
| 29 | 29 | import java.util.concurrent.TimeUnit; |
| 30 | 30 | import java.util.regex.Pattern; |
| 31 | 31 | |
| 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 | + | |
| 32 | 39 | import com.datastax.driver.core.exceptions.InvalidTypeException; |
| 33 | 40 | import com.datastax.driver.core.utils.Bytes; |
| 34 | 41 | |
| 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; | |
| 133 | 128 | |
| 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)); | |
| 139 | 137 | } |
| 140 | 138 | |
| 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; | |
| 147 | 145 | } |
| 148 | 146 | |
| 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; | |
| 151 | 153 | } |
| 152 | 154 | |
| 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; | |
| 155 | 161 | } |
| 156 | 162 | |
| 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> | |
| 159 | 175 | * |
| 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); | |
| 332 | 256 | } |
| 333 | 257 | |
| 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); | |
| 339 | 270 | } |
| 340 | 271 | |
| 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())); | |
| 356 | 302 | } |
| 357 | 303 | |
| 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 | + | |
| 372 | 399 | } |
| 373 | 400 | |
| 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> { | |
| 375 | 406 | |
| 376 | 407 | private final Charset charset; |
| 377 | 408 | |
| 378 | - private StringCodec(Charset charset) { | |
| 409 | + public StringCodec(DataType cqlType, Charset charset) { | |
| 410 | + super(cqlType, String.class); | |
| 379 | 411 | this.charset = charset; |
| 380 | 412 | } |
| 381 | 413 | |
| 382 | 414 | @Override |
| 383 | 415 | public String parse(String value) { |
| 416 | + if (value == null || value.isEmpty() || value.equals(NULL)) return null; | |
| 384 | 417 | 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"); | |
| 386 | 419 | |
| 387 | 420 | return value.substring(1, value.length() - 1).replace("''", "'"); |
| 388 | 421 | } |
| 389 | 422 | |
| 390 | 423 | @Override |
| 391 | 424 | public String format(String value) { |
| 425 | + if (value == null) | |
| 426 | + return NULL; | |
| 392 | 427 | return '\'' + replace(value, '\'', "''") + '\''; |
| 393 | 428 | } |
| 394 | 429 | |
| @@ -401,7 +436,7 @@ | ||
| 401 | 436 | int nbMatch = 0; |
| 402 | 437 | int start = -1; |
| 403 | 438 | do { |
| 404 | - start = text.indexOf(search, start+1); | |
| 439 | + start = text.indexOf(search, start + 1); | |
| 405 | 440 | if (start != -1) |
| 406 | 441 | ++nbMatch; |
| 407 | 442 | } while (start != -1); |
| @@ -425,26 +460,78 @@ | ||
| 425 | 460 | } |
| 426 | 461 | |
| 427 | 462 | @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)); | |
| 430 | 465 | } |
| 431 | 466 | |
| 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 | + */ | |
| 432 | 473 | @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 ""; | |
| 434 | 479 | return new String(Bytes.getArray(bytes), charset); |
| 435 | 480 | } |
| 436 | 481 | } |
| 437 | 482 | |
| 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 | + } | |
| 439 | 520 | |
| 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 { | |
| 441 | 526 | |
| 442 | - private LongCodec() {} | |
| 527 | + public LongCodec(DataType cqlType) { | |
| 528 | + super(cqlType, Long.class); | |
| 529 | + } | |
| 443 | 530 | |
| 444 | 531 | @Override |
| 445 | 532 | public Long parse(String value) { |
| 446 | 533 | try { |
| 447 | - return Long.parseLong(value); | |
| 534 | + return value == null || value.isEmpty() || value.equals(NULL) ? null : Long.parseLong(value); | |
| 448 | 535 | } catch (NumberFormatException e) { |
| 449 | 536 | throw new InvalidTypeException(String.format("Cannot parse 64-bits long value from \"%s\"", value)); |
| 450 | 537 | } |
| @@ -452,26 +539,32 @@ | ||
| 452 | 539 | |
| 453 | 540 | @Override |
| 454 | 541 | public String format(Long value) { |
| 542 | + if (value == null) | |
| 543 | + return NULL; | |
| 455 | 544 | return Long.toString(value); |
| 456 | 545 | } |
| 457 | 546 | |
| 458 | 547 | @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); | |
| 461 | 550 | } |
| 462 | 551 | |
| 463 | - public ByteBuffer serializeNoBoxing(long value) { | |
| 552 | + @Override | |
| 553 | + public ByteBuffer serializeNoBoxing(long value, ProtocolVersion protocolVersion) { | |
| 464 | 554 | ByteBuffer bb = ByteBuffer.allocate(8); |
| 465 | 555 | bb.putLong(0, value); |
| 466 | 556 | return bb; |
| 467 | 557 | } |
| 468 | 558 | |
| 469 | 559 | @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); | |
| 472 | 562 | } |
| 473 | 563 | |
| 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; | |
| 475 | 568 | if (bytes.remaining() != 8) |
| 476 | 569 | throw new InvalidTypeException("Invalid 64-bits long value, expecting 8 bytes but got " + bytes.remaining()); |
| 477 | 570 | |
| @@ -479,43 +572,119 @@ | ||
| 479 | 572 | } |
| 480 | 573 | } |
| 481 | 574 | |
| 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 | + } | |
| 483 | 634 | |
| 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> { | |
| 485 | 641 | |
| 486 | - private BytesCodec() {} | |
| 642 | + public CustomCodec(DataType custom) { | |
| 643 | + super(custom, ByteBuffer.class); | |
| 644 | + assert custom.getName() == Name.CUSTOM; | |
| 645 | + } | |
| 487 | 646 | |
| 488 | 647 | @Override |
| 489 | 648 | public ByteBuffer parse(String value) { |
| 490 | - return Bytes.fromHexString(value); | |
| 649 | + return value == null || value.isEmpty() || value.equals(NULL) ? null : Bytes.fromHexString(value); | |
| 491 | 650 | } |
| 492 | 651 | |
| 493 | 652 | @Override |
| 494 | 653 | public String format(ByteBuffer value) { |
| 654 | + if (value == null) | |
| 655 | + return NULL; | |
| 495 | 656 | return Bytes.toHexString(value); |
| 496 | 657 | } |
| 497 | 658 | |
| 498 | 659 | @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(); | |
| 501 | 662 | } |
| 502 | 663 | |
| 503 | 664 | @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(); | |
| 506 | 667 | } |
| 507 | 668 | } |
| 508 | 669 | |
| 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 }); | |
| 512 | 677 | |
| 513 | 678 | public static final BooleanCodec instance = new BooleanCodec(); |
| 514 | 679 | |
| 515 | - private BooleanCodec() {} | |
| 680 | + private BooleanCodec() { | |
| 681 | + super(cboolean(), Boolean.class); | |
| 682 | + } | |
| 516 | 683 | |
| 517 | 684 | @Override |
| 518 | 685 | public Boolean parse(String value) { |
| 686 | + if (value == null || value.isEmpty() || value.equals(NULL)) | |
| 687 | + return null; | |
| 519 | 688 | if (value.equalsIgnoreCase(Boolean.FALSE.toString())) |
| 520 | 689 | return false; |
| 521 | 690 | if (value.equalsIgnoreCase(Boolean.TRUE.toString())) |
| @@ -526,24 +695,30 @@ | ||
| 526 | 695 | |
| 527 | 696 | @Override |
| 528 | 697 | public String format(Boolean value) { |
| 698 | + if (value == null) | |
| 699 | + return NULL; | |
| 529 | 700 | return value ? "true" : "false"; |
| 530 | 701 | } |
| 531 | 702 | |
| 532 | 703 | @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); | |
| 535 | 706 | } |
| 536 | 707 | |
| 537 | - public ByteBuffer serializeNoBoxing(boolean value) { | |
| 708 | + @Override | |
| 709 | + public ByteBuffer serializeNoBoxing(boolean value, ProtocolVersion protocolVersion) { | |
| 538 | 710 | return value ? TRUE.duplicate() : FALSE.duplicate(); |
| 539 | 711 | } |
| 540 | 712 | |
| 541 | 713 | @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); | |
| 544 | 716 | } |
| 545 | 717 | |
| 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; | |
| 547 | 722 | if (bytes.remaining() != 1) |
| 548 | 723 | throw new InvalidTypeException("Invalid boolean value, expecting 1 byte but got " + bytes.remaining()); |
| 549 | 724 | |
| @@ -551,16 +726,21 @@ | ||
| 551 | 726 | } |
| 552 | 727 | } |
| 553 | 728 | |
| 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> { | |
| 555 | 733 | |
| 556 | 734 | public static final DecimalCodec instance = new DecimalCodec(); |
| 557 | 735 | |
| 558 | - private DecimalCodec() {} | |
| 736 | + private DecimalCodec() { | |
| 737 | + super(decimal(), BigDecimal.class); | |
| 738 | + } | |
| 559 | 739 | |
| 560 | 740 | @Override |
| 561 | 741 | public BigDecimal parse(String value) { |
| 562 | 742 | try { |
| 563 | - return new BigDecimal(value); | |
| 743 | + return value == null || value.isEmpty() || value.equals(NULL) ? null : new BigDecimal(value); | |
| 564 | 744 | } catch (NumberFormatException e) { |
| 565 | 745 | throw new InvalidTypeException(String.format("Cannot parse decimal value from \"%s\"", value)); |
| 566 | 746 | } |
| @@ -568,11 +748,15 @@ | ||
| 568 | 748 | |
| 569 | 749 | @Override |
| 570 | 750 | public String format(BigDecimal value) { |
| 751 | + if (value == null) | |
| 752 | + return NULL; | |
| 571 | 753 | return value.toString(); |
| 572 | 754 | } |
| 573 | 755 | |
| 574 | 756 | @Override |
| 575 | - public ByteBuffer serialize(BigDecimal value) { | |
| 757 | + public ByteBuffer serialize(BigDecimal value, ProtocolVersion protocolVersion) { | |
| 758 | + if (value == null) | |
| 759 | + return null; | |
| 576 | 760 | BigInteger bi = value.unscaledValue(); |
| 577 | 761 | int scale = value.scale(); |
| 578 | 762 | byte[] bibytes = bi.toByteArray(); |
| @@ -585,7 +769,9 @@ | ||
| 585 | 769 | } |
| 586 | 770 | |
| 587 | 771 | @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; | |
| 589 | 775 | if (bytes.remaining() < 4) |
| 590 | 776 | throw new InvalidTypeException("Invalid decimal value, expecting at least 4 bytes but got " + bytes.remaining()); |
| 591 | 777 | |
| @@ -599,16 +785,21 @@ | ||
| 599 | 785 | } |
| 600 | 786 | } |
| 601 | 787 | |
| 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 { | |
| 603 | 792 | |
| 604 | 793 | public static final DoubleCodec instance = new DoubleCodec(); |
| 605 | 794 | |
| 606 | - private DoubleCodec() {} | |
| 795 | + private DoubleCodec() { | |
| 796 | + super(cdouble(), Double.class); | |
| 797 | + } | |
| 607 | 798 | |
| 608 | 799 | @Override |
| 609 | 800 | public Double parse(String value) { |
| 610 | 801 | try { |
| 611 | - return Double.parseDouble(value); | |
| 802 | + return value == null || value.isEmpty() || value.equals(NULL) ? null : Double.parseDouble(value); | |
| 612 | 803 | } catch (NumberFormatException e) { |
| 613 | 804 | throw new InvalidTypeException(String.format("Cannot parse 64-bits double value from \"%s\"", value)); |
| 614 | 805 | } |
| @@ -616,26 +807,32 @@ | ||
| 616 | 807 | |
| 617 | 808 | @Override |
| 618 | 809 | public String format(Double value) { |
| 810 | + if (value == null) | |
| 811 | + return NULL; | |
| 619 | 812 | return Double.toString(value); |
| 620 | 813 | } |
| 621 | 814 | |
| 622 | 815 | @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); | |
| 625 | 818 | } |
| 626 | 819 | |
| 627 | - public ByteBuffer serializeNoBoxing(double value) { | |
| 820 | + @Override | |
| 821 | + public ByteBuffer serializeNoBoxing(double value, ProtocolVersion protocolVersion) { | |
| 628 | 822 | ByteBuffer bb = ByteBuffer.allocate(8); |
| 629 | 823 | bb.putDouble(0, value); |
| 630 | 824 | return bb; |
| 631 | 825 | } |
| 632 | 826 | |
| 633 | 827 | @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); | |
| 636 | 830 | } |
| 637 | 831 | |
| 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; | |
| 639 | 836 | if (bytes.remaining() != 8) |
| 640 | 837 | throw new InvalidTypeException("Invalid 64-bits double value, expecting 8 bytes but got " + bytes.remaining()); |
| 641 | 838 | |
| @@ -643,16 +840,21 @@ | ||
| 643 | 840 | } |
| 644 | 841 | } |
| 645 | 842 | |
| 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 { | |
| 647 | 847 | |
| 648 | 848 | public static final FloatCodec instance = new FloatCodec(); |
| 649 | 849 | |
| 650 | - private FloatCodec() {} | |
| 850 | + private FloatCodec() { | |
| 851 | + super(cfloat(), Float.class); | |
| 852 | + } | |
| 651 | 853 | |
| 652 | 854 | @Override |
| 653 | 855 | public Float parse(String value) { |
| 654 | 856 | try { |
| 655 | - return Float.parseFloat(value); | |
| 857 | + return value == null || value.isEmpty() || value.equals(NULL) ? null : Float.parseFloat(value); | |
| 656 | 858 | } catch (NumberFormatException e) { |
| 657 | 859 | throw new InvalidTypeException(String.format("Cannot parse 32-bits float value from \"%s\"", value)); |
| 658 | 860 | } |
| @@ -660,26 +862,32 @@ | ||
| 660 | 862 | |
| 661 | 863 | @Override |
| 662 | 864 | public String format(Float value) { |
| 865 | + if (value == null) | |
| 866 | + return NULL; | |
| 663 | 867 | return Float.toString(value); |
| 664 | 868 | } |
| 665 | 869 | |
| 666 | 870 | @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); | |
| 669 | 873 | } |
| 670 | 874 | |
| 671 | - public ByteBuffer serializeNoBoxing(float value) { | |
| 875 | + @Override | |
| 876 | + public ByteBuffer serializeNoBoxing(float value, ProtocolVersion protocolVersion) { | |
| 672 | 877 | ByteBuffer bb = ByteBuffer.allocate(4); |
| 673 | 878 | bb.putFloat(0, value); |
| 674 | 879 | return bb; |
| 675 | 880 | } |
| 676 | 881 | |
| 677 | 882 | @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); | |
| 680 | 885 | } |
| 681 | 886 | |
| 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; | |
| 683 | 891 | if (bytes.remaining() != 4) |
| 684 | 892 | throw new InvalidTypeException("Invalid 32-bits float value, expecting 4 bytes but got " + bytes.remaining()); |
| 685 | 893 | |
| @@ -687,14 +895,22 @@ | ||
| 687 | 895 | } |
| 688 | 896 | } |
| 689 | 897 | |
| 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> { | |
| 691 | 902 | |
| 692 | 903 | public static final InetCodec instance = new InetCodec(); |
| 693 | 904 | |
| 694 | - private InetCodec() {} | |
| 905 | + private InetCodec() { | |
| 906 | + super(inet(), InetAddress.class); | |
| 907 | + } | |
| 695 | 908 | |
| 696 | 909 | @Override |
| 697 | 910 | public InetAddress parse(String value) { |
| 911 | + if (value == null || value.isEmpty() || value.equals(NULL)) | |
| 912 | + return null; | |
| 913 | + | |
| 698 | 914 | value = value.trim(); |
| 699 | 915 | if (value.charAt(0) != '\'' || value.charAt(value.length() - 1) != '\'') |
| 700 | 916 | throw new InvalidTypeException(String.format("inet values must be enclosed in single quotes (\"%s\")", value)); |
| @@ -707,16 +923,20 @@ | ||
| 707 | 923 | |
| 708 | 924 | @Override |
| 709 | 925 | public String format(InetAddress value) { |
| 926 | + if (value == null) | |
| 927 | + return NULL; | |
| 710 | 928 | return "'" + value.getHostAddress() + "'"; |
| 711 | 929 | } |
| 712 | 930 | |
| 713 | 931 | @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()); | |
| 716 | 934 | } |
| 717 | 935 | |
| 718 | 936 | @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; | |
| 720 | 940 | try { |
| 721 | 941 | return InetAddress.getByAddress(Bytes.getArray(bytes)); |
| 722 | 942 | } catch (UnknownHostException e) { |
| @@ -725,16 +945,21 @@ | ||
| 725 | 945 | } |
| 726 | 946 | } |
| 727 | 947 | |
| 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 { | |
| 729 | 952 | |
| 730 | 953 | public static final TinyIntCodec instance = new TinyIntCodec(); |
| 731 | 954 | |
| 732 | - private TinyIntCodec() {} | |
| 955 | + private TinyIntCodec() { | |
| 956 | + super(tinyint(), Byte.class); | |
| 957 | + } | |
| 733 | 958 | |
| 734 | 959 | @Override |
| 735 | 960 | public Byte parse(String value) { |
| 736 | 961 | try { |
| 737 | - return Byte.parseByte(value); | |
| 962 | + return value == null || value.isEmpty() || value.equals(NULL) ? null : Byte.parseByte(value); | |
| 738 | 963 | } catch (NumberFormatException e) { |
| 739 | 964 | throw new InvalidTypeException(String.format("Cannot parse 8-bits int value from \"%s\"", value)); |
| 740 | 965 | } |
| @@ -742,26 +967,32 @@ | ||
| 742 | 967 | |
| 743 | 968 | @Override |
| 744 | 969 | public String format(Byte value) { |
| 970 | + if (value == null) | |
| 971 | + return NULL; | |
| 745 | 972 | return Byte.toString(value); |
| 746 | 973 | } |
| 747 | 974 | |
| 748 | 975 | @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); | |
| 751 | 978 | } |
| 752 | 979 | |
| 753 | - public ByteBuffer serializeNoBoxing(byte value) { | |
| 980 | + @Override | |
| 981 | + public ByteBuffer serializeNoBoxing(byte value, ProtocolVersion protocolVersion) { | |
| 754 | 982 | ByteBuffer bb = ByteBuffer.allocate(1); |
| 755 | 983 | bb.put(0, value); |
| 756 | 984 | return bb; |
| 757 | 985 | } |
| 758 | 986 | |
| 759 | 987 | @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); | |
| 762 | 990 | } |
| 763 | 991 | |
| 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; | |
| 765 | 996 | if (bytes.remaining() != 1) |
| 766 | 997 | throw new InvalidTypeException("Invalid 8-bits integer value, expecting 1 byte but got " + bytes.remaining()); |
| 767 | 998 | |
| @@ -769,16 +1000,21 @@ | ||
| 769 | 1000 | } |
| 770 | 1001 | } |
| 771 | 1002 | |
| 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 { | |
| 773 | 1007 | |
| 774 | 1008 | public static final SmallIntCodec instance = new SmallIntCodec(); |
| 775 | 1009 | |
| 776 | - private SmallIntCodec() {} | |
| 1010 | + private SmallIntCodec() { | |
| 1011 | + super(smallint(), Short.class); | |
| 1012 | + } | |
| 777 | 1013 | |
| 778 | 1014 | @Override |
| 779 | 1015 | public Short parse(String value) { |
| 780 | 1016 | try { |
| 781 | - return Short.parseShort(value); | |
| 1017 | + return value == null || value.isEmpty() || value.equals(NULL) ? null : Short.parseShort(value); | |
| 782 | 1018 | } catch (NumberFormatException e) { |
| 783 | 1019 | throw new InvalidTypeException(String.format("Cannot parse 16-bits int value from \"%s\"", value)); |
| 784 | 1020 | } |
| @@ -786,26 +1022,32 @@ | ||
| 786 | 1022 | |
| 787 | 1023 | @Override |
| 788 | 1024 | public String format(Short value) { |
| 1025 | + if (value == null) | |
| 1026 | + return NULL; | |
| 789 | 1027 | return Short.toString(value); |
| 790 | 1028 | } |
| 791 | 1029 | |
| 792 | 1030 | @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); | |
| 795 | 1033 | } |
| 796 | 1034 | |
| 797 | - public ByteBuffer serializeNoBoxing(short value) { | |
| 1035 | + @Override | |
| 1036 | + public ByteBuffer serializeNoBoxing(short value, ProtocolVersion protocolVersion) { | |
| 798 | 1037 | ByteBuffer bb = ByteBuffer.allocate(2); |
| 799 | 1038 | bb.putShort(0, value); |
| 800 | 1039 | return bb; |
| 801 | 1040 | } |
| 802 | 1041 | |
| 803 | 1042 | @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); | |
| 806 | 1045 | } |
| 807 | 1046 | |
| 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; | |
| 809 | 1051 | if (bytes.remaining() != 2) |
| 810 | 1052 | throw new InvalidTypeException("Invalid 16-bits integer value, expecting 2 bytes but got " + bytes.remaining()); |
| 811 | 1053 | |
| @@ -813,16 +1055,21 @@ | ||
| 813 | 1055 | } |
| 814 | 1056 | } |
| 815 | 1057 | |
| 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 { | |
| 817 | 1062 | |
| 818 | 1063 | public static final IntCodec instance = new IntCodec(); |
| 819 | 1064 | |
| 820 | - private IntCodec() {} | |
| 1065 | + private IntCodec() { | |
| 1066 | + super(cint(), Integer.class); | |
| 1067 | + } | |
| 821 | 1068 | |
| 822 | 1069 | @Override |
| 823 | 1070 | public Integer parse(String value) { |
| 824 | 1071 | try { |
| 825 | - return Integer.parseInt(value); | |
| 1072 | + return value == null || value.isEmpty() || value.equals(NULL) ? null : Integer.parseInt(value); | |
| 826 | 1073 | } catch (NumberFormatException e) { |
| 827 | 1074 | throw new InvalidTypeException(String.format("Cannot parse 32-bits int value from \"%s\"", value)); |
| 828 | 1075 | } |
| @@ -830,26 +1077,32 @@ | ||
| 830 | 1077 | |
| 831 | 1078 | @Override |
| 832 | 1079 | public String format(Integer value) { |
| 1080 | + if (value == null) | |
| 1081 | + return NULL; | |
| 833 | 1082 | return Integer.toString(value); |
| 834 | 1083 | } |
| 835 | 1084 | |
| 836 | 1085 | @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); | |
| 839 | 1088 | } |
| 840 | 1089 | |
| 841 | - public ByteBuffer serializeNoBoxing(int value) { | |
| 1090 | + @Override | |
| 1091 | + public ByteBuffer serializeNoBoxing(int value, ProtocolVersion protocolVersion) { | |
| 842 | 1092 | ByteBuffer bb = ByteBuffer.allocate(4); |
| 843 | 1093 | bb.putInt(0, value); |
| 844 | 1094 | return bb; |
| 845 | 1095 | } |
| 846 | 1096 | |
| 847 | 1097 | @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); | |
| 850 | 1100 | } |
| 851 | 1101 | |
| 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; | |
| 853 | 1106 | if (bytes.remaining() != 4) |
| 854 | 1107 | throw new InvalidTypeException("Invalid 32-bits integer value, expecting 4 bytes but got " + bytes.remaining()); |
| 855 | 1108 | |
| @@ -857,9 +1110,12 @@ | ||
| 857 | 1110 | } |
| 858 | 1111 | } |
| 859 | 1112 | |
| 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> { | |
| 861 | 1117 | |
| 862 | - private static final String[] iso8601Patterns = new String[] { | |
| 1118 | + private static final String[] iso8601Patterns = new String[]{ | |
| 863 | 1119 | "yyyy-MM-dd HH:mm", |
| 864 | 1120 | "yyyy-MM-dd HH:mm:ss", |
| 865 | 1121 | "yyyy-MM-dd HH:mmZ", |
| @@ -877,9 +1133,12 @@ | ||
| 877 | 1133 | }; |
| 878 | 1134 | |
| 879 | 1135 | public static final TimestampCodec instance = new TimestampCodec(); |
| 1136 | + | |
| 880 | 1137 | private static final Pattern IS_LONG_PATTERN = Pattern.compile("^-?\\d+$"); |
| 881 | 1138 | |
| 882 | - private TimestampCodec() {} | |
| 1139 | + private TimestampCodec() { | |
| 1140 | + super(timestamp(), Date.class); | |
| 1141 | + } | |
| 883 | 1142 | |
| 884 | 1143 | /* |
| 885 | 1144 | * Copied and adapted from apache commons DateUtils.parseStrictly method (that is used Cassandra side |
| @@ -908,8 +1167,10 @@ | ||
| 908 | 1167 | |
| 909 | 1168 | @Override |
| 910 | 1169 | public Date parse(String value) { |
| 1170 | + if (value == null || value.isEmpty() || value.equals(NULL)) | |
| 1171 | + return null; | |
| 1172 | + | |
| 911 | 1173 | // strip enclosing single quotes, if any |
| 912 | - // enclosing quotes are optional for long literals, mandatory for date patterns | |
| 913 | 1174 | if (value.charAt(0) == '\'' && value.charAt(value.length() - 1) == '\'') |
| 914 | 1175 | value = value.substring(1, value.length() - 1); |
| 915 | 1176 | |
| @@ -930,33 +1191,42 @@ | ||
| 930 | 1191 | |
| 931 | 1192 | @Override |
| 932 | 1193 | public String format(Date value) { |
| 1194 | + if (value == null) | |
| 1195 | + return NULL; | |
| 933 | 1196 | return Long.toString(value.getTime()); |
| 934 | 1197 | } |
| 935 | 1198 | |
| 936 | 1199 | @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); | |
| 939 | 1202 | } |
| 940 | 1203 | |
| 941 | 1204 | @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)); | |
| 944 | 1207 | } |
| 945 | 1208 | } |
| 946 | 1209 | |
| 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> { | |
| 948 | 1214 | |
| 949 | 1215 | public static final DateCodec instance = new DateCodec(); |
| 1216 | + | |
| 950 | 1217 | private static final Pattern IS_LONG_PATTERN = Pattern.compile("^-?\\d+$"); |
| 951 | 1218 | private static final String pattern = "yyyy-MM-dd"; |
| 952 | 1219 | private static final long MAX_LONG_VALUE = (1L << 32) - 1; |
| 953 | 1220 | private static final long EPOCH_AS_CQL_LONG = (1L << 31); |
| 954 | 1221 | |
| 955 | 1222 | private DateCodec() { |
| 1223 | + super(date(), LocalDate.class); | |
| 956 | 1224 | } |
| 957 | 1225 | |
| 958 | 1226 | @Override |
| 959 | 1227 | public LocalDate parse(String value) { |
| 1228 | + if (value == null || value.isEmpty() || value.equals(NULL)) | |
| 1229 | + return null; | |
| 960 | 1230 | |
| 961 | 1231 | // strip enclosing single quotes, if any |
| 962 | 1232 | // single quotes are optional for long literals, mandatory for date patterns |
| @@ -981,6 +1251,7 @@ | ||
| 981 | 1251 | return LocalDate.fromDaysSinceEpoch(days); |
| 982 | 1252 | } |
| 983 | 1253 | |
| 1254 | + | |
| 984 | 1255 | SimpleDateFormat parser = new SimpleDateFormat(pattern); |
| 985 | 1256 | parser.setLenient(false); |
| 986 | 1257 | parser.setTimeZone(TimeZone.getTimeZone("UTC")); |
| @@ -996,17 +1267,19 @@ | ||
| 996 | 1267 | |
| 997 | 1268 | @Override |
| 998 | 1269 | public String format(LocalDate value) { |
| 1270 | + if (value == null) | |
| 1271 | + return NULL; | |
| 999 | 1272 | return "'" + value.toString() + "'"; |
| 1000 | 1273 | } |
| 1001 | 1274 | |
| 1002 | 1275 | @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); | |
| 1005 | 1278 | } |
| 1006 | 1279 | |
| 1007 | 1280 | @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))); | |
| 1010 | 1283 | } |
| 1011 | 1284 | |
| 1012 | 1285 | // The protocol encodes DATE as an _unsigned_ int with the epoch in the middle of the range (2^31). |
| @@ -1021,13 +1294,17 @@ | ||
| 1021 | 1294 | } |
| 1022 | 1295 | } |
| 1023 | 1296 | |
| 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 { | |
| 1025 | 1301 | |
| 1026 | 1302 | private static final Pattern IS_LONG_PATTERN = Pattern.compile("^-?\\d+$"); |
| 1027 | 1303 | |
| 1028 | 1304 | public static final TimeCodec instance = new TimeCodec(); |
| 1029 | 1305 | |
| 1030 | 1306 | private TimeCodec() { |
| 1307 | + super(time()); | |
| 1031 | 1308 | } |
| 1032 | 1309 | |
| 1033 | 1310 | // Time specific parsing loosely based on java.sql.Timestamp |
| @@ -1093,6 +1370,9 @@ | ||
| 1093 | 1370 | |
| 1094 | 1371 | @Override |
| 1095 | 1372 | public Long parse(String value) { |
| 1373 | + if (value == null || value.isEmpty() || value.equals(NULL)) | |
| 1374 | + return null; | |
| 1375 | + | |
| 1096 | 1376 | // enclosing single quotes required, even for long literals |
| 1097 | 1377 | if (value.charAt(0) != '\'' || value.charAt(value.length() - 1) != '\'') |
| 1098 | 1378 | throw new InvalidTypeException("time values must be enclosed by single quotes"); |
| @@ -1116,7 +1396,7 @@ | ||
| 1116 | 1396 | @Override |
| 1117 | 1397 | public String format(Long value) { |
| 1118 | 1398 | if (value == null) |
| 1119 | - return "null"; | |
| 1399 | + return NULL; | |
| 1120 | 1400 | int nano = (int)(value % 1000000000); |
| 1121 | 1401 | value -= nano; |
| 1122 | 1402 | value /= 1000000000; |
| @@ -1148,16 +1428,19 @@ | ||
| 1148 | 1428 | |
| 1149 | 1429 | } |
| 1150 | 1430 | |
| 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> { | |
| 1154 | 1435 | |
| 1155 | - protected UUIDCodec() {} | |
| 1436 | + private AbstractUUIDCodec(DataType cqlType) { | |
| 1437 | + super(cqlType, UUID.class); | |
| 1438 | + } | |
| 1156 | 1439 | |
| 1157 | 1440 | @Override |
| 1158 | 1441 | public UUID parse(String value) { |
| 1159 | 1442 | try { |
| 1160 | - return UUID.fromString(value); | |
| 1443 | + return value == null || value.isEmpty() || value.equals(NULL) ? null : UUID.fromString(value); | |
| 1161 | 1444 | } catch (IllegalArgumentException e) { |
| 1162 | 1445 | throw new InvalidTypeException(String.format("Cannot parse UUID value from \"%s\"", value)); |
| 1163 | 1446 | } |
| @@ -1165,11 +1448,15 @@ | ||
| 1165 | 1448 | |
| 1166 | 1449 | @Override |
| 1167 | 1450 | public String format(UUID value) { |
| 1451 | + if (value == null) | |
| 1452 | + return NULL; | |
| 1168 | 1453 | return value.toString(); |
| 1169 | 1454 | } |
| 1170 | 1455 | |
| 1171 | 1456 | @Override |
| 1172 | - public ByteBuffer serialize(UUID value) { | |
| 1457 | + public ByteBuffer serialize(UUID value, ProtocolVersion protocolVersion) { | |
| 1458 | + if(value == null) | |
| 1459 | + return null; | |
| 1173 | 1460 | ByteBuffer bb = ByteBuffer.allocate(16); |
| 1174 | 1461 | bb.putLong(0, value.getMostSignificantBits()); |
| 1175 | 1462 | bb.putLong(8, value.getLeastSignificantBits()); |
| @@ -1177,44 +1464,78 @@ | ||
| 1177 | 1464 | } |
| 1178 | 1465 | |
| 1179 | 1466 | @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()); | |
| 1182 | 1481 | } |
| 1482 | + | |
| 1183 | 1483 | } |
| 1184 | 1484 | |
| 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 { | |
| 1186 | 1489 | |
| 1187 | 1490 | public static final TimeUUIDCodec instance = new TimeUUIDCodec(); |
| 1188 | 1491 | |
| 1189 | - private TimeUUIDCodec() {} | |
| 1492 | + private TimeUUIDCodec() { | |
| 1493 | + super(timeuuid()); | |
| 1494 | + } | |
| 1190 | 1495 | |
| 1191 | 1496 | @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); | |
| 1197 | 1512 | } |
| 1198 | 1513 | |
| 1199 | 1514 | @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); | |
| 1205 | 1521 | } |
| 1206 | 1522 | } |
| 1207 | 1523 | |
| 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> { | |
| 1209 | 1528 | |
| 1210 | - public static final BigIntegerCodec instance = new BigIntegerCodec(); | |
| 1529 | + public static final VarintCodec instance = new VarintCodec(); | |
| 1211 | 1530 | |
| 1212 | - private BigIntegerCodec() {} | |
| 1531 | + private VarintCodec() { | |
| 1532 | + super(varint(), BigInteger.class); | |
| 1533 | + } | |
| 1213 | 1534 | |
| 1214 | 1535 | @Override |
| 1215 | 1536 | public BigInteger parse(String value) { |
| 1216 | 1537 | try { |
| 1217 | - return new BigInteger(value); | |
| 1538 | + return value == null || value.isEmpty() || value.equals(NULL) ? null : new BigInteger(value); | |
| 1218 | 1539 | } catch (NumberFormatException e) { |
| 1219 | 1540 | throw new InvalidTypeException(String.format("Cannot parse varint value from \"%s\"", value)); |
| 1220 | 1541 | } |
| @@ -1222,42 +1543,107 @@ | ||
| 1222 | 1543 | |
| 1223 | 1544 | @Override |
| 1224 | 1545 | public String format(BigInteger value) { |
| 1546 | + if (value == null) | |
| 1547 | + return NULL; | |
| 1225 | 1548 | return value.toString(); |
| 1226 | 1549 | } |
| 1227 | 1550 | |
| 1228 | 1551 | @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()); | |
| 1231 | 1554 | } |
| 1232 | 1555 | |
| 1233 | 1556 | @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)); | |
| 1236 | 1559 | } |
| 1237 | 1560 | } |
| 1238 | 1561 | |
| 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> { | |
| 1240 | 1568 | |
| 1241 | - private final TypeCodec<T> eltCodec; | |
| 1242 | - private final ProtocolVersion protocolVersion; | |
| 1569 | + protected final TypeCodec<E> eltCodec; | |
| 1243 | 1570 | |
| 1244 | - public ListCodec(TypeCodec<T> eltCodec, ProtocolVersion protocolVersion) { | |
| 1571 | + public CollectionCodec(CollectionType cqlType, TypeToken<C> javaType, TypeCodec<E> eltCodec) { | |
| 1572 | + super(cqlType, javaType); | |
| 1245 | 1573 | this.eltCodec = eltCodec; |
| 1246 | - this.protocolVersion = protocolVersion; | |
| 1247 | 1574 | } |
| 1248 | 1575 | |
| 1249 | 1576 | @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 | + | |
| 1251 | 1637 | int idx = ParseUtils.skipSpaces(value, 0); |
| 1252 | - if (value.charAt(idx++) != '[') | |
| 1638 | + if (value.charAt(idx++) != getOpeningChar()) | |
| 1253 | 1639 | throw new InvalidTypeException(String.format("cannot parse list value from \"%s\", at character %d expecting '[' but got '%c'", value, idx, value.charAt(idx))); |
| 1254 | 1640 | |
| 1255 | 1641 | idx = ParseUtils.skipSpaces(value, idx); |
| 1256 | 1642 | |
| 1257 | - if (value.charAt(idx) == ']') | |
| 1258 | - return Collections.<T>emptyList(); | |
| 1643 | + if (value.charAt(idx) == getClosingChar()) | |
| 1644 | + return newInstance(0); | |
| 1259 | 1645 | |
| 1260 | - List<T> l = new ArrayList<T>(); | |
| 1646 | + C l = newInstance(10); | |
| 1261 | 1647 | while (idx < value.length()) { |
| 1262 | 1648 | int n; |
| 1263 | 1649 | try { |
| @@ -1270,7 +1656,7 @@ | ||
| 1270 | 1656 | idx = n; |
| 1271 | 1657 | |
| 1272 | 1658 | idx = ParseUtils.skipSpaces(value, idx); |
| 1273 | - if (value.charAt(idx) == ']') | |
| 1659 | + if (value.charAt(idx) == getClosingChar()) | |
| 1274 | 1660 | return l; |
| 1275 | 1661 | if (value.charAt(idx++) != ',') |
| 1276 | 1662 | 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 @@ | ||
| 1281 | 1667 | } |
| 1282 | 1668 | |
| 1283 | 1669 | @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; | |
| 1294 | 1680 | } |
| 1295 | 1681 | |
| 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); | |
| 1301 | 1683 | |
| 1302 | - return pack(bbs, value.size(), protocolVersion); | |
| 1303 | - } | |
| 1684 | + protected abstract C unmodifiable(C coll); | |
| 1304 | 1685 | |
| 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(); | |
| 1321 | 1687 | |
| 1322 | - static class SetCodec<T> extends TypeCodec<Set<T>> { | |
| 1688 | + protected abstract char getClosingChar(); | |
| 1323 | 1689 | |
| 1324 | - private final TypeCodec<T> eltCodec; | |
| 1325 | - private final ProtocolVersion protocolVersion; | |
| 1690 | + } | |
| 1326 | 1691 | |
| 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); | |
| 1330 | 1699 | } |
| 1331 | 1700 | |
| 1332 | 1701 | @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 | + } | |
| 1337 | 1705 | |
| 1338 | - idx = ParseUtils.skipSpaces(value, idx); | |
| 1706 | + @Override | |
| 1707 | + protected List<T> unmodifiable(List<T> coll) { | |
| 1708 | + return Collections.unmodifiableList(coll); | |
| 1709 | + } | |
| 1339 | 1710 | |
| 1340 | - if (value.charAt(idx) == '}') | |
| 1341 | - return Collections.<T>emptySet(); | |
| 1711 | + @Override | |
| 1712 | + protected char getOpeningChar() { | |
| 1713 | + return '['; | |
| 1714 | + } | |
| 1342 | 1715 | |
| 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 | + } | |
| 1351 | 1720 | |
| 1352 | - s.add(eltCodec.parse(value.substring(idx, n))); | |
| 1353 | - idx = n; | |
| 1721 | + } | |
| 1354 | 1722 | |
| 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>> { | |
| 1360 | 1727 | |
| 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); | |
| 1364 | 1730 | } |
| 1365 | 1731 | |
| 1366 | 1732 | @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); | |
| 1378 | 1735 | } |
| 1379 | 1736 | |
| 1380 | 1737 | @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 | + } | |
| 1385 | 1741 | |
| 1386 | - return pack(bbs, value.size(), protocolVersion); | |
| 1742 | + @Override | |
| 1743 | + protected char getOpeningChar() { | |
| 1744 | + return '{'; | |
| 1387 | 1745 | } |
| 1388 | 1746 | |
| 1389 | 1747 | @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 '}'; | |
| 1403 | 1750 | } |
| 1404 | 1751 | } |
| 1405 | 1752 | |
| 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>> { | |
| 1407 | 1757 | |
| 1408 | 1758 | private final TypeCodec<K> keyCodec; |
| 1759 | + | |
| 1409 | 1760 | private final TypeCodec<V> valueCodec; |
| 1410 | - private final ProtocolVersion protocolVersion; | |
| 1411 | 1761 | |
| 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())); | |
| 1413 | 1764 | this.keyCodec = keyCodec; |
| 1414 | 1765 | 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; | |
| 1416 | 1779 | } |
| 1417 | 1780 | |
| 1418 | 1781 | @Override |
| 1419 | 1782 | public Map<K, V> parse(String value) { |
| 1783 | + if (value == null || value.isEmpty() || value.equals(NULL)) | |
| 1784 | + return null; | |
| 1785 | + | |
| 1420 | 1786 | int idx = ParseUtils.skipSpaces(value, 0); |
| 1421 | 1787 | if (value.charAt(idx++) != '{') |
| 1422 | 1788 | 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 @@ | ||
| 1424 | 1790 | idx = ParseUtils.skipSpaces(value, idx); |
| 1425 | 1791 | |
| 1426 | 1792 | if (value.charAt(idx) == '}') |
| 1427 | - return Collections.<K, V>emptyMap(); | |
| 1793 | + return Collections.emptyMap(); | |
| 1428 | 1794 | |
| 1429 | 1795 | Map<K, V> m = new HashMap<K, V>(); |
| 1430 | 1796 | while (idx < value.length()) { |
| @@ -1468,12 +1834,14 @@ | ||
| 1468 | 1834 | |
| 1469 | 1835 | @Override |
| 1470 | 1836 | public String format(Map<K, V> value) { |
| 1837 | + if (value == null) | |
| 1838 | + return NULL; | |
| 1471 | 1839 | StringBuilder sb = new StringBuilder(); |
| 1472 | 1840 | sb.append("{"); |
| 1473 | 1841 | int i = 0; |
| 1474 | 1842 | for (Map.Entry<K, V> e : value.entrySet()) { |
| 1475 | 1843 | if (i++ != 0) |
| 1476 | - sb.append(", "); | |
| 1844 | + sb.append(","); | |
| 1477 | 1845 | sb.append(keyCodec.format(e.getKey())); |
| 1478 | 1846 | sb.append(":"); |
| 1479 | 1847 | sb.append(valueCodec.format(e.getValue())); |
| @@ -1483,57 +1851,146 @@ | ||
| 1483 | 1851 | } |
| 1484 | 1852 | |
| 1485 | 1853 | @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; | |
| 1487 | 1857 | List<ByteBuffer> bbs = new ArrayList<ByteBuffer>(2 * value.size()); |
| 1488 | 1858 | 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); | |
| 1491 | 1881 | } |
| 1492 | - return pack(bbs, value.size(), protocolVersion); | |
| 1882 | + return CodecUtils.pack(bbs, value.size(), protocolVersion); | |
| 1493 | 1883 | } |
| 1494 | 1884 | |
| 1495 | 1885 | @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(); | |
| 1497 | 1889 | try { |
| 1498 | 1890 | ByteBuffer input = bytes.duplicate(); |
| 1499 | - int n = readCollectionSize(input, protocolVersion); | |
| 1891 | + int n = CodecUtils.readCollectionSize(input, protocolVersion); | |
| 1500 | 1892 | Map<K, V> m = new LinkedHashMap<K, V>(n); |
| 1501 | 1893 | 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)); | |
| 1505 | 1897 | } |
| 1506 | - return m; | |
| 1898 | + return Collections.unmodifiableMap(m); | |
| 1507 | 1899 | } catch (BufferUnderflowException e) { |
| 1508 | 1900 | throw new InvalidTypeException("Not enough bytes to deserialize a map"); |
| 1509 | 1901 | } |
| 1510 | 1902 | } |
| 1511 | 1903 | } |
| 1512 | 1904 | |
| 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> { | |
| 1514 | 1909 | |
| 1515 | 1910 | private final UserType definition; |
| 1516 | 1911 | |
| 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); | |
| 1521 | 1914 | 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; | |
| 1523 | 1923 | } |
| 1524 | 1924 | |
| 1525 | 1925 | @Override |
| 1526 | 1926 | 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)); | |
| 1528 | 1981 | } |
| 1529 | 1982 | |
| 1530 | 1983 | @Override |
| 1531 | 1984 | public String format(UDTValue value) { |
| 1985 | + if (value == null) | |
| 1986 | + return NULL; | |
| 1532 | 1987 | return value.toString(); |
| 1533 | 1988 | } |
| 1534 | 1989 | |
| 1535 | 1990 | @Override |
| 1536 | - public ByteBuffer serialize(UDTValue value) { | |
| 1991 | + public ByteBuffer serialize(UDTValue value, ProtocolVersion protocolVersion) { | |
| 1992 | + if (value == null) | |
| 1993 | + return null; | |
| 1537 | 1994 | int size = 0; |
| 1538 | 1995 | for (ByteBuffer v : value.values) |
| 1539 | 1996 | size += 4 + (v == null ? 0 : v.remaining()); |
| @@ -1551,32 +2008,53 @@ | ||
| 1551 | 2008 | } |
| 1552 | 2009 | |
| 1553 | 2010 | @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; | |
| 1555 | 2014 | ByteBuffer input = bytes.duplicate(); |
| 1556 | 2015 | UDTValue value = definition.newValue(); |
| 1557 | 2016 | |
| 1558 | 2017 | int i = 0; |
| 1559 | 2018 | while (input.hasRemaining() && i < value.values.length) { |
| 1560 | 2019 | 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); | |
| 1562 | 2021 | } |
| 1563 | 2022 | return value; |
| 1564 | 2023 | } |
| 1565 | 2024 | } |
| 1566 | 2025 | |
| 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; | |
| 1568 | 2032 | |
| 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 | + } | |
| 1571 | 2044 | |
| 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()); | |
| 1575 | 2050 | } |
| 1576 | 2051 | |
| 1577 | 2052 | @Override |
| 1578 | 2053 | 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(); | |
| 1580 | 2058 | |
| 1581 | 2059 | int idx = ParseUtils.skipSpaces(value, 0); |
| 1582 | 2060 | if (value.charAt(idx++) != '(') |
| @@ -1596,8 +2074,9 @@ | ||
| 1596 | 2074 | throw new InvalidTypeException(String.format("Cannot parse tuple value from \"%s\", invalid CQL value at character %d", value, idx), e); |
| 1597 | 2075 | } |
| 1598 | 2076 | |
| 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()); | |
| 1601 | 2080 | idx = n; |
| 1602 | 2081 | i += 1; |
| 1603 | 2082 | |
| @@ -1615,11 +2094,15 @@ | ||
| 1615 | 2094 | |
| 1616 | 2095 | @Override |
| 1617 | 2096 | public String format(TupleValue value) { |
| 2097 | + if (value == null) | |
| 2098 | + return NULL; | |
| 1618 | 2099 | return value.toString(); |
| 1619 | 2100 | } |
| 1620 | 2101 | |
| 1621 | 2102 | @Override |
| 1622 | - public ByteBuffer serialize(TupleValue value) { | |
| 2103 | + public ByteBuffer serialize(TupleValue value, ProtocolVersion protocolVersion) { | |
| 2104 | + if (value == null) | |
| 2105 | + return null; | |
| 1623 | 2106 | int size = 0; |
| 1624 | 2107 | for (ByteBuffer v : value.values) |
| 1625 | 2108 | size += 4 + (v == null ? 0 : v.remaining()); |
| @@ -1637,16 +2120,226 @@ | ||
| 1637 | 2120 | } |
| 1638 | 2121 | |
| 1639 | 2122 | @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; | |
| 1641 | 2126 | ByteBuffer input = bytes.duplicate(); |
| 1642 | - TupleValue value = type.newValue(); | |
| 2127 | + TupleValue value = definition.newValue(); | |
| 1643 | 2128 | |
| 1644 | 2129 | int i = 0; |
| 1645 | 2130 | while (input.hasRemaining() && i < value.values.length) { |
| 1646 | 2131 | 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); | |
| 1648 | 2133 | } |
| 1649 | 2134 | return value; |
| 1650 | 2135 | } |
| 1651 | 2136 | } |
| 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 | + | |
| 1652 | 2345 | } |
modified driver-core/src/main/java/com/datastax/driver/core/UDTValue.java +17 −5
| @@ -15,6 +15,8 @@ | ||
| 15 | 15 | */ |
| 16 | 16 | package com.datastax.driver.core; |
| 17 | 17 | |
| 18 | +import com.google.common.base.Joiner; | |
| 19 | + | |
| 18 | 20 | /** |
| 19 | 21 | * A value for a User Defined Type. |
| 20 | 22 | */ |
| @@ -23,8 +25,7 @@ | ||
| 23 | 25 | private final UserType definition; |
| 24 | 26 | |
| 25 | 27 | 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()); | |
| 28 | 29 | this.definition = definition; |
| 29 | 30 | } |
| 30 | 31 | |
| @@ -36,6 +37,11 @@ | ||
| 36 | 37 | return definition.byIdx[i].getName(); |
| 37 | 38 | } |
| 38 | 39 | |
| 40 | + @Override | |
| 41 | + protected CodecRegistry getCodecRegistry() { | |
| 42 | + return definition.getCodecRegistry(); | |
| 43 | + } | |
| 44 | + | |
| 39 | 45 | protected int[] getAllIndexesOf(String name) { |
| 40 | 46 | int[] indexes = definition.byName.get(Metadata.handleId(name)); |
| 41 | 47 | if (indexes == null) |
| @@ -75,12 +81,18 @@ | ||
| 75 | 81 | sb.append("{"); |
| 76 | 82 | for (int i = 0; i < values.length; i++) { |
| 77 | 83 | if (i > 0) |
| 78 | - sb.append(", "); | |
| 84 | + sb.append(","); | |
| 79 | 85 | |
| 80 | 86 | sb.append(getName(i)); |
| 81 | 87 | 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 | + } | |
| 84 | 96 | } |
| 85 | 97 | sb.append("}"); |
| 86 | 98 | return sb.toString(); |
modified driver-core/src/main/java/com/datastax/driver/core/UserType.java +34 −73
| @@ -19,9 +19,6 @@ | ||
| 19 | 19 | |
| 20 | 20 | import com.google.common.collect.ImmutableMap; |
| 21 | 21 | import com.google.common.collect.Iterators; |
| 22 | -import com.google.common.reflect.TypeToken; | |
| 23 | - | |
| 24 | -import com.datastax.driver.core.exceptions.InvalidTypeException; | |
| 25 | 22 | |
| 26 | 23 | /** |
| 27 | 24 | * A User Defined Type (UDT). |
| @@ -36,6 +33,9 @@ | ||
| 36 | 33 | |
| 37 | 34 | private final String keyspace; |
| 38 | 35 | private final String typeName; |
| 36 | + private final ProtocolVersion protocolVersion; | |
| 37 | + | |
| 38 | + private volatile CodecRegistry codecRegistry; | |
| 39 | 39 | |
| 40 | 40 | // Note that we don't expose the order of fields, from an API perspective this is a map |
| 41 | 41 | // of String->Field, but internally we care about the order because the serialization format |
| @@ -46,11 +46,14 @@ | ||
| 46 | 46 | // implementation. |
| 47 | 47 | final Map<String, int[]> byName; |
| 48 | 48 | |
| 49 | - UserType(String keyspace, String typeName, Collection<Field> fields) { | |
| 49 | + UserType(String keyspace, String typeName, Collection<Field> fields, ProtocolVersion protocolVersion, CodecRegistry codecRegistry) { | |
| 50 | 50 | super(DataType.Name.UDT); |
| 51 | - | |
| 52 | 51 | this.keyspace = keyspace; |
| 53 | 52 | 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; | |
| 54 | 57 | this.byIdx = fields.toArray(new Field[fields.size()]); |
| 55 | 58 | |
| 56 | 59 | ImmutableMap.Builder<String, int[]> builder = new ImmutableMap.Builder<String, int[]>(); |
| @@ -59,7 +62,7 @@ | ||
| 59 | 62 | this.byName = builder.build(); |
| 60 | 63 | } |
| 61 | 64 | |
| 62 | - static UserType build(Row row) { | |
| 65 | + static UserType build(Row row, ProtocolVersion protocolVersion, CodecRegistry codecRegistry) { | |
| 63 | 66 | String keyspace = row.getString(KeyspaceMetadata.KS_NAME); |
| 64 | 67 | String name = row.getString(TYPE_NAME); |
| 65 | 68 | |
| @@ -68,15 +71,9 @@ | ||
| 68 | 71 | |
| 69 | 72 | List<Field> fields = new ArrayList<Field>(fieldNames.size()); |
| 70 | 73 | 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))); | |
| 75 | 75 | |
| 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); | |
| 80 | 77 | } |
| 81 | 78 | |
| 82 | 79 | /** |
| @@ -172,11 +169,6 @@ | ||
| 172 | 169 | return true; |
| 173 | 170 | } |
| 174 | 171 | |
| 175 | - @Override | |
| 176 | - boolean canBeDeserializedAs(TypeToken typeToken) { | |
| 177 | - return typeToken.isAssignableFrom(getName().javaType); | |
| 178 | - } | |
| 179 | - | |
| 180 | 172 | @Override |
| 181 | 173 | public final int hashCode() { |
| 182 | 174 | return Arrays.hashCode(new Object[]{ name, keyspace, typeName, byIdx }); |
| @@ -224,6 +216,29 @@ | ||
| 224 | 216 | return asCQLQuery(false); |
| 225 | 217 | } |
| 226 | 218 | |
| 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 | + | |
| 227 | 242 | private String asCQLQuery(boolean formatted) { |
| 228 | 243 | StringBuilder sb = new StringBuilder(); |
| 229 | 244 | |
| @@ -244,60 +259,6 @@ | ||
| 244 | 259 | return "frozen<" + Metadata.escapeId(getKeyspace()) + '.' + Metadata.escapeId(getTypeName()) + ">"; |
| 245 | 260 | } |
| 246 | 261 | |
| 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 | - | |
| 301 | 262 | /** |
| 302 | 263 | * A UDT field. |
| 303 | 264 | */ |
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 @@ | ||
| 15 | 15 | */ |
| 16 | 16 | package com.datastax.driver.core.querybuilder; |
| 17 | 17 | |
| 18 | -import java.nio.ByteBuffer; | |
| 19 | 18 | import java.util.List; |
| 20 | 19 | |
| 20 | +import com.datastax.driver.core.CodecRegistry; | |
| 21 | + | |
| 21 | 22 | import static com.datastax.driver.core.querybuilder.Utils.appendName; |
| 22 | 23 | import static com.datastax.driver.core.querybuilder.Utils.appendValue; |
| 23 | 24 | |
| @@ -50,10 +51,10 @@ | ||
| 50 | 51 | } |
| 51 | 52 | |
| 52 | 53 | @Override |
| 53 | - void appendTo(StringBuilder sb, List<Object> variables) { | |
| 54 | + void appendTo(StringBuilder sb, List<Object> variables, CodecRegistry codecRegistry) { | |
| 54 | 55 | appendName(name, sb); |
| 55 | 56 | sb.append('='); |
| 56 | - appendValue(value, sb, variables); | |
| 57 | + appendValue(value, codecRegistry, sb, variables); | |
| 57 | 58 | } |
| 58 | 59 | |
| 59 | 60 | @Override |
| @@ -84,10 +85,10 @@ | ||
| 84 | 85 | } |
| 85 | 86 | |
| 86 | 87 | @Override |
| 87 | - void appendTo(StringBuilder sb, List<Object> variables) { | |
| 88 | + void appendTo(StringBuilder sb, List<Object> variables, CodecRegistry codecRegistry) { | |
| 88 | 89 | appendName(name, sb).append('='); |
| 89 | 90 | appendName(name, sb).append(isIncr ? "+" : "-"); |
| 90 | - appendValue(value, sb, variables); | |
| 91 | + appendValue(value, codecRegistry, sb, variables); | |
| 91 | 92 | } |
| 92 | 93 | |
| 93 | 94 | @Override |
| @@ -111,9 +112,9 @@ | ||
| 111 | 112 | } |
| 112 | 113 | |
| 113 | 114 | @Override |
| 114 | - void appendTo(StringBuilder sb, List<Object> variables) { | |
| 115 | + void appendTo(StringBuilder sb, List<Object> variables, CodecRegistry codecRegistry) { | |
| 115 | 116 | appendName(name, sb).append('='); |
| 116 | - appendValue(value, sb, variables); | |
| 117 | + appendValue(value, codecRegistry, sb, variables); | |
| 117 | 118 | sb.append('+'); |
| 118 | 119 | appendName(name, sb); |
| 119 | 120 | } |
| @@ -141,9 +142,9 @@ | ||
| 141 | 142 | } |
| 142 | 143 | |
| 143 | 144 | @Override |
| 144 | - void appendTo(StringBuilder sb, List<Object> variables) { | |
| 145 | + void appendTo(StringBuilder sb, List<Object> variables, CodecRegistry codecRegistry) { | |
| 145 | 146 | appendName(name, sb).append('[').append(idx).append("]="); |
| 146 | - appendValue(value, sb, variables); | |
| 147 | + appendValue(value, codecRegistry, sb, variables); | |
| 147 | 148 | } |
| 148 | 149 | |
| 149 | 150 | @Override |
| @@ -175,10 +176,10 @@ | ||
| 175 | 176 | } |
| 176 | 177 | |
| 177 | 178 | @Override |
| 178 | - void appendTo(StringBuilder sb, List<Object> variables) { | |
| 179 | + void appendTo(StringBuilder sb, List<Object> variables, CodecRegistry codecRegistry) { | |
| 179 | 180 | appendName(name, sb).append('='); |
| 180 | 181 | appendName(name, sb).append(isAdd ? "+" : "-"); |
| 181 | - appendValue(collection, sb, variables); | |
| 182 | + appendValue(collection, codecRegistry, sb, variables); | |
| 182 | 183 | } |
| 183 | 184 | |
| 184 | 185 | @Override |
| @@ -204,11 +205,11 @@ | ||
| 204 | 205 | } |
| 205 | 206 | |
| 206 | 207 | @Override |
| 207 | - void appendTo(StringBuilder sb, List<Object> variables) { | |
| 208 | + void appendTo(StringBuilder sb, List<Object> variables, CodecRegistry codecRegistry) { | |
| 208 | 209 | appendName(name, sb).append('['); |
| 209 | - appendValue(key, sb, variables); | |
| 210 | + appendValue(key, codecRegistry, sb, variables); | |
| 210 | 211 | sb.append("]="); |
| 211 | - appendValue(value, sb, variables); | |
| 212 | + appendValue(value, codecRegistry, sb, variables); | |
| 212 | 213 | } |
| 213 | 214 | |
| 214 | 215 | @Override |
modified driver-core/src/main/java/com/datastax/driver/core/querybuilder/Batch.java +14 −14
| @@ -19,9 +19,7 @@ | ||
| 19 | 19 | import java.util.ArrayList; |
| 20 | 20 | import java.util.List; |
| 21 | 21 | |
| 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.*; | |
| 25 | 23 | |
| 26 | 24 | /** |
| 27 | 25 | * A built BATCH statement. |
| @@ -31,13 +29,12 @@ | ||
| 31 | 29 | private final List<RegularStatement> statements; |
| 32 | 30 | private final boolean logged; |
| 33 | 31 | private final Options usings; |
| 34 | - private ByteBuffer routingKey; | |
| 35 | 32 | |
| 36 | 33 | // Only used when we add at last one statement that is not a BuiltStatement subclass |
| 37 | 34 | private int nonBuiltStatementValues; |
| 38 | 35 | |
| 39 | - Batch(RegularStatement[] statements, boolean logged) { | |
| 40 | - super((String)null); | |
| 36 | + Batch(Cluster cluster, RegularStatement[] statements, boolean logged) { | |
| 37 | + super((String)null, cluster); | |
| 41 | 38 | this.statements = statements.length == 0 |
| 42 | 39 | ? new ArrayList<RegularStatement>() |
| 43 | 40 | : new ArrayList<RegularStatement>(statements.length); |
| @@ -58,7 +55,7 @@ | ||
| 58 | 55 | |
| 59 | 56 | if (!usings.usings.isEmpty()) { |
| 60 | 57 | builder.append(" USING "); |
| 61 | - Utils.joinAndAppend(builder, " AND ", usings.usings, variables); | |
| 58 | + Utils.joinAndAppend(builder, getCodecRegistry(), " AND ", usings.usings, variables); | |
| 62 | 59 | } |
| 63 | 60 | builder.append(' '); |
| 64 | 61 | |
| @@ -116,21 +113,18 @@ | ||
| 116 | 113 | |
| 117 | 114 | checkForBindMarkers(null); |
| 118 | 115 | |
| 119 | - if (routingKey == null && statement.getRoutingKey() != null) | |
| 120 | - routingKey = statement.getRoutingKey(); | |
| 121 | - | |
| 122 | 116 | return this; |
| 123 | 117 | } |
| 124 | 118 | |
| 125 | 119 | @Override |
| 126 | - public ByteBuffer[] getValues(ProtocolVersion protocolVersion) { | |
| 120 | + public ByteBuffer[] getValues() { | |
| 127 | 121 | // If there is some non-BuiltStatement inside the batch with values, we shouldn't |
| 128 | 122 | // use super.getValues() since it will ignore the values of said non-BuiltStatement. |
| 129 | 123 | // If that's the case, we just collects all those values (and we know |
| 130 | 124 | // super.getValues() == null in that case since we've explicitely set this.hasBindMarker |
| 131 | 125 | // to true). Otherwise, we simply call super.getValues(). |
| 132 | 126 | if (nonBuiltStatementValues == 0) |
| 133 | - return super.getValues(protocolVersion); | |
| 127 | + return super.getValues(); | |
| 134 | 128 | |
| 135 | 129 | ByteBuffer[] values = new ByteBuffer[nonBuiltStatementValues]; |
| 136 | 130 | int i = 0; |
| @@ -139,7 +133,7 @@ | ||
| 139 | 133 | if (statement instanceof BuiltStatement) |
| 140 | 134 | continue; |
| 141 | 135 | |
| 142 | - ByteBuffer[] statementValues = statement.getValues(protocolVersion); | |
| 136 | + ByteBuffer[] statementValues = statement.getValues(); | |
| 143 | 137 | System.arraycopy(statementValues, 0, values, i, statementValues.length); |
| 144 | 138 | i += statementValues.length; |
| 145 | 139 | } |
| @@ -164,7 +158,13 @@ | ||
| 164 | 158 | */ |
| 165 | 159 | @Override |
| 166 | 160 | 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; | |
| 168 | 168 | } |
| 169 | 169 | |
| 170 | 170 | /** |
modified driver-core/src/main/java/com/datastax/driver/core/querybuilder/BuiltStatement.java +57 −60
| @@ -17,12 +17,16 @@ | ||
| 17 | 17 | |
| 18 | 18 | import java.nio.ByteBuffer; |
| 19 | 19 | import java.util.ArrayList; |
| 20 | +import java.util.Arrays; | |
| 20 | 21 | import java.util.List; |
| 21 | 22 | import java.util.regex.Pattern; |
| 22 | 23 | |
| 23 | 24 | import com.datastax.driver.core.*; |
| 24 | 25 | import com.datastax.driver.core.policies.RetryPolicy; |
| 25 | 26 | |
| 27 | +import static com.datastax.driver.core.CodecUtils.compose; | |
| 28 | +import static com.datastax.driver.core.CodecUtils.convert; | |
| 29 | + | |
| 26 | 30 | /** |
| 27 | 31 | * Common ancestor to the query builder built statements. |
| 28 | 32 | */ |
| @@ -31,13 +35,13 @@ | ||
| 31 | 35 | private static final Pattern lowercaseId = Pattern.compile("[a-z][a-z0-9_]*"); |
| 32 | 36 | |
| 33 | 37 | private final List<ColumnMetadata> partitionKey; |
| 34 | - private final ByteBuffer[] routingKey; | |
| 38 | + private final List<Object> routingKeyValues; | |
| 35 | 39 | final String keyspace; |
| 40 | + protected final Cluster cluster; | |
| 36 | 41 | |
| 37 | 42 | private boolean dirty; |
| 38 | 43 | private String cache; |
| 39 | 44 | private List<Object> values; |
| 40 | - | |
| 41 | 45 | Boolean isCounterOp; |
| 42 | 46 | boolean hasNonIdempotentOps; |
| 43 | 47 | |
| @@ -46,16 +50,18 @@ | ||
| 46 | 50 | boolean hasBindMarkers; |
| 47 | 51 | private boolean forceNoValues; |
| 48 | 52 | |
| 49 | - BuiltStatement(String keyspace) { | |
| 53 | + BuiltStatement(String keyspace, Cluster cluster) { | |
| 50 | 54 | this.partitionKey = null; |
| 51 | - this.routingKey = null; | |
| 55 | + this.routingKeyValues = null; | |
| 52 | 56 | this.keyspace = keyspace; |
| 57 | + this.cluster = cluster; | |
| 53 | 58 | } |
| 54 | 59 | |
| 55 | - BuiltStatement(TableMetadata tableMetadata) { | |
| 60 | + BuiltStatement(TableMetadata tableMetadata, Cluster cluster) { | |
| 56 | 61 | this.partitionKey = tableMetadata.getPartitionKey(); |
| 57 | - this.routingKey = new ByteBuffer[tableMetadata.getPartitionKey().size()]; | |
| 62 | + this.routingKeyValues = Arrays.asList(new Object[tableMetadata.getPartitionKey().size()]); | |
| 58 | 63 | this.keyspace = escapeId(tableMetadata.getKeyspace().getName()); |
| 64 | + this.cluster = cluster; | |
| 59 | 65 | } |
| 60 | 66 | |
| 61 | 67 | // Same as Metadata.escapeId, but we don't have access to it here. |
| @@ -142,32 +148,47 @@ | ||
| 142 | 148 | |
| 143 | 149 | // TODO: Correctly document the InvalidTypeException |
| 144 | 150 | 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) | |
| 146 | 152 | return; |
| 147 | 153 | |
| 148 | 154 | for (int i = 0; i < partitionKey.size(); i++) { |
| 149 | 155 | 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); | |
| 154 | 157 | return; |
| 155 | 158 | } |
| 156 | 159 | } |
| 157 | 160 | } |
| 158 | 161 | |
| 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 | + */ | |
| 159 | 176 | @Override |
| 160 | 177 | public ByteBuffer getRoutingKey() { |
| 161 | - if (routingKey == null) | |
| 178 | + if (routingKeyValues == null) | |
| 162 | 179 | 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) | |
| 166 | 185 | 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); | |
| 171 | 192 | } |
| 172 | 193 | |
| 173 | 194 | @Override |
| @@ -175,10 +196,15 @@ | ||
| 175 | 196 | return keyspace; |
| 176 | 197 | } |
| 177 | 198 | |
| 199 | + /** | |
| 200 | + * {@inheritDoc} | |
| 201 | + * <p> | |
| 202 | + * Note: Calling this method may trigger the underlying {@link Cluster} initialization. | |
| 203 | + */ | |
| 178 | 204 | @Override |
| 179 | - public ByteBuffer[] getValues(ProtocolVersion protocolVersion) { | |
| 205 | + public ByteBuffer[] getValues() { | |
| 180 | 206 | maybeRebuildCache(); |
| 181 | - return values == null ? null : Utils.convert(values, protocolVersion); | |
| 207 | + return values == null ? null : convert(values.toArray(), getProtocolVersion(), getCodecRegistry()); | |
| 182 | 208 | } |
| 183 | 209 | |
| 184 | 210 | @Override |
| @@ -197,20 +223,19 @@ | ||
| 197 | 223 | return !hasNonIdempotentOps(); |
| 198 | 224 | } |
| 199 | 225 | |
| 226 | + /** | |
| 227 | + * {@inheritDoc} | |
| 228 | + * <p> | |
| 229 | + * Note: Calling this method may trigger the underlying {@link Cluster} initialization. | |
| 230 | + */ | |
| 200 | 231 | @Override |
| 201 | 232 | public String toString() { |
| 202 | - if (forceNoValues) | |
| 233 | + if (forceNoValues) { | |
| 203 | 234 | return getQueryString(); |
| 204 | - | |
| 235 | + } | |
| 205 | 236 | return maybeAddSemicolon(buildQueryString(null)).toString(); |
| 206 | 237 | } |
| 207 | 238 | |
| 208 | - // Not meant to be public | |
| 209 | - List<Object> getRawValues() { | |
| 210 | - maybeRebuildCache(); | |
| 211 | - return values; | |
| 212 | - } | |
| 213 | - | |
| 214 | 239 | /** |
| 215 | 240 | * Allows to force this builder to not generate values (through its {@code getValues()} method). |
| 216 | 241 | * <p> |
| @@ -245,29 +270,6 @@ | ||
| 245 | 270 | return this; |
| 246 | 271 | } |
| 247 | 272 | |
| 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 | - | |
| 271 | 273 | /** |
| 272 | 274 | * An utility class to create a BuiltStatement that encapsulate another one. |
| 273 | 275 | */ |
| @@ -276,7 +278,7 @@ | ||
| 276 | 278 | T statement; |
| 277 | 279 | |
| 278 | 280 | ForwardingStatement(T statement) { |
| 279 | - super((String)null); | |
| 281 | + super((String)null, statement.cluster); | |
| 280 | 282 | this.statement = statement; |
| 281 | 283 | } |
| 282 | 284 | |
| @@ -316,11 +318,6 @@ | ||
| 316 | 318 | return this; |
| 317 | 319 | } |
| 318 | 320 | |
| 319 | - @Override | |
| 320 | - List<Object> getRawValues() { | |
| 321 | - return statement.getRawValues(); | |
| 322 | - } | |
| 323 | - | |
| 324 | 321 | @Override |
| 325 | 322 | public Statement setConsistencyLevel(ConsistencyLevel consistency) { |
| 326 | 323 | statement.setConsistencyLevel(consistency); |
| @@ -361,8 +358,8 @@ | ||
| 361 | 358 | } |
| 362 | 359 | |
| 363 | 360 | @Override |
| 364 | - public ByteBuffer[] getValues(ProtocolVersion protocolVersion) { | |
| 365 | - return statement.getValues(protocolVersion); | |
| 361 | + public ByteBuffer[] getValues() { | |
| 362 | + return statement.getValues(); | |
| 366 | 363 | } |
| 367 | 364 | |
| 368 | 365 | @Override |
modified driver-core/src/main/java/com/datastax/driver/core/querybuilder/Clause.java +14 −12
| @@ -17,6 +17,8 @@ | ||
| 17 | 17 | |
| 18 | 18 | import java.util.List; |
| 19 | 19 | |
| 20 | +import com.datastax.driver.core.CodecRegistry; | |
| 21 | + | |
| 20 | 22 | public abstract class Clause extends Utils.Appendeable { |
| 21 | 23 | |
| 22 | 24 | abstract String name(); |
| @@ -47,9 +49,9 @@ | ||
| 47 | 49 | } |
| 48 | 50 | |
| 49 | 51 | @Override |
| 50 | - void appendTo(StringBuilder sb, List<Object> variables) { | |
| 52 | + void appendTo(StringBuilder sb, List<Object> variables, CodecRegistry codecRegistry) { | |
| 51 | 53 | Utils.appendName(name, sb).append(op); |
| 52 | - Utils.appendValue(value, sb, variables); | |
| 54 | + Utils.appendValue(value, codecRegistry, sb, variables); | |
| 53 | 55 | } |
| 54 | 56 | |
| 55 | 57 | @Override |
| @@ -78,7 +80,7 @@ | ||
| 78 | 80 | } |
| 79 | 81 | |
| 80 | 82 | @Override |
| 81 | - void appendTo(StringBuilder sb, List<Object> variables) { | |
| 83 | + void appendTo(StringBuilder sb, List<Object> variables, CodecRegistry codecRegistry) { | |
| 82 | 84 | |
| 83 | 85 | // We special case the case of just one bind marker because there is little |
| 84 | 86 | // reasons to do: |
| @@ -93,7 +95,7 @@ | ||
| 93 | 95 | } |
| 94 | 96 | |
| 95 | 97 | Utils.appendName(name, sb).append(" IN ("); |
| 96 | - Utils.joinAndAppendValues(sb, ",", values, variables).append(')'); | |
| 98 | + Utils.joinAndAppendValues(sb, codecRegistry, ",", values, variables).append(')'); | |
| 97 | 99 | } |
| 98 | 100 | |
| 99 | 101 | @Override |
| @@ -123,9 +125,9 @@ | ||
| 123 | 125 | } |
| 124 | 126 | |
| 125 | 127 | @Override |
| 126 | - void appendTo(StringBuilder sb, List<Object> variables) { | |
| 128 | + void appendTo(StringBuilder sb, List<Object> variables, CodecRegistry codecRegistry) { | |
| 127 | 129 | Utils.appendName(name, sb).append(" CONTAINS "); |
| 128 | - Utils.appendValue(value, sb, variables); | |
| 130 | + Utils.appendValue(value, codecRegistry, sb, variables); | |
| 129 | 131 | } |
| 130 | 132 | |
| 131 | 133 | @Override |
| @@ -153,9 +155,9 @@ | ||
| 153 | 155 | } |
| 154 | 156 | |
| 155 | 157 | @Override |
| 156 | - void appendTo(StringBuilder sb, List<Object> variables) { | |
| 158 | + void appendTo(StringBuilder sb, List<Object> variables, CodecRegistry codecRegistry) { | |
| 157 | 159 | Utils.appendName(name, sb).append(" CONTAINS KEY "); |
| 158 | - Utils.appendValue(value, sb, variables); | |
| 160 | + Utils.appendValue(value, codecRegistry, sb, variables); | |
| 159 | 161 | } |
| 160 | 162 | |
| 161 | 163 | @Override |
| @@ -198,14 +200,14 @@ | ||
| 198 | 200 | |
| 199 | 201 | @Override |
| 200 | 202 | 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)) | |
| 203 | 205 | return true; |
| 204 | 206 | return false; |
| 205 | 207 | } |
| 206 | 208 | |
| 207 | 209 | @Override |
| 208 | - void appendTo(StringBuilder sb, List<Object> variables) { | |
| 210 | + void appendTo(StringBuilder sb, List<Object> variables, CodecRegistry codecRegistry) { | |
| 209 | 211 | sb.append("("); |
| 210 | 212 | for (int i = 0; i < names.size(); i++) { |
| 211 | 213 | if (i > 0) |
| @@ -216,7 +218,7 @@ | ||
| 216 | 218 | for (int i = 0; i < values.size(); i++) { |
| 217 | 219 | if (i > 0) |
| 218 | 220 | sb.append(","); |
| 219 | - Utils.appendValue(values.get(i), sb, variables); | |
| 221 | + Utils.appendValue(values.get(i), codecRegistry, sb, variables); | |
| 220 | 222 | } |
| 221 | 223 | sb.append(")"); |
| 222 | 224 | } |
modified driver-core/src/main/java/com/datastax/driver/core/querybuilder/Delete.java +28 −19
| @@ -18,6 +18,8 @@ | ||
| 18 | 18 | import java.util.ArrayList; |
| 19 | 19 | import java.util.List; |
| 20 | 20 | |
| 21 | +import com.datastax.driver.core.Cluster; | |
| 22 | +import com.datastax.driver.core.CodecRegistry; | |
| 21 | 23 | import com.datastax.driver.core.TableMetadata; |
| 22 | 24 | |
| 23 | 25 | /** |
| @@ -32,8 +34,8 @@ | ||
| 32 | 34 | private final Conditions conditions; |
| 33 | 35 | private boolean ifExists; |
| 34 | 36 | |
| 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); | |
| 37 | 39 | this.table = table; |
| 38 | 40 | this.columns = columns; |
| 39 | 41 | this.where = new Where(this); |
| @@ -41,8 +43,8 @@ | ||
| 41 | 43 | this.conditions = new Conditions(this); |
| 42 | 44 | } |
| 43 | 45 | |
| 44 | - Delete(TableMetadata table, List<Selector> columns) { | |
| 45 | - super(table); | |
| 46 | + Delete(Cluster cluster, TableMetadata table, List<Selector> columns) { | |
| 47 | + super(table, cluster); | |
| 46 | 48 | this.table = escapeId(table.getName()); |
| 47 | 49 | this.columns = columns; |
| 48 | 50 | this.where = new Where(this); |
| @@ -54,9 +56,10 @@ | ||
| 54 | 56 | StringBuilder buildQueryString(List<Object> variables) { |
| 55 | 57 | StringBuilder builder = new StringBuilder(); |
| 56 | 58 | |
| 59 | + CodecRegistry codecRegistry = getCodecRegistry(); | |
| 57 | 60 | builder.append("DELETE"); |
| 58 | 61 | if (!columns.isEmpty()) |
| 59 | - Utils.joinAndAppend(builder.append(" "), ",", columns, variables); | |
| 62 | + Utils.joinAndAppend(builder.append(" "), codecRegistry, ",", columns, variables); | |
| 60 | 63 | |
| 61 | 64 | builder.append(" FROM "); |
| 62 | 65 | if (keyspace != null) |
| @@ -64,12 +67,12 @@ | ||
| 64 | 67 | Utils.appendName(table, builder); |
| 65 | 68 | if (!usings.usings.isEmpty()) { |
| 66 | 69 | builder.append(" USING "); |
| 67 | - Utils.joinAndAppend(builder, " AND ", usings.usings, variables); | |
| 70 | + Utils.joinAndAppend(builder, codecRegistry, " AND ", usings.usings, variables); | |
| 68 | 71 | } |
| 69 | 72 | |
| 70 | 73 | if (!where.clauses.isEmpty()) { |
| 71 | 74 | builder.append(" WHERE "); |
| 72 | - Utils.joinAndAppend(builder, " AND ", where.clauses, variables); | |
| 75 | + Utils.joinAndAppend(builder, codecRegistry, " AND ", where.clauses, variables); | |
| 73 | 76 | } |
| 74 | 77 | |
| 75 | 78 | if (ifExists) { |
| @@ -78,7 +81,7 @@ | ||
| 78 | 81 | |
| 79 | 82 | if (!conditions.conditions.isEmpty()) { |
| 80 | 83 | builder.append(" IF "); |
| 81 | - Utils.joinAndAppend(builder, " AND ", conditions.conditions, variables); | |
| 84 | + Utils.joinAndAppend(builder, codecRegistry, " AND ", conditions.conditions, variables); | |
| 82 | 85 | } |
| 83 | 86 | |
| 84 | 87 | return builder; |
| @@ -274,12 +277,16 @@ | ||
| 274 | 277 | */ |
| 275 | 278 | public static class Builder { |
| 276 | 279 | |
| 280 | + private final Cluster cluster; | |
| 281 | + | |
| 277 | 282 | List<Selector> columns = new ArrayList<Selector>(); |
| 278 | 283 | |
| 279 | - Builder() { | |
| 284 | + Builder(Cluster cluster) { | |
| 285 | + this.cluster = cluster; | |
| 280 | 286 | } |
| 281 | 287 | |
| 282 | - Builder(String... columnNames) { | |
| 288 | + Builder(Cluster cluster, String... columnNames) { | |
| 289 | + this.cluster = cluster; | |
| 283 | 290 | for (String columnName : columnNames) { |
| 284 | 291 | this.columns.add(new Selector(columnName)); |
| 285 | 292 | } |
| @@ -303,7 +310,7 @@ | ||
| 303 | 310 | * @return a newly built DELETE statement that deletes from {@code keyspace.table}. |
| 304 | 311 | */ |
| 305 | 312 | public Delete from(String keyspace, String table) { |
| 306 | - return new Delete(keyspace, table, columns); | |
| 313 | + return new Delete(cluster, keyspace, table, columns); | |
| 307 | 314 | } |
| 308 | 315 | |
| 309 | 316 | /** |
| @@ -313,7 +320,7 @@ | ||
| 313 | 320 | * @return a newly built DELETE statement that deletes from {@code table}. |
| 314 | 321 | */ |
| 315 | 322 | public Delete from(TableMetadata table) { |
| 316 | - return new Delete(table, columns); | |
| 323 | + return new Delete(cluster, table, columns); | |
| 317 | 324 | } |
| 318 | 325 | } |
| 319 | 326 | |
| @@ -322,6 +329,10 @@ | ||
| 322 | 329 | */ |
| 323 | 330 | public static class Selection extends Builder { |
| 324 | 331 | |
| 332 | + Selection(Cluster cluster) { | |
| 333 | + super(cluster); | |
| 334 | + } | |
| 335 | + | |
| 325 | 336 | /** |
| 326 | 337 | * Deletes all columns (i.e. "DELETE FROM ...") |
| 327 | 338 | * |
| @@ -424,7 +435,7 @@ | ||
| 424 | 435 | } |
| 425 | 436 | |
| 426 | 437 | @Override |
| 427 | - void appendTo(StringBuilder sb, List<Object> values) { | |
| 438 | + void appendTo(StringBuilder sb, List<Object> values, CodecRegistry codecRegistry) { | |
| 428 | 439 | Utils.appendName(columnName, sb); |
| 429 | 440 | } |
| 430 | 441 | |
| @@ -435,9 +446,7 @@ | ||
| 435 | 446 | |
| 436 | 447 | @Override |
| 437 | 448 | public String toString() { |
| 438 | - StringBuilder sb = new StringBuilder(); | |
| 439 | - appendTo(sb, new ArrayList<Object>()); | |
| 440 | - return sb.toString(); | |
| 449 | + return columnName; | |
| 441 | 450 | } |
| 442 | 451 | } |
| 443 | 452 | |
| @@ -454,10 +463,10 @@ | ||
| 454 | 463 | } |
| 455 | 464 | |
| 456 | 465 | @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); | |
| 459 | 468 | sb.append('['); |
| 460 | - Utils.appendValue(key, sb); | |
| 469 | + Utils.appendValue(key, codecRegistry, sb, values); | |
| 461 | 470 | sb.append(']'); |
| 462 | 471 | } |
| 463 | 472 |
modified driver-core/src/main/java/com/datastax/driver/core/querybuilder/Insert.java +10 −7
| @@ -19,6 +19,8 @@ | ||
| 19 | 19 | import java.util.Arrays; |
| 20 | 20 | import java.util.List; |
| 21 | 21 | |
| 22 | +import com.datastax.driver.core.Cluster; | |
| 23 | +import com.datastax.driver.core.CodecRegistry; | |
| 22 | 24 | import com.datastax.driver.core.TableMetadata; |
| 23 | 25 | |
| 24 | 26 | /** |
| @@ -32,14 +34,14 @@ | ||
| 32 | 34 | private final Options usings; |
| 33 | 35 | private boolean ifNotExists; |
| 34 | 36 | |
| 35 | - Insert(String keyspace, String table) { | |
| 36 | - super(keyspace); | |
| 37 | + Insert(Cluster cluster, String keyspace, String table) { | |
| 38 | + super(keyspace, cluster); | |
| 37 | 39 | this.table = table; |
| 38 | 40 | this.usings = new Options(this); |
| 39 | 41 | } |
| 40 | 42 | |
| 41 | - Insert(TableMetadata table) { | |
| 42 | - super(table); | |
| 43 | + Insert(Cluster cluster, TableMetadata table) { | |
| 44 | + super(table, cluster); | |
| 43 | 45 | this.table = escapeId(table.getName()); |
| 44 | 46 | this.usings = new Options(this); |
| 45 | 47 | } |
| @@ -48,14 +50,15 @@ | ||
| 48 | 50 | StringBuilder buildQueryString(List<Object> variables) { |
| 49 | 51 | StringBuilder builder = new StringBuilder(); |
| 50 | 52 | |
| 53 | + CodecRegistry codecRegistry = getCodecRegistry(); | |
| 51 | 54 | builder.append("INSERT INTO "); |
| 52 | 55 | if (keyspace != null) |
| 53 | 56 | Utils.appendName(keyspace, builder).append('.'); |
| 54 | 57 | Utils.appendName(table, builder); |
| 55 | 58 | builder.append('('); |
| 56 | - Utils.joinAndAppendNames(builder, ",", names); | |
| 59 | + Utils.joinAndAppendNames(builder, codecRegistry, ",", names); | |
| 57 | 60 | builder.append(") VALUES ("); |
| 58 | - Utils.joinAndAppendValues(builder, ",", values, variables); | |
| 61 | + Utils.joinAndAppendValues(builder, codecRegistry, ",", values, variables); | |
| 59 | 62 | builder.append(')'); |
| 60 | 63 | |
| 61 | 64 | if (ifNotExists) |
| @@ -63,7 +66,7 @@ | ||
| 63 | 66 | |
| 64 | 67 | if (!usings.usings.isEmpty()) { |
| 65 | 68 | builder.append(" USING "); |
| 66 | - Utils.joinAndAppend(builder, " AND ", usings.usings, variables); | |
| 69 | + Utils.joinAndAppend(builder, codecRegistry, " AND ", usings.usings, variables); | |
| 67 | 70 | } |
| 68 | 71 | return builder; |
| 69 | 72 | } |
modified driver-core/src/main/java/com/datastax/driver/core/querybuilder/Ordering.java +3 −1
| @@ -17,6 +17,8 @@ | ||
| 17 | 17 | |
| 18 | 18 | import java.util.List; |
| 19 | 19 | |
| 20 | +import com.datastax.driver.core.CodecRegistry; | |
| 21 | + | |
| 20 | 22 | public class Ordering extends Utils.Appendeable { |
| 21 | 23 | |
| 22 | 24 | private final String name; |
| @@ -28,7 +30,7 @@ | ||
| 28 | 30 | } |
| 29 | 31 | |
| 30 | 32 | @Override |
| 31 | - void appendTo(StringBuilder sb, List<Object> variables) { | |
| 33 | + void appendTo(StringBuilder sb, List<Object> variables, CodecRegistry codecRegistry) { | |
| 32 | 34 | Utils.appendName(name, sb); |
| 33 | 35 | sb.append(isDesc ? " DESC" : " ASC"); |
| 34 | 36 | } |
modified driver-core/src/main/java/com/datastax/driver/core/querybuilder/QueryBuilder.java +48 −35
| @@ -17,12 +17,13 @@ | ||
| 17 | 17 | |
| 18 | 18 | import java.util.*; |
| 19 | 19 | |
| 20 | +import com.datastax.driver.core.Cluster; | |
| 20 | 21 | import com.datastax.driver.core.RegularStatement; |
| 21 | 22 | import com.datastax.driver.core.TableMetadata; |
| 22 | 23 | import com.datastax.driver.core.exceptions.InvalidQueryException; |
| 23 | 24 | |
| 24 | 25 | /** |
| 25 | - * Static methods to build a CQL3 query. | |
| 26 | + * Builds CQL3 query via a fluent API. | |
| 26 | 27 | * <p> |
| 27 | 28 | * The queries built by this builder will provide a value for the |
| 28 | 29 | * {@link com.datastax.driver.core.Statement#getRoutingKey} method only when a |
| @@ -30,15 +31,27 @@ | ||
| 30 | 31 | * It is thus advised to do so if a {@link com.datastax.driver.core.policies.TokenAwarePolicy} |
| 31 | 32 | * is in use. |
| 32 | 33 | * <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. | |
| 34 | 35 | * There is thus no guarantee that a built query is valid, and it is |
| 35 | 36 | * definitively possible to create invalid queries. |
| 36 | 37 | * <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. | |
| 38 | 40 | */ |
| 39 | 41 | public final class QueryBuilder { |
| 40 | 42 | |
| 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 | + } | |
| 42 | 55 | |
| 43 | 56 | /** |
| 44 | 57 | * Start building a new SELECT query that selects the provided names. |
| @@ -49,8 +62,8 @@ | ||
| 49 | 62 | * @return an in-construction SELECT query (you will need to provide at |
| 50 | 63 | * least a FROM clause to complete the query). |
| 51 | 64 | */ |
| 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)); | |
| 54 | 67 | } |
| 55 | 68 | |
| 56 | 69 | /** |
| @@ -59,9 +72,9 @@ | ||
| 59 | 72 | * @return an in-construction SELECT query (you will need to provide a |
| 60 | 73 | * column selection and at least a FROM clause to complete the query). |
| 61 | 74 | */ |
| 62 | - public static Select.Selection select() { | |
| 75 | + public Select.Selection select() { | |
| 63 | 76 | // Note: the fact we return Select.Selection as return type is on purpose. |
| 64 | - return new Select.SelectionOrAlias(); | |
| 77 | + return new Select.SelectionOrAlias(cluster); | |
| 65 | 78 | } |
| 66 | 79 | |
| 67 | 80 | /** |
| @@ -70,8 +83,8 @@ | ||
| 70 | 83 | * @param table the name of the table in which to insert. |
| 71 | 84 | * @return an in-construction INSERT query. |
| 72 | 85 | */ |
| 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); | |
| 75 | 88 | } |
| 76 | 89 | |
| 77 | 90 | /** |
| @@ -81,8 +94,8 @@ | ||
| 81 | 94 | * @param table the name of the table to insert into. |
| 82 | 95 | * @return an in-construction INSERT query. |
| 83 | 96 | */ |
| 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); | |
| 86 | 99 | } |
| 87 | 100 | |
| 88 | 101 | /** |
| @@ -91,8 +104,8 @@ | ||
| 91 | 104 | * @param table the name of the table to insert into. |
| 92 | 105 | * @return an in-construction INSERT query. |
| 93 | 106 | */ |
| 94 | - public static Insert insertInto(TableMetadata table) { | |
| 95 | - return new Insert(table); | |
| 107 | + public Insert insertInto(TableMetadata table) { | |
| 108 | + return new Insert(cluster, table); | |
| 96 | 109 | } |
| 97 | 110 | |
| 98 | 111 | /** |
| @@ -102,8 +115,8 @@ | ||
| 102 | 115 | * @return an in-construction UPDATE query (at least a SET and a WHERE |
| 103 | 116 | * clause needs to be provided to complete the query). |
| 104 | 117 | */ |
| 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); | |
| 107 | 120 | } |
| 108 | 121 | |
| 109 | 122 | /** |
| @@ -114,8 +127,8 @@ | ||
| 114 | 127 | * @return an in-construction UPDATE query (at least a SET and a WHERE |
| 115 | 128 | * clause needs to be provided to complete the query). |
| 116 | 129 | */ |
| 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); | |
| 119 | 132 | } |
| 120 | 133 | |
| 121 | 134 | /** |
| @@ -125,8 +138,8 @@ | ||
| 125 | 138 | * @return an in-construction UPDATE query (at least a SET and a WHERE |
| 126 | 139 | * clause needs to be provided to complete the query). |
| 127 | 140 | */ |
| 128 | - public static Update update(TableMetadata table) { | |
| 129 | - return new Update(table); | |
| 141 | + public Update update(TableMetadata table) { | |
| 142 | + return new Update(cluster, table); | |
| 130 | 143 | } |
| 131 | 144 | |
| 132 | 145 | /** |
| @@ -136,8 +149,8 @@ | ||
| 136 | 149 | * @return an in-construction DELETE query (At least a FROM and a WHERE |
| 137 | 150 | * clause needs to be provided to complete the query). |
| 138 | 151 | */ |
| 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); | |
| 141 | 154 | } |
| 142 | 155 | |
| 143 | 156 | /** |
| @@ -147,8 +160,8 @@ | ||
| 147 | 160 | * column selection and at least a FROM and a WHERE clause to complete the |
| 148 | 161 | * query). |
| 149 | 162 | */ |
| 150 | - public static Delete.Selection delete() { | |
| 151 | - return new Delete.Selection(); | |
| 163 | + public Delete.Selection delete() { | |
| 164 | + return new Delete.Selection(cluster); | |
| 152 | 165 | } |
| 153 | 166 | |
| 154 | 167 | /** |
| @@ -164,8 +177,8 @@ | ||
| 164 | 177 | * @param statements the statements to batch. |
| 165 | 178 | * @return a new {@code RegularStatement} that batch {@code statements}. |
| 166 | 179 | */ |
| 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); | |
| 169 | 182 | } |
| 170 | 183 | |
| 171 | 184 | /** |
| @@ -185,8 +198,8 @@ | ||
| 185 | 198 | * @return a new {@code RegularStatement} that batch {@code statements} without |
| 186 | 199 | * using the batch log. |
| 187 | 200 | */ |
| 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); | |
| 190 | 203 | } |
| 191 | 204 | |
| 192 | 205 | /** |
| @@ -195,8 +208,8 @@ | ||
| 195 | 208 | * @param table the name of the table to truncate. |
| 196 | 209 | * @return the truncation query. |
| 197 | 210 | */ |
| 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); | |
| 200 | 213 | } |
| 201 | 214 | |
| 202 | 215 | /** |
| @@ -206,8 +219,8 @@ | ||
| 206 | 219 | * @param table the name of the table to truncate. |
| 207 | 220 | * @return the truncation query. |
| 208 | 221 | */ |
| 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); | |
| 211 | 224 | } |
| 212 | 225 | |
| 213 | 226 | /** |
| @@ -216,8 +229,8 @@ | ||
| 216 | 229 | * @param table the table to truncate. |
| 217 | 230 | * @return the truncation query. |
| 218 | 231 | */ |
| 219 | - public static Truncate truncate(TableMetadata table) { | |
| 220 | - return new Truncate(table); | |
| 232 | + public Truncate truncate(TableMetadata table) { | |
| 233 | + return new Truncate(cluster, table); | |
| 221 | 234 | } |
| 222 | 235 | |
| 223 | 236 | /** |
| @@ -255,7 +268,7 @@ | ||
| 255 | 268 | public static String token(String... columnNames) { |
| 256 | 269 | StringBuilder sb = new StringBuilder(); |
| 257 | 270 | sb.append("token("); |
| 258 | - Utils.joinAndAppendNames(sb, ",", Arrays.asList((Object[])columnNames)); | |
| 271 | + Utils.joinAndAppendNames(sb, null, ",", Arrays.asList((Object[])columnNames)); | |
| 259 | 272 | sb.append(')'); |
| 260 | 273 | return sb.toString(); |
| 261 | 274 | } |
modified driver-core/src/main/java/com/datastax/driver/core/querybuilder/Select.java +25 −13
| @@ -15,12 +15,13 @@ | ||
| 15 | 15 | */ |
| 16 | 16 | package com.datastax.driver.core.querybuilder; |
| 17 | 17 | |
| 18 | -import java.nio.ByteBuffer; | |
| 19 | 18 | import java.util.ArrayList; |
| 20 | 19 | import java.util.Arrays; |
| 21 | 20 | import java.util.Collections; |
| 22 | 21 | import java.util.List; |
| 23 | 22 | |
| 23 | +import com.datastax.driver.core.Cluster; | |
| 24 | +import com.datastax.driver.core.CodecRegistry; | |
| 24 | 25 | import com.datastax.driver.core.TableMetadata; |
| 25 | 26 | |
| 26 | 27 | /** |
| @@ -38,16 +39,16 @@ | ||
| 38 | 39 | private Object limit; |
| 39 | 40 | private boolean allowFiltering; |
| 40 | 41 | |
| 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); | |
| 43 | 44 | this.table = table; |
| 44 | 45 | this.isDistinct = isDistinct; |
| 45 | 46 | this.columnNames = columnNames; |
| 46 | 47 | this.where = new Where(this); |
| 47 | 48 | } |
| 48 | 49 | |
| 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); | |
| 51 | 52 | this.table = escapeId(table.getName()); |
| 52 | 53 | this.isDistinct = isDistinct; |
| 53 | 54 | this.columnNames = columnNames; |
| @@ -58,13 +59,14 @@ | ||
| 58 | 59 | StringBuilder buildQueryString(List<Object> variables) { |
| 59 | 60 | StringBuilder builder = new StringBuilder(); |
| 60 | 61 | |
| 62 | + CodecRegistry codecRegistry = getCodecRegistry(); | |
| 61 | 63 | builder.append("SELECT "); |
| 62 | 64 | if (isDistinct) |
| 63 | 65 | builder.append("DISTINCT "); |
| 64 | 66 | if (columnNames == null) { |
| 65 | 67 | builder.append('*'); |
| 66 | 68 | } else { |
| 67 | - Utils.joinAndAppendNames(builder, ",", columnNames); | |
| 69 | + Utils.joinAndAppendNames(builder, codecRegistry, ",", columnNames); | |
| 68 | 70 | } |
| 69 | 71 | builder.append(" FROM "); |
| 70 | 72 | if (keyspace != null) |
| @@ -73,12 +75,12 @@ | ||
| 73 | 75 | |
| 74 | 76 | if (!where.clauses.isEmpty()) { |
| 75 | 77 | builder.append(" WHERE "); |
| 76 | - Utils.joinAndAppend(builder, " AND ", where.clauses, variables); | |
| 78 | + Utils.joinAndAppend(builder, codecRegistry, " AND ", where.clauses, variables); | |
| 77 | 79 | } |
| 78 | 80 | |
| 79 | 81 | if (orderings != null) { |
| 80 | 82 | builder.append(" ORDER BY "); |
| 81 | - Utils.joinAndAppend(builder, ",", orderings, variables); | |
| 83 | + Utils.joinAndAppend(builder, codecRegistry, ",", orderings, variables); | |
| 82 | 84 | } |
| 83 | 85 | |
| 84 | 86 | if (limit != null) { |
| @@ -255,12 +257,16 @@ | ||
| 255 | 257 | */ |
| 256 | 258 | public static class Builder { |
| 257 | 259 | |
| 260 | + private final Cluster cluster; | |
| 258 | 261 | List<Object> columnNames; |
| 259 | 262 | boolean isDistinct; |
| 260 | 263 | |
| 261 | - Builder() {} | |
| 264 | + Builder(Cluster cluster) { | |
| 265 | + this.cluster = cluster; | |
| 266 | + } | |
| 262 | 267 | |
| 263 | - Builder(List<Object> columnNames) { | |
| 268 | + Builder(Cluster cluster, List<Object> columnNames) { | |
| 269 | + this.cluster = cluster; | |
| 264 | 270 | this.columnNames = columnNames; |
| 265 | 271 | } |
| 266 | 272 | |
| @@ -292,7 +298,7 @@ | ||
| 292 | 298 | * @return a newly built SELECT statement that selects from {@code keyspace.table}. |
| 293 | 299 | */ |
| 294 | 300 | public Select from(String keyspace, String table) { |
| 295 | - return new Select(keyspace, table, columnNames, isDistinct); | |
| 301 | + return new Select(cluster, keyspace, table, columnNames, isDistinct); | |
| 296 | 302 | } |
| 297 | 303 | |
| 298 | 304 | /** |
| @@ -302,7 +308,7 @@ | ||
| 302 | 308 | * @return a newly built SELECT statement that selects from {@code table}. |
| 303 | 309 | */ |
| 304 | 310 | public Select from(TableMetadata table) { |
| 305 | - return new Select(table, columnNames, isDistinct); | |
| 311 | + return new Select(cluster, table, columnNames, isDistinct); | |
| 306 | 312 | } |
| 307 | 313 | } |
| 308 | 314 | |
| @@ -311,6 +317,10 @@ | ||
| 311 | 317 | */ |
| 312 | 318 | public static abstract class Selection extends Builder { |
| 313 | 319 | |
| 320 | + Selection(Cluster cluster) { | |
| 321 | + super(cluster); | |
| 322 | + } | |
| 323 | + | |
| 314 | 324 | /** |
| 315 | 325 | * Uses DISTINCT selection. |
| 316 | 326 | * |
| @@ -395,7 +405,9 @@ | ||
| 395 | 405 | |
| 396 | 406 | private Object previousSelection; |
| 397 | 407 | |
| 398 | - SelectionOrAlias() {} | |
| 408 | + SelectionOrAlias(Cluster cluster) { | |
| 409 | + super(cluster); | |
| 410 | + } | |
| 399 | 411 | |
| 400 | 412 | /** |
| 401 | 413 | * 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 @@ | ||
| 15 | 15 | */ |
| 16 | 16 | package com.datastax.driver.core.querybuilder; |
| 17 | 17 | |
| 18 | -import java.nio.ByteBuffer; | |
| 19 | 18 | import java.util.List; |
| 20 | 19 | |
| 20 | +import com.datastax.driver.core.Cluster; | |
| 21 | 21 | import com.datastax.driver.core.TableMetadata; |
| 22 | 22 | |
| 23 | 23 | /** |
| @@ -27,13 +27,13 @@ | ||
| 27 | 27 | |
| 28 | 28 | private final String table; |
| 29 | 29 | |
| 30 | - Truncate(String keyspace, String table) { | |
| 31 | - super(keyspace); | |
| 30 | + Truncate(Cluster cluster, String keyspace, String table) { | |
| 31 | + super(keyspace, cluster); | |
| 32 | 32 | this.table = table; |
| 33 | 33 | } |
| 34 | 34 | |
| 35 | - Truncate(TableMetadata table) { | |
| 36 | - super(table); | |
| 35 | + Truncate(Cluster cluster, TableMetadata table) { | |
| 36 | + super(table, cluster); | |
| 37 | 37 | this.table = escapeId(table.getName()); |
| 38 | 38 | } |
| 39 | 39 |
modified driver-core/src/main/java/com/datastax/driver/core/querybuilder/Update.java +11 −9
| @@ -15,10 +15,11 @@ | ||
| 15 | 15 | */ |
| 16 | 16 | package com.datastax.driver.core.querybuilder; |
| 17 | 17 | |
| 18 | -import java.nio.ByteBuffer; | |
| 19 | 18 | import java.util.ArrayList; |
| 20 | 19 | import java.util.List; |
| 21 | 20 | |
| 21 | +import com.datastax.driver.core.Cluster; | |
| 22 | +import com.datastax.driver.core.CodecRegistry; | |
| 22 | 23 | import com.datastax.driver.core.TableMetadata; |
| 23 | 24 | import com.datastax.driver.core.querybuilder.Assignment.CounterAssignment; |
| 24 | 25 | |
| @@ -33,8 +34,8 @@ | ||
| 33 | 34 | private final Options usings; |
| 34 | 35 | private final Conditions conditions; |
| 35 | 36 | |
| 36 | - Update(String keyspace, String table) { | |
| 37 | - super(keyspace); | |
| 37 | + Update(Cluster cluster, String keyspace, String table) { | |
| 38 | + super(keyspace, cluster); | |
| 38 | 39 | this.table = table; |
| 39 | 40 | this.assignments = new Assignments(this); |
| 40 | 41 | this.where = new Where(this); |
| @@ -42,8 +43,8 @@ | ||
| 42 | 43 | this.conditions = new Conditions(this); |
| 43 | 44 | } |
| 44 | 45 | |
| 45 | - Update(TableMetadata table) { | |
| 46 | - super(table); | |
| 46 | + Update(Cluster cluster, TableMetadata table) { | |
| 47 | + super(table, cluster); | |
| 47 | 48 | this.table = escapeId(table.getName()); |
| 48 | 49 | this.assignments = new Assignments(this); |
| 49 | 50 | this.where = new Where(this); |
| @@ -60,24 +61,25 @@ | ||
| 60 | 61 | Utils.appendName(keyspace, builder).append('.'); |
| 61 | 62 | Utils.appendName(table, builder); |
| 62 | 63 | |
| 64 | + CodecRegistry codecRegistry = getCodecRegistry(); | |
| 63 | 65 | if (!usings.usings.isEmpty()) { |
| 64 | 66 | builder.append(" USING "); |
| 65 | - Utils.joinAndAppend(builder, " AND ", usings.usings, variables); | |
| 67 | + Utils.joinAndAppend(builder, codecRegistry, " AND ", usings.usings, variables); | |
| 66 | 68 | } |
| 67 | 69 | |
| 68 | 70 | if (!assignments.assignments.isEmpty()) { |
| 69 | 71 | builder.append(" SET "); |
| 70 | - Utils.joinAndAppend(builder, ",", assignments.assignments, variables); | |
| 72 | + Utils.joinAndAppend(builder, codecRegistry, ",", assignments.assignments, variables); | |
| 71 | 73 | } |
| 72 | 74 | |
| 73 | 75 | if (!where.clauses.isEmpty()) { |
| 74 | 76 | builder.append(" WHERE "); |
| 75 | - Utils.joinAndAppend(builder, " AND ", where.clauses, variables); | |
| 77 | + Utils.joinAndAppend(builder, codecRegistry, " AND ", where.clauses, variables); | |
| 76 | 78 | } |
| 77 | 79 | |
| 78 | 80 | if (!conditions.conditions.isEmpty()) { |
| 79 | 81 | builder.append(" IF "); |
| 80 | - Utils.joinAndAppend(builder, " AND ", conditions.conditions, variables); | |
| 82 | + Utils.joinAndAppend(builder, codecRegistry, " AND ", conditions.conditions, variables); | |
| 81 | 83 | } |
| 82 | 84 | |
| 83 | 85 | return builder; |
modified driver-core/src/main/java/com/datastax/driver/core/querybuilder/Using.java +4 −2
| @@ -17,6 +17,8 @@ | ||
| 17 | 17 | |
| 18 | 18 | import java.util.List; |
| 19 | 19 | |
| 20 | +import com.datastax.driver.core.CodecRegistry; | |
| 21 | + | |
| 20 | 22 | public abstract class Using extends Utils.Appendeable { |
| 21 | 23 | |
| 22 | 24 | final String optionName; |
| @@ -34,7 +36,7 @@ | ||
| 34 | 36 | } |
| 35 | 37 | |
| 36 | 38 | @Override |
| 37 | - void appendTo(StringBuilder sb, List<Object> variables) { | |
| 39 | + void appendTo(StringBuilder sb, List<Object> variables, CodecRegistry codecRegistry) { | |
| 38 | 40 | sb.append(optionName).append(' ').append(value); |
| 39 | 41 | } |
| 40 | 42 | |
| @@ -53,7 +55,7 @@ | ||
| 53 | 55 | } |
| 54 | 56 | |
| 55 | 57 | @Override |
| 56 | - void appendTo(StringBuilder sb, List<Object> variables) { | |
| 58 | + void appendTo(StringBuilder sb, List<Object> variables, CodecRegistry codecRegistry) { | |
| 57 | 59 | sb.append(optionName).append(' ').append(marker); |
| 58 | 60 | } |
| 59 | 61 |
modified driver-core/src/main/java/com/datastax/driver/core/querybuilder/Utils.java +40 −196
| @@ -17,241 +17,93 @@ | ||
| 17 | 17 | |
| 18 | 18 | import java.math.BigDecimal; |
| 19 | 19 | 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; | |
| 23 | 23 | import java.util.regex.Pattern; |
| 24 | 24 | |
| 25 | 25 | import static com.google.common.base.Preconditions.checkNotNull; |
| 26 | 26 | |
| 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; | |
| 31 | 29 | |
| 32 | 30 | // Static utilities private to the query builder |
| 33 | 31 | abstract class Utils { |
| 34 | 32 | |
| 35 | 33 | private static final Pattern cnamePattern = Pattern.compile("\\w+(?:\\[.+\\])?"); |
| 36 | 34 | |
| 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) { | |
| 38 | 36 | for (int i = 0; i < values.size(); i++) { |
| 39 | 37 | if (i > 0) |
| 40 | 38 | sb.append(separator); |
| 41 | - values.get(i).appendTo(sb, variables); | |
| 39 | + values.get(i).appendTo(sb, variables, codecRegistry); | |
| 42 | 40 | } |
| 43 | 41 | return sb; |
| 44 | 42 | } |
| 45 | 43 | |
| 46 | - static StringBuilder joinAndAppendNames(StringBuilder sb, String separator, List<?> values) { | |
| 44 | + static StringBuilder joinAndAppendNames(StringBuilder sb, CodecRegistry codecRegistry, String separator, List<?> values) { | |
| 47 | 45 | for (int i = 0; i < values.size(); i++) { |
| 48 | 46 | if (i > 0) |
| 49 | 47 | sb.append(separator); |
| 50 | - appendName(values.get(i), sb); | |
| 48 | + appendName(values.get(i), codecRegistry, sb); | |
| 51 | 49 | } |
| 52 | 50 | return sb; |
| 53 | 51 | } |
| 54 | 52 | |
| 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) { | |
| 56 | 54 | for (int i = 0; i < values.size(); i++) { |
| 57 | 55 | if (i > 0) |
| 58 | 56 | sb.append(separator); |
| 59 | - appendValue(values.get(i), sb, variables); | |
| 57 | + appendValue(values.get(i), codecRegistry, sb, variables); | |
| 60 | 58 | } |
| 61 | 59 | return sb; |
| 62 | 60 | } |
| 63 | 61 | |
| 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 | |
| 74 | 67 | // 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); | |
| 133 | 70 | } |
| 134 | 71 | |
| 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"); | |
| 148 | 75 | } else if (value instanceof BindMarker) { |
| 149 | 76 | sb.append(value); |
| 150 | - return true; | |
| 151 | 77 | } else if (value instanceof FCall) { |
| 152 | 78 | FCall fcall = (FCall)value; |
| 153 | 79 | sb.append(fcall.name).append('('); |
| 154 | 80 | for (int i = 0; i < fcall.parameters.length; i++) { |
| 155 | 81 | if (i > 0) |
| 156 | 82 | sb.append(','); |
| 157 | - appendValue(fcall.parameters[i], sb, null); | |
| 83 | + appendValue(fcall.parameters[i], codecRegistry, sb, variables); | |
| 158 | 84 | } |
| 159 | 85 | sb.append(')'); |
| 160 | - return true; | |
| 161 | 86 | } 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)); | |
| 192 | 96 | } 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 | |
| 193 | 100 | sb.append('?'); |
| 194 | 101 | variables.add(value); |
| 102 | + return sb; | |
| 195 | 103 | } |
| 196 | 104 | return sb; |
| 197 | 105 | } |
| 198 | 106 | |
| 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 | - | |
| 255 | 107 | static boolean containsBindMarker(Object value) { |
| 256 | 108 | if (value instanceof BindMarker) |
| 257 | 109 | return true; |
| @@ -291,10 +143,6 @@ | ||
| 291 | 143 | return true; |
| 292 | 144 | } |
| 293 | 145 | |
| 294 | - private static StringBuilder appendValueString(String value, StringBuilder sb) { | |
| 295 | - return sb.append(DataType.text().format(value)); | |
| 296 | - } | |
| 297 | - | |
| 298 | 146 | static boolean isRawValue(Object value) { |
| 299 | 147 | return value != null |
| 300 | 148 | && !(value instanceof FCall) |
| @@ -302,10 +150,6 @@ | ||
| 302 | 150 | && !(value instanceof BindMarker); |
| 303 | 151 | } |
| 304 | 152 | |
| 305 | - static String toRawString(Object value) { | |
| 306 | - return appendValue(value, new StringBuilder()).toString(); | |
| 307 | - } | |
| 308 | - | |
| 309 | 153 | static StringBuilder appendName(String name, StringBuilder sb) { |
| 310 | 154 | name = name.trim(); |
| 311 | 155 | // FIXME: checking for token( specifically is uber ugly, we'll need some better solution. |
| @@ -316,23 +160,23 @@ | ||
| 316 | 160 | return sb; |
| 317 | 161 | } |
| 318 | 162 | |
| 319 | - static StringBuilder appendName(Object name, StringBuilder sb) { | |
| 163 | + static StringBuilder appendName(Object name, CodecRegistry codecRegistry, StringBuilder sb) { | |
| 320 | 164 | if (name instanceof String) { |
| 321 | 165 | appendName((String)name, sb); |
| 322 | 166 | } else if (name instanceof CName) { |
| 323 | - appendName(((CName)name).name, sb); | |
| 167 | + appendName(((CName)name).name, codecRegistry, sb); | |
| 324 | 168 | } else if (name instanceof FCall) { |
| 325 | 169 | FCall fcall = (FCall)name; |
| 326 | 170 | sb.append(fcall.name).append('('); |
| 327 | 171 | for (int i = 0; i < fcall.parameters.length; i++) { |
| 328 | 172 | if (i > 0) |
| 329 | 173 | sb.append(','); |
| 330 | - appendValue(fcall.parameters[i], sb, null); | |
| 174 | + appendValue(fcall.parameters[i], codecRegistry, sb, null); | |
| 331 | 175 | } |
| 332 | 176 | sb.append(')'); |
| 333 | 177 | } else if (name instanceof Alias) { |
| 334 | 178 | Alias alias = (Alias)name; |
| 335 | - appendName(alias.column, sb); | |
| 179 | + appendName(alias.column, codecRegistry, sb); | |
| 336 | 180 | sb.append(" AS ").append(alias.alias); |
| 337 | 181 | } else if (name instanceof RawString) { |
| 338 | 182 | sb.append(((RawString)name).str); |
| @@ -343,7 +187,7 @@ | ||
| 343 | 187 | } |
| 344 | 188 | |
| 345 | 189 | static abstract class Appendeable { |
| 346 | - abstract void appendTo(StringBuilder sb, List<Object> values); | |
| 190 | + abstract void appendTo(StringBuilder sb, List<Object> values, CodecRegistry codecRegistry); | |
| 347 | 191 | abstract boolean containsBindMarker(); |
| 348 | 192 | } |
| 349 | 193 |
modified driver-core/src/main/java/com/datastax/driver/core/schemabuilder/SchemaStatement.java +1 −2
| @@ -21,7 +21,6 @@ | ||
| 21 | 21 | |
| 22 | 22 | import com.google.common.base.Strings; |
| 23 | 23 | |
| 24 | -import com.datastax.driver.core.ProtocolVersion; | |
| 25 | 24 | import com.datastax.driver.core.RegularStatement; |
| 26 | 25 | |
| 27 | 26 | /** |
| @@ -51,7 +50,7 @@ | ||
| 51 | 50 | } |
| 52 | 51 | |
| 53 | 52 | @Override |
| 54 | - public ByteBuffer[] getValues(ProtocolVersion protocolVersion) { | |
| 53 | + public ByteBuffer[] getValues() { | |
| 55 | 54 | // DDL statements never have values |
| 56 | 55 | return new ByteBuffer[0]; |
| 57 | 56 | } |
modified driver-core/src/test/java/com/datastax/driver/core/AbstractPoliciesTest.java +13 −8
| @@ -20,11 +20,16 @@ | ||
| 20 | 20 | import java.util.HashMap; |
| 21 | 21 | import java.util.Map; |
| 22 | 22 | |
| 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; | |
| 24 | 26 | |
| 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; | |
| 28 | 33 | |
| 29 | 34 | public abstract class AbstractPoliciesTest { |
| 30 | 35 | private static final boolean DEBUG = false; |
| @@ -179,11 +184,11 @@ | ||
| 179 | 184 | for (int i = 0; i < n; ++i) |
| 180 | 185 | if (batch) |
| 181 | 186 | // 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 })) | |
| 184 | 189 | .setConsistencyLevel(cl)); |
| 185 | 190 | 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)); | |
| 187 | 192 | } |
| 188 | 193 | |
| 189 | 194 | |
| @@ -211,7 +216,7 @@ | ||
| 211 | 216 | ByteBuffer routingKey = ByteBuffer.allocate(4); |
| 212 | 217 | routingKey.putInt(0, 0); |
| 213 | 218 | 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))); | |
| 215 | 220 | } |
| 216 | 221 | } |
| 217 | 222 | } |
modified driver-core/src/test/java/com/datastax/driver/core/AbstractReplicationStrategyTest.java +1 −1
| @@ -39,7 +39,7 @@ | ||
| 39 | 39 | private final String address; |
| 40 | 40 | |
| 41 | 41 | 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); | |
| 43 | 43 | this.address = address; |
| 44 | 44 | } |
| 45 | 45 |
modified driver-core/src/test/java/com/datastax/driver/core/AggregateMetadataTest.java +9 −8
| @@ -33,6 +33,7 @@ | ||
| 33 | 33 | // These tests needs a protocol version to (de)serialize INITCONDs. Since we're using basic types, I don't think the binary format |
| 34 | 34 | // is going to change at any time in the future, so the actual version does not matter. |
| 35 | 35 | private static final ProtocolVersion PROTOCOL_VERSION = ProtocolVersion.NEWEST_SUPPORTED; |
| 36 | + private CodecRegistry codecRegistry = new CodecRegistry(); | |
| 36 | 37 | |
| 37 | 38 | KeyspaceMetadata keyspace; |
| 38 | 39 | |
| @@ -46,7 +47,7 @@ | ||
| 46 | 47 | FunctionMetadata stateFunc = mock(FunctionMetadata.class); |
| 47 | 48 | keyspace.functions.put("cat(text,int)", stateFunc); |
| 48 | 49 | |
| 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); | |
| 50 | 51 | |
| 51 | 52 | assertThat(aggregate).isNotNull(); |
| 52 | 53 | assertThat(aggregate.getFullName()).isEqualTo("cat_tos(int)"); |
| @@ -72,7 +73,7 @@ | ||
| 72 | 73 | FunctionMetadata stateFunc = mock(FunctionMetadata.class); |
| 73 | 74 | keyspace.functions.put("inc(int)", stateFunc); |
| 74 | 75 | |
| 75 | - AggregateMetadata aggregate = AggregateMetadata.build(keyspace, SYSTEM_ROW_MYCOUNT, PROTOCOL_VERSION); | |
| 76 | + AggregateMetadata aggregate = AggregateMetadata.build(keyspace, SYSTEM_ROW_MYCOUNT, PROTOCOL_VERSION, codecRegistry); | |
| 76 | 77 | |
| 77 | 78 | assertThat(aggregate).isNotNull(); |
| 78 | 79 | assertThat(aggregate.getFullName()).isEqualTo("mycount()"); |
| @@ -100,7 +101,7 @@ | ||
| 100 | 101 | FunctionMetadata finalFunc = mock(FunctionMetadata.class); |
| 101 | 102 | keyspace.functions.put("announce(int)", finalFunc); |
| 102 | 103 | |
| 103 | - AggregateMetadata aggregate = AggregateMetadata.build(keyspace, SYSTEM_ROW_PRETTYSUM, PROTOCOL_VERSION); | |
| 104 | + AggregateMetadata aggregate = AggregateMetadata.build(keyspace, SYSTEM_ROW_PRETTYSUM, PROTOCOL_VERSION, codecRegistry); | |
| 104 | 105 | |
| 105 | 106 | assertThat(aggregate).isNotNull(); |
| 106 | 107 | assertThat(aggregate.getFullName()).isEqualTo("prettysum(int)"); |
| @@ -127,7 +128,7 @@ | ||
| 127 | 128 | FunctionMetadata stateFunc = mock(FunctionMetadata.class); |
| 128 | 129 | keyspace.functions.put("plus(int,int)", stateFunc); |
| 129 | 130 | |
| 130 | - AggregateMetadata aggregate = AggregateMetadata.build(keyspace, SYSTEM_ROW_SUM, PROTOCOL_VERSION); | |
| 131 | + AggregateMetadata aggregate = AggregateMetadata.build(keyspace, SYSTEM_ROW_SUM, PROTOCOL_VERSION, codecRegistry); | |
| 131 | 132 | |
| 132 | 133 | assertThat(aggregate).isNotNull(); |
| 133 | 134 | assertThat(aggregate.getFullName()).isEqualTo("sum(int)"); |
| @@ -151,13 +152,13 @@ | ||
| 151 | 152 | private static final String TEXT = "org.apache.cassandra.db.marshal.UTF8Type"; |
| 152 | 153 | |
| 153 | 154 | 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); | |
| 155 | 156 | |
| 156 | 157 | 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); | |
| 158 | 159 | |
| 159 | 160 | 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); | |
| 161 | 162 | |
| 162 | 163 | private static final Row SYSTEM_ROW_SUM = mockRow("sum", ImmutableList.of("int"), ImmutableList.of(INT), |
| 163 | 164 | null, null, INT, "plus", INT); |
| @@ -177,4 +178,4 @@ | ||
| 177 | 178 | |
| 178 | 179 | return row; |
| 179 | 180 | } |
| 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 @@ | ||
| 20 | 20 | /** |
| 21 | 21 | * Augment AssertJ with custom assertions for the Java driver. |
| 22 | 22 | */ |
| 23 | -public class Assertions extends org.assertj.core.api.Assertions{ | |
| 23 | +public class Assertions extends org.assertj.core.api.Assertions { | |
| 24 | 24 | public static ClusterAssert assertThat(Cluster cluster) { |
| 25 | 25 | return new ClusterAssert(cluster); |
| 26 | 26 | } |
| @@ -36,7 +36,7 @@ | ||
| 36 | 36 | public static DataTypeAssert assertThat(DataType type) { |
| 37 | 37 | return new DataTypeAssert(type); |
| 38 | 38 | } |
| 39 | - | |
| 39 | + | |
| 40 | 40 | public static IndexMetadataAssert assertThat(IndexMetadata indexMetadata) { |
| 41 | 41 | return new IndexMetadataAssert(indexMetadata); |
| 42 | 42 | } |
| @@ -53,4 +53,8 @@ | ||
| 53 | 53 | return new ColumnMetadataAssert(column); |
| 54 | 54 | } |
| 55 | 55 | |
| 56 | + public static TypeCodecAssert assertThat(TypeCodec codec) { | |
| 57 | + return new TypeCodecAssert(codec); | |
| 58 | + } | |
| 59 | + | |
| 56 | 60 | } |
modified driver-core/src/test/java/com/datastax/driver/core/AsyncResultSetTest.java +1 −1
| @@ -57,7 +57,7 @@ | ||
| 57 | 57 | for (int i = 0; i < totalCount; i++) |
| 58 | 58 | session.execute(String.format("insert into ints (i) values (%d)", i)); |
| 59 | 59 | |
| 60 | - Statement statement = new SimpleStatement("select * from ints").setFetchSize(fetchSize); | |
| 60 | + Statement statement = session.newSimpleStatement("select * from ints").setFetchSize(fetchSize); | |
| 61 | 61 | ResultsAccumulator results = new ResultsAccumulator(); |
| 62 | 62 | |
| 63 | 63 | ListenableFuture<ResultSet> future = Futures.transform( |
modified driver-core/src/test/java/com/datastax/driver/core/BatchStatementTest.java +2 −2
| @@ -40,7 +40,7 @@ | ||
| 40 | 40 | |
| 41 | 41 | BatchStatement batch = new BatchStatement(); |
| 42 | 42 | |
| 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)); | |
| 44 | 44 | batch.add(st.bind("key1", 1)); |
| 45 | 45 | batch.add(st.bind("key2", 0)); |
| 46 | 46 | |
| @@ -87,7 +87,7 @@ | ||
| 87 | 87 | |
| 88 | 88 | BatchStatement batch = new BatchStatement(); |
| 89 | 89 | |
| 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)); | |
| 91 | 91 | batch.add(st.bind("key1", 1)); |
| 92 | 92 | batch.add(st.bind("key1", 2)); |
| 93 | 93 |
modified driver-core/src/test/java/com/datastax/driver/core/CassandraTypeParserTest.java +17 −14
| @@ -29,24 +29,27 @@ | ||
| 29 | 29 | |
| 30 | 30 | public class CassandraTypeParserTest { |
| 31 | 31 | |
| 32 | + private ProtocolVersion protocolVersion = TestUtils.getDesiredProtocolVersion(); | |
| 33 | + private CodecRegistry codecRegistry = new CodecRegistry(); | |
| 34 | + | |
| 32 | 35 | @Test(groups = "unit") |
| 33 | 36 | public void parseOneTest() { |
| 34 | 37 | |
| 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()); | |
| 42 | 45 | |
| 43 | 46 | String s; |
| 44 | 47 | |
| 45 | 48 | 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)); | |
| 47 | 50 | |
| 48 | 51 | 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())); | |
| 50 | 53 | } |
| 51 | 54 | |
| 52 | 55 | @Test(groups = "unit") |
| @@ -54,13 +57,13 @@ | ||
| 54 | 57 | |
| 55 | 58 | String s = "org.apache.cassandra.db.marshal.CompositeType(org.apache.cassandra.db.marshal.Int32Type, org.apache.cassandra.db.marshal.UTF8Type,"; |
| 56 | 59 | 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); | |
| 58 | 61 | assertTrue(r1.isComposite); |
| 59 | 62 | assertEquals(r1.types, Arrays.asList(DataType.cint(), DataType.text())); |
| 60 | 63 | assertEquals(r1.collections.size(), 1); |
| 61 | 64 | assertEquals(r1.collections.get("ab"), DataType.list(DataType.cint())); |
| 62 | 65 | |
| 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); | |
| 64 | 67 | assertFalse(r2.isComposite); |
| 65 | 68 | assertEquals(r2.types, Arrays.asList(DataType.timestamp())); |
| 66 | 69 | assertEquals(r2.collections.size(), 0); |
| @@ -70,7 +73,7 @@ | ||
| 70 | 73 | public void parseUserTypes() { |
| 71 | 74 | |
| 72 | 75 | 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); | |
| 74 | 77 | |
| 75 | 78 | assertEquals(def.getKeyspace(), "foo"); |
| 76 | 79 | assertEquals(def.getTypeName(), "address"); |
| @@ -109,7 +112,7 @@ | ||
| 109 | 112 | @Test(groups = "unit") |
| 110 | 113 | public void parseTupleTest() { |
| 111 | 114 | 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); | |
| 113 | 116 | assertNotNull(type); |
| 114 | 117 | assertEquals(type.getComponentTypes().get(0), DataType.cint()); |
| 115 | 118 | assertEquals(type.getComponentTypes().get(1), DataType.text()); |
| @@ -121,7 +124,7 @@ | ||
| 121 | 124 | // map<text, frozen<map<int,int>>> |
| 122 | 125 | 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)))"; |
| 123 | 126 | |
| 124 | - DataType parentMap = CassandraTypeParser.parseOne(s); | |
| 127 | + DataType parentMap = CassandraTypeParser.parseOne(s, protocolVersion, codecRegistry); | |
| 125 | 128 | assertThat(parentMap) |
| 126 | 129 | .hasName(DataType.Name.MAP) |
| 127 | 130 | .isNotFrozen() |
modified driver-core/src/test/java/com/datastax/driver/core/ClusterInitTest.java +2 −2
| @@ -35,10 +35,10 @@ | ||
| 35 | 35 | import com.datastax.driver.core.exceptions.NoHostAvailableException; |
| 36 | 36 | import com.datastax.driver.core.policies.ConstantReconnectionPolicy; |
| 37 | 37 | import com.datastax.driver.core.querybuilder.Insert; |
| 38 | +import com.datastax.driver.core.querybuilder.QueryBuilder; | |
| 38 | 39 | import com.datastax.driver.core.utils.UUIDs; |
| 39 | 40 | |
| 40 | 41 | import static com.datastax.driver.core.FakeHost.Behavior.THROWING_CONNECT_TIMEOUTS; |
| 41 | -import static com.datastax.driver.core.querybuilder.QueryBuilder.insertInto; | |
| 42 | 42 | |
| 43 | 43 | public class ClusterInitTest { |
| 44 | 44 | private static final Logger logger = LoggerFactory.getLogger(ClusterInitTest.class); |
| @@ -141,7 +141,7 @@ | ||
| 141 | 141 | .one().getString("release_version"); |
| 142 | 142 | |
| 143 | 143 | for (int i = 2; i <= 6; i++) { |
| 144 | - Insert insertStmt = insertInto("peers") | |
| 144 | + Insert insertStmt = new QueryBuilder(cluster).insertInto("peers") | |
| 145 | 145 | .value("peer", InetAddress.getByName(CCMBridge.ipOfNode(i))) |
| 146 | 146 | .value("data_center", "datacenter1") |
| 147 | 147 | .value("host_id", UUIDs.random()) |
modified driver-core/src/test/java/com/datastax/driver/core/ConditionalUpdateTest.java +1 −1
| @@ -78,7 +78,7 @@ | ||
| 78 | 78 | |
| 79 | 79 | // This is really contrived, we just want to cover the code path in ArrayBackedResultSet#MultiPage. |
| 80 | 80 | // 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)); | |
| 82 | 82 | |
| 83 | 83 | assertTrue(rs.wasApplied()); |
| 84 | 84 | } |
modified driver-core/src/test/java/com/datastax/driver/core/CustomPayloadTest.java +15 −14
| @@ -64,7 +64,7 @@ | ||
| 64 | 64 | |
| 65 | 65 | @Test(groups = "short") |
| 66 | 66 | 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); | |
| 68 | 68 | statement.setOutgoingPayload(payload1); |
| 69 | 69 | ResultSet rows = session.execute(statement); |
| 70 | 70 | Map<String, ByteBuffer> actual = rows.getExecutionInfo().getIncomingPayload(); |
| @@ -73,7 +73,7 @@ | ||
| 73 | 73 | |
| 74 | 74 | @Test(groups = "short") |
| 75 | 75 | 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')")); | |
| 77 | 77 | statement.setOutgoingPayload(payload1); |
| 78 | 78 | ResultSet rows = session.execute(statement); |
| 79 | 79 | Map<String, ByteBuffer> actual = rows.getExecutionInfo().getIncomingPayload(); |
| @@ -82,7 +82,8 @@ | ||
| 82 | 82 | |
| 83 | 83 | @Test(groups = "short") |
| 84 | 84 | 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); | |
| 86 | 87 | ResultSet rows = session.execute(statement); |
| 87 | 88 | Map<String, ByteBuffer> actual = rows.getExecutionInfo().getIncomingPayload(); |
| 88 | 89 | assertThat(actual).isEqualTo(payload1); |
| @@ -96,7 +97,7 @@ | ||
| 96 | 97 | */ |
| 97 | 98 | @Test(groups = "short") |
| 98 | 99 | 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 = ?"); | |
| 100 | 101 | statement.setOutgoingPayload(payload1); |
| 101 | 102 | PreparedStatement ps = session.prepare(statement); |
| 102 | 103 | // Prepared statement should inherit outgoing payload |
| @@ -123,7 +124,7 @@ | ||
| 123 | 124 | */ |
| 124 | 125 | @Test(groups = "short") |
| 125 | 126 | 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 = ?"); | |
| 127 | 128 | statement.setOutgoingPayload(payload1); |
| 128 | 129 | PreparedStatement ps = session.prepare(statement); |
| 129 | 130 | // Prepared statement should inherit outgoing payload |
| @@ -150,7 +151,7 @@ | ||
| 150 | 151 | */ |
| 151 | 152 | @Test(groups = "short") |
| 152 | 153 | 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 = ?"); | |
| 154 | 155 | PreparedStatement ps = session.prepare(statement); |
| 155 | 156 | assertThat(ps.getOutgoingPayload()).isNull(); |
| 156 | 157 | assertThat(ps.getIncomingPayload()).isNull(); |
| @@ -181,7 +182,7 @@ | ||
| 181 | 182 | public void should_echo_custom_payload_when_paginating() throws Exception { |
| 182 | 183 | session.execute("INSERT INTO t1 (c1) VALUES (1)"); |
| 183 | 184 | 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)"); | |
| 185 | 186 | statement.setFetchSize(1); |
| 186 | 187 | statement.setOutgoingPayload(payload1); |
| 187 | 188 | ResultSet rows = session.execute(statement); |
| @@ -200,7 +201,7 @@ | ||
| 200 | 201 | public void should_encode_null_values() throws Exception { |
| 201 | 202 | Map<String, ByteBuffer> payload = new HashMap<String, ByteBuffer>(); |
| 202 | 203 | 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); | |
| 204 | 205 | statement.setOutgoingPayload(payload); |
| 205 | 206 | ResultSet rows = session.execute(statement); |
| 206 | 207 | Map<String, ByteBuffer> actual = rows.getExecutionInfo().getIncomingPayload(); |
| @@ -211,28 +212,28 @@ | ||
| 211 | 212 | public void should_throw_npe_when_null_key_on_regular_statement() throws Exception { |
| 212 | 213 | Map<String, ByteBuffer> payload = new HashMap<String, ByteBuffer>(); |
| 213 | 214 | 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); | |
| 215 | 216 | } |
| 216 | 217 | |
| 217 | 218 | @Test(groups = "unit", expectedExceptions = NullPointerException.class) |
| 218 | 219 | public void should_throw_npe_when_null_value_on_regular_statement() throws Exception { |
| 219 | 220 | Map<String, ByteBuffer> payload = new HashMap<String, ByteBuffer>(); |
| 220 | 221 | 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); | |
| 222 | 223 | } |
| 223 | 224 | |
| 224 | 225 | @Test(groups = "short", expectedExceptions = NullPointerException.class) |
| 225 | 226 | public void should_throw_npe_when_null_key_on_prepared_statement() throws Exception { |
| 226 | 227 | Map<String, ByteBuffer> payload = new HashMap<String, ByteBuffer>(); |
| 227 | 228 | 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); | |
| 229 | 230 | } |
| 230 | 231 | |
| 231 | 232 | @Test(groups = "short", expectedExceptions = NullPointerException.class) |
| 232 | 233 | public void should_throw_npe_when_null_value_on_prepared_statement() throws Exception { |
| 233 | 234 | Map<String, ByteBuffer> payload = new HashMap<String, ByteBuffer>(); |
| 234 | 235 | 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); | |
| 236 | 237 | } |
| 237 | 238 | |
| 238 | 239 | @Test(groups = "short") |
| @@ -246,7 +247,7 @@ | ||
| 246 | 247 | .build() |
| 247 | 248 | .init(); |
| 248 | 249 | 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); | |
| 250 | 251 | statement.setOutgoingPayload(payload1); |
| 251 | 252 | v3session.execute(statement); |
| 252 | 253 | fail("Should not send custom payloads with protocol V3"); |
| @@ -282,7 +283,7 @@ | ||
| 282 | 283 | try { |
| 283 | 284 | logger.setLevel(TRACE); |
| 284 | 285 | 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); | |
| 286 | 287 | statement.setOutgoingPayload(payload1); |
| 287 | 288 | session.execute(statement); |
| 288 | 289 | String logs = appender.waitAndGet(10000); |
modified driver-core/src/test/java/com/datastax/driver/core/DataTypeAssert.java +0 −11
| @@ -15,7 +15,6 @@ | ||
| 15 | 15 | */ |
| 16 | 16 | package com.datastax.driver.core; |
| 17 | 17 | |
| 18 | -import com.google.common.reflect.TypeToken; | |
| 19 | 18 | import org.assertj.core.api.AbstractAssert; |
| 20 | 19 | |
| 21 | 20 | import static com.datastax.driver.core.Assertions.assertThat; |
| @@ -40,16 +39,6 @@ | ||
| 40 | 39 | return this; |
| 41 | 40 | } |
| 42 | 41 | |
| 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 | - | |
| 53 | 42 | public DataTypeAssert hasTypeArgument(int position, DataType expected) { |
| 54 | 43 | assertThat(actual.getTypeArguments().get(position)).isEqualTo(expected); |
| 55 | 44 | return this; |
modified driver-core/src/test/java/com/datastax/driver/core/DataTypeIntegrationTest.java +126 −40
| @@ -22,6 +22,7 @@ | ||
| 22 | 22 | import com.google.common.collect.*; |
| 23 | 23 | import org.slf4j.Logger; |
| 24 | 24 | import org.slf4j.LoggerFactory; |
| 25 | +import org.testng.annotations.AfterClass; | |
| 25 | 26 | import org.testng.annotations.Test; |
| 26 | 27 | |
| 27 | 28 | import static org.assertj.core.api.Assertions.assertThat; |
| @@ -62,6 +63,16 @@ | ||
| 62 | 63 | return statements; |
| 63 | 64 | } |
| 64 | 65 | |
| 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 | + | |
| 65 | 76 | @Test(groups = "long") |
| 66 | 77 | public void should_insert_and_retrieve_data_with_legacy_statements() { |
| 67 | 78 | should_insert_and_retrieve_data(StatementType.RAW_STRING); |
| @@ -80,58 +91,77 @@ | ||
| 80 | 91 | |
| 81 | 92 | protected void should_insert_and_retrieve_data(StatementType statementType) { |
| 82 | 93 | ProtocolVersion protocolVersion = cluster.getConfiguration().getProtocolOptions().getProtocolVersion(); |
| 94 | + CodecRegistry codecRegistry = cluster.getConfiguration().getCodecRegistry(); | |
| 83 | 95 | |
| 84 | 96 | for (TestTable table : tables) { |
| 85 | 97 | if (cassandraVersion.compareTo(table.minCassandraVersion) < 0) |
| 86 | 98 | continue; |
| 87 | 99 | |
| 100 | + TypeCodec<Object> codec = codecRegistry.codecFor(table.testColumnType); | |
| 88 | 101 | switch (statementType) { |
| 89 | 102 | 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); | |
| 91 | 107 | break; |
| 92 | 108 | case SIMPLE_WITH_PARAM: |
| 93 | - SimpleStatement statement = new SimpleStatement(table.insertStatement, table.sampleValue); | |
| 109 | + SimpleStatement statement = session.newSimpleStatement(table.insertStatement, table.sampleValue); | |
| 94 | 110 | checkGetValuesReturnsSerializedValue(protocolVersion, statement, table); |
| 95 | 111 | session.execute(statement); |
| 96 | 112 | break; |
| 97 | 113 | case PREPARED: |
| 98 | 114 | PreparedStatement ps = session.prepare(table.insertStatement); |
| 99 | 115 | BoundStatement bs = ps.bind(table.sampleValue); |
| 100 | - checkGetterReturnsBoundValue(bs, table); | |
| 116 | + checkGetterReturnsValue(bs, table); | |
| 101 | 117 | session.execute(bs); |
| 102 | 118 | break; |
| 103 | 119 | } |
| 104 | 120 | |
| 105 | 121 | 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); | |
| 107 | 123 | |
| 124 | + // Since codec.deserialize will get the unboxed version for primitive check against expected unboxed value. | |
| 108 | 125 | 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 | + | |
| 115 | 143 | |
| 116 | 144 | session.execute(table.truncateStatement); |
| 117 | 145 | } |
| 118 | 146 | } |
| 119 | 147 | |
| 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); | |
| 123 | 152 | |
| 124 | 153 | // 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); | |
| 127 | 156 | } |
| 128 | 157 | |
| 129 | 158 | 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(); | |
| 131 | 161 | assertThat(values.length).isEqualTo(1); |
| 132 | 162 | 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)); | |
| 135 | 165 | } |
| 136 | 166 | |
| 137 | 167 | /** |
| @@ -143,6 +173,8 @@ | ||
| 143 | 173 | |
| 144 | 174 | final DataType testColumnType; |
| 145 | 175 | final Object sampleValue; |
| 176 | + final Object expectedValue; | |
| 177 | + final Object expectedPrimitiveValue; | |
| 146 | 178 | |
| 147 | 179 | final String createStatement; |
| 148 | 180 | final String insertStatement = String.format("INSERT INTO %s (k, v) VALUES (1, ?)", tableName); |
| @@ -152,8 +184,18 @@ | ||
| 152 | 184 | final VersionNumber minCassandraVersion; |
| 153 | 185 | |
| 154 | 186 | 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) { | |
| 155 | 195 | this.testColumnType = testColumnType; |
| 156 | 196 | this.sampleValue = sampleValue; |
| 197 | + this.expectedValue = expectedValue; | |
| 198 | + this.expectedPrimitiveValue = expectedPrimitiveValue; | |
| 157 | 199 | this.minCassandraVersion = VersionNumber.parse(minCassandraVersion); |
| 158 | 200 | |
| 159 | 201 | this.createStatement = String.format("CREATE TABLE %s (k int PRIMARY KEY, v %s)", tableName, testColumnType); |
| @@ -164,6 +206,7 @@ | ||
| 164 | 206 | List<TestTable> tables = Lists.newArrayList(); |
| 165 | 207 | |
| 166 | 208 | tables.addAll(tablesWithPrimitives()); |
| 209 | + tables.addAll(tablesWithPrimitivesNull()); | |
| 167 | 210 | tables.addAll(tablesWithCollectionsOfPrimitives()); |
| 168 | 211 | tables.addAll(tablesWithMapsOfPrimitives()); |
| 169 | 212 | tables.addAll(tablesWithNestedCollections()); |
| @@ -179,6 +222,46 @@ | ||
| 179 | 222 | return tables; |
| 180 | 223 | } |
| 181 | 224 | |
| 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 | + | |
| 182 | 265 | private static List<TestTable> tablesWithCollectionsOfPrimitives() { |
| 183 | 266 | List<TestTable> tables = Lists.newArrayList(); |
| 184 | 267 | for (Map.Entry<DataType, Object> entry : PrimitiveTypeSamples.ALL.entrySet()) { |
| @@ -260,7 +343,7 @@ | ||
| 260 | 343 | |
| 261 | 344 | int typeIdx = type.getTypeArguments().size() > 1 ? 1 : 0; |
| 262 | 345 | DataType argument = type.getTypeArguments().get(typeIdx); |
| 263 | - boolean isAtBottom = !argument.isCollection(); | |
| 346 | + boolean isAtBottom = !(argument instanceof DataType.CollectionType); | |
| 264 | 347 | |
| 265 | 348 | if(isAtBottom) { |
| 266 | 349 | switch(type.getName()) { |
| @@ -343,51 +426,54 @@ | ||
| 343 | 426 | return null; |
| 344 | 427 | } |
| 345 | 428 | |
| 346 | - private Object getBoundValue(BoundStatement bs, DataType dataType) { | |
| 429 | + private Object getValue(GettableByIndexData data, DataType dataType) { | |
| 347 | 430 | // This is kind of lame, but better than testing all getters manually |
| 431 | + CodecRegistry codecRegistry = cluster.getConfiguration().getCodecRegistry(); | |
| 348 | 432 | switch (dataType.getName()) { |
| 349 | 433 | case ASCII: |
| 350 | - return bs.getString(0); | |
| 434 | + return data.getString(0); | |
| 351 | 435 | case BIGINT: |
| 352 | - return bs.getLong(0); | |
| 436 | + return data.getLong(0); | |
| 353 | 437 | case BLOB: |
| 354 | - return bs.getBytes(0); | |
| 438 | + return data.getBytes(0); | |
| 355 | 439 | case BOOLEAN: |
| 356 | - return bs.getBool(0); | |
| 440 | + return data.getBool(0); | |
| 357 | 441 | case DECIMAL: |
| 358 | - return bs.getDecimal(0); | |
| 442 | + return data.getDecimal(0); | |
| 359 | 443 | case DOUBLE: |
| 360 | - return bs.getDouble(0); | |
| 444 | + return data.getDouble(0); | |
| 361 | 445 | case FLOAT: |
| 362 | - return bs.getFloat(0); | |
| 446 | + return data.getFloat(0); | |
| 363 | 447 | case INET: |
| 364 | - return bs.getInet(0); | |
| 448 | + return data.getInet(0); | |
| 365 | 449 | case TINYINT: |
| 366 | - return bs.getByte(0); | |
| 450 | + return data.getByte(0); | |
| 367 | 451 | case SMALLINT: |
| 368 | - return bs.getShort(0); | |
| 452 | + return data.getShort(0); | |
| 369 | 453 | case INT: |
| 370 | - return bs.getInt(0); | |
| 454 | + return data.getInt(0); | |
| 371 | 455 | case TEXT: |
| 372 | 456 | case VARCHAR: |
| 373 | - return bs.getString(0); | |
| 457 | + return data.getString(0); | |
| 374 | 458 | case TIMESTAMP: |
| 375 | - return bs.getTimestamp(0); | |
| 459 | + return data.getTimestamp(0); | |
| 376 | 460 | case DATE: |
| 377 | - return bs.getDate(0); | |
| 461 | + return data.getDate(0); | |
| 378 | 462 | case TIME: |
| 379 | - return bs.getTime(0); | |
| 463 | + return data.getTime(0); | |
| 380 | 464 | case UUID: |
| 381 | 465 | case TIMEUUID: |
| 382 | - return bs.getUUID(0); | |
| 466 | + return data.getUUID(0); | |
| 383 | 467 | case VARINT: |
| 384 | - return bs.getVarint(0); | |
| 468 | + return data.getVarint(0); | |
| 385 | 469 | case LIST: |
| 386 | - return bs.getList(0, dataType.getTypeArguments().get(0).asJavaClass()); | |
| 470 | + return data.getList(0, codecRegistry.codecFor(dataType.getTypeArguments().get(0)).getJavaType()); | |
| 387 | 471 | case SET: |
| 388 | - return bs.getSet(0, dataType.getTypeArguments().get(0).asJavaClass()); | |
| 472 | + return data.getSet(0, codecRegistry.codecFor(dataType.getTypeArguments().get(0)).getJavaType()); | |
| 389 | 473 | 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()); | |
| 391 | 477 | case CUSTOM: |
| 392 | 478 | case COUNTER: |
| 393 | 479 | default: |
modified driver-core/src/test/java/com/datastax/driver/core/DataTypeTest.java +71 −66
| @@ -22,9 +22,9 @@ | ||
| 22 | 22 | import java.util.*; |
| 23 | 23 | |
| 24 | 24 | import com.google.common.collect.Lists; |
| 25 | -import com.google.common.reflect.TypeToken; | |
| 26 | 25 | import org.testng.annotations.Test; |
| 27 | 26 | |
| 27 | +import static com.google.common.collect.Lists.newArrayList; | |
| 28 | 28 | import static org.testng.Assert.assertEquals; |
| 29 | 29 | import static org.testng.Assert.fail; |
| 30 | 30 | |
| @@ -38,6 +38,10 @@ | ||
| 38 | 38 | */ |
| 39 | 39 | public class DataTypeTest { |
| 40 | 40 | |
| 41 | + CodecRegistry codecRegistry = new CodecRegistry(); | |
| 42 | + | |
| 43 | + ProtocolVersion protocolVersion = TestUtils.getDesiredProtocolVersion(); | |
| 44 | + | |
| 41 | 45 | static boolean exclude(DataType t) { |
| 42 | 46 | return t.getName() == DataType.Name.COUNTER; |
| 43 | 47 | } |
| @@ -65,80 +69,97 @@ | ||
| 65 | 69 | case VARCHAR: |
| 66 | 70 | return new TestValue[]{ |
| 67 | 71 | 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") }; | |
| 69 | 74 | case BIGINT: |
| 70 | 75 | return new TestValue[]{ |
| 71 | 76 | new TestValue(42L, "42", "42"), |
| 72 | 77 | new TestValue(91294377723L, "91294377723", "91294377723"), |
| 73 | - new TestValue(-133L, "-133", "-133") }; | |
| 78 | + new TestValue(-133L, "-133", "-133"), | |
| 79 | + new TestValue(null, null, "NULL") }; | |
| 74 | 80 | case TIMESTAMP: |
| 75 | 81 | // input: single quotes are optional for long literals, mandatory for date patterns |
| 76 | 82 | return new TestValue[]{ |
| 77 | 83 | new TestValue(new Date(42L), "42", "42"), |
| 78 | 84 | new TestValue(new Date(91294377723L), "91294377723", "91294377723"), |
| 79 | 85 | 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") }; | |
| 81 | 88 | case DATE: |
| 82 | 89 | // input: single quotes are optional for long literals, mandatory for date patterns |
| 83 | 90 | return new TestValue[]{ |
| 84 | 91 | new TestValue(LocalDate.fromDaysSinceEpoch(16071), "'2014-01-01'", "'2014-01-01'"), |
| 85 | 92 | new TestValue(LocalDate.fromDaysSinceEpoch(0), "'1970-01-01'", "'1970-01-01'"), |
| 86 | 93 | 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") }; | |
| 88 | 96 | case TIME: |
| 89 | 97 | // input: all literals must by enclosed in single quotes |
| 90 | 98 | return new TestValue[]{ |
| 91 | 99 | new TestValue(54012123450000L, "'54012123450000'", "'15:00:12.123450000'"), |
| 92 | 100 | 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") }; | |
| 94 | 103 | case BLOB: |
| 95 | 104 | return new TestValue[]{ |
| 96 | 105 | 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") }; | |
| 98 | 108 | case BOOLEAN: |
| 99 | 109 | return new TestValue[]{ |
| 100 | 110 | new TestValue(true, "true", "true"), |
| 101 | - new TestValue(false, "false", "false") }; | |
| 111 | + new TestValue(false, "false", "false"), | |
| 112 | + new TestValue(null, null, "NULL") }; | |
| 102 | 113 | case DECIMAL: |
| 103 | 114 | 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") }; | |
| 105 | 117 | case DOUBLE: |
| 106 | 118 | return new TestValue[]{ |
| 107 | 119 | 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") }; | |
| 109 | 122 | case FLOAT: |
| 110 | 123 | return new TestValue[]{ |
| 111 | 124 | 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") }; | |
| 113 | 127 | case INET: |
| 114 | 128 | try { |
| 115 | 129 | 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") }; | |
| 117 | 132 | } catch (java.net.UnknownHostException e) { |
| 118 | 133 | throw new RuntimeException(); |
| 119 | 134 | } |
| 120 | 135 | case TINYINT: |
| 121 | 136 | return new TestValue[]{ |
| 122 | 137 | 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") }; | |
| 124 | 140 | case SMALLINT: |
| 125 | 141 | return new TestValue[]{ |
| 126 | 142 | 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") }; | |
| 128 | 145 | case INT: |
| 129 | 146 | return new TestValue[]{ |
| 130 | 147 | new TestValue(-2, "-2", "-2"), |
| 131 | - new TestValue(42, "42", "42") }; | |
| 148 | + new TestValue(42, "42", "42"), | |
| 149 | + new TestValue(null, null, "NULL") }; | |
| 132 | 150 | case TIMEUUID: |
| 133 | 151 | 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") }; | |
| 135 | 154 | case UUID: |
| 136 | 155 | return new TestValue[]{ |
| 137 | 156 | 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") }; | |
| 139 | 159 | case VARINT: |
| 140 | 160 | 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") }; | |
| 142 | 163 | default: |
| 143 | 164 | throw new RuntimeException("Missing handling of " + dt); |
| 144 | 165 | } |
| @@ -151,7 +172,7 @@ | ||
| 151 | 172 | continue; |
| 152 | 173 | |
| 153 | 174 | for (TestValue value : primitiveTestValues(dt)) |
| 154 | - assertThat(dt.parse(value.cqlInputString)) | |
| 175 | + assertThat(codecRegistry.codecFor(dt).parse(value.cqlInputString)) | |
| 155 | 176 | .as("Parsing input %s to a %s", value.cqlInputString, dt) |
| 156 | 177 | .isEqualTo(value.javaObject); |
| 157 | 178 | } |
| @@ -164,7 +185,7 @@ | ||
| 164 | 185 | continue; |
| 165 | 186 | |
| 166 | 187 | for (TestValue value : primitiveTestValues(dt)) |
| 167 | - assertThat(dt.format(value.javaObject)) | |
| 188 | + assertThat(codecRegistry.codecFor(dt).format(value.javaObject)) | |
| 168 | 189 | .as("Formatting a %s expecting %s", dt, value.cqlOutputString) |
| 169 | 190 | .isEqualTo(value.cqlOutputString); |
| 170 | 191 | } |
| @@ -172,46 +193,47 @@ | ||
| 172 | 193 | |
| 173 | 194 | @Test(groups = "unit") |
| 174 | 195 | public void parseFormatListTest() { |
| 175 | - String toParse = "['Foo', 'Bar', 'Foo''bar']"; | |
| 196 | + String toParse = "['Foo','Bar','Foo''bar']"; | |
| 176 | 197 | List<String> toFormat = Arrays.asList("Foo", "Bar", "Foo'bar"); |
| 177 | 198 | 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); | |
| 180 | 201 | } |
| 181 | 202 | |
| 182 | 203 | @SuppressWarnings("serial") |
| 183 | 204 | @Test(groups = "unit") |
| 184 | 205 | 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"); }}; | |
| 187 | 209 | 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); | |
| 190 | 212 | } |
| 191 | 213 | |
| 192 | 214 | @SuppressWarnings("serial") |
| 193 | 215 | @Test(groups = "unit") |
| 194 | 216 | public void parseFormatMapTest() { |
| 195 | - String toParse = "{'Foo':3, 'Bar':42, 'Foo''bar':-24}"; | |
| 217 | + String toParse = "{'Foo':3,'Bar':42,'Foo''bar':-24}"; | |
| 196 | 218 | Map<String, Integer> toFormat = new LinkedHashMap<String, Integer>(){{ put("Foo", 3); put("Bar", 42); put("Foo'bar", -24); }}; |
| 197 | 219 | 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); | |
| 200 | 222 | } |
| 201 | 223 | |
| 202 | 224 | @SuppressWarnings("serial") |
| 203 | 225 | @Test(groups = "unit") |
| 204 | 226 | public void parseFormatUDTTest() { |
| 205 | 227 | |
| 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}}}"; | |
| 207 | 229 | |
| 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); | |
| 209 | 231 | UserType udt2 = new UserType("ks", "t", Arrays.asList( |
| 210 | 232 | new UserType.Field("t", DataType.text()), |
| 211 | 233 | new UserType.Field("i", DataType.cint()), |
| 212 | 234 | new UserType.Field("l", DataType.list(DataType.text())), |
| 213 | 235 | new UserType.Field("s", DataType.map(DataType.cint(), udt1)) |
| 214 | - )); | |
| 236 | + ), protocolVersion, codecRegistry); | |
| 215 | 237 | |
| 216 | 238 | UDTValue toFormat = udt2.newValue(); |
| 217 | 239 | toFormat.setString("t", "fo'o"); |
| @@ -219,19 +241,20 @@ | ||
| 219 | 241 | toFormat.setList("l", Arrays.<String>asList("a", "b")); |
| 220 | 242 | toFormat.setMap("s", new HashMap<Integer, UDTValue>(){{ put(3, udt1.newValue().setBytes("a", ByteBuffer.wrap(new byte[]{1}))); }}); |
| 221 | 243 | |
| 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); | |
| 224 | 246 | } |
| 225 | 247 | |
| 248 | + @SuppressWarnings("deprecation") | |
| 226 | 249 | @Test(groups = "unit") |
| 227 | 250 | public void parseFormatTupleTest() { |
| 228 | 251 | |
| 229 | 252 | 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); | |
| 231 | 254 | TupleValue toFormat = t.newValue(1, "foo", 1.0f); |
| 232 | 255 | |
| 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); | |
| 235 | 258 | } |
| 236 | 259 | |
| 237 | 260 | @Test(groups = "unit") |
| @@ -247,17 +270,15 @@ | ||
| 247 | 270 | continue; |
| 248 | 271 | |
| 249 | 272 | 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); | |
| 251 | 275 | } |
| 252 | 276 | |
| 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()); | |
| 257 | 278 | |
| 258 | 279 | try { |
| 259 | 280 | ByteBuffer badValue = ByteBuffer.allocate(4); |
| 260 | - DataType.bigint().deserialize(badValue, version); | |
| 281 | + codec.deserialize(badValue, version); | |
| 261 | 282 | fail("This should not have worked"); |
| 262 | 283 | } catch (InvalidTypeException e) { /* That's what we want */ } |
| 263 | 284 | } |
| @@ -273,39 +294,23 @@ | ||
| 273 | 294 | List<String> l = Arrays.asList("foo", "bar"); |
| 274 | 295 | |
| 275 | 296 | 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); | |
| 277 | 299 | |
| 278 | 300 | 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); | |
| 280 | 304 | fail("This should not have worked"); |
| 281 | 305 | } catch (InvalidTypeException e) { /* That's what we want */ } |
| 282 | 306 | } |
| 283 | 307 | |
| 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 | - | |
| 303 | 308 | @Test(groups = "unit") |
| 304 | 309 | public void should_not_return_v4_types_in_all_primitive_types_with_v3() { |
| 305 | 310 | Set<DataType> dataTypes = DataType.allPrimitiveTypes(ProtocolVersion.V3); |
| 306 | 311 | |
| 307 | 312 | // 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())); | |
| 309 | 314 | |
| 310 | 315 | // Ensure all values are <= V3. |
| 311 | 316 | for(DataType dataType : dataTypes) { |
modified driver-core/src/test/java/com/datastax/driver/core/ExceptionsTest.java +11 −11
| @@ -202,12 +202,12 @@ | ||
| 202 | 202 | c.session.execute("USE " + keyspace); |
| 203 | 203 | c.session.execute(String.format("CREATE TABLE %s (k text PRIMARY KEY, t text, i int, f float)", table)); |
| 204 | 204 | |
| 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)); | |
| 207 | 207 | |
| 208 | 208 | c.cassandraCluster.forceStop(2); |
| 209 | 209 | 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)); | |
| 211 | 211 | } catch (ReadTimeoutException e) { |
| 212 | 212 | assertEquals(e.getConsistencyLevel(), ConsistencyLevel.ALL); |
| 213 | 213 | assertEquals(e.getReceivedAcknowledgements(), 2); |
| @@ -318,15 +318,15 @@ | ||
| 318 | 318 | c.session.execute("USE " + keyspace); |
| 319 | 319 | c.session.execute(String.format("CREATE TABLE %s (k text PRIMARY KEY, t text, i int, f float)", table)); |
| 320 | 320 | |
| 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)); | |
| 323 | 323 | |
| 324 | 324 | c.cassandraCluster.stop(2); |
| 325 | 325 | |
| 326 | 326 | waitForDownWithWait(CCMBridge.IP_PREFIX + '2', c.cluster, 10); |
| 327 | 327 | |
| 328 | 328 | 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)); | |
| 330 | 330 | } catch (UnavailableException e) { |
| 331 | 331 | String expectedError = String.format("Not enough replica available for query at consistency %s (%d required but only %d alive)", "ALL", 3, 2); |
| 332 | 332 | assertEquals(e.getMessage(), expectedError); |
| @@ -336,7 +336,7 @@ | ||
| 336 | 336 | } |
| 337 | 337 | |
| 338 | 338 | 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)); | |
| 340 | 340 | } catch (UnavailableException e) { |
| 341 | 341 | String expectedError = String.format("Not enough replica available for query at consistency %s (%d required but only %d alive)", "ALL", 3, 2); |
| 342 | 342 | assertEquals(e.getMessage(), expectedError); |
| @@ -371,12 +371,12 @@ | ||
| 371 | 371 | c.session.execute("USE " + keyspace); |
| 372 | 372 | c.session.execute(String.format("CREATE TABLE %s (k text PRIMARY KEY, t text, i int, f float)", table)); |
| 373 | 373 | |
| 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)); | |
| 376 | 376 | |
| 377 | 377 | c.cassandraCluster.forceStop(2); |
| 378 | 378 | 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)); | |
| 380 | 380 | } catch (WriteTimeoutException e) { |
| 381 | 381 | assertEquals(e.getConsistencyLevel(), ConsistencyLevel.ALL); |
| 382 | 382 | assertEquals(e.getReceivedAcknowledgements(), 2); |
| @@ -429,7 +429,7 @@ | ||
| 429 | 429 | |
| 430 | 430 | try { |
| 431 | 431 | // 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)) | |
| 433 | 433 | .setConsistencyLevel(ConsistencyLevel.ALL)); |
| 434 | 434 | } catch(WriteFailureException e) { |
| 435 | 435 | // 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 @@ | ||
| 43 | 43 | for (int i = 0; i < 100; i++) |
| 44 | 44 | session.execute(String.format("INSERT INTO test (k, v) VALUES ('%s', %d)", key, i)); |
| 45 | 45 | |
| 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)); | |
| 47 | 47 | st.setFetchSize(5); // Ridiculously small fetch size for testing purpose. Don't do at home. |
| 48 | 48 | ResultSet rs = session.execute(st); |
| 49 | 49 |
modified driver-core/src/test/java/com/datastax/driver/core/FunctionMetadataTest.java +5 −3
| @@ -29,6 +29,8 @@ | ||
| 29 | 29 | |
| 30 | 30 | public class FunctionMetadataTest { |
| 31 | 31 | KeyspaceMetadata keyspace; |
| 32 | + private ProtocolVersion protocolVersion = TestUtils.getDesiredProtocolVersion(); | |
| 33 | + private CodecRegistry codecRegistry = new CodecRegistry(); | |
| 32 | 34 | |
| 33 | 35 | @BeforeMethod(groups = "unit") |
| 34 | 36 | public void setup() { |
| @@ -37,7 +39,7 @@ | ||
| 37 | 39 | |
| 38 | 40 | @Test(groups = "unit") |
| 39 | 41 | 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); | |
| 41 | 43 | |
| 42 | 44 | assertThat(function).isNotNull(); |
| 43 | 45 | assertThat(function.getKeyspace()).isEqualTo(keyspace); |
| @@ -68,7 +70,7 @@ | ||
| 68 | 70 | |
| 69 | 71 | @Test(groups = "unit") |
| 70 | 72 | 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); | |
| 72 | 74 | |
| 73 | 75 | assertThat(function).isNotNull(); |
| 74 | 76 | assertThat(function.getKeyspace()).isEqualTo(keyspace); |
| @@ -120,4 +122,4 @@ | ||
| 120 | 122 | |
| 121 | 123 | return row; |
| 122 | 124 | } |
| 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 @@ | ||
| 15 | 15 | */ |
| 16 | 16 | package com.datastax.driver.core; |
| 17 | 17 | |
| 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 | - | |
| 29 | 18 | import java.nio.ByteBuffer; |
| 30 | 19 | import java.util.Collection; |
| 31 | 20 | import java.util.List; |
| 32 | 21 | |
| 22 | +import com.google.common.collect.ImmutableList; | |
| 23 | +import com.google.common.primitives.Ints; | |
| 33 | 24 | import org.testng.annotations.Test; |
| 34 | 25 | |
| 35 | -import com.datastax.driver.core.ColumnMetadata.IndexMetadata; | |
| 36 | -import com.datastax.driver.core.ColumnMetadata.Raw; | |
| 26 | +import com.datastax.driver.core.ColumnMetadata.*; | |
| 37 | 27 | import com.datastax.driver.core.Token.M3PToken; |
| 38 | 28 | 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; | |
| 41 | 34 | |
| 42 | 35 | @CassandraVersion( |
| 43 | 36 | major = 1.2) |
| @@ -55,6 +48,10 @@ | ||
| 55 | 48 | definition(VALIDATOR, text()), |
| 56 | 49 | definition(INDEX_OPTIONS, text()) |
| 57 | 50 | }); |
| 51 | + | |
| 52 | + static { | |
| 53 | + defs.setCodecRegistry(new CodecRegistry()); | |
| 54 | + } | |
| 58 | 55 | |
| 59 | 56 | @Override |
| 60 | 57 | protected Collection<String> getTableDefinitions() { |
| @@ -205,7 +202,7 @@ | ||
| 205 | 202 | wrap("{\"foo\" : \"bar\", \"class_name\" : \"dummy.DummyIndex\"}") // index options |
| 206 | 203 | ); |
| 207 | 204 | 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())); | |
| 209 | 206 | IndexMetadata index = column.getIndex(); |
| 210 | 207 | assertThat(index).hasName("custom_index") |
| 211 | 208 | .isNotKeys() |
| @@ -240,7 +237,10 @@ | ||
| 240 | 237 | wrap("null") // index options |
| 241 | 238 | ); |
| 242 | 239 | 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())); | |
| 244 | 244 | IndexMetadata index = column.getIndex(); |
| 245 | 245 | |
| 246 | 246 | 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<timestamp,varchar></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<timestamp,varchar></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 @@ | ||
| 18 | 18 | import java.nio.ByteBuffer; |
| 19 | 19 | |
| 20 | 20 | import org.testng.annotations.Test; |
| 21 | + | |
| 21 | 22 | import static org.testng.Assert.assertEquals; |
| 22 | 23 | import static org.testng.Assert.assertTrue; |
| 23 | 24 | |
| 24 | -import com.datastax.driver.core.exceptions.InvalidQueryException; | |
| 25 | 25 | import com.datastax.driver.core.querybuilder.Batch; |
| 26 | 26 | import com.datastax.driver.core.querybuilder.Insert; |
| 27 | +import com.datastax.driver.core.querybuilder.QueryBuilder; | |
| 27 | 28 | import com.datastax.driver.core.utils.CassandraVersion; |
| 28 | 29 | |
| 29 | 30 | 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; | |
| 32 | 32 | |
| 33 | 33 | /** |
| 34 | 34 | * Test limitations when using large amounts of data with the driver |
| @@ -43,12 +43,13 @@ | ||
| 43 | 43 | */ |
| 44 | 44 | private void testWideRows(CCMBridge.CCMCluster c, int key) throws Throwable { |
| 45 | 45 | // Write data |
| 46 | + QueryBuilder builder = new QueryBuilder(c.cluster); | |
| 46 | 47 | 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)); | |
| 48 | 49 | } |
| 49 | 50 | |
| 50 | 51 | // 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))); | |
| 52 | 53 | |
| 53 | 54 | // Verify data |
| 54 | 55 | int i = 0; |
| @@ -65,14 +66,15 @@ | ||
| 65 | 66 | */ |
| 66 | 67 | private void testWideBatchRows(CCMBridge.CCMCluster c, int key) throws Throwable { |
| 67 | 68 | // Write data |
| 68 | - Batch q = batch(); | |
| 69 | + QueryBuilder builder = new QueryBuilder(c.cluster); | |
| 70 | + Batch q = builder.batch(); | |
| 69 | 71 | 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)); | |
| 71 | 73 | } |
| 72 | 74 | c.session.execute(q.setConsistencyLevel(ConsistencyLevel.QUORUM)); |
| 73 | 75 | |
| 74 | 76 | // 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))); | |
| 76 | 78 | |
| 77 | 79 | // Verify data |
| 78 | 80 | int i = 0; |
| @@ -94,12 +96,13 @@ | ||
| 94 | 96 | bb.flip(); |
| 95 | 97 | |
| 96 | 98 | // Write data |
| 99 | + QueryBuilder builder = new QueryBuilder(c.cluster); | |
| 97 | 100 | 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)); | |
| 99 | 102 | } |
| 100 | 103 | |
| 101 | 104 | // 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))); | |
| 103 | 106 | |
| 104 | 107 | // Verify data |
| 105 | 108 | for (Row row : rs) { |
| @@ -115,15 +118,16 @@ | ||
| 115 | 118 | */ |
| 116 | 119 | private void testLargeText(CCMBridge.CCMCluster c, int key) throws Throwable { |
| 117 | 120 | // Write data |
| 121 | + QueryBuilder builder = new QueryBuilder(c.cluster); | |
| 118 | 122 | StringBuilder b = new StringBuilder(); |
| 119 | 123 | for (int i = 0; i < 1000000; ++i) { |
| 120 | 124 | // Create ultra-long text |
| 121 | 125 | b.append(i); |
| 122 | 126 | } |
| 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)); | |
| 124 | 128 | |
| 125 | 129 | // 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(); | |
| 127 | 131 | |
| 128 | 132 | // Verify data |
| 129 | 133 | assertTrue(b.toString().equals(row.getString("txt"))); |
| @@ -163,14 +167,15 @@ | ||
| 163 | 167 | */ |
| 164 | 168 | private void testWideTable(CCMBridge.CCMCluster c, int key) throws Throwable { |
| 165 | 169 | // 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); | |
| 167 | 172 | for (int i = 0; i < 330; ++i) { |
| 168 | 173 | insertStatement = insertStatement.value(createColumnName(i), i); |
| 169 | 174 | } |
| 170 | 175 | c.session.execute(insertStatement.setConsistencyLevel(ConsistencyLevel.QUORUM)); |
| 171 | 176 | |
| 172 | 177 | // 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(); | |
| 174 | 179 | |
| 175 | 180 | // Verify data |
| 176 | 181 | 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 @@ | ||
| 66 | 66 | retryDecision = RetryDecision.retry(ConsistencyLevel.ONE); |
| 67 | 67 | |
| 68 | 68 | // 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); | |
| 70 | 70 | session.execute(statement); |
| 71 | 71 | |
| 72 | 72 | 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 @@ | ||
| 19 | 19 | import java.util.Collections; |
| 20 | 20 | import java.util.Iterator; |
| 21 | 21 | |
| 22 | -import com.datastax.driver.core.utils.CassandraVersion; | |
| 23 | 22 | import org.slf4j.Logger; |
| 24 | 23 | import org.slf4j.LoggerFactory; |
| 25 | 24 | import org.testng.annotations.BeforeClass; |
| @@ -28,6 +27,7 @@ | ||
| 28 | 27 | import static org.assertj.core.api.Assertions.assertThat; |
| 29 | 28 | |
| 30 | 29 | import com.datastax.driver.core.exceptions.PagingStateException; |
| 30 | +import com.datastax.driver.core.utils.CassandraVersion; | |
| 31 | 31 | |
| 32 | 32 | @CassandraVersion(major=2.0) |
| 33 | 33 | public class PagingStateTest extends CCMBridge.PerClassSingleNodeCluster { |
| @@ -55,12 +55,12 @@ | ||
| 55 | 55 | */ |
| 56 | 56 | @Test(groups = "short") |
| 57 | 57 | 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)); | |
| 59 | 59 | ResultSet result = session.execute(st.setFetchSize(20)); |
| 60 | 60 | int pageSize = result.getAvailableWithoutFetching(); |
| 61 | 61 | String savedPagingStateString = result.getExecutionInfo().getPagingState().toString(); |
| 62 | 62 | |
| 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)); | |
| 64 | 64 | result = session.execute(st.setFetchSize(20).setPagingState(PagingState.fromString(savedPagingStateString))); |
| 65 | 65 | |
| 66 | 66 | //We have the result starting from the next page we stopped |
| @@ -85,7 +85,7 @@ | ||
| 85 | 85 | boolean setWithFalseContent = false; |
| 86 | 86 | boolean setWithWrongStatement = false; |
| 87 | 87 | |
| 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)); | |
| 89 | 89 | ResultSet result = session.execute(st.setFetchSize(20)); |
| 90 | 90 | |
| 91 | 91 | PagingState savedPagingState = result.getExecutionInfo().getPagingState(); |
| @@ -106,7 +106,7 @@ | ||
| 106 | 106 | } |
| 107 | 107 | |
| 108 | 108 | // 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")); | |
| 110 | 110 | try { |
| 111 | 111 | st.setFetchSize(20).setPagingState(PagingState.fromString(savedPagingStateString)); |
| 112 | 112 | } catch (PagingStateException e) { |
| @@ -170,7 +170,7 @@ | ||
| 170 | 170 | */ |
| 171 | 171 | @Test(groups = "short") |
| 172 | 172 | 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)); | |
| 174 | 174 | ResultSet result = session.execute(st.setFetchSize(20)); |
| 175 | 175 | |
| 176 | 176 | // Consume enough of the iterator to cause all the results to be paged in. |
| @@ -181,7 +181,7 @@ | ||
| 181 | 181 | |
| 182 | 182 | String savedPagingStateString = result.getExecutionInfo().getPagingState().toString(); |
| 183 | 183 | |
| 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)); | |
| 185 | 185 | result = session.execute(st.setFetchSize(20).setPagingState(PagingState.fromString(savedPagingStateString))); |
| 186 | 186 | |
| 187 | 187 | assertThat(result.one()).isNull(); |
| @@ -218,12 +218,12 @@ | ||
| 218 | 218 | */ |
| 219 | 219 | @Test(groups = "short") |
| 220 | 220 | 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)); | |
| 222 | 222 | ResultSet result = session.execute(st.setFetchSize(20)); |
| 223 | 223 | int pageSize = result.getAvailableWithoutFetching(); |
| 224 | 224 | byte[] savedPagingState = result.getExecutionInfo().getPagingStateUnsafe(); |
| 225 | 225 | |
| 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)); | |
| 227 | 227 | result = session.execute(st.setFetchSize(20).setPagingStateUnsafe(savedPagingState)); |
| 228 | 228 | |
| 229 | 229 | //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 @@ | ||
| 128 | 128 | session.execute(setBoundValue(bs, name, type, getFixedValue(type))); |
| 129 | 129 | |
| 130 | 130 | 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); | |
| 132 | 132 | } |
| 133 | 133 | } |
| 134 | 134 | |
| @@ -149,7 +149,7 @@ | ||
| 149 | 149 | session.execute(setBoundValue(bs, name, type, getFixedValue2(type))); |
| 150 | 150 | |
| 151 | 151 | 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); | |
| 153 | 153 | } |
| 154 | 154 | } |
| 155 | 155 | |
| @@ -170,7 +170,7 @@ | ||
| 170 | 170 | session.execute(setBoundValue(bs, name, type, value)); |
| 171 | 171 | |
| 172 | 172 | 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); | |
| 174 | 174 | } |
| 175 | 175 | } |
| 176 | 176 | |
| @@ -194,7 +194,7 @@ | ||
| 194 | 194 | session.execute(setBoundValue(bs, name, type, value)); |
| 195 | 195 | |
| 196 | 196 | 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); | |
| 198 | 198 | } |
| 199 | 199 | } |
| 200 | 200 | |
| @@ -215,7 +215,7 @@ | ||
| 215 | 215 | session.execute(setBoundValue(bs, name, type, value)); |
| 216 | 216 | |
| 217 | 217 | 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); | |
| 219 | 219 | } |
| 220 | 220 | } |
| 221 | 221 | |
| @@ -239,7 +239,7 @@ | ||
| 239 | 239 | session.execute(setBoundValue(bs, name, type, value)); |
| 240 | 240 | |
| 241 | 241 | 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); | |
| 243 | 243 | } |
| 244 | 244 | } |
| 245 | 245 | |
| @@ -265,7 +265,7 @@ | ||
| 265 | 265 | session.execute(setBoundValue(bs, name, type, value)); |
| 266 | 266 | |
| 267 | 267 | 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); | |
| 269 | 269 | } |
| 270 | 270 | } |
| 271 | 271 | } |
| @@ -295,7 +295,7 @@ | ||
| 295 | 295 | session.execute(setBoundValue(bs, name, type, value)); |
| 296 | 296 | |
| 297 | 297 | 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); | |
| 299 | 299 | } |
| 300 | 300 | } |
| 301 | 301 | } |
| @@ -368,7 +368,7 @@ | ||
| 368 | 368 | @Test(groups = "short") |
| 369 | 369 | public void prepareStatementInheritPropertiesTest() { |
| 370 | 370 | |
| 371 | - RegularStatement toPrepare = new SimpleStatement("SELECT * FROM test WHERE k=?"); | |
| 371 | + RegularStatement toPrepare = session.newSimpleStatement("SELECT * FROM test WHERE k=?"); | |
| 372 | 372 | toPrepare.setConsistencyLevel(ConsistencyLevel.QUORUM); |
| 373 | 373 | toPrepare.enableTracing(); |
| 374 | 374 | |
| @@ -400,7 +400,7 @@ | ||
| 400 | 400 | BatchStatement bs = new BatchStatement(); |
| 401 | 401 | bs.add(ps1.bind("one", "foo")); |
| 402 | 402 | 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')")); | |
| 404 | 404 | |
| 405 | 405 | session.execute(bs); |
| 406 | 406 | |
| @@ -540,7 +540,7 @@ | ||
| 540 | 540 | st2.setString(0, "foo"); |
| 541 | 541 | // i is UNSET |
| 542 | 542 | 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'"); | |
| 544 | 544 | st3.enableTracing(); |
| 545 | 545 | ResultSet rows = session.execute(st3); |
| 546 | 546 | assertThat(rows.one().getInt("i")).isEqualTo(1234); |
| @@ -569,7 +569,7 @@ | ||
| 569 | 569 | st2.setString(0, "foo"); |
| 570 | 570 | // i is UNSET |
| 571 | 571 | 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'"); | |
| 573 | 573 | st3.enableTracing(); |
| 574 | 574 | ResultSet rows = session.execute(st3); |
| 575 | 575 | assertThat(rows.one().getInt("i")).isEqualTo(1234); |
| @@ -591,7 +591,7 @@ | ||
| 591 | 591 | st1.setString(0, "foo"); |
| 592 | 592 | st1.setToNull(1); |
| 593 | 593 | 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'"); | |
| 595 | 595 | st2.enableTracing(); |
| 596 | 596 | ResultSet rows = session.execute(st2); |
| 597 | 597 | assertThat(rows.one().isNull(0)).isTrue(); |
| @@ -614,7 +614,7 @@ | ||
| 614 | 614 | st1.setString(0, "foo"); |
| 615 | 615 | st1.setToNull(1); |
| 616 | 616 | 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'"); | |
| 618 | 618 | st2.enableTracing(); |
| 619 | 619 | ResultSet rows = session.execute(st2); |
| 620 | 620 | assertThat(rows.one().isNull(0)).isTrue(); |
modified driver-core/src/test/java/com/datastax/driver/core/QueryLoggerTest.java +5 −2
| @@ -277,6 +277,7 @@ | ||
| 277 | 277 | public ByteBuffer getRoutingKey() { |
| 278 | 278 | return null; |
| 279 | 279 | } |
| 280 | + | |
| 280 | 281 | @Override |
| 281 | 282 | public String getKeyspace() { |
| 282 | 283 | return null; |
| @@ -495,8 +496,10 @@ | ||
| 495 | 496 | .contains("Query completed normally") |
| 496 | 497 | .contains(ipOfNode(1)) |
| 497 | 498 | .contains(query); |
| 499 | + CodecRegistry codecRegistry = cluster.getConfiguration().getCodecRegistry(); | |
| 498 | 500 | 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))); | |
| 500 | 503 | } |
| 501 | 504 | } |
| 502 | 505 | |
| @@ -726,4 +729,4 @@ | ||
| 726 | 729 | return Lists.newArrayList("CREATE TABLE test (pk int PRIMARY KEY, " + definitions + ")"); |
| 727 | 730 | } |
| 728 | 731 | |
| 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 @@ | ||
| 62 | 62 | public void should_use_CQL_timestamp_over_anything_else() { |
| 63 | 63 | timestampFromGenerator = 10; |
| 64 | 64 | 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)); | |
| 66 | 66 | |
| 67 | 67 | long writeTime = session.execute("SELECT writeTime(v) FROM foo WHERE k = 1").one().getLong(0); |
| 68 | 68 | assertEquals(writeTime, 20); |
| @@ -72,7 +72,7 @@ | ||
| 72 | 72 | public void should_use_statement_timestamp_over_generator() { |
| 73 | 73 | timestampFromGenerator = 10; |
| 74 | 74 | 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)); | |
| 76 | 76 | |
| 77 | 77 | long writeTime = session.execute("SELECT writeTime(v) FROM foo WHERE k = 1").one().getLong(0); |
| 78 | 78 | assertEquals(writeTime, 30); |
| @@ -102,8 +102,8 @@ | ||
| 102 | 102 | @Test(groups = "short") |
| 103 | 103 | public void should_apply_statement_timestamp_only_to_batched_queries_without_timestamp() { |
| 104 | 104 | 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")); | |
| 107 | 107 | batch.setDefaultTimestamp(10); |
| 108 | 108 | session.execute(batch); |
| 109 | 109 | |
| @@ -117,8 +117,8 @@ | ||
| 117 | 117 | public void should_apply_generator_timestamp_only_to_batched_queries_without_timestamp() { |
| 118 | 118 | timestampFromGenerator = 10; |
| 119 | 119 | 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")); | |
| 122 | 122 | session.execute(batch); |
| 123 | 123 | |
| 124 | 124 | long writeTime1 = session.execute("SELECT writeTime(v) FROM foo WHERE k = 1").one().getLong(0); |
| @@ -132,8 +132,8 @@ | ||
| 132 | 132 | timestampFromGenerator = Long.MIN_VALUE; |
| 133 | 133 | long clientTime = System.currentTimeMillis() * 1000; |
| 134 | 134 | 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")); | |
| 137 | 137 | session.execute(batch); |
| 138 | 138 | |
| 139 | 139 | long writeTime1 = session.execute("SELECT writeTime(v) FROM foo WHERE k = 1").one().getLong(0); |
| @@ -144,7 +144,7 @@ | ||
| 144 | 144 | |
| 145 | 145 | @Test(groups = "short") |
| 146 | 146 | 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)"); | |
| 148 | 148 | statement.setDefaultTimestamp(10); |
| 149 | 149 | // This will fail since we test against a single-host cluster. The DowngradingConsistencyRetryPolicy |
| 150 | 150 | // will retry it at ONE. |
modified driver-core/src/test/java/com/datastax/driver/core/SchemaAgreementTest.java +1 −1
| @@ -102,7 +102,7 @@ | ||
| 102 | 102 | |
| 103 | 103 | private static void forceSchemaVersion(Session session, InetAddress peerAddress, UUID schemaVersion) { |
| 104 | 104 | 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))); | |
| 106 | 106 | } |
| 107 | 107 | |
| 108 | 108 | @AfterMethod(groups = "short") |
modified driver-core/src/test/java/com/datastax/driver/core/SessionTest.java +4 −4
| @@ -62,11 +62,11 @@ | ||
| 62 | 62 | |
| 63 | 63 | // execute |
| 64 | 64 | 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); | |
| 66 | 66 | |
| 67 | 67 | // executeAsync |
| 68 | 68 | 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); | |
| 70 | 70 | } |
| 71 | 71 | |
| 72 | 72 | @Test(groups = "short") |
| @@ -151,11 +151,11 @@ | ||
| 151 | 151 | |
| 152 | 152 | // execute |
| 153 | 153 | 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); | |
| 155 | 155 | |
| 156 | 156 | // executeAsync |
| 157 | 157 | 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); | |
| 159 | 159 | |
| 160 | 160 | } finally { |
| 161 | 161 | 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 @@ | ||
| 18 | 18 | import java.util.Collections; |
| 19 | 19 | import java.util.List; |
| 20 | 20 | |
| 21 | +import org.testng.annotations.BeforeClass; | |
| 21 | 22 | import org.testng.annotations.Test; |
| 22 | 23 | |
| 24 | +import static org.mockito.Mockito.mock; | |
| 25 | +import static org.mockito.Mockito.when; | |
| 26 | + | |
| 23 | 27 | 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 | + | |
| 24 | 40 | @Test(groups = "unit", expectedExceptions = { IllegalArgumentException.class }) |
| 25 | 41 | public void should_fail_if_too_many_variables() { |
| 26 | 42 | List<Object> args = Collections.nCopies(1 << 16, (Object)1); |
| 27 | - new SimpleStatement("mock query", args.toArray()); | |
| 43 | + new SimpleStatement("mock query", cluster, args.toArray()); | |
| 28 | 44 | } |
| 29 | 45 | } |
| 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 @@ | ||
| 67 | 67 | |
| 68 | 68 | BatchStatement batch = new BatchStatement(); |
| 69 | 69 | 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)); | |
| 71 | 71 | } |
| 72 | 72 | session.execute(batch); |
| 73 | 73 |
modified driver-core/src/test/java/com/datastax/driver/core/SpeculativeExecutionTest.java +1 −1
| @@ -104,7 +104,7 @@ | ||
| 104 | 104 | long execStartCount = errors.getSpeculativeExecutions().getCount(); |
| 105 | 105 | long retriesStartCount = errors.getRetriesOnUnavailable().getCount(); |
| 106 | 106 | |
| 107 | - SimpleStatement statement = new SimpleStatement("mock query"); | |
| 107 | + SimpleStatement statement = session.newSimpleStatement("mock query"); | |
| 108 | 108 | statement.setConsistencyLevel(ConsistencyLevel.TWO); |
| 109 | 109 | ResultSet rs = session.execute(statement); |
| 110 | 110 | Row row = rs.one(); |
modified driver-core/src/test/java/com/datastax/driver/core/StatementIdempotenceTest.java +65 −43
| @@ -19,19 +19,41 @@ | ||
| 19 | 19 | import com.google.common.collect.ImmutableMap; |
| 20 | 20 | import com.google.common.collect.Lists; |
| 21 | 21 | import com.google.common.collect.Sets; |
| 22 | +import org.testng.annotations.BeforeMethod; | |
| 22 | 23 | import org.testng.annotations.Test; |
| 23 | 24 | |
| 24 | 25 | import static org.assertj.core.api.Assertions.assertThat; |
| 26 | +import static org.mockito.Mockito.mock; | |
| 27 | +import static org.mockito.Mockito.when; | |
| 25 | 28 | |
| 26 | 29 | import com.datastax.driver.core.querybuilder.BuiltStatement; |
| 30 | +import com.datastax.driver.core.querybuilder.QueryBuilder; | |
| 27 | 31 | |
| 28 | 32 | import static com.datastax.driver.core.querybuilder.QueryBuilder.*; |
| 29 | 33 | |
| 30 | 34 | 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 | + | |
| 31 | 53 | @Test(groups = "unit") |
| 32 | 54 | public void should_default_to_false_when_not_set_on_statement_nor_query_options() { |
| 33 | 55 | QueryOptions queryOptions = new QueryOptions(); |
| 34 | - SimpleStatement statement = new SimpleStatement(""); | |
| 56 | + SimpleStatement statement = new SimpleStatement("", cluster); | |
| 35 | 57 | |
| 36 | 58 | assertThat(statement.isIdempotentWithDefault(queryOptions)).isFalse(); |
| 37 | 59 | } |
| @@ -39,7 +61,7 @@ | ||
| 39 | 61 | @Test(groups = "unit") |
| 40 | 62 | public void should_use_query_options_when_not_set_on_statement() { |
| 41 | 63 | QueryOptions queryOptions = new QueryOptions(); |
| 42 | - SimpleStatement statement = new SimpleStatement(""); | |
| 64 | + SimpleStatement statement = new SimpleStatement("", cluster); | |
| 43 | 65 | |
| 44 | 66 | for (boolean valueInOptions : new boolean[]{ true, false }) { |
| 45 | 67 | queryOptions.setDefaultIdempotence(valueInOptions); |
| @@ -50,7 +72,7 @@ | ||
| 50 | 72 | @Test(groups = "unit") |
| 51 | 73 | public void should_use_statement_when_set_on_statement() { |
| 52 | 74 | QueryOptions queryOptions = new QueryOptions(); |
| 53 | - SimpleStatement statement = new SimpleStatement(""); | |
| 75 | + SimpleStatement statement = new SimpleStatement("", cluster); | |
| 54 | 76 | |
| 55 | 77 | for (boolean valueInOptions : new boolean[]{ true, false }) |
| 56 | 78 | for (boolean valueInStatement : new boolean[]{ true, false }) { |
| @@ -88,68 +110,68 @@ | ||
| 88 | 110 | } |
| 89 | 111 | } |
| 90 | 112 | |
| 91 | - private static ImmutableList<BuiltStatement> idempotentBuiltStatements() { | |
| 113 | + private ImmutableList<BuiltStatement> idempotentBuiltStatements() { | |
| 92 | 114 | 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 | |
| 96 | 118 | |
| 97 | 119 | // 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)) | |
| 102 | 124 | |
| 103 | 125 | ); |
| 104 | 126 | } |
| 105 | 127 | |
| 106 | - private static ImmutableList<BuiltStatement> nonIdempotentBuiltStatements() { | |
| 128 | + private ImmutableList<BuiltStatement> nonIdempotentBuiltStatements() { | |
| 107 | 129 | 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 | |
| 111 | 133 | |
| 112 | 134 | // function calls |
| 113 | 135 | |
| 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()), | |
| 117 | 139 | |
| 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())), | |
| 121 | 143 | |
| 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()}), | |
| 125 | 147 | |
| 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())}), | |
| 129 | 151 | |
| 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")}), | |
| 133 | 155 | |
| 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)), | |
| 137 | 159 | |
| 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)), | |
| 141 | 163 | |
| 142 | 164 | // raw() calls |
| 143 | 165 | |
| 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()"))), | |
| 146 | 168 | |
| 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")}), | |
| 150 | 172 | |
| 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)) | |
| 153 | 175 | |
| 154 | 176 | ); |
| 155 | 177 | } |
modified driver-core/src/test/java/com/datastax/driver/core/StatementWrapperTest.java +3 −3
| @@ -48,7 +48,7 @@ | ||
| 48 | 48 | public void should_pass_wrapped_statement_to_load_balancing_policy() { |
| 49 | 49 | loadBalancingPolicy.customStatementsHandled.set(0); |
| 50 | 50 | |
| 51 | - SimpleStatement s = new SimpleStatement("select * from system.local"); | |
| 51 | + SimpleStatement s = session.newSimpleStatement("select * from system.local"); | |
| 52 | 52 | session.execute(s); |
| 53 | 53 | assertThat(loadBalancingPolicy.customStatementsHandled.get()).isEqualTo(0); |
| 54 | 54 | |
| @@ -60,7 +60,7 @@ | ||
| 60 | 60 | public void should_pass_wrapped_statement_to_speculative_execution_policy() { |
| 61 | 61 | speculativeExecutionPolicy.customStatementsHandled.set(0); |
| 62 | 62 | |
| 63 | - SimpleStatement s = new SimpleStatement("select * from system.local"); | |
| 63 | + SimpleStatement s = session.newSimpleStatement("select * from system.local"); | |
| 64 | 64 | session.execute(s); |
| 65 | 65 | assertThat(speculativeExecutionPolicy.customStatementsHandled.get()).isEqualTo(0); |
| 66 | 66 | |
| @@ -74,7 +74,7 @@ | ||
| 74 | 74 | |
| 75 | 75 | // Set CL TWO with only one node, so the statement will always cause UNAVAILABLE, |
| 76 | 76 | // which our custom policy ignores. |
| 77 | - Statement s = new SimpleStatement("select * from system.local") | |
| 77 | + Statement s = session.newSimpleStatement("select * from system.local") | |
| 78 | 78 | .setConsistencyLevel(ConsistencyLevel.TWO); |
| 79 | 79 | |
| 80 | 80 | session.execute(s); |
modified driver-core/src/test/java/com/datastax/driver/core/TestUtils.java +8 −4
| @@ -130,7 +130,7 @@ | ||
| 130 | 130 | return bs; |
| 131 | 131 | } |
| 132 | 132 | |
| 133 | - public static Object getValue(Row row, String name, DataType type) { | |
| 133 | + public static Object getValue(Row row, String name, DataType type, CodecRegistry codecRegistry) { | |
| 134 | 134 | switch (type.getName()) { |
| 135 | 135 | case ASCII: |
| 136 | 136 | return row.getString(name); |
| @@ -173,11 +173,15 @@ | ||
| 173 | 173 | case TIMEUUID: |
| 174 | 174 | return row.getUUID(name); |
| 175 | 175 | 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); | |
| 177 | 178 | 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); | |
| 179 | 181 | 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); | |
| 181 | 185 | } |
| 182 | 186 | throw new RuntimeException("Missing handling of " + type); |
| 183 | 187 | } |
modified driver-core/src/test/java/com/datastax/driver/core/TokenIntegrationTest.java +1 −1
| @@ -114,7 +114,7 @@ | ||
| 114 | 114 | |
| 115 | 115 | // Find the replica for a given partition key |
| 116 | 116 | 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())); | |
| 118 | 118 | assertThat(replicas).hasSize(1); |
| 119 | 119 | Host replica = replicas.iterator().next(); |
| 120 | 120 |
modified driver-core/src/test/java/com/datastax/driver/core/TracingTest.java +2 −2
| @@ -58,7 +58,7 @@ | ||
| 58 | 58 | */ |
| 59 | 59 | @Test(groups = "short") |
| 60 | 60 | 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)); | |
| 62 | 62 | ResultSet result = session.execute(st.setFetchSize(40).enableTracing()); |
| 63 | 63 | result.all(); |
| 64 | 64 | |
| @@ -87,7 +87,7 @@ | ||
| 87 | 87 | */ |
| 88 | 88 | @Test(groups = "short") |
| 89 | 89 | 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)); | |
| 91 | 91 | st.setConsistencyLevel(ConsistencyLevel.THREE).enableTracing(); |
| 92 | 92 | |
| 93 | 93 | ResultSet result = session.execute(st); |
modified driver-core/src/test/java/com/datastax/driver/core/TupleTest.java +17 −15
| @@ -30,6 +30,8 @@ | ||
| 30 | 30 | @CassandraVersion(major=2.1) |
| 31 | 31 | public class TupleTest extends CCMBridge.PerClassSingleNodeCluster { |
| 32 | 32 | |
| 33 | + ProtocolVersion protocolVersion = TestUtils.getDesiredProtocolVersion(); | |
| 34 | + | |
| 33 | 35 | @Override |
| 34 | 36 | protected Collection<String> getTableDefinitions() { |
| 35 | 37 | return Arrays.asList("CREATE TABLE t (k int PRIMARY KEY, v frozen<tuple<int, text, float>>)"); |
| @@ -37,7 +39,7 @@ | ||
| 37 | 39 | |
| 38 | 40 | @Test(groups = "short") |
| 39 | 41 | 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()); | |
| 41 | 43 | TupleValue v = t.newValue(); |
| 42 | 44 | v.setInt(0, 1); |
| 43 | 45 | v.setString(1, "a"); |
| @@ -52,7 +54,7 @@ | ||
| 52 | 54 | assertEquals(v.getString(1), "a"); |
| 53 | 55 | assertEquals(v.getFloat(2), 1.0f); |
| 54 | 56 | |
| 55 | - assertEquals(t.format(v), "(1, 'a', 1.0)"); | |
| 57 | + assertEquals(new TypeCodec.TupleCodec(t).format(v), "(1, 'a', 1.0)"); | |
| 56 | 58 | } |
| 57 | 59 | |
| 58 | 60 | @Test(groups = "short") |
| @@ -62,7 +64,7 @@ | ||
| 62 | 64 | PreparedStatement ins = session.prepare("INSERT INTO t(k, v) VALUES (?, ?)"); |
| 63 | 65 | PreparedStatement sel = session.prepare("SELECT * FROM t WHERE k=?"); |
| 64 | 66 | |
| 65 | - TupleType t = TupleType.of(DataType.cint(), DataType.text(), DataType.cfloat()); | |
| 67 | + TupleType t = cluster.getMetadata().newTupleType(DataType.cint(), DataType.text(), DataType.cfloat()); | |
| 66 | 68 | |
| 67 | 69 | int k = 1; |
| 68 | 70 | TupleValue v = t.newValue(1, "a", 1.0f); |
| @@ -99,7 +101,7 @@ | ||
| 99 | 101 | session.execute("USE test_tuple_type"); |
| 100 | 102 | session.execute("CREATE TABLE mytable (a int PRIMARY KEY, b frozen<tuple<ascii, int, boolean>>)"); |
| 101 | 103 | |
| 102 | - TupleType t = TupleType.of(DataType.ascii(), DataType.cint(), DataType.cboolean()); | |
| 104 | + TupleType t = cluster.getMetadata().newTupleType(DataType.ascii(), DataType.cint(), DataType.cboolean()); | |
| 103 | 105 | |
| 104 | 106 | // test non-prepared statement |
| 105 | 107 | TupleValue complete = t.newValue("foo", 123, true); |
| @@ -114,7 +116,7 @@ | ||
| 114 | 116 | } catch (IllegalArgumentException e) {} |
| 115 | 117 | |
| 116 | 118 | // 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()); | |
| 118 | 120 | TupleValue partial = t1.newValue("bar", 456); |
| 119 | 121 | TupleValue partionResult = t.newValue("bar", 456, null); |
| 120 | 122 | session.execute("INSERT INTO mytable (a, b) VALUES (0, ?)", partial); |
| @@ -128,7 +130,7 @@ | ||
| 128 | 130 | } catch (IllegalArgumentException e) {} |
| 129 | 131 | |
| 130 | 132 | // test single value tuples with new TupleType |
| 131 | - TupleType t2 = TupleType.of(DataType.ascii()); | |
| 133 | + TupleType t2 = cluster.getMetadata().newTupleType(DataType.ascii()); | |
| 132 | 134 | TupleValue subpartial = t2.newValue("zoo"); |
| 133 | 135 | TupleValue subpartialResult = t.newValue("zoo", null, null); |
| 134 | 136 | session.execute("INSERT INTO mytable (a, b) VALUES (0, ?)", subpartial); |
| @@ -188,7 +190,7 @@ | ||
| 188 | 190 | dataTypes.add(DataType.cint()); |
| 189 | 191 | values.add(j); |
| 190 | 192 | } |
| 191 | - TupleType t = new TupleType(dataTypes); | |
| 193 | + TupleType t = new TupleType(dataTypes, protocolVersion, cluster.getConfiguration().getCodecRegistry()); | |
| 192 | 194 | TupleValue createdTuple = t.newValue(values.toArray()); |
| 193 | 195 | |
| 194 | 196 | // write tuple |
| @@ -250,8 +252,8 @@ | ||
| 250 | 252 | } |
| 251 | 253 | |
| 252 | 254 | // 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()); | |
| 255 | 257 | TupleValue createdTuple = t.newValue(createdValues.toArray()); |
| 256 | 258 | TupleValue completeTuple = t2.newValue(completeValues.toArray()); |
| 257 | 259 | |
| @@ -318,7 +320,7 @@ | ||
| 318 | 320 | dataTypes.add(DataType.list(datatype)); |
| 319 | 321 | createdValues.add(Arrays.asList(PrimitiveTypeSamples.ALL.get(datatype))); |
| 320 | 322 | |
| 321 | - TupleType t = new TupleType(dataTypes); | |
| 323 | + TupleType t = new TupleType(dataTypes, protocolVersion, cluster.getConfiguration().getCodecRegistry()); | |
| 322 | 324 | TupleValue createdTuple = t.newValue(createdValues.toArray()); |
| 323 | 325 | |
| 324 | 326 | // write tuple |
| @@ -341,7 +343,7 @@ | ||
| 341 | 343 | dataTypes.add(DataType.set(datatype)); |
| 342 | 344 | createdValues.add(new HashSet<Object>(Arrays.asList(PrimitiveTypeSamples.ALL.get(datatype)))); |
| 343 | 345 | |
| 344 | - TupleType t = new TupleType(dataTypes); | |
| 346 | + TupleType t = new TupleType(dataTypes, protocolVersion, cluster.getConfiguration().getCodecRegistry()); | |
| 345 | 347 | TupleValue createdTuple = t.newValue(createdValues.toArray()); |
| 346 | 348 | |
| 347 | 349 | // write tuple |
| @@ -367,7 +369,7 @@ | ||
| 367 | 369 | dataTypes.add(DataType.map(datatype, datatype)); |
| 368 | 370 | createdValues.add(hm); |
| 369 | 371 | |
| 370 | - TupleType t = new TupleType(dataTypes); | |
| 372 | + TupleType t = new TupleType(dataTypes, protocolVersion, cluster.getConfiguration().getCodecRegistry()); | |
| 371 | 373 | TupleValue createdTuple = t.newValue(createdValues.toArray()); |
| 372 | 374 | |
| 373 | 375 | // write tuple |
| @@ -405,11 +407,11 @@ | ||
| 405 | 407 | */ |
| 406 | 408 | private TupleValue nestedTuplesCreatorHelper(int depth) { |
| 407 | 409 | if (depth == 1) { |
| 408 | - TupleType baseTuple = TupleType.of(DataType.cint()); | |
| 410 | + TupleType baseTuple = cluster.getMetadata().newTupleType(DataType.cint()); | |
| 409 | 411 | return baseTuple.newValue(303); |
| 410 | 412 | } else { |
| 411 | 413 | TupleValue innerTuple = nestedTuplesCreatorHelper(depth - 1); |
| 412 | - TupleType t = TupleType.of(innerTuple.getType()); | |
| 414 | + TupleType t = cluster.getMetadata().newTupleType(innerTuple.getType()); | |
| 413 | 415 | return t.newValue(innerTuple); |
| 414 | 416 | } |
| 415 | 417 | } |
| @@ -479,7 +481,7 @@ | ||
| 479 | 481 | UserType userTypeDef = cluster.getMetadata().getKeyspace("testTuplesWithNulls").getUserType("user"); |
| 480 | 482 | UDTValue userType = userTypeDef.newValue(); |
| 481 | 483 | |
| 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()); | |
| 483 | 485 | TupleValue v = t.newValue(null, null, null, null); |
| 484 | 486 | userType.setTupleValue("b", v); |
| 485 | 487 |
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<timestamp,text></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 @@ | ||
| 16 | 16 | package com.datastax.driver.core; |
| 17 | 17 | |
| 18 | 18 | import java.nio.ByteBuffer; |
| 19 | -import java.util.Map; | |
| 20 | -import java.util.Collections; | |
| 21 | -import java.util.List; | |
| 19 | +import java.util.*; | |
| 22 | 20 | |
| 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; | |
| 24 | 26 | 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; | |
| 27 | 29 | import org.testng.annotations.Test; |
| 28 | 30 | |
| 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; | |
| 30 | 42 | |
| 31 | 43 | public class TypeCodecTest { |
| 32 | 44 | |
| 33 | 45 | public static final DataType CUSTOM_FOO = DataType.custom("com.example.FooBar"); |
| 34 | 46 | |
| 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 | + | |
| 35 | 52 | @Test(groups = "unit") |
| 36 | 53 | 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); | |
| 39 | 57 | } |
| 40 | 58 | |
| 41 | 59 | @Test(groups = "unit") |
| 42 | 60 | 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); | |
| 45 | 64 | } |
| 46 | 65 | |
| 47 | 66 | @Test(groups = "unit") |
| 48 | 67 | 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); | |
| 51 | 71 | } |
| 52 | 72 | |
| 53 | 73 | @Test(groups = "unit") |
| 54 | 74 | 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); | |
| 57 | 78 | } |
| 58 | 79 | |
| 59 | 80 | @Test(groups = "unit", expectedExceptions = { IllegalArgumentException.class }) |
| 60 | 81 | public void collectionTooLargeTest() throws Exception { |
| 61 | - TypeCodec<List<Integer>> listType = TypeCodec.listOf(DataType.cint(), ProtocolVersion.V2); | |
| 82 | + DataType cqlType = DataType.list(DataType.cint()); | |
| 62 | 83 | 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); | |
| 65 | 86 | } |
| 66 | 87 | |
| 67 | 88 | @Test(groups = "unit", expectedExceptions = { IllegalArgumentException.class }) |
| 68 | 89 | 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 | + } | |
| 71 | 374 | |
| 72 | - listType.serialize(list); | |
| 375 | + @Override | |
| 376 | + public String format(B value) throws InvalidTypeException { | |
| 377 | + return null; // not tested | |
| 378 | + } | |
| 73 | 379 | } |
| 74 | 380 | } |
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 @@ | ||
| 394 | 394 | alldatatypes.setMap(index, ImmutableMap.of(sampleElement, sampleElement)); |
| 395 | 395 | break; |
| 396 | 396 | case TUPLE: |
| 397 | - alldatatypes.setTupleValue(index, TupleType.of(dataType).newValue(sampleElement)); | |
| 397 | + alldatatypes.setTupleValue(index, cluster.getMetadata().newTupleType(dataType).newValue(sampleElement)); | |
| 398 | 398 | } |
| 399 | 399 | } |
| 400 | 400 |
modified driver-core/src/test/java/com/datastax/driver/core/policies/DowngradingConsistencyRetryPolicyIntegrationTest.java +1 −1
| @@ -90,7 +90,7 @@ | ||
| 90 | 90 | RetryPolicy retryPolicy = session.getCluster().getConfiguration().getPolicies().getRetryPolicy(); |
| 91 | 91 | Mockito.reset(retryPolicy); |
| 92 | 92 | |
| 93 | - Statement s = new SimpleStatement("SELECT * FROM test.foo WHERE k = 0") | |
| 93 | + Statement s = session.newSimpleStatement("SELECT * FROM test.foo WHERE k = 0") | |
| 94 | 94 | .setConsistencyLevel(requested); |
| 95 | 95 | |
| 96 | 96 | ResultSet rs = session.execute(s); |
modified driver-core/src/test/java/com/datastax/driver/core/policies/TokenAwarePolicyTest.java +1 −1
| @@ -58,7 +58,7 @@ | ||
| 58 | 58 | keyspace)); |
| 59 | 59 | |
| 60 | 60 | // 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"); | |
| 62 | 62 | statement.setKeyspace(keyspace); |
| 63 | 63 | statement.setRoutingKey(routingKey); |
| 64 | 64 |
modified driver-core/src/test/java/com/datastax/driver/core/querybuilder/QueryBuilder21ExecutionTest.java +13 −4
| @@ -20,6 +20,8 @@ | ||
| 20 | 20 | import com.datastax.driver.core.ResultSet; |
| 21 | 21 | import com.datastax.driver.core.Row; |
| 22 | 22 | import com.datastax.driver.core.utils.CassandraVersion; |
| 23 | + | |
| 24 | +import org.testng.annotations.BeforeMethod; | |
| 23 | 25 | import org.testng.annotations.Test; |
| 24 | 26 | |
| 25 | 27 | import java.util.Arrays; |
| @@ -31,6 +33,8 @@ | ||
| 31 | 33 | @CassandraVersion(major=2.1) |
| 32 | 34 | public class QueryBuilder21ExecutionTest extends CCMBridge.PerClassSingleNodeCluster { |
| 33 | 35 | |
| 36 | + private QueryBuilder builder; | |
| 37 | + | |
| 34 | 38 | @Override |
| 35 | 39 | protected Collection<String> getTableDefinitions() { |
| 36 | 40 | // Taken from http://www.datastax.com/dev/blog/cql-in-2-1 |
| @@ -49,9 +53,14 @@ | ||
| 49 | 53 | ); |
| 50 | 54 | } |
| 51 | 55 | |
| 56 | + @BeforeMethod(groups = "short") | |
| 57 | + public void setUpQueryBuilder() throws Exception { | |
| 58 | + builder = new QueryBuilder(cluster); | |
| 59 | + } | |
| 60 | + | |
| 52 | 61 | @Test(groups="short") |
| 53 | 62 | 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") | |
| 55 | 64 | .from("products") |
| 56 | 65 | .where(contains("categories", bindMarker("category")))); |
| 57 | 66 | |
| @@ -65,7 +74,7 @@ | ||
| 65 | 74 | |
| 66 | 75 | @Test(groups="short") |
| 67 | 76 | 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") | |
| 69 | 78 | .from("products") |
| 70 | 79 | .where(contains("buyers", bindMarker("buyer")))); |
| 71 | 80 | |
| @@ -79,7 +88,7 @@ | ||
| 79 | 88 | |
| 80 | 89 | @Test(groups="short") |
| 81 | 90 | 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") | |
| 83 | 92 | .from("products") |
| 84 | 93 | .where(contains("features_values", bindMarker("feature")))); |
| 85 | 94 | |
| @@ -94,7 +103,7 @@ | ||
| 94 | 103 | |
| 95 | 104 | @Test(groups="short") |
| 96 | 105 | 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") | |
| 98 | 107 | .from("products") |
| 99 | 108 | .where(containsKey("features_keys", bindMarker("feature")))); |
| 100 | 109 |
modified driver-core/src/test/java/com/datastax/driver/core/querybuilder/QueryBuilderExecutionTest.java +27 −20
| @@ -17,6 +17,7 @@ | ||
| 17 | 17 | |
| 18 | 18 | import java.util.*; |
| 19 | 19 | |
| 20 | +import org.testng.annotations.BeforeMethod; | |
| 20 | 21 | import org.testng.annotations.Test; |
| 21 | 22 | |
| 22 | 23 | import static org.assertj.core.api.Assertions.assertThat; |
| @@ -33,6 +34,8 @@ | ||
| 33 | 34 | |
| 34 | 35 | private static final String TABLE1 = "test1"; |
| 35 | 36 | |
| 37 | + private QueryBuilder builder; | |
| 38 | + | |
| 36 | 39 | @Override |
| 37 | 40 | protected Collection<String> getTableDefinitions() { |
| 38 | 41 | return Arrays.asList( |
| @@ -41,13 +44,18 @@ | ||
| 41 | 44 | "CREATE TABLE test_coll (k int PRIMARY KEY, a list<int>, b map<int,text>, c set<text>)"); |
| 42 | 45 | } |
| 43 | 46 | |
| 47 | + @BeforeMethod(groups = "short") | |
| 48 | + public void setUpQueryBuilder() throws Exception { | |
| 49 | + builder = new QueryBuilder(cluster); | |
| 50 | + } | |
| 51 | + | |
| 44 | 52 | @Test(groups = "short") |
| 45 | 53 | public void executeTest() throws Exception { |
| 46 | 54 | |
| 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"))); | |
| 49 | 57 | |
| 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(); | |
| 51 | 59 | |
| 52 | 60 | assertEquals(2, rows.size()); |
| 53 | 61 | |
| @@ -68,8 +76,8 @@ | ||
| 68 | 76 | public void dateHandlingTest() throws Exception { |
| 69 | 77 | |
| 70 | 78 | 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(); | |
| 73 | 81 | List<Row> rows = session.execute(query).all(); |
| 74 | 82 | |
| 75 | 83 | assertEquals(1, rows.size()); |
| @@ -78,26 +86,25 @@ | ||
| 78 | 86 | assertEquals(d, r1.getTimestamp("t")); |
| 79 | 87 | } |
| 80 | 88 | |
| 81 | - @Test(groups = "unit") | |
| 89 | + @Test(groups = "short") | |
| 82 | 90 | public void prepareTest() throws Exception { |
| 83 | - | |
| 84 | 91 | // Just check we correctly avoid values when there is a bind marker |
| 85 | 92 | 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); | |
| 87 | 94 | assertEquals(stmt.getQueryString(), query); |
| 88 | 95 | |
| 89 | 96 | 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); | |
| 91 | 98 | assertEquals(stmt.getQueryString(), query); |
| 92 | 99 | } |
| 93 | 100 | |
| 94 | 101 | @Test(groups = "short") |
| 95 | 102 | 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(); | |
| 101 | 108 | assertEquals(2, rows.size()); |
| 102 | 109 | |
| 103 | 110 | Row r1 = rows.get(0); |
| @@ -114,7 +121,7 @@ | ||
| 114 | 121 | //given |
| 115 | 122 | session.execute("INSERT INTO test_coll (k, a, b) VALUES (1, [1,2,3], null)"); |
| 116 | 123 | //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)); | |
| 118 | 125 | session.execute(statement); |
| 119 | 126 | //then |
| 120 | 127 | List<Integer> actual = session.execute("SELECT a FROM test_coll WHERE k = 1").one().getList("a", Integer.class); |
| @@ -126,7 +133,7 @@ | ||
| 126 | 133 | //given |
| 127 | 134 | session.execute("INSERT INTO test_coll (k, a) VALUES (1, [1,2,3])"); |
| 128 | 135 | //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)); | |
| 130 | 137 | PreparedStatement ps = session.prepare(statement); |
| 131 | 138 | session.execute(ps.bind(1)); |
| 132 | 139 | //then |
| @@ -139,7 +146,7 @@ | ||
| 139 | 146 | //given |
| 140 | 147 | session.execute("INSERT INTO test_coll (k, c) VALUES (1, {'foo','bar','qix'})"); |
| 141 | 148 | //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)); | |
| 143 | 150 | session.execute(statement); |
| 144 | 151 | //then |
| 145 | 152 | Set<String> actual = session.execute("SELECT c FROM test_coll WHERE k = 1").one().getSet("c", String.class); |
| @@ -151,7 +158,7 @@ | ||
| 151 | 158 | //given |
| 152 | 159 | session.execute("INSERT INTO test_coll (k, c) VALUES (1, {'foo','bar','qix'})"); |
| 153 | 160 | //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)); | |
| 155 | 162 | PreparedStatement ps = session.prepare(statement); |
| 156 | 163 | session.execute(ps.bind("foo")); |
| 157 | 164 | //then |
| @@ -164,7 +171,7 @@ | ||
| 164 | 171 | //given |
| 165 | 172 | session.execute("INSERT INTO test_coll (k, b) VALUES (1, {1:'foo', 2:'bar'})"); |
| 166 | 173 | //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)); | |
| 168 | 175 | session.execute(statement); |
| 169 | 176 | //then |
| 170 | 177 | 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 @@ | ||
| 176 | 183 | //given |
| 177 | 184 | session.execute("INSERT INTO test_coll (k, a, b) VALUES (1, null, {1:'foo', 2:'bar'})"); |
| 178 | 185 | //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)); | |
| 180 | 187 | PreparedStatement ps = session.prepare(statement); |
| 181 | 188 | session.execute(ps.bind().setInt(0, 1)); |
| 182 | 189 | //then |
modified driver-core/src/test/java/com/datastax/driver/core/querybuilder/QueryBuilderITest.java +38 −31
| @@ -19,6 +19,7 @@ | ||
| 19 | 19 | import java.util.Collection; |
| 20 | 20 | import java.util.TreeSet; |
| 21 | 21 | |
| 22 | +import org.testng.annotations.BeforeMethod; | |
| 22 | 23 | import org.testng.annotations.Test; |
| 23 | 24 | |
| 24 | 25 | import static org.testng.Assert.*; |
| @@ -33,6 +34,7 @@ | ||
| 33 | 34 | |
| 34 | 35 | private static final String TABLE_TEXT = "test_text"; |
| 35 | 36 | private static final String TABLE_INT = "test_int"; |
| 37 | + private QueryBuilder builder; | |
| 36 | 38 | |
| 37 | 39 | @Override |
| 38 | 40 | protected Collection<String> getTableDefinitions() { |
| @@ -40,6 +42,11 @@ | ||
| 40 | 42 | String.format("CREATE TABLE %s (k int PRIMARY KEY, a int, b int)", TABLE_INT)); |
| 41 | 43 | } |
| 42 | 44 | |
| 45 | + @BeforeMethod(groups = "short") | |
| 46 | + public void setUpQueryBuilder() throws Exception { | |
| 47 | + builder = new QueryBuilder(cluster); | |
| 48 | + } | |
| 49 | + | |
| 43 | 50 | @Test(groups = "short") |
| 44 | 51 | public void remainingDeleteTests() throws Exception { |
| 45 | 52 | |
| @@ -48,7 +55,7 @@ | ||
| 48 | 55 | assertNotNull(table); |
| 49 | 56 | |
| 50 | 57 | String expected = String.format("DELETE k FROM %s.test_text;", keyspace); |
| 51 | - query = delete("k").from(table); | |
| 58 | + query = builder.delete("k").from(table); | |
| 52 | 59 | assertEquals(query.toString(), expected); |
| 53 | 60 | try { |
| 54 | 61 | session.execute(query); |
| @@ -71,7 +78,7 @@ | ||
| 71 | 78 | session.execute("USE foo"); |
| 72 | 79 | |
| 73 | 80 | 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())); | |
| 75 | 82 | System.out.println(select.toString()); |
| 76 | 83 | System.out.println(session); |
| 77 | 84 | ps = session.prepare(select.toString()); |
| @@ -80,45 +87,45 @@ | ||
| 80 | 87 | session.execute(bs.setString("k", "4 AND c=5")); |
| 81 | 88 | |
| 82 | 89 | 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")); | |
| 84 | 91 | assertEquals(select.toString(), query); |
| 85 | 92 | |
| 86 | 93 | 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")); | |
| 88 | 95 | assertEquals(select.toString(), query); |
| 89 | 96 | |
| 90 | 97 | 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;")); | |
| 92 | 99 | assertEquals(select.toString(), query); |
| 93 | 100 | |
| 94 | 101 | query = "SELECT \"*\" FROM foo;"; |
| 95 | - select = select("*").from("foo"); | |
| 102 | + select = builder.select("*").from("foo"); | |
| 96 | 103 | assertEquals(select.toString(), query); |
| 97 | 104 | |
| 98 | 105 | 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") | |
| 100 | 107 | .where(in("a", "b", "c'); --comment")); |
| 101 | 108 | assertEquals(select.toString(), query); |
| 102 | 109 | |
| 103 | 110 | // User Injection? |
| 104 | 111 | 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"); | |
| 106 | 113 | assertEquals(select.toString(), query); |
| 107 | 114 | |
| 108 | 115 | 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(); | |
| 110 | 117 | assertEquals(select.toString(), query); |
| 111 | 118 | |
| 112 | 119 | 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(); | |
| 114 | 121 | assertEquals(select.toString(), query); |
| 115 | 122 | |
| 116 | 123 | 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); | |
| 118 | 125 | assertEquals(select.toString(), query); |
| 119 | 126 | |
| 120 | 127 | 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))); | |
| 122 | 129 | assertEquals(select.toString(), query); |
| 123 | 130 | } |
| 124 | 131 | |
| @@ -130,17 +137,17 @@ | ||
| 130 | 137 | Statement insert; |
| 131 | 138 | |
| 132 | 139 | query = "INSERT INTO foo(a) VALUES ('123); --comment');"; |
| 133 | - insert = insertInto("foo") | |
| 140 | + insert = builder.insertInto("foo") | |
| 134 | 141 | .value("a", "123); --comment"); |
| 135 | 142 | assertEquals(insert.toString(), query); |
| 136 | 143 | |
| 137 | 144 | query = "INSERT INTO foo(\"a,b\") VALUES (123);"; |
| 138 | - insert = insertInto("foo") | |
| 145 | + insert = builder.insertInto("foo") | |
| 139 | 146 | .value("a,b", 123); |
| 140 | 147 | assertEquals(insert.toString(), query); |
| 141 | 148 | |
| 142 | 149 | 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)); | |
| 144 | 151 | assertEquals(insert.toString(), query); |
| 145 | 152 | } |
| 146 | 153 | |
| @@ -151,15 +158,15 @@ | ||
| 151 | 158 | Statement update; |
| 152 | 159 | |
| 153 | 160 | 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")); | |
| 155 | 162 | assertEquals(update.toString(), query); |
| 156 | 163 | |
| 157 | 164 | 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")); | |
| 159 | 166 | assertEquals(update.toString(), query); |
| 160 | 167 | |
| 161 | 168 | 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)); | |
| 163 | 170 | assertEquals(update.toString(), query); |
| 164 | 171 | } |
| 165 | 172 | |
| @@ -170,40 +177,40 @@ | ||
| 170 | 177 | Statement delete; |
| 171 | 178 | |
| 172 | 179 | query = "DELETE FROM \"foo WHERE k=4\";"; |
| 173 | - delete = delete().from("foo WHERE k=4"); | |
| 180 | + delete = builder.delete().from("foo WHERE k=4"); | |
| 174 | 181 | assertEquals(delete.toString(), query); |
| 175 | 182 | |
| 176 | 183 | 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")); | |
| 178 | 185 | assertEquals(delete.toString(), query); |
| 179 | 186 | |
| 180 | 187 | 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")); | |
| 182 | 189 | assertEquals(delete.toString(), query); |
| 183 | 190 | |
| 184 | 191 | 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")); | |
| 186 | 193 | assertEquals(delete.toString(), query); |
| 187 | 194 | |
| 188 | 195 | 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;")); | |
| 190 | 197 | assertEquals(delete.toString(), query); |
| 191 | 198 | |
| 192 | 199 | query = "DELETE \"*\" FROM foo;"; |
| 193 | - delete = delete("*").from("foo"); | |
| 200 | + delete = builder.delete("*").from("foo"); | |
| 194 | 201 | assertEquals(delete.toString(), query); |
| 195 | 202 | |
| 196 | 203 | 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") | |
| 198 | 205 | .where(in("a", "b", "c'); --comment")); |
| 199 | 206 | assertEquals(delete.toString(), query); |
| 200 | 207 | |
| 201 | 208 | 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)); | |
| 203 | 210 | assertEquals(delete.toString(), query); |
| 204 | 211 | |
| 205 | 212 | 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))); | |
| 207 | 214 | assertEquals(delete.toString(), query); |
| 208 | 215 | } |
| 209 | 216 | |
| @@ -214,21 +221,21 @@ | ||
| 214 | 221 | |
| 215 | 222 | Statement delete; |
| 216 | 223 | 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(); | |
| 218 | 225 | row = session.execute(delete).one(); |
| 219 | 226 | assertFalse(row.getBool("[applied]")); |
| 220 | 227 | |
| 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(); | |
| 222 | 229 | row = session.execute(delete).one(); |
| 223 | 230 | assertTrue(row.getBool("[applied]")); |
| 224 | 231 | |
| 225 | 232 | session.execute(String.format("INSERT INTO %s.test_int (k, a, b) VALUES (1, 1, 1)", keyspace)); |
| 226 | 233 | |
| 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)); | |
| 228 | 235 | row = session.execute(delete).one(); |
| 229 | 236 | assertFalse(row.getBool("[applied]")); |
| 230 | 237 | |
| 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)); | |
| 232 | 239 | row = session.execute(delete).one(); |
| 233 | 240 | assertTrue(row.getBool("[applied]")); |
| 234 | 241 | } |
modified driver-core/src/test/java/com/datastax/driver/core/querybuilder/QueryBuilderRoutingKeyTest.java +17 −16
| @@ -42,16 +42,17 @@ | ||
| 42 | 42 | @Test(groups = "short") |
| 43 | 43 | public void textRoutingKeyTest() throws Exception { |
| 44 | 44 | |
| 45 | - Statement query; | |
| 45 | + BuiltStatement query; | |
| 46 | 46 | TableMetadata table = cluster.getMetadata().getKeyspace(keyspace).getTable(TABLE_TEXT); |
| 47 | 47 | assertNotNull(table); |
| 48 | 48 | |
| 49 | 49 | 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}); | |
| 51 | 52 | assertEquals(query.getRoutingKey(), ByteBuffer.wrap(txt.getBytes())); |
| 52 | 53 | session.execute(query); |
| 53 | 54 | |
| 54 | - query = select().from(table).where(eq("k", txt)); | |
| 55 | + query = builder.select().from(table).where(eq("k", txt)); | |
| 55 | 56 | assertEquals(query.getRoutingKey(), ByteBuffer.wrap(txt.getBytes())); |
| 56 | 57 | Row row = session.execute(query).one(); |
| 57 | 58 | assertEquals(row.getString("k"), txt); |
| @@ -62,17 +63,17 @@ | ||
| 62 | 63 | @Test(groups = "short") |
| 63 | 64 | public void intRoutingKeyTest() throws Exception { |
| 64 | 65 | |
| 65 | - Statement query; | |
| 66 | + BuiltStatement query; | |
| 66 | 67 | TableMetadata table = cluster.getMetadata().getKeyspace(keyspace).getTable(TABLE_INT); |
| 67 | 68 | assertNotNull(table); |
| 68 | 69 | |
| 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}); | |
| 70 | 71 | ByteBuffer bb = ByteBuffer.allocate(4); |
| 71 | 72 | bb.putInt(0, 42); |
| 72 | 73 | assertEquals(query.getRoutingKey(), bb); |
| 73 | 74 | session.execute(query); |
| 74 | 75 | |
| 75 | - query = select().from(table).where(eq("k", 42)); | |
| 76 | + query = new QueryBuilder(cluster).select().from(table).where(eq("k", 42)); | |
| 76 | 77 | assertEquals(query.getRoutingKey(), bb); |
| 77 | 78 | Row row = session.execute(query).one(); |
| 78 | 79 | assertEquals(row.getInt("k"), 42); |
| @@ -83,7 +84,7 @@ | ||
| 83 | 84 | @Test(groups = "short") |
| 84 | 85 | public void intRoutingBatchKeyTest() throws Exception { |
| 85 | 86 | |
| 86 | - RegularStatement query; | |
| 87 | + BuiltStatement query; | |
| 87 | 88 | TableMetadata table = cluster.getMetadata().getKeyspace(keyspace).getTable(TABLE_INT); |
| 88 | 89 | assertNotNull(table); |
| 89 | 90 | |
| @@ -91,18 +92,18 @@ | ||
| 91 | 92 | bb.putInt(0, 42); |
| 92 | 93 | |
| 93 | 94 | String batch_query; |
| 94 | - Statement batch; | |
| 95 | - ResultSet rs; | |
| 95 | + BuiltStatement batch; | |
| 96 | 96 | |
| 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)); | |
| 98 | 99 | |
| 99 | 100 | batch_query = "BEGIN BATCH "; |
| 100 | 101 | batch_query += String.format("INSERT INTO %s.test_int(k,a) VALUES (42,1);", keyspace); |
| 101 | 102 | batch_query += String.format("UPDATE %s.test_int USING TTL 400;", keyspace); |
| 102 | 103 | 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))); | |
| 106 | 107 | assertEquals(batch.getRoutingKey(), bb); |
| 107 | 108 | assertEquals(batch.toString(), batch_query); |
| 108 | 109 | // TODO: rs = session.execute(batch); // Not guaranteed to be valid CQL |
| @@ -110,7 +111,7 @@ | ||
| 110 | 111 | batch_query = "BEGIN BATCH "; |
| 111 | 112 | batch_query += String.format("SELECT * FROM %s.test_int WHERE k=42;", keyspace); |
| 112 | 113 | batch_query += "APPLY BATCH;"; |
| 113 | - batch = batch(query); | |
| 114 | + batch = builder.batch(query); | |
| 114 | 115 | assertEquals(batch.getRoutingKey(), bb); |
| 115 | 116 | assertEquals(batch.toString(), batch_query); |
| 116 | 117 | // TODO: rs = session.execute(batch); // Not guaranteed to be valid CQL |
| @@ -118,7 +119,7 @@ | ||
| 118 | 119 | batch_query = "BEGIN BATCH "; |
| 119 | 120 | batch_query += "SELECT * FROM foo WHERE k=42;"; |
| 120 | 121 | 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))); | |
| 122 | 123 | assertEquals(batch.getRoutingKey(), null); |
| 123 | 124 | assertEquals(batch.toString(), batch_query); |
| 124 | 125 | // TODO: rs = session.execute(batch); // Not guaranteed to be valid CQL |
| @@ -126,7 +127,7 @@ | ||
| 126 | 127 | batch_query = "BEGIN BATCH USING TIMESTAMP 42 "; |
| 127 | 128 | batch_query += "INSERT INTO foo.bar(a) VALUES (123);"; |
| 128 | 129 | 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)); | |
| 130 | 131 | assertEquals(batch.getRoutingKey(), null); |
| 131 | 132 | assertEquals(batch.toString(), batch_query); |
| 132 | 133 | // 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 @@ | ||
| 22 | 22 | |
| 23 | 23 | import com.google.common.collect.ImmutableList; |
| 24 | 24 | import com.google.common.collect.ImmutableMap; |
| 25 | +import org.testng.annotations.BeforeMethod; | |
| 25 | 26 | import org.testng.annotations.Test; |
| 26 | 27 | |
| 27 | 28 | import static org.assertj.core.api.Assertions.assertThat; |
| 29 | +import static org.mockito.Mockito.mock; | |
| 30 | +import static org.mockito.Mockito.when; | |
| 28 | 31 | import static org.testng.Assert.assertEquals; |
| 29 | 32 | import static org.testng.Assert.assertTrue; |
| 30 | 33 | import static org.testng.Assert.fail; |
| 31 | 34 | |
| 32 | 35 | import com.datastax.driver.core.*; |
| 36 | +import com.datastax.driver.core.exceptions.CodecNotFoundException; | |
| 33 | 37 | import com.datastax.driver.core.exceptions.InvalidQueryException; |
| 34 | 38 | import com.datastax.driver.core.utils.Bytes; |
| 35 | 39 | import com.datastax.driver.core.utils.CassandraVersion; |
| 36 | 40 | |
| 37 | -import static com.datastax.driver.core.DataType.cint; | |
| 38 | 41 | import static com.datastax.driver.core.querybuilder.QueryBuilder.*; |
| 39 | 42 | |
| 40 | 43 | public class QueryBuilderTest { |
| 41 | 44 | |
| 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 | + | |
| 42 | 60 | @Test(groups = "unit") |
| 43 | 61 | public void selectTest() throws Exception { |
| 44 | 62 | |
| @@ -46,15 +64,15 @@ | ||
| 46 | 64 | Statement select; |
| 47 | 65 | |
| 48 | 66 | 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")); | |
| 50 | 68 | assertEquals(select.toString(), query); |
| 51 | 69 | |
| 52 | 70 | // 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")); | |
| 54 | 72 | assertEquals(select.toString(), query); |
| 55 | 73 | |
| 56 | 74 | 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") | |
| 58 | 76 | .where(in("a", InetAddress.getByName("127.0.0.1"), InetAddress.getByName("127.0.0.3"))) |
| 59 | 77 | .and(eq(quote("C"), "foo")) |
| 60 | 78 | .orderBy(asc("a"), desc("b")) |
| @@ -62,114 +80,113 @@ | ||
| 62 | 80 | assertEquals(select.toString(), query); |
| 63 | 81 | |
| 64 | 82 | 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(); | |
| 66 | 84 | assertEquals(select.toString(), query); |
| 67 | 85 | |
| 68 | 86 | 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")); | |
| 70 | 88 | assertEquals(select.toString(), query); |
| 71 | 89 | |
| 72 | 90 | 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")); | |
| 74 | 92 | assertEquals(select.toString(), query); |
| 75 | 93 | |
| 76 | 94 | 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")); | |
| 78 | 96 | assertEquals(select.toString(), query); |
| 79 | 97 | |
| 80 | 98 | 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")); | |
| 82 | 100 | assertEquals(select.toString(), query); |
| 83 | 101 | |
| 84 | 102 | 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())); | |
| 86 | 104 | assertEquals(select.toString(), query); |
| 87 | 105 | |
| 88 | 106 | 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)); | |
| 90 | 108 | assertEquals(select.toString(), query); |
| 91 | 109 | |
| 92 | 110 | 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)); | |
| 94 | 112 | assertEquals(select.toString(), query); |
| 95 | 113 | |
| 96 | 114 | query = "SELECT count(*) FROM foo;"; |
| 97 | - select = select().countAll().from("foo"); | |
| 115 | + select = builder.select().countAll().from("foo"); | |
| 98 | 116 | assertEquals(select.toString(), query); |
| 99 | 117 | |
| 100 | 118 | 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"); | |
| 102 | 120 | assertEquals(select.toString(), query); |
| 103 | 121 | |
| 104 | 122 | 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); | |
| 106 | 124 | assertEquals(select.toString(), query); |
| 107 | 125 | |
| 108 | 126 | 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))); | |
| 110 | 128 | assertEquals(select.toString(), query); |
| 111 | 129 | |
| 112 | 130 | 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))); | |
| 114 | 132 | assertEquals(select.toString(), query); |
| 115 | 133 | |
| 116 | 134 | 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")); | |
| 118 | 136 | assertEquals(select.toString(), query); |
| 119 | 137 | |
| 120 | 138 | 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")); | |
| 122 | 140 | assertEquals(select.toString(), query); |
| 123 | 141 | |
| 124 | 142 | Date date = new Date(); |
| 125 | 143 | date.setTime(1234325); |
| 126 | 144 | 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)); | |
| 128 | 146 | assertEquals(select.toString(), query); |
| 129 | 147 | |
| 130 | 148 | 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"))); | |
| 132 | 150 | assertEquals(select.toString(), query); |
| 133 | 151 | |
| 134 | 152 | 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")); | |
| 136 | 154 | assertEquals(select.toString(), query); |
| 137 | 155 | |
| 138 | 156 | 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")); | |
| 140 | 158 | assertEquals(select.toString(), query); |
| 141 | 159 | |
| 142 | - | |
| 143 | 160 | 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")); | |
| 145 | 162 | fail(); |
| 146 | 163 | } catch (IllegalStateException e) { |
| 147 | 164 | assertEquals(e.getMessage(), "An ORDER BY clause has already been provided"); |
| 148 | 165 | } |
| 149 | 166 | |
| 150 | 167 | try { |
| 151 | - select().column("a").all().from("foo"); | |
| 168 | + builder.select().column("a").all().from("foo"); | |
| 152 | 169 | fail(); |
| 153 | 170 | } catch (IllegalStateException e) { |
| 154 | 171 | assertEquals(e.getMessage(), "Some columns ([a]) have already been selected."); |
| 155 | 172 | } |
| 156 | 173 | |
| 157 | 174 | try { |
| 158 | - select().column("a").countAll().from("foo"); | |
| 175 | + builder.select().column("a").countAll().from("foo"); | |
| 159 | 176 | fail(); |
| 160 | 177 | } catch (IllegalStateException e) { |
| 161 | 178 | assertEquals(e.getMessage(), "Some columns ([a]) have already been selected."); |
| 162 | 179 | } |
| 163 | 180 | |
| 164 | 181 | try { |
| 165 | - select().all().from("foo").limit(-42); | |
| 182 | + builder.select().all().from("foo").limit(-42); | |
| 166 | 183 | fail(); |
| 167 | 184 | } catch (IllegalArgumentException e) { |
| 168 | 185 | assertEquals(e.getMessage(), "Invalid LIMIT value, must be strictly positive"); |
| 169 | 186 | } |
| 170 | 187 | |
| 171 | 188 | try { |
| 172 | - select().all().from("foo").limit(42).limit(42); | |
| 189 | + builder.select().all().from("foo").limit(42).limit(42); | |
| 173 | 190 | fail(); |
| 174 | 191 | } catch (IllegalStateException e) { |
| 175 | 192 | assertEquals(e.getMessage(), "A LIMIT value has already been provided"); |
| @@ -177,14 +194,14 @@ | ||
| 177 | 194 | } |
| 178 | 195 | |
| 179 | 196 | @Test(groups = "unit") |
| 180 | - @SuppressWarnings("serial") | |
| 197 | + @SuppressWarnings({ "serial", "deprecation" }) | |
| 181 | 198 | public void insertTest() throws Exception { |
| 182 | 199 | |
| 183 | 200 | String query; |
| 184 | 201 | Statement insert; |
| 185 | 202 | |
| 186 | 203 | 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") | |
| 188 | 205 | .value("a", 123) |
| 189 | 206 | .value("b", InetAddress.getByName("127.0.0.1")) |
| 190 | 207 | .value(quote("C"), "foo'bar") |
| @@ -196,13 +213,13 @@ | ||
| 196 | 213 | assertEquals(insert.toString(), query); |
| 197 | 214 | |
| 198 | 215 | query = "INSERT INTO foo(a,b) VALUES (2,null);"; |
| 199 | - insert = insertInto("foo") | |
| 216 | + insert = builder.insertInto("foo") | |
| 200 | 217 | .value("a", 2) |
| 201 | 218 | .value("b", null); |
| 202 | 219 | assertEquals(insert.toString(), query); |
| 203 | 220 | |
| 204 | 221 | 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>() {{ | |
| 206 | 223 | add(2); |
| 207 | 224 | add(3); |
| 208 | 225 | add(4); |
| @@ -210,7 +227,7 @@ | ||
| 210 | 227 | assertEquals(insert.toString(), query); |
| 211 | 228 | |
| 212 | 229 | 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") | |
| 214 | 231 | .values(new String[]{ "a", "b" }, new Object[]{ new TreeSet<Integer>() {{ |
| 215 | 232 | add(2); |
| 216 | 233 | add(3); |
| @@ -222,7 +239,7 @@ | ||
| 222 | 239 | |
| 223 | 240 | // commutative result of TIMESTAMP |
| 224 | 241 | 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") | |
| 226 | 243 | .using(timestamp(42)) |
| 227 | 244 | .values(new String[]{ "a", "b" }, new Object[]{ new TreeSet<Integer>() {{ |
| 228 | 245 | add(2); |
| @@ -234,7 +251,7 @@ | ||
| 234 | 251 | |
| 235 | 252 | // commutative result of value() and values() |
| 236 | 253 | 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") | |
| 238 | 255 | .using(timestamp(42)) |
| 239 | 256 | .value("c", 123) |
| 240 | 257 | .values(new String[]{ "a", "b" }, new Object[]{ new TreeSet<Integer>() {{ |
| @@ -245,7 +262,7 @@ | ||
| 245 | 262 | assertEquals(insert.toString(), query); |
| 246 | 263 | |
| 247 | 264 | 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 }); | |
| 249 | 266 | fail(); |
| 250 | 267 | } catch (IllegalArgumentException e) { |
| 251 | 268 | assertEquals(e.getMessage(), "Got 2 names but 3 values"); |
| @@ -253,13 +270,10 @@ | ||
| 253 | 270 | |
| 254 | 271 | // CAS test |
| 255 | 272 | 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(); | |
| 261 | 274 | assertEquals(insert.toString(), query); |
| 262 | 275 | |
| 276 | + // Tuples: see QueryBuilderTupleExecutionTest | |
| 263 | 277 | // UDT: see QueryBuilderExecutionTest |
| 264 | 278 | } |
| 265 | 279 | |
| @@ -271,23 +285,23 @@ | ||
| 271 | 285 | Statement update; |
| 272 | 286 | |
| 273 | 287 | 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)); | |
| 275 | 289 | assertEquals(update.toString(), query); |
| 276 | 290 | |
| 277 | 291 | 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)); | |
| 279 | 293 | assertEquals(update.toString(), query); |
| 280 | 294 | |
| 281 | 295 | 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)); | |
| 283 | 297 | assertEquals(update.toString(), query); |
| 284 | 298 | |
| 285 | 299 | 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)); | |
| 287 | 301 | assertEquals(update.toString(), query); |
| 288 | 302 | |
| 289 | 303 | 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>() {{ | |
| 291 | 305 | add(2); |
| 292 | 306 | add(3); |
| 293 | 307 | add(4); |
| @@ -295,7 +309,7 @@ | ||
| 295 | 309 | assertEquals(update.toString(), query); |
| 296 | 310 | |
| 297 | 311 | 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>() {{ | |
| 299 | 313 | add(2); |
| 300 | 314 | add(3); |
| 301 | 315 | add(4); |
| @@ -308,27 +322,27 @@ | ||
| 308 | 322 | assertEquals(update.toString(), query); |
| 309 | 323 | |
| 310 | 324 | query = "UPDATE foo USING TTL 400;"; |
| 311 | - update = update("foo").using(ttl(400)); | |
| 325 | + update = builder.update("foo").using(ttl(400)); | |
| 312 | 326 | assertEquals(update.toString(), query); |
| 313 | 327 | |
| 314 | 328 | 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)); | |
| 316 | 330 | assertEquals(update.toString(), query); |
| 317 | 331 | |
| 318 | 332 | 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)); | |
| 320 | 334 | assertEquals(update.toString(), query); |
| 321 | 335 | |
| 322 | 336 | // 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))); | |
| 324 | 338 | assertEquals(update.toString(), query); |
| 325 | 339 | |
| 326 | 340 | // 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))); | |
| 328 | 342 | assertEquals(update.toString(), query); |
| 329 | 343 | |
| 330 | 344 | try { |
| 331 | - update("foo").using(ttl(-400)); | |
| 345 | + builder.update("foo").using(ttl(-400)); | |
| 332 | 346 | fail(); |
| 333 | 347 | } catch (IllegalArgumentException e) { |
| 334 | 348 | assertEquals(e.getMessage(), "Invalid ttl, must be positive"); |
| @@ -336,7 +350,7 @@ | ||
| 336 | 350 | |
| 337 | 351 | // CAS test |
| 338 | 352 | 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)); | |
| 340 | 354 | assertEquals(update.toString(), query); |
| 341 | 355 | } |
| 342 | 356 | |
| @@ -347,60 +361,60 @@ | ||
| 347 | 361 | Statement delete; |
| 348 | 362 | |
| 349 | 363 | 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)); | |
| 351 | 365 | assertEquals(delete.toString(), query); |
| 352 | 366 | |
| 353 | 367 | 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)); | |
| 355 | 369 | assertEquals(delete.toString(), query); |
| 356 | 370 | |
| 357 | 371 | 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)); | |
| 359 | 373 | assertEquals(delete.toString(), query); |
| 360 | 374 | |
| 361 | 375 | // Invalid CQL, testing edge case |
| 362 | 376 | query = "DELETE a,b,c FROM foo;"; |
| 363 | - delete = delete("a", "b", "c").from("foo"); | |
| 377 | + delete = builder.delete("a", "b", "c").from("foo"); | |
| 364 | 378 | assertEquals(delete.toString(), query); |
| 365 | 379 | |
| 366 | 380 | 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")); | |
| 368 | 382 | 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")); | |
| 370 | 384 | assertEquals(delete.toString(), query); |
| 371 | 385 | |
| 372 | 386 | 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)); | |
| 374 | 388 | assertEquals(delete.toString(), query); |
| 375 | 389 | |
| 376 | 390 | 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)); | |
| 378 | 392 | assertEquals(delete.toString(), query); |
| 379 | 393 | |
| 380 | 394 | try { |
| 381 | - delete().column("a").all().from("foo"); | |
| 395 | + builder.delete().column("a").all().from("foo"); | |
| 382 | 396 | fail(); |
| 383 | 397 | } catch (IllegalStateException e) { |
| 384 | 398 | assertEquals(e.getMessage(), "Some columns ([a]) have already been selected."); |
| 385 | 399 | } |
| 386 | 400 | |
| 387 | 401 | try { |
| 388 | - delete().from("foo").using(timestamp(-1240003134L)); | |
| 402 | + builder.delete().from("foo").using(timestamp(-1240003134L)); | |
| 389 | 403 | fail(); |
| 390 | 404 | } catch (IllegalArgumentException e) { |
| 391 | 405 | assertEquals(e.getMessage(), "Invalid timestamp, must be positive"); |
| 392 | 406 | } |
| 393 | 407 | |
| 394 | 408 | 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(); | |
| 396 | 410 | assertEquals(delete.toString(), query); |
| 397 | 411 | |
| 398 | 412 | 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)); | |
| 400 | 414 | assertEquals(delete.toString(), query); |
| 401 | 415 | |
| 402 | 416 | 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"))); | |
| 404 | 418 | assertEquals(delete.toString(), query); |
| 405 | 419 | } |
| 406 | 420 | |
| @@ -415,14 +429,14 @@ | ||
| 415 | 429 | query += "UPDATE foo SET a[2]='foo',b=[3,2,1]+b,c=c-{'a'} WHERE k=2;"; |
| 416 | 430 | query += "DELETE a[3],b['foo'],c FROM foo WHERE k=1;"; |
| 417 | 431 | 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>() {{ | |
| 420 | 434 | add(2); |
| 421 | 435 | add(3); |
| 422 | 436 | add(4); |
| 423 | 437 | }}, 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))) | |
| 426 | 440 | .using(timestamp(42)); |
| 427 | 441 | assertEquals(batch.toString(), query); |
| 428 | 442 | |
| @@ -430,10 +444,10 @@ | ||
| 430 | 444 | query = "BEGIN BATCH "; |
| 431 | 445 | query += "DELETE a[3] FROM foo WHERE k=1;"; |
| 432 | 446 | 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))); | |
| 434 | 448 | assertEquals(batch.toString(), query); |
| 435 | 449 | |
| 436 | - assertEquals(batch().toString(), "BEGIN BATCH APPLY BATCH;"); | |
| 450 | + assertEquals(builder.batch().toString(), "BEGIN BATCH APPLY BATCH;"); | |
| 437 | 451 | } |
| 438 | 452 | |
| 439 | 453 | @Test(groups = "unit") |
| @@ -447,10 +461,10 @@ | ||
| 447 | 461 | query += "UPDATE foo SET b=b+2;"; |
| 448 | 462 | query += "UPDATE foo SET c=c+3;"; |
| 449 | 463 | 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))) | |
| 454 | 468 | .using(timestamp(42)); |
| 455 | 469 | assertEquals(batch.toString(), query); |
| 456 | 470 | |
| @@ -460,10 +474,10 @@ | ||
| 460 | 474 | query += "UPDATE foo SET b=b+1;"; |
| 461 | 475 | query += "UPDATE foo SET c=c+1;"; |
| 462 | 476 | 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"))) | |
| 467 | 481 | .using(timestamp(42)); |
| 468 | 482 | assertEquals(batch.toString(), query); |
| 469 | 483 | |
| @@ -473,10 +487,10 @@ | ||
| 473 | 487 | query += "UPDATE foo SET b=b-2;"; |
| 474 | 488 | query += "UPDATE foo SET c=c-3;"; |
| 475 | 489 | 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))) | |
| 480 | 494 | .using(timestamp(42)); |
| 481 | 495 | assertEquals(batch.toString(), query); |
| 482 | 496 | |
| @@ -486,10 +500,10 @@ | ||
| 486 | 500 | query += "UPDATE foo SET b=b-1;"; |
| 487 | 501 | query += "UPDATE foo SET c=c-1;"; |
| 488 | 502 | 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"))) | |
| 493 | 507 | .using(timestamp(42)); |
| 494 | 508 | assertEquals(batch.toString(), query); |
| 495 | 509 | |
| @@ -499,20 +513,20 @@ | ||
| 499 | 513 | query += "UPDATE foo SET b=b+-2;"; |
| 500 | 514 | query += "UPDATE foo SET c=c-3;"; |
| 501 | 515 | 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))) | |
| 506 | 520 | .using(timestamp(42)); |
| 507 | 521 | assertEquals(batch.toString(), query); |
| 508 | 522 | } |
| 509 | 523 | |
| 510 | 524 | @Test(groups = "unit", expectedExceptions = { IllegalArgumentException.class }) |
| 511 | 525 | 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))) | |
| 516 | 530 | .using(timestamp(42)); |
| 517 | 531 | } |
| 518 | 532 | |
| @@ -522,7 +536,7 @@ | ||
| 522 | 536 | Statement insert; |
| 523 | 537 | |
| 524 | 538 | query = "INSERT INTO test(k,c) VALUES (0,?);"; |
| 525 | - insert = insertInto("test") | |
| 539 | + insert = builder.insertInto("test") | |
| 526 | 540 | .value("k", 0) |
| 527 | 541 | .value("c", bindMarker()); |
| 528 | 542 | assertEquals(insert.toString(), query); |
| @@ -535,19 +549,19 @@ | ||
| 535 | 549 | Statement select; |
| 536 | 550 | |
| 537 | 551 | 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!")); | |
| 539 | 553 | assertEquals(select.toString(), query); |
| 540 | 554 | |
| 541 | 555 | 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!"))); | |
| 543 | 557 | assertEquals(select.toString(), query); |
| 544 | 558 | |
| 545 | 559 | 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"))); | |
| 547 | 561 | assertEquals(select.toString(), query); |
| 548 | 562 | |
| 549 | 563 | 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()'"))); | |
| 551 | 565 | assertEquals(select.toString(), query); |
| 552 | 566 | } |
| 553 | 567 | |
| @@ -558,52 +572,52 @@ | ||
| 558 | 572 | Statement select; |
| 559 | 573 | |
| 560 | 574 | 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"); | |
| 562 | 576 | assertEquals(select.toString(), query); |
| 563 | 577 | |
| 564 | 578 | 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")); | |
| 566 | 580 | assertEquals(select.toString(), query); |
| 567 | 581 | |
| 568 | 582 | 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")); | |
| 570 | 584 | assertEquals(select.toString(), query); |
| 571 | 585 | |
| 572 | 586 | 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")); | |
| 574 | 588 | assertEquals(select.toString(), query); |
| 575 | 589 | |
| 576 | 590 | 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;")); | |
| 578 | 592 | assertEquals(select.toString(), query); |
| 579 | 593 | |
| 580 | 594 | query = "SELECT \"*\" FROM foo;"; |
| 581 | - select = select("*").from("foo"); | |
| 595 | + select = builder.select("*").from("foo"); | |
| 582 | 596 | assertEquals(select.toString(), query); |
| 583 | 597 | |
| 584 | 598 | 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")); | |
| 586 | 600 | assertEquals(select.toString(), query); |
| 587 | 601 | |
| 588 | 602 | // User Injection? |
| 589 | 603 | 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"); | |
| 591 | 605 | assertEquals(select.toString(), query); |
| 592 | 606 | |
| 593 | 607 | 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(); | |
| 595 | 609 | assertEquals(select.toString(), query); |
| 596 | 610 | |
| 597 | 611 | 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(); | |
| 599 | 613 | assertEquals(select.toString(), query); |
| 600 | 614 | |
| 601 | 615 | 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); | |
| 603 | 617 | assertEquals(select.toString(), query); |
| 604 | 618 | |
| 605 | 619 | 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))); | |
| 607 | 621 | assertEquals(select.toString(), query); |
| 608 | 622 | } |
| 609 | 623 | |
| @@ -615,15 +629,15 @@ | ||
| 615 | 629 | Statement insert; |
| 616 | 630 | |
| 617 | 631 | 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"); | |
| 619 | 633 | assertEquals(insert.toString(), query); |
| 620 | 634 | |
| 621 | 635 | 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); | |
| 623 | 637 | assertEquals(insert.toString(), query); |
| 624 | 638 | |
| 625 | 639 | 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>() {{ | |
| 627 | 641 | add("2'} space"); |
| 628 | 642 | add("3"); |
| 629 | 643 | add("4"); |
| @@ -638,15 +652,15 @@ | ||
| 638 | 652 | Statement update; |
| 639 | 653 | |
| 640 | 654 | 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")); | |
| 642 | 656 | assertEquals(update.toString(), query); |
| 643 | 657 | |
| 644 | 658 | 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")); | |
| 646 | 660 | assertEquals(update.toString(), query); |
| 647 | 661 | |
| 648 | 662 | 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)); | |
| 650 | 664 | assertEquals(update.toString(), query); |
| 651 | 665 | } |
| 652 | 666 | |
| @@ -657,47 +671,47 @@ | ||
| 657 | 671 | Statement delete; |
| 658 | 672 | |
| 659 | 673 | query = "DELETE FROM \"foo WHERE k=4\";"; |
| 660 | - delete = delete().from("foo WHERE k=4"); | |
| 674 | + delete = builder.delete().from("foo WHERE k=4"); | |
| 661 | 675 | assertEquals(delete.toString(), query); |
| 662 | 676 | |
| 663 | 677 | 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")); | |
| 665 | 679 | assertEquals(delete.toString(), query); |
| 666 | 680 | |
| 667 | 681 | 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")); | |
| 669 | 683 | assertEquals(delete.toString(), query); |
| 670 | 684 | |
| 671 | 685 | 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")); | |
| 673 | 687 | assertEquals(delete.toString(), query); |
| 674 | 688 | |
| 675 | 689 | 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;")); | |
| 677 | 691 | assertEquals(delete.toString(), query); |
| 678 | 692 | |
| 679 | 693 | query = "DELETE \"*\" FROM foo;"; |
| 680 | - delete = delete("*").from("foo"); | |
| 694 | + delete = builder.delete("*").from("foo"); | |
| 681 | 695 | assertEquals(delete.toString(), query); |
| 682 | 696 | |
| 683 | 697 | 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") | |
| 685 | 699 | .where(in("a", "b", "c'); --comment")); |
| 686 | 700 | assertEquals(delete.toString(), query); |
| 687 | 701 | |
| 688 | 702 | 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)); | |
| 690 | 704 | assertEquals(delete.toString(), query); |
| 691 | 705 | |
| 692 | 706 | 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))); | |
| 694 | 708 | assertEquals(delete.toString(), query); |
| 695 | 709 | } |
| 696 | 710 | |
| 697 | 711 | @Test(groups = "unit") |
| 698 | 712 | public void statementForwardingTest() throws Exception { |
| 699 | 713 | |
| 700 | - Update upd = update("foo"); | |
| 714 | + Update upd = builder.update("foo"); | |
| 701 | 715 | upd.setConsistencyLevel(ConsistencyLevel.QUORUM); |
| 702 | 716 | upd.enableTracing(); |
| 703 | 717 | |
| @@ -709,40 +723,39 @@ | ||
| 709 | 723 | |
| 710 | 724 | @Test(groups = "unit") |
| 711 | 725 | public void rejectUnknownValueTest() throws Exception { |
| 712 | - | |
| 713 | 726 | try { |
| 714 | 727 | //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(); | |
| 716 | 729 | fail("Byte arrays should not be valid, ByteBuffer should be used instead"); |
| 717 | - } catch (IllegalArgumentException e) { | |
| 730 | + } catch (CodecNotFoundException e) { | |
| 718 | 731 | // Ok, that's what we expect |
| 719 | 732 | } |
| 720 | 733 | } |
| 721 | 734 | |
| 722 | 735 | @Test(groups = "unit") |
| 723 | 736 | 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\";"); | |
| 726 | 739 | } |
| 727 | 740 | |
| 728 | 741 | @Test(groups = "unit") |
| 729 | 742 | public void quotingTest() { |
| 730 | - assertEquals(QueryBuilder.select().from("Metrics", "epochs").getQueryString(), | |
| 743 | + assertEquals(builder.select().from("Metrics", "epochs").toString(), | |
| 731 | 744 | "SELECT * FROM Metrics.epochs;"); |
| 732 | - assertEquals(QueryBuilder.select().from("Metrics", quote("epochs")).getQueryString(), | |
| 745 | + assertEquals(builder.select().from("Metrics", quote("epochs")).toString(), | |
| 733 | 746 | "SELECT * FROM Metrics.\"epochs\";"); |
| 734 | - assertEquals(QueryBuilder.select().from(quote("Metrics"), "epochs").getQueryString(), | |
| 747 | + assertEquals(builder.select().from(quote("Metrics"), "epochs").toString(), | |
| 735 | 748 | "SELECT * FROM \"Metrics\".epochs;"); |
| 736 | - assertEquals(QueryBuilder.select().from(quote("Metrics"), quote("epochs")).getQueryString(), | |
| 749 | + assertEquals(builder.select().from(quote("Metrics"), quote("epochs")).toString(), | |
| 737 | 750 | "SELECT * FROM \"Metrics\".\"epochs\";"); |
| 738 | 751 | |
| 739 | - assertEquals(QueryBuilder.insertInto("Metrics", "epochs").getQueryString(), | |
| 752 | + assertEquals(builder.insertInto("Metrics", "epochs").toString(), | |
| 740 | 753 | "INSERT INTO Metrics.epochs() VALUES ();"); |
| 741 | - assertEquals(QueryBuilder.insertInto("Metrics", quote("epochs")).getQueryString(), | |
| 754 | + assertEquals(builder.insertInto("Metrics", quote("epochs")).toString(), | |
| 742 | 755 | "INSERT INTO Metrics.\"epochs\"() VALUES ();"); |
| 743 | - assertEquals(QueryBuilder.insertInto(quote("Metrics"), "epochs").getQueryString(), | |
| 756 | + assertEquals(builder.insertInto(quote("Metrics"), "epochs").toString(), | |
| 744 | 757 | "INSERT INTO \"Metrics\".epochs() VALUES ();"); |
| 745 | - assertEquals(QueryBuilder.insertInto(quote("Metrics"), quote("epochs")).getQueryString(), | |
| 758 | + assertEquals(builder.insertInto(quote("Metrics"), quote("epochs")).toString(), | |
| 746 | 759 | "INSERT INTO \"Metrics\".\"epochs\"() VALUES ();"); |
| 747 | 760 | } |
| 748 | 761 | |
| @@ -752,23 +765,23 @@ | ||
| 752 | 765 | Statement select; |
| 753 | 766 | |
| 754 | 767 | 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))); | |
| 756 | 769 | assertEquals(select.toString(), query); |
| 757 | 770 | |
| 758 | 771 | 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))) | |
| 760 | 773 | .and(lt(Arrays.asList("c1", "c2"), Arrays.<Object>asList("b", 0))); |
| 761 | 774 | assertEquals(select.toString(), query); |
| 762 | 775 | |
| 763 | 776 | 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))); | |
| 765 | 778 | assertEquals(select.toString(), query); |
| 766 | 779 | } |
| 767 | 780 | |
| 768 | 781 | @Test(groups = "unit", expectedExceptions = IllegalArgumentException.class) |
| 769 | 782 | public void should_fail_if_in_clause_has_too_many_values() { |
| 770 | 783 | 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())); | |
| 772 | 785 | } |
| 773 | 786 | |
| 774 | 787 | @Test(groups = "unit", expectedExceptions = IllegalArgumentException.class) |
| @@ -776,24 +789,13 @@ | ||
| 776 | 789 | List<Object> values = Collections.<Object>nCopies(65535, "a"); |
| 777 | 790 | |
| 778 | 791 | // 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") | |
| 780 | 793 | .where(eq("bar", "a")) |
| 781 | 794 | .and(in("baz", values.toArray())); |
| 782 | 795 | |
| 783 | 796 | // But we still want to check it client-side, to fail fast instead of sending a bad query to Cassandra. |
| 784 | 797 | // 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(); | |
| 797 | 799 | } |
| 798 | 800 | |
| 799 | 801 | @Test(groups = "unit") |
| @@ -804,57 +806,57 @@ | ||
| 804 | 806 | |
| 805 | 807 | query = "UPDATE foo SET l=[[1],[2]] WHERE k=1;"; |
| 806 | 808 | 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)); | |
| 808 | 810 | assertThat(statement.toString()).isEqualTo(query); |
| 809 | 811 | |
| 810 | 812 | 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)); | |
| 812 | 814 | assertThat(statement.toString()).isEqualTo(query); |
| 813 | 815 | |
| 814 | 816 | 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)); | |
| 816 | 818 | assertThat(statement.toString()).isEqualTo(query); |
| 817 | 819 | |
| 818 | 820 | 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)); | |
| 820 | 822 | assertThat(statement.toString()).isEqualTo(query); |
| 821 | 823 | |
| 822 | 824 | 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)); | |
| 824 | 826 | assertThat(statement.toString()).isEqualTo(query); |
| 825 | 827 | } |
| 826 | 828 | |
| 827 | 829 | @Test(groups = "unit", expectedExceptions = InvalidQueryException.class) |
| 828 | 830 | public void should_not_allow_bind_marker_for_add() { |
| 829 | 831 | // 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)); | |
| 831 | 833 | } |
| 832 | 834 | |
| 833 | 835 | @Test(groups = "unit", expectedExceptions = InvalidQueryException.class) |
| 834 | 836 | 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)); | |
| 836 | 838 | } |
| 837 | 839 | |
| 838 | 840 | @Test(groups = "unit", expectedExceptions = InvalidQueryException.class) |
| 839 | 841 | 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)); | |
| 841 | 843 | } |
| 842 | 844 | |
| 843 | 845 | @Test(groups = "unit", expectedExceptions = InvalidQueryException.class) |
| 844 | 846 | 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)); | |
| 846 | 848 | } |
| 847 | 849 | |
| 848 | 850 | @Test(groups = "unit", expectedExceptions = InvalidQueryException.class) |
| 849 | 851 | 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)); | |
| 851 | 853 | } |
| 852 | 854 | |
| 853 | 855 | @Test(groups = "unit") |
| 854 | 856 | public void should_quote_complex_column_names() { |
| 855 | 857 | // A column name can be anything as long as it's quoted, so "foo.bar" is a valid name |
| 856 | 858 | 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)); | |
| 858 | 860 | |
| 859 | 861 | assertThat(statement.toString()).isEqualTo(query); |
| 860 | 862 | } |
| @@ -863,15 +865,15 @@ | ||
| 863 | 865 | public void should_quote_column_names_with_escaped_quotes() { |
| 864 | 866 | // A column name can include quotes as long as it is escaped with another set of quotes, so "foo""bar" is a valid name. |
| 865 | 867 | 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)); | |
| 867 | 869 | |
| 868 | 870 | assertThat(statement.toString()).isEqualTo(query); |
| 869 | 871 | } |
| 870 | 872 | |
| 871 | 873 | @Test(groups = "unit") |
| 872 | 874 | 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"))); | |
| 874 | 876 | assertThat(select.getQueryString()).doesNotContain("?"); |
| 875 | - assertThat(select.getValues(ProtocolVersion.V3)).isNull(); | |
| 877 | + assertThat(select.getValues()).isNull(); | |
| 876 | 878 | } |
| 877 | 879 | } |
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 @@ | ||
| 32 | 32 | import com.datastax.driver.core.utils.CassandraVersion; |
| 33 | 33 | |
| 34 | 34 | import static com.datastax.driver.core.querybuilder.QueryBuilder.eq; |
| 35 | -import static com.datastax.driver.core.querybuilder.QueryBuilder.insertInto; | |
| 36 | 35 | 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; | |
| 39 | 36 | |
| 40 | 37 | @CassandraVersion(major=2.1, minor=3) |
| 41 | 38 | public class QueryBuilderUDTExecutionTest extends CCMBridge.PerClassSingleNodeCluster { |
| @@ -51,12 +48,12 @@ | ||
| 51 | 48 | UserType udtType = cluster.getMetadata().getKeyspace(keyspace).getUserType("udt"); |
| 52 | 49 | UDTValue udtValue = udtType.newValue().setInt("i", 2).setInet("a", InetAddress.getByName("localhost")); |
| 53 | 50 | |
| 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'});"); | |
| 56 | 53 | |
| 57 | 54 | session.execute(insert); |
| 58 | 55 | |
| 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(); | |
| 60 | 57 | |
| 61 | 58 | assertEquals(rows.size(), 1); |
| 62 | 59 | |
| @@ -70,12 +67,12 @@ | ||
| 70 | 67 | UDTValue udtValue = udtType.newValue().setInt("i", 2).setInet("a", InetAddress.getByName("localhost")); |
| 71 | 68 | UDTValue udtValue2 = udtType.newValue().setInt("i", 3).setInet("a", InetAddress.getByName("localhost")); |
| 72 | 69 | |
| 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'}]);"); | |
| 75 | 72 | |
| 76 | 73 | session.execute(insert); |
| 77 | 74 | |
| 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(); | |
| 79 | 76 | |
| 80 | 77 | assertThat(rows.size()).isEqualTo(1); |
| 81 | 78 | |
| @@ -85,13 +82,13 @@ | ||
| 85 | 82 | Map<Integer, UDTValue> map = Maps.newHashMap(); |
| 86 | 83 | map.put(0, udtValue); |
| 87 | 84 | 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)); | |
| 89 | 86 | 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;"); | |
| 91 | 88 | |
| 92 | 89 | session.execute(updateMap); |
| 93 | 90 | |
| 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(); | |
| 95 | 92 | r1 = rows.get(0); |
| 96 | 93 | assertThat(r1.getMap("m", Integer.class, UDTValue.class)).isEqualTo(map); |
| 97 | 94 | } |
modified driver-core/src/test/java/com/datastax/driver/core/utils/UUIDsTest.java +4 −3
| @@ -26,6 +26,7 @@ | ||
| 26 | 26 | |
| 27 | 27 | import com.datastax.driver.core.DataType; |
| 28 | 28 | import com.datastax.driver.core.ProtocolVersion; |
| 29 | +import com.datastax.driver.core.TypeCodec; | |
| 29 | 30 | |
| 30 | 31 | public class UUIDsTest { |
| 31 | 32 | |
| @@ -110,9 +111,9 @@ | ||
| 110 | 111 | } |
| 111 | 112 | |
| 112 | 113 | 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); | |
| 116 | 117 | assertTrue(compareTimestampBytes(lb, uuidBytes) <= 0); |
| 117 | 118 | assertTrue(compareTimestampBytes(ub, uuidBytes) >= 0); |
| 118 | 119 | } |
modified driver-examples/osgi/src/main/java/com/datastax/driver/osgi/impl/MailboxImpl.java +5 −6
| @@ -22,16 +22,14 @@ | ||
| 22 | 22 | |
| 23 | 23 | import com.datastax.driver.core.*; |
| 24 | 24 | import com.datastax.driver.core.exceptions.InvalidQueryException; |
| 25 | +import com.datastax.driver.core.querybuilder.QueryBuilder; | |
| 25 | 26 | import com.datastax.driver.core.utils.UUIDs; |
| 26 | 27 | import com.datastax.driver.osgi.api.MailboxException; |
| 27 | 28 | import com.datastax.driver.osgi.api.MailboxMessage; |
| 28 | 29 | import com.datastax.driver.osgi.api.MailboxService; |
| 29 | 30 | |
| 30 | 31 | import static com.datastax.driver.core.querybuilder.QueryBuilder.bindMarker; |
| 31 | -import static com.datastax.driver.core.querybuilder.QueryBuilder.delete; | |
| 32 | 32 | 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; | |
| 35 | 33 | |
| 36 | 34 | public class MailboxImpl implements MailboxService { |
| 37 | 35 | |
| @@ -73,17 +71,18 @@ | ||
| 73 | 71 | "PRIMARY KEY (recipient, time))"); |
| 74 | 72 | } |
| 75 | 73 | |
| 76 | - retrieveStatement = session.prepare(select() | |
| 74 | + QueryBuilder builder = new QueryBuilder(session.getCluster()); | |
| 75 | + retrieveStatement = session.prepare(builder.select() | |
| 77 | 76 | .from(keyspace, TABLE) |
| 78 | 77 | .where(eq("recipient", bindMarker()))); |
| 79 | 78 | |
| 80 | - insertStatement = session.prepare(insertInto(keyspace, TABLE) | |
| 79 | + insertStatement = session.prepare(builder.insertInto(keyspace, TABLE) | |
| 81 | 80 | .value("recipient", bindMarker()) |
| 82 | 81 | .value("time", bindMarker()) |
| 83 | 82 | .value("sender", bindMarker()) |
| 84 | 83 | .value("body", bindMarker())); |
| 85 | 84 | |
| 86 | - deleteStatement = session.prepare(delete().from(keyspace, TABLE) | |
| 85 | + deleteStatement = session.prepare(builder.delete().from(keyspace, TABLE) | |
| 87 | 86 | .where(eq("recipient", bindMarker()))); |
| 88 | 87 | |
| 89 | 88 | initialized = true; |
modified driver-examples/stress/src/main/java/com/datastax/driver/stress/Generators.java +6 −6
| @@ -104,11 +104,11 @@ | ||
| 104 | 104 | public QueryGenerator create(int id, int iterations, OptionSet options, Session session) { |
| 105 | 105 | |
| 106 | 106 | return options.has("no-prepare") |
| 107 | - ? createRegular(id, iterations, options) | |
| 107 | + ? createRegular(id, iterations, options, session) | |
| 108 | 108 | : createPrepared(id, iterations, options, session); |
| 109 | 109 | } |
| 110 | 110 | |
| 111 | - public QueryGenerator createRegular(int id, int iterations, OptionSet options) { | |
| 111 | + public QueryGenerator createRegular(int id, int iterations, OptionSet options, final Session session) { | |
| 112 | 112 | final int valueSize = (Integer)options.valueOf("value-size"); |
| 113 | 113 | final int columnsPerRow = (Integer)options.valueOf("columns-per-row"); |
| 114 | 114 | final long prefix = (long) id << 32; |
| @@ -124,7 +124,7 @@ | ||
| 124 | 124 | } |
| 125 | 125 | sb.append(" WHERE key = ").append(prefix | iteration); |
| 126 | 126 | ++iteration; |
| 127 | - return new QueryGenerator.Request.SimpleQuery(new SimpleStatement(sb.toString())); | |
| 127 | + return new QueryGenerator.Request.SimpleQuery(session.newSimpleStatement(sb.toString())); | |
| 128 | 128 | } |
| 129 | 129 | }; |
| 130 | 130 | } |
| @@ -184,11 +184,11 @@ | ||
| 184 | 184 | |
| 185 | 185 | public QueryGenerator create(int id, int iterations, OptionSet options, Session session) { |
| 186 | 186 | return options.has("no-prepare") |
| 187 | - ? createRegular(id, iterations) | |
| 187 | + ? createRegular(id, iterations, session) | |
| 188 | 188 | : createPrepared(id, iterations, session); |
| 189 | 189 | } |
| 190 | 190 | |
| 191 | - public QueryGenerator createRegular(long id, int iterations) { | |
| 191 | + public QueryGenerator createRegular(long id, int iterations, final Session session) { | |
| 192 | 192 | final long prefix = (long) id << 32; |
| 193 | 193 | return new AbstractGenerator(iterations) { |
| 194 | 194 | @Override |
| @@ -196,7 +196,7 @@ | ||
| 196 | 196 | StringBuilder sb = new StringBuilder(); |
| 197 | 197 | sb.append("SELECT * FROM standard1 WHERE key = ").append(prefix | iteration); |
| 198 | 198 | ++iteration; |
| 199 | - return new QueryGenerator.Request.SimpleQuery(new SimpleStatement(sb.toString())); | |
| 199 | + return new QueryGenerator.Request.SimpleQuery(session.newSimpleStatement(sb.toString())); | |
| 200 | 200 | } |
| 201 | 201 | }; |
| 202 | 202 | } |
modified driver-mapping/src/main/java/com/datastax/driver/mapping/AnnotationParser.java +69 −34
| @@ -25,12 +25,13 @@ | ||
| 25 | 25 | import java.util.concurrent.atomic.AtomicInteger; |
| 26 | 26 | |
| 27 | 27 | import com.google.common.base.Strings; |
| 28 | +import com.google.common.reflect.TypeToken; | |
| 28 | 29 | |
| 29 | 30 | import com.datastax.driver.core.ConsistencyLevel; |
| 31 | +import com.datastax.driver.core.TypeCodec; | |
| 32 | +import com.datastax.driver.core.UserType; | |
| 30 | 33 | import com.datastax.driver.mapping.MethodMapper.EnumParamMapper; |
| 31 | -import com.datastax.driver.mapping.MethodMapper.NestedUDTParamMapper; | |
| 32 | 34 | import com.datastax.driver.mapping.MethodMapper.ParamMapper; |
| 33 | -import com.datastax.driver.mapping.MethodMapper.UDTParamMapper; | |
| 34 | 35 | import com.datastax.driver.mapping.annotations.*; |
| 35 | 36 | |
| 36 | 37 | /** |
| @@ -112,7 +113,7 @@ | ||
| 112 | 113 | return mapper; |
| 113 | 114 | } |
| 114 | 115 | |
| 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) { | |
| 116 | 117 | UDT udt = AnnotationChecks.getTypeAnnotation(UDT.class, udtClass); |
| 117 | 118 | |
| 118 | 119 | String ksName = udt.caseSensitiveKeyspace() ? udt.keyspace() : udt.keyspace().toLowerCase(); |
| @@ -122,23 +123,23 @@ | ||
| 122 | 123 | ksName = mappingManager.getSession().getLoggedKeyspace(); |
| 123 | 124 | if (Strings.isNullOrEmpty(ksName)) |
| 124 | 125 | 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", | |
| 126 | 127 | udtClass.getSimpleName(), |
| 127 | 128 | UDT.class.getSimpleName() |
| 128 | 129 | )); |
| 129 | 130 | } |
| 130 | 131 | |
| 131 | - EntityMapper<T> mapper = factory.create(udtClass, ksName, udtName, null, null); | |
| 132 | + UserType userType = mappingManager.getSession().getCluster().getMetadata().getKeyspace(ksName).getUserType(udtName); | |
| 132 | 133 | |
| 133 | 134 | List<Field> columns = new ArrayList<Field>(); |
| 134 | 135 | |
| 135 | 136 | for (Field field : udtClass.getDeclaredFields()) { |
| 136 | 137 | if(field.isSynthetic() || (field.getModifiers() & Modifier.STATIC) == Modifier.STATIC) |
| 137 | 138 | continue; |
| 138 | - | |
| 139 | + | |
| 139 | 140 | 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); | |
| 142 | 143 | |
| 143 | 144 | if (field.getAnnotation(Transient.class) != null) |
| 144 | 145 | continue; |
| @@ -153,9 +154,8 @@ | ||
| 153 | 154 | break; |
| 154 | 155 | } |
| 155 | 156 | } |
| 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); | |
| 159 | 159 | } |
| 160 | 160 | |
| 161 | 161 | private static <T> List<ColumnMapper<T>> convert(List<Field> fields, EntityMapper.Factory factory, Class<T> klass, MappingManager mappingManager, AtomicInteger columnCounter) { |
| @@ -244,6 +244,36 @@ | ||
| 244 | 244 | |
| 245 | 245 | } |
| 246 | 246 | |
| 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 | + | |
| 247 | 277 | public static <T> AccessorMapper<T> parseAccessor(Class<T> accClass, AccessorMapper.Factory factory, MappingManager mappingManager) { |
| 248 | 278 | if (!accClass.isInterface()) |
| 249 | 279 | throw new IllegalArgumentException("@Accessor annotation is only allowed on interfaces"); |
| @@ -261,21 +291,29 @@ | ||
| 261 | 291 | Annotation[][] paramAnnotations = m.getParameterAnnotations(); |
| 262 | 292 | Type[] paramTypes = m.getGenericParameterTypes(); |
| 263 | 293 | ParamMapper[] paramMappers = new ParamMapper[paramAnnotations.length]; |
| 264 | - Boolean hasParamAnnotation = null; | |
| 294 | + Boolean allParamsNamed = null; | |
| 265 | 295 | for (int i = 0; i < paramMappers.length; i++) { |
| 266 | 296 | String paramName = null; |
| 297 | + Class<? extends TypeCodec<?>> codecClass = null; | |
| 267 | 298 | for (Annotation a : paramAnnotations[i]) { |
| 268 | 299 | 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; | |
| 270 | 307 | break; |
| 271 | 308 | } |
| 272 | 309 | } |
| 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); | |
| 279 | 317 | } |
| 280 | 318 | |
| 281 | 319 | ConsistencyLevel cl = null; |
| @@ -296,13 +334,10 @@ | ||
| 296 | 334 | } |
| 297 | 335 | |
| 298 | 336 | @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) { | |
| 300 | 338 | if (paramType instanceof Class) { |
| 301 | 339 | 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()) { | |
| 306 | 341 | EnumType enumType = EnumType.STRING; |
| 307 | 342 | for (Annotation annotation : paramAnnotations) { |
| 308 | 343 | if (annotation instanceof Enumerated) { |
| @@ -311,16 +346,16 @@ | ||
| 311 | 346 | } |
| 312 | 347 | return new EnumParamMapper(paramName, idx, enumType); |
| 313 | 348 | } |
| 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); | |
| 324 | 359 | } else { |
| 325 | 360 | throw new IllegalArgumentException(String.format("Cannot map class %s for parameter %s of %s.%s", paramType, paramName, className, methodName)); |
| 326 | 361 | } |
modified driver-mapping/src/main/java/com/datastax/driver/mapping/ColumnMapper.java +19 −11
| @@ -18,7 +18,9 @@ | ||
| 18 | 18 | import java.lang.reflect.Field; |
| 19 | 19 | import java.util.concurrent.atomic.AtomicInteger; |
| 20 | 20 | |
| 21 | -import com.datastax.driver.core.DataType; | |
| 21 | +import com.google.common.reflect.TypeToken; | |
| 22 | + | |
| 23 | +import com.datastax.driver.core.TypeCodec; | |
| 22 | 24 | |
| 23 | 25 | import static com.datastax.driver.core.querybuilder.QueryBuilder.quote; |
| 24 | 26 | |
| @@ -29,24 +31,23 @@ | ||
| 29 | 31 | private final String columnName; |
| 30 | 32 | private final String alias; |
| 31 | 33 | 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; | |
| 37 | 36 | protected final Kind kind; |
| 38 | 37 | protected final int position; |
| 38 | + protected final TypeCodec<Object> customCodec; | |
| 39 | 39 | |
| 40 | - protected ColumnMapper(Field field, DataType dataType, int position, AtomicInteger columnCounter) { | |
| 40 | + @SuppressWarnings("unchecked") | |
| 41 | + protected ColumnMapper(Field field, int position, AtomicInteger columnCounter) { | |
| 41 | 42 | this.columnName = AnnotationParser.columnName(field); |
| 42 | 43 | this.alias = (columnCounter != null) |
| 43 | 44 | ? AnnotationParser.newAlias(field, columnCounter.incrementAndGet()) |
| 44 | 45 | : null; |
| 45 | 46 | this.fieldName = field.getName(); |
| 46 | - this.javaType = field.getType(); | |
| 47 | - this.dataType = dataType; | |
| 47 | + this.fieldType = (TypeToken<Object>)TypeToken.of(field.getGenericType()); | |
| 48 | 48 | this.kind = AnnotationParser.kind(field); |
| 49 | 49 | this.position = position; |
| 50 | + this.customCodec = AnnotationParser.customCodec(field); | |
| 50 | 51 | } |
| 51 | 52 | |
| 52 | 53 | public abstract Object getValue(T entity); |
| @@ -63,8 +64,15 @@ | ||
| 63 | 64 | return alias; |
| 64 | 65 | } |
| 65 | 66 | |
| 66 | - public DataType getDataType() { | |
| 67 | - return dataType; | |
| 67 | + public TypeCodec<Object> getCustomCodec() { | |
| 68 | + return customCodec; | |
| 68 | 69 | } |
| 69 | 70 | |
| 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 | + } | |
| 70 | 78 | } |
modified driver-mapping/src/main/java/com/datastax/driver/mapping/EnumType.java +12 −2
| @@ -15,6 +15,8 @@ | ||
| 15 | 15 | */ |
| 16 | 16 | package com.datastax.driver.mapping; |
| 17 | 17 | |
| 18 | +import com.google.common.reflect.TypeToken; | |
| 19 | + | |
| 18 | 20 | /** |
| 19 | 21 | * The types of way to persist a JAVA Enum. |
| 20 | 22 | */ |
| @@ -25,7 +27,15 @@ | ||
| 25 | 27 | * Note that this relies on the order of the values in source code, and will change |
| 26 | 28 | * if values are added/removed before existing ones. |
| 27 | 29 | */ |
| 28 | - ORDINAL, | |
| 30 | + ORDINAL(Integer.class), | |
| 29 | 31 | /** 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; | |
| 31 | 41 | } |
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 @@ | ||
| 200 | 200 | BoundStatement bs = getPreparedQuery(QueryType.SAVE, values.keySet(), options).bind(); |
| 201 | 201 | int i = 0; |
| 202 | 202 | for (Map.Entry<ColumnMapper<?>, Object> entry : values.entrySet()) { |
| 203 | - DataType type = entry.getKey().getDataType(); | |
| 203 | + ColumnMapper<?> mapper = entry.getKey(); | |
| 204 | 204 | Object value = entry.getValue(); |
| 205 | - bs.setBytesUnsafe(i++, value == null ? null : type.serialize(value, protocolVersion)); | |
| 205 | + setObject(bs, i++, value, mapper); | |
| 206 | 206 | } |
| 207 | 207 | |
| 208 | 208 | if (mapper.writeConsistency != null) |
| @@ -221,6 +221,14 @@ | ||
| 221 | 221 | return option == null || option.saveNullFields; |
| 222 | 222 | } |
| 223 | 223 | |
| 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 | + | |
| 224 | 232 | /** |
| 225 | 233 | * Save an entity mapped by this mapper. |
| 226 | 234 | * <p> |
| @@ -328,7 +336,7 @@ | ||
| 328 | 336 | if (value == null) { |
| 329 | 337 | throw new IllegalArgumentException(String.format("Invalid null value for PRIMARY KEY column %s (argument %d)", column.getColumnName(), i)); |
| 330 | 338 | } |
| 331 | - bs.setBytesUnsafe(i++, column.getDataType().serialize(value, protocolVersion)); | |
| 339 | + setObject(bs, i++, value, column); | |
| 332 | 340 | } |
| 333 | 341 | |
| 334 | 342 | if (mapper.readConsistency != null) |
| @@ -510,7 +518,7 @@ | ||
| 510 | 518 | if (value == null) { |
| 511 | 519 | throw new IllegalArgumentException(String.format("Invalid null value for PRIMARY KEY column %s (argument %d)", column.getColumnName(), i)); |
| 512 | 520 | } |
| 513 | - bs.setBytesUnsafe(i++, column.getDataType().serialize(value, protocolVersion)); | |
| 521 | + setObject(bs, i++, value, column); | |
| 514 | 522 | columnNumber++; |
| 515 | 523 | } |
| 516 | 524 | return bs; |
modified driver-mapping/src/main/java/com/datastax/driver/mapping/MappingManager.java +42 −27
| @@ -18,11 +18,16 @@ | ||
| 18 | 18 | import java.util.Collections; |
| 19 | 19 | import java.util.HashMap; |
| 20 | 20 | import java.util.Map; |
| 21 | +import java.util.Set; | |
| 22 | + | |
| 23 | +import com.google.common.collect.Sets; | |
| 21 | 24 | |
| 22 | 25 | import com.datastax.driver.core.ProtocolVersion; |
| 23 | 26 | import com.datastax.driver.core.Session; |
| 27 | +import com.datastax.driver.core.TypeCodec; | |
| 24 | 28 | import com.datastax.driver.mapping.annotations.Accessor; |
| 25 | 29 | import com.datastax.driver.mapping.annotations.Table; |
| 30 | +import com.datastax.driver.mapping.annotations.UDT; | |
| 26 | 31 | |
| 27 | 32 | /** |
| 28 | 33 | * Mapping manager from which to obtain entity mappers. |
| @@ -30,11 +35,14 @@ | ||
| 30 | 35 | public class MappingManager { |
| 31 | 36 | |
| 32 | 37 | private final Session session; |
| 38 | + private final ProtocolVersion protocolVersion; | |
| 33 | 39 | final boolean isCassandraV1; |
| 34 | 40 | |
| 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(); | |
| 38 | 46 | |
| 39 | 47 | /** |
| 40 | 48 | * Creates a new {@code MappingManager} using the provided {@code Session}. |
| @@ -45,11 +53,12 @@ | ||
| 45 | 53 | */ |
| 46 | 54 | public MappingManager(Session session) { |
| 47 | 55 | this.session = session; |
| 56 | + this.protocolVersion = getProtocolVersion(session); | |
| 48 | 57 | // This is not strictly correct because we could connect to C* 2.0 with the v1 protocol. |
| 49 | 58 | // But mappers need to make a decision early so that generated queries are compatible, and we don't know in advance |
| 50 | 59 | // which nodes might join the cluster later. |
| 51 | 60 | // 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; | |
| 53 | 62 | } |
| 54 | 63 | |
| 55 | 64 | private static ProtocolVersion getProtocolVersion(Session session) { |
| @@ -78,6 +87,10 @@ | ||
| 78 | 87 | * <p> |
| 79 | 88 | * The {@code MappingManager} only ever keeps one Mapper for each class, and so calling this |
| 80 | 89 | * 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. | |
| 81 | 94 | * |
| 82 | 95 | * @param <T> the type of the class to map. |
| 83 | 96 | * @param klass the (annotated) class for which to return the mapper. |
| @@ -88,21 +101,22 @@ | ||
| 88 | 101 | } |
| 89 | 102 | |
| 90 | 103 | /** |
| 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. | |
| 94 | 109 | * <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). | |
| 99 | 113 | * |
| 100 | 114 | * @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. | |
| 103 | 117 | */ |
| 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); | |
| 106 | 120 | } |
| 107 | 121 | |
| 108 | 122 | /** |
| @@ -139,21 +153,22 @@ | ||
| 139 | 153 | } |
| 140 | 154 | |
| 141 | 155 | @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; | |
| 153 | 168 | } |
| 154 | 169 | } |
| 155 | 170 | } |
| 156 | - return mapper; | |
| 171 | + return codec; | |
| 157 | 172 | } |
| 158 | 173 | |
| 159 | 174 | @SuppressWarnings("unchecked") |
modified driver-mapping/src/main/java/com/datastax/driver/mapping/MethodMapper.java +23 −56
| @@ -18,10 +18,10 @@ | ||
| 18 | 18 | import java.lang.reflect.Method; |
| 19 | 19 | import java.lang.reflect.ParameterizedType; |
| 20 | 20 | import java.lang.reflect.Type; |
| 21 | -import java.nio.ByteBuffer; | |
| 22 | 21 | import java.util.Set; |
| 23 | 22 | |
| 24 | 23 | import com.google.common.collect.Sets; |
| 24 | +import com.google.common.reflect.TypeToken; | |
| 25 | 25 | import com.google.common.util.concurrent.Futures; |
| 26 | 26 | import com.google.common.util.concurrent.ListenableFuture; |
| 27 | 27 | |
| @@ -175,81 +175,48 @@ | ||
| 175 | 175 | } |
| 176 | 176 | |
| 177 | 177 | 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. | |
| 179 | 179 | private final String paramName; |
| 180 | 180 | 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) { | |
| 184 | 186 | this.paramName = paramName; |
| 185 | 187 | 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 | + } | |
| 191 | 197 | } |
| 192 | 198 | |
| 193 | 199 | void setValue(BoundStatement boundStatement, Object arg, ProtocolVersion protocolVersion) { |
| 194 | - ByteBuffer serializedArg = (dataType == null) | |
| 195 | - ? DataType.serializeValue(arg, protocolVersion) | |
| 196 | - : dataType.serialize(arg, protocolVersion); | |
| 197 | 200 | if (paramName == null) { |
| 198 | - if (arg == null) | |
| 199 | - boundStatement.setToNull(paramIdx); | |
| 201 | + if (codec == null) | |
| 202 | + boundStatement.set(paramIdx, arg, paramType); | |
| 200 | 203 | else |
| 201 | - boundStatement.setBytesUnsafe(paramIdx, serializedArg); | |
| 204 | + boundStatement.set(paramIdx, arg, codec); | |
| 202 | 205 | } else { |
| 203 | - if (arg == null) | |
| 204 | - boundStatement.setToNull(paramName); | |
| 206 | + if (codec == null) | |
| 207 | + boundStatement.set(paramName, arg, paramType); | |
| 205 | 208 | else |
| 206 | - boundStatement.setBytesUnsafe(paramName, serializedArg); | |
| 209 | + boundStatement.set(paramName, arg, codec); | |
| 207 | 210 | } |
| 208 | 211 | } |
| 209 | 212 | } |
| 210 | 213 | |
| 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 | - | |
| 247 | 214 | static class EnumParamMapper extends ParamMapper { |
| 248 | 215 | |
| 249 | 216 | private final EnumType enumType; |
| 250 | 217 | |
| 251 | 218 | public EnumParamMapper(String paramName, int paramIdx, EnumType enumType) { |
| 252 | - super(paramName, paramIdx); | |
| 219 | + super(paramName, paramIdx, enumType.pivotType, null); | |
| 253 | 220 | this.enumType = enumType; |
| 254 | 221 | } |
| 255 | 222 |
modified driver-mapping/src/main/java/com/datastax/driver/mapping/QueryType.java +9 −7
| @@ -25,6 +25,7 @@ | ||
| 25 | 25 | import com.datastax.driver.core.TableMetadata; |
| 26 | 26 | import com.datastax.driver.core.querybuilder.Delete; |
| 27 | 27 | import com.datastax.driver.core.querybuilder.Insert; |
| 28 | +import com.datastax.driver.core.querybuilder.QueryBuilder; | |
| 28 | 29 | import com.datastax.driver.core.querybuilder.Select; |
| 29 | 30 | |
| 30 | 31 | import static com.datastax.driver.core.querybuilder.QueryBuilder.*; |
| @@ -62,11 +63,12 @@ | ||
| 62 | 63 | } |
| 63 | 64 | |
| 64 | 65 | String makePreparedQueryString(TableMetadata table, EntityMapper<?> mapper, MappingManager manager, Set<ColumnMapper<?>> columns, Collection<Mapper.Option> options) { |
| 66 | + QueryBuilder builder = new QueryBuilder(manager.getSession().getCluster()); | |
| 65 | 67 | switch (kind) { |
| 66 | 68 | case SAVE: { |
| 67 | 69 | Insert insert = table == null |
| 68 | - ? insertInto(mapper.getKeyspace(), mapper.getTable()) | |
| 69 | - : insertInto(table); | |
| 70 | + ? builder.insertInto(mapper.getKeyspace(), mapper.getTable()) | |
| 71 | + : builder.insertInto(table); | |
| 70 | 72 | for (ColumnMapper<?> cm : columns) |
| 71 | 73 | if (cm.kind != ColumnMapper.Kind.COMPUTED) |
| 72 | 74 | insert.value(cm.getColumnName(), bindMarker()); |
| @@ -80,7 +82,7 @@ | ||
| 80 | 82 | return insert.toString(); |
| 81 | 83 | } |
| 82 | 84 | case GET: { |
| 83 | - Select.Selection selection = select(); | |
| 85 | + Select.Selection selection = builder.select(); | |
| 84 | 86 | for (ColumnMapper cm : mapper.allColumns()) { |
| 85 | 87 | Select.SelectionOrAlias column = (cm.kind == ColumnMapper.Kind.COMPUTED) |
| 86 | 88 | ? ((Select.SelectionOrAlias)selection).raw(cm.getColumnName()) |
| @@ -108,8 +110,8 @@ | ||
| 108 | 110 | } |
| 109 | 111 | case DEL: { |
| 110 | 112 | 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); | |
| 113 | 115 | Delete.Where where = delete.where(); |
| 114 | 116 | for (int i = 0; i < mapper.primaryKeySize(); i++) |
| 115 | 117 | where.and(eq(mapper.getPrimaryKeyColumn(i).getColumnName(), bindMarker())); |
| @@ -124,8 +126,8 @@ | ||
| 124 | 126 | case SLICE: |
| 125 | 127 | case REVERSED_SLICE: { |
| 126 | 128 | 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); | |
| 129 | 131 | Select.Where where = select.where(); |
| 130 | 132 | for (int i = 0; i < mapper.partitionKeys.size(); i++) |
| 131 | 133 | 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 @@ | ||
| 19 | 19 | import java.beans.PropertyDescriptor; |
| 20 | 20 | import java.lang.reflect.Field; |
| 21 | 21 | import java.lang.reflect.Method; |
| 22 | -import java.lang.reflect.ParameterizedType; | |
| 23 | -import java.lang.reflect.Type; | |
| 24 | 22 | import java.util.HashMap; |
| 25 | 23 | import java.util.Map; |
| 26 | 24 | import java.util.concurrent.atomic.AtomicInteger; |
| 27 | 25 | |
| 26 | +import com.google.common.reflect.TypeToken; | |
| 27 | + | |
| 28 | 28 | import com.datastax.driver.core.ConsistencyLevel; |
| 29 | -import com.datastax.driver.core.DataType; | |
| 30 | -import com.datastax.driver.core.UDTValue; | |
| 31 | 29 | |
| 32 | 30 | /** |
| 33 | 31 | * An {@link EntityMapper} implementation that use reflection to read and write fields |
| @@ -59,12 +57,8 @@ | ||
| 59 | 57 | private final Method readMethod; |
| 60 | 58 | private final Method writeMethod; |
| 61 | 59 | |
| 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); | |
| 68 | 62 | this.readMethod = pd.getReadMethod(); |
| 69 | 63 | this.writeMethod = pd.getWriteMethod(); |
| 70 | 64 | } |
| @@ -98,12 +92,12 @@ | ||
| 98 | 92 | private final Map<String, Object> fromString; |
| 99 | 93 | |
| 100 | 94 | 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); | |
| 102 | 96 | this.enumType = enumType; |
| 103 | 97 | |
| 104 | 98 | 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()) | |
| 107 | 101 | fromString.put(constant.toString().toLowerCase(), constant); |
| 108 | 102 | |
| 109 | 103 | } else { |
| @@ -132,70 +126,18 @@ | ||
| 132 | 126 | converted = fromString.get(value.toString().toLowerCase()); |
| 133 | 127 | break; |
| 134 | 128 | case ORDINAL: |
| 135 | - converted = javaType.getEnumConstants()[(Integer)value]; | |
| 129 | + converted = fieldType.getRawType().getEnumConstants()[(Integer)value]; | |
| 136 | 130 | break; |
| 137 | 131 | } |
| 138 | 132 | super.setValue(entity, converted); |
| 139 | 133 | } |
| 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 | - } | |
| 181 | 134 | |
| 182 | 135 | @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; | |
| 185 | 138 | } |
| 186 | 139 | } |
| 187 | 140 | |
| 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 | - | |
| 199 | 141 | private static class ReflectionFactory implements Factory { |
| 200 | 142 | |
| 201 | 143 | public <T> EntityMapper<T> create(Class<T> entityClass, String keyspace, String table, ConsistencyLevel writeConsistency, ConsistencyLevel readConsistency) { |
| @@ -212,21 +154,8 @@ | ||
| 212 | 154 | return new EnumMapper<T>(field, position, pd, AnnotationParser.enumType(field), columnCounter); |
| 213 | 155 | } |
| 214 | 156 | |
| 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); | |
| 230 | 159 | |
| 231 | 160 | return new LiteralMapper<T>(field, position, pd, columnCounter); |
| 232 | 161 |
modified driver-mapping/src/main/java/com/datastax/driver/mapping/Result.java +21 −4
| @@ -15,7 +15,6 @@ | ||
| 15 | 15 | */ |
| 16 | 16 | package com.datastax.driver.mapping; |
| 17 | 17 | |
| 18 | -import java.nio.ByteBuffer; | |
| 19 | 18 | import java.util.*; |
| 20 | 19 | |
| 21 | 20 | import com.datastax.driver.core.*; |
| @@ -47,13 +46,31 @@ | ||
| 47 | 46 | String name = cm.getAlias() != null && this.useAlias ? cm.getAlias() : cm.getColumnName(); |
| 48 | 47 | if (!row.getColumnDefinitions().contains(name)) |
| 49 | 48 | 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 | + } | |
| 53 | 60 | } |
| 54 | 61 | return entity; |
| 55 | 62 | } |
| 56 | 63 | |
| 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 | + | |
| 57 | 74 | /** |
| 58 | 75 | * Test whether this mapped result set has more results. |
| 59 | 76 | * |
modified driver-mapping/src/main/java/com/datastax/driver/mapping/TypeMappings.java +50 −54
| @@ -15,14 +15,15 @@ | ||
| 15 | 15 | */ |
| 16 | 16 | package com.datastax.driver.mapping; |
| 17 | 17 | |
| 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 | + | |
| 26 | 27 | import com.datastax.driver.core.TupleValue; |
| 27 | 28 | import com.datastax.driver.core.UDTValue; |
| 28 | 29 | import com.datastax.driver.mapping.annotations.UDT; |
| @@ -32,63 +33,22 @@ | ||
| 32 | 33 | */ |
| 33 | 34 | class TypeMappings { |
| 34 | 35 | |
| 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); | |
| 74 | 38 | } |
| 75 | 39 | |
| 76 | - static boolean mapsToList(Class<?> klass) { | |
| 40 | + private static boolean mapsToList(Class<?> klass) { | |
| 77 | 41 | return List.class.equals(klass); |
| 78 | 42 | } |
| 79 | 43 | |
| 80 | - static boolean mapsToSet(Class<?> klass) { | |
| 44 | + private static boolean mapsToSet(Class<?> klass) { | |
| 81 | 45 | return Set.class.equals(klass); |
| 82 | 46 | } |
| 83 | 47 | |
| 84 | - static boolean mapsToMap(Class<?> klass) { | |
| 48 | + private static boolean mapsToMap(Class<?> klass) { | |
| 85 | 49 | return Map.class.equals(klass); |
| 86 | 50 | } |
| 87 | 51 | |
| 88 | - static boolean mapsToCollection(Class<?> klass) { | |
| 89 | - return mapsToList(klass) || mapsToSet(klass) || mapsToMap(klass); | |
| 90 | - } | |
| 91 | - | |
| 92 | 52 | static boolean isMappedUDT(Class<?> klass) { |
| 93 | 53 | return klass.isAnnotationPresent(UDT.class); |
| 94 | 54 | } |
| @@ -98,4 +58,40 @@ | ||
| 98 | 58 | klass.equals(UDTValue.class) || |
| 99 | 59 | klass.equals(TupleValue.class); |
| 100 | 60 | } |
| 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 | + } | |
| 101 | 97 | } |
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 @@ | ||
| 20 | 20 | import java.lang.annotation.RetentionPolicy; |
| 21 | 21 | import java.lang.annotation.Target; |
| 22 | 22 | |
| 23 | +import com.datastax.driver.core.TypeCodec; | |
| 24 | + | |
| 23 | 25 | /** |
| 24 | 26 | * Annotation that allows to specify the name of the CQL column to which the |
| 25 | 27 | * field should be mapped. |
| @@ -49,4 +51,12 @@ | ||
| 49 | 51 | * @return whether the column name is a case sensitive one. |
| 50 | 52 | */ |
| 51 | 53 | 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; | |
| 52 | 62 | } |
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 @@ | ||
| 20 | 20 | import java.lang.annotation.RetentionPolicy; |
| 21 | 21 | import java.lang.annotation.Target; |
| 22 | 22 | |
| 23 | +import com.datastax.driver.core.TypeCodec; | |
| 24 | + | |
| 23 | 25 | /** |
| 24 | 26 | * Annotation that allows to specify the name of the CQL UDT field to which the |
| 25 | 27 | * Java field should be mapped. |
| @@ -49,4 +51,12 @@ | ||
| 49 | 51 | * @return whether the column name is a case sensitive one. |
| 50 | 52 | */ |
| 51 | 53 | 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; | |
| 52 | 62 | } |
modified driver-mapping/src/main/java/com/datastax/driver/mapping/annotations/Param.java +11 −1
| @@ -20,6 +20,8 @@ | ||
| 20 | 20 | import java.lang.annotation.RetentionPolicy; |
| 21 | 21 | import java.lang.annotation.Target; |
| 22 | 22 | |
| 23 | +import com.datastax.driver.core.TypeCodec; | |
| 24 | + | |
| 23 | 25 | /** |
| 24 | 26 | * Provides a name for a parameter of a method in an {@link Accessor} interface that |
| 25 | 27 | * can be used to reference to that parameter in method {@link Query}. |
| @@ -32,5 +34,13 @@ | ||
| 32 | 34 | * |
| 33 | 35 | * @return the name of the parameter. |
| 34 | 36 | */ |
| 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; | |
| 36 | 46 | } |
modified driver-mapping/src/test/java/com/datastax/driver/core/CoreHooks.java +1 −1
| @@ -21,5 +21,5 @@ | ||
| 21 | 21 | * Provides access to package-private members of the core module. |
| 22 | 22 | */ |
| 23 | 23 | 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()); | |
| 25 | 25 | } |
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 @@ | ||
| 26 | 26 | import static org.assertj.core.api.Assertions.fail; |
| 27 | 27 | |
| 28 | 28 | import com.datastax.driver.core.*; |
| 29 | +import com.datastax.driver.core.exceptions.CodecNotFoundException; | |
| 29 | 30 | import com.datastax.driver.core.exceptions.InvalidQueryException; |
| 30 | 31 | import com.datastax.driver.core.utils.CassandraVersion; |
| 31 | 32 | import com.datastax.driver.mapping.annotations.*; |
| @@ -125,10 +126,12 @@ | ||
| 125 | 126 | assertThat(user.getWriteTime()).isEqualTo(0); |
| 126 | 127 | } |
| 127 | 128 | |
| 128 | - @Test(groups = "short", expectedExceptions = IllegalArgumentException.class) | |
| 129 | + @Test(groups = "short", expectedExceptions = CodecNotFoundException.class) | |
| 129 | 130 | @CassandraVersion(major = 2.0) |
| 130 | 131 | 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"); | |
| 132 | 135 | } |
| 133 | 136 | |
| 134 | 137 | @Test(groups = "short") |
| @@ -213,8 +216,8 @@ | ||
| 213 | 216 | private String login; |
| 214 | 217 | private String name; |
| 215 | 218 | |
| 216 | - @Column(name = "writetime(v)") | |
| 217 | - byte writeTime; | |
| 219 | + @Computed(value = "writetime(name)") | |
| 220 | + String writeTime; | |
| 218 | 221 | |
| 219 | 222 | public String getLogin() { |
| 220 | 223 | return login; |
| @@ -232,11 +235,11 @@ | ||
| 232 | 235 | this.name = name; |
| 233 | 236 | } |
| 234 | 237 | |
| 235 | - public byte getWriteTime() { | |
| 238 | + public String getWriteTime() { | |
| 236 | 239 | return writeTime; |
| 237 | 240 | } |
| 238 | 241 | |
| 239 | - public void setWriteTime(byte writeTime) { | |
| 242 | + public void setWriteTime(String writeTime) { | |
| 240 | 243 | this.writeTime = writeTime; |
| 241 | 244 | } |
| 242 | 245 | } |
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 @@ | ||
| 15 | 15 | */ |
| 16 | 16 | package com.datastax.driver.mapping; |
| 17 | 17 | |
| 18 | -import java.util.*; | |
| 18 | +import java.util.Arrays; | |
| 19 | +import java.util.Collection; | |
| 20 | +import java.util.UUID; | |
| 19 | 21 | |
| 20 | -import com.datastax.driver.core.Session; | |
| 21 | -import com.datastax.driver.core.utils.CassandraVersion; | |
| 22 | -import com.datastax.driver.mapping.annotations.*; | |
| 23 | 22 | import com.google.common.base.Objects; |
| 24 | 23 | import org.testng.annotations.Test; |
| 25 | 24 | |
| 26 | -import static com.datastax.driver.core.TestUtils.CREATE_KEYSPACE_SIMPLE_FORMAT; | |
| 27 | 25 | import static org.testng.Assert.assertEquals; |
| 28 | 26 | import static org.testng.Assert.assertNull; |
| 29 | 27 | |
| 30 | 28 | import com.datastax.driver.core.CCMBridge; |
| 29 | +import com.datastax.driver.core.Session; | |
| 30 | +import com.datastax.driver.core.utils.CassandraVersion; | |
| 31 | 31 | import com.datastax.driver.core.utils.UUIDs; |
| 32 | +import com.datastax.driver.mapping.annotations.*; | |
| 32 | 33 | |
| 33 | 34 | /** |
| 34 | 35 | * Tests usage of mapping annotations without specifying a keyspace. |
| @@ -39,10 +40,76 @@ | ||
| 39 | 40 | private static final String KEYSPACE = "mapper_default_keyspace_test_ks"; |
| 40 | 41 | |
| 41 | 42 | 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); | |
| 44 | 110 | } |
| 45 | 111 | |
| 112 | + | |
| 46 | 113 | /* |
| 47 | 114 | * An entity that does not specify a keyspace in its @Table annotation. When a keyspace is |
| 48 | 115 | * not specified, the mapper uses the session's logged in keyspace. |
| @@ -95,28 +162,6 @@ | ||
| 95 | 162 | } |
| 96 | 163 | } |
| 97 | 164 | |
| 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 | - | |
| 120 | 165 | @Table(keyspace = KEYSPACE, name = "groups2") |
| 121 | 166 | public static class Group2 { |
| 122 | 167 | |
| @@ -204,47 +249,4 @@ | ||
| 204 | 249 | } |
| 205 | 250 | } |
| 206 | 251 | |
| 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 | - } | |
| 250 | 252 | } |
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 @@ | ||
| 17 | 17 | |
| 18 | 18 | import java.util.*; |
| 19 | 19 | |
| 20 | +import com.datastax.driver.core.*; | |
| 21 | +import com.datastax.driver.core.exceptions.CodecNotFoundException; | |
| 20 | 22 | import com.google.common.collect.Maps; |
| 23 | +import org.assertj.core.data.MapEntry; | |
| 21 | 24 | import org.testng.annotations.BeforeMethod; |
| 22 | 25 | |
| 23 | 26 | import com.google.common.base.Objects; |
| 24 | 27 | import org.testng.annotations.Test; |
| 25 | 28 | |
| 26 | 29 | import static org.assertj.core.api.Assertions.assertThat; |
| 30 | +import static org.assertj.core.api.Assertions.fail; | |
| 27 | 31 | import static org.testng.Assert.assertEquals; |
| 28 | 32 | import static org.testng.Assert.assertNull; |
| 29 | 33 | import static org.testng.Assert.assertTrue; |
| 30 | 34 | |
| 31 | -import com.datastax.driver.core.CCMBridge; | |
| 32 | -import com.datastax.driver.core.ResultSet; | |
| 33 | -import com.datastax.driver.core.Row; | |
| 34 | 35 | import com.datastax.driver.core.utils.UUIDs; |
| 35 | 36 | |
| 36 | 37 | import com.datastax.driver.mapping.annotations.*; |
| @@ -273,4 +274,70 @@ | ||
| 273 | 274 | assertEquals(u.one(), u5); |
| 274 | 275 | assertTrue(u.isExhausted()); |
| 275 | 276 | } |
| 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 | + } | |
| 276 | 343 | } |
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 @@ | ||
| 71 | 71 | in both cases, the payload will be sent along with the `PREPARE` or `QUERY` request respectively: |
| 72 | 72 | |
| 73 | 73 | ```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"); | |
| 75 | 75 | statement.setOutgoingPayload(myCustomPayload); |
| 76 | 76 | session.execute(statement); // myCustomPayload will be sent with QUERY request |
| 77 | 77 | session.prepare(statement); // myCustomPayload will be sent with PREPARE request |
| @@ -88,7 +88,7 @@ | ||
| 88 | 88 | `BatchStatement` itself, *not* to internal statements: |
| 89 | 89 | |
| 90 | 90 | ```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')") | |
| 92 | 92 | // correct |
| 93 | 93 | Statement batch = new BatchStatement().add(statement); |
| 94 | 94 | batch.setOutgoingPayload(myCustomPayload); |
| @@ -104,7 +104,7 @@ | ||
| 104 | 104 | sent over and over for every new page request*. |
| 105 | 105 | |
| 106 | 106 | ```java |
| 107 | -Statement statement = new SimpleStatement("..."); | |
| 107 | +Statement statement = session.newSimpleStatement("..."); | |
| 108 | 108 | statement.setOutgoingPayload(myCustomPayload); |
| 109 | 109 | ResultSet rows = session.execute(...); // myCustomPayload will be sent with first QUERY request |
| 110 | 110 | for (Row row : rows) { |
| @@ -148,7 +148,7 @@ | ||
| 148 | 148 | 1) From a `ResultSet`: use the `ExecutionInfo` class to retrieve the payload sent by the server. |
| 149 | 149 | |
| 150 | 150 | ```java |
| 151 | -Statement statement = new SimpleStatement("..."); | |
| 151 | +Statement statement = session.newSimpleStatement("..."); | |
| 152 | 152 | ResultSet rows = session.execute(...); |
| 153 | 153 | // last payload sent by the server |
| 154 | 154 | Map<String,ByteBuffer> serverPayload = rows.getExecutionInfo().getIncomingPayload(); |
| @@ -160,7 +160,7 @@ | ||
| 160 | 160 | payloads for all `RESULT` responses, use the following method instead: |
| 161 | 161 | |
| 162 | 162 | ```java |
| 163 | -Statement statement = new SimpleStatement("..."); | |
| 163 | +Statement statement = session.newSimpleStatement("..."); | |
| 164 | 164 | ResultSet rows = session.execute(...); |
| 165 | 165 | //all payloads sent by the server |
| 166 | 166 | for (ExecutionInfo info : rows.getAllExecutionInfo()) { |
| @@ -183,7 +183,7 @@ | ||
| 183 | 183 | payload, if any, will become the default outgoing payload for the prepared statement. |
| 184 | 184 | |
| 185 | 185 | ```java |
| 186 | -Statement statement = new SimpleStatement("..."); | |
| 186 | +Statement statement = session.newSimpleStatement("..."); | |
| 187 | 187 | statement.setOutgoingPayload(myCustomPayload) |
| 188 | 188 | PreparedStatement ps = session.prepare(...); // myCustomPayload will be sent with PREPARE request |
| 189 | 189 | // AND become the default outgoing payload |
| @@ -194,7 +194,7 @@ | ||
| 194 | 194 | with the `PREPARE` request: |
| 195 | 195 | |
| 196 | 196 | ```java |
| 197 | -Statement statement = new SimpleStatement("..."); | |
| 197 | +Statement statement = session.newSimpleStatement("..."); | |
| 198 | 198 | PreparedStatement ps = session.prepare(...); // no payload sent with PREPARE request |
| 199 | 199 | ps.setOutgoingPayload(myCustomPayload) // default outgoing payload is now myCustomPayload |
| 200 | 200 | ``` |
| @@ -218,7 +218,7 @@ | ||
| 218 | 218 | like in the example below: |
| 219 | 219 | |
| 220 | 220 | ```java |
| 221 | -Statement statement = new SimpleStatement("..."); | |
| 221 | +Statement statement = session.newSimpleStatement("..."); | |
| 222 | 222 | PreparedStatement ps = session.prepare(...); // no payload sent with PREPARE request |
| 223 | 223 | BoundStatement bs = ps.bind(1); // no outgoing payload by default |
| 224 | 224 | 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 @@ | ||
| 175 | 175 | |
| 176 | 176 | [Result]: http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/mapping/Result.html |
| 177 | 177 | |
| 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 | - | |
| 196 | 178 | ### Accessors |
| 197 | 179 | |
| 198 | 180 | `Accessor`s provide a way to map custom queries not supported by the |
modified features/paging/README.md +3 −3
| @@ -25,7 +25,7 @@ | ||
| 25 | 25 | The fetch size can also be set on a statement: |
| 26 | 26 | |
| 27 | 27 | ```java |
| 28 | -Statement statement = new SimpleStatement("your query"); | |
| 28 | +Statement statement = session.newSimpleStatement("your query"); | |
| 29 | 29 | statement.setFetchSize(2000); |
| 30 | 30 | ``` |
| 31 | 31 | |
| @@ -125,7 +125,7 @@ | ||
| 125 | 125 | |
| 126 | 126 | ```java |
| 127 | 127 | PagingState pagingState = PagingState.fromString(string); |
| 128 | -Statement st = new SimpleStatement("your query"); | |
| 128 | +Statement st = session.newSimpleStatement("your query"); | |
| 129 | 129 | st.setPagingState(pagingState); |
| 130 | 130 | ResultSet rs = session.execute(st); |
| 131 | 131 | ``` |
| @@ -142,7 +142,7 @@ | ||
| 142 | 142 | ```java |
| 143 | 143 | final int RESULTS_PER_PAGE = 100; |
| 144 | 144 | |
| 145 | -Statement st = new SimpleStatement("your query"); | |
| 145 | +Statement st = session.newSimpleStatement("your query"); | |
| 146 | 146 | st.setFetchSize(RESULTS_PER_PAGE); |
| 147 | 147 | |
| 148 | 148 | String requestedPage = extractPagingStateStringFromURL(); |
modified features/query_timestamps/README.md +1 −1
| @@ -36,7 +36,7 @@ | ||
| 36 | 36 | per-statement basis: |
| 37 | 37 | |
| 38 | 38 | ```java |
| 39 | -Statement statement = new SimpleStatement( | |
| 39 | +Statement statement = session.newSimpleStatement( | |
| 40 | 40 | "UPDATE users SET email = 'x@y.com' where id = 1"); |
| 41 | 41 | statement.setDefaultTimestamp(1234567890); |
| 42 | 42 | session.execute(statement); |
modified features/speculative_execution/README.md +1 −1
| @@ -92,7 +92,7 @@ | ||
| 92 | 92 | You can override the value on each statement: |
| 93 | 93 | |
| 94 | 94 | ```java |
| 95 | -Statement s = new SimpleStatement("SELECT * FROM users WHERE id = 1"); | |
| 95 | +Statement s = session.newSimpleStatement("SELECT * FROM users WHERE id = 1"); | |
| 96 | 96 | s.setIdempotent(true); |
| 97 | 97 | ``` |
| 98 | 98 |
modified pom.xml +2 −6
| @@ -43,15 +43,11 @@ | ||
| 43 | 43 | |
| 44 | 44 | <properties> |
| 45 | 45 | <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> | |
| 47 | 47 | <java.version>1.6</java.version> |
| 48 | 48 | <log4j.version>1.2.17</log4j.version> |
| 49 | 49 | <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> | |
| 55 | 51 | <netty.version>4.0.27.Final</netty.version> |
| 56 | 52 | <metrics.version>3.0.2</metrics.version> |
| 57 | 53 | <snappy.version>1.0.5</snappy.version> |
modified upgrade_guide/README.md +87 −27
| @@ -5,45 +5,105 @@ | ||
| 5 | 5 | |
| 6 | 6 | ### 2.2.0 |
| 7 | 7 | |
| 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 | |
| 12 | 81 | default version have been removed (they were already deprecated in |
| 13 | 82 | 2.1): |
| 14 | 83 | * `AbstractGettableData(int)` |
| 15 | 84 | * `Cluster.Builder#withProtocolVersion(int)` |
| 16 | - * in `DataType`: | |
| 17 | - * `serialize(Object, int)` | |
| 18 | - * `serialize(Object)` | |
| 19 | - * `deserialize(ByteBuffer)` | |
| 20 | - * `serializeValue(Object, int)` | |
| 21 | - * `serializeValue(Object)` | |
| 22 | 85 | * in `ProtocolOptions`: |
| 23 | 86 | * `NEWEST_SUPPORTED_PROTOCOL_VERSION` (replaced by |
| 24 | 87 | `ProtocolVersion#NEWEST_SUPPORTED`) |
| 25 | 88 | * `int getProtocolVersion()` |
| 26 | - * in `RegularStatement`: | |
| 27 | - * `getValues(int)` | |
| 28 | - * `getValues()` | |
| 29 | 89 | |
| 30 | 90 | There are now variants of these methods using the `ProtocolVersion` |
| 31 | 91 | enum. In addition, `ProtocolOptions#getProtocolVersionEnum` has been |
| 32 | 92 | renamed to `ProtocolOptions#getProtocolVersion`. |
| 33 | 93 | |
| 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 | |
| 35 | 95 | (they had been deprecated in 2.1.6 when the suspicion mechanism was |
| 36 | 96 | removed): |
| 37 | 97 | * `Host.StateListener#onSuspected()` (was inherited by |
| 38 | 98 | `LoadBalancingPolicy`) |
| 39 | 99 | * `Host#getInitialReconnectionAttemptFuture()` |
| 40 | 100 | |
| 41 | -3. `PoolingOptions#setMinSimultaneousRequestsPerConnectionThreshold(HostDistance, | |
| 101 | +6. `PoolingOptions#setMinSimultaneousRequestsPerConnectionThreshold(HostDistance, | |
| 42 | 102 | int)` has been removed. The new connection pool resizing algorithm introduced by |
| 43 | 103 | [JAVA-419](https://datastax-oss.atlassian.net/browse/JAVA-419) does not need this |
| 44 | 104 | threshold anymore. |
| 45 | 105 | |
| 46 | -4. `AddressTranslater` has been renamed to `AddressTranslator`. All | |
| 106 | +7. `AddressTranslater` has been renamed to `AddressTranslator`. All | |
| 47 | 107 | related methods and classes have also been renamed. |
| 48 | 108 | |
| 49 | 109 | In addition, the `close()` method has been pulled up into |
| @@ -51,12 +111,12 @@ | ||
| 51 | 111 | Existing third-party `AddressTranslator` implementations only need |
| 52 | 112 | to add an empty `close()` method. |
| 53 | 113 | |
| 54 | -5. The `close()` method has been pulled up into `LoadBalancingPolicy`, | |
| 114 | +8. The `close()` method has been pulled up into `LoadBalancingPolicy`, | |
| 55 | 115 | and `CloseableLoadBalancingPolicy` has been removed. Existing third-party |
| 56 | 116 | `LoadBalancingPolicy` implementations only need to add an empty |
| 57 | 117 | `close()` method. |
| 58 | 118 | |
| 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 | |
| 60 | 120 | associated with a `Cluster` instance: |
| 61 | 121 | * `ReconnectionPolicy`, `RetryPolicy`, `AddressTranslator`, |
| 62 | 122 | and `TimestampGenerator`: |
| @@ -70,22 +130,22 @@ | ||
| 70 | 130 | initialization / cleanup tasks. Existing third-party implementations |
| 71 | 131 | only need to add empty methods. |
| 72 | 132 | |
| 73 | -7. `LoadBalancingPolicy` does not extend `Host.StateListener` anymore: | |
| 133 | +10. `LoadBalancingPolicy` does not extend `Host.StateListener` anymore: | |
| 74 | 134 | callback methods (`onUp`, `onDown`, etc.) have been duplicated. This |
| 75 | 135 | is unlikely to affect clients. |
| 76 | 136 | |
| 77 | -8. [Client-side timestamp generation](../features/query_timestamps/) is | |
| 137 | +11. [Client-side timestamp generation](../features/query_timestamps/) is | |
| 78 | 138 | now the default (provided that [native |
| 79 | 139 | protocol](../features/native_protocol) v3 or higher is in use). The |
| 80 | 140 | generator used is `AtomicMonotonicTimestampGenerator`. |
| 81 | 141 | |
| 82 | -9. If a DNS name resolves to multiple A-records, | |
| 142 | +12. If a DNS name resolves to multiple A-records, | |
| 83 | 143 | `Cluster.Builder#addContactPoint(String)` will now use all of these |
| 84 | 144 | addresses as contact points. This gives you the possibility of |
| 85 | 145 | maintaining contact points in DNS configuration, and having a single, |
| 86 | 146 | static contact point in your Java code. |
| 87 | 147 | |
| 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): | |
| 89 | 149 | * in `PreparedStatement`: `getIncomingPayload()`, |
| 90 | 150 | `getOutgoingPayload()` and |
| 91 | 151 | `setOutgoingPayload(Map<String,ByteBuffer>)` |
| @@ -98,7 +158,7 @@ | ||
| 98 | 158 | This breaks binary compatibility for these two classes; if you have |
| 99 | 159 | custom implementations, you will have to adapt them accordingly. |
| 100 | 160 | |
| 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 | |
| 102 | 162 | new CQL types: |
| 103 | 163 | * `getByte`/`setByte` for the `TINYINT` type |
| 104 | 164 | * `getShort`/`setShort` for the `SMALLINT` type |
| @@ -110,7 +170,7 @@ | ||
| 110 | 170 | |
| 111 | 171 | This affects `Row`, `BoundStatement`, `TupleValue` and `UDTValue`. |
| 112 | 172 | |
| 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 | |
| 114 | 174 | errors introduced in Cassandra 2.2: |
| 115 | 175 | * `ReadFailureException` |
| 116 | 176 | * `WriteFailureException` |
| @@ -125,13 +185,13 @@ | ||
| 125 | 185 | exception hierarchy, it now has new child classes that are not |
| 126 | 186 | related to timeouts). |
| 127 | 187 | |
| 128 | -13. `ResultSet#fetchMoreResults()` now returns a `ListenableFuture<ResultSet>`. | |
| 188 | +16. `ResultSet#fetchMoreResults()` now returns a `ListenableFuture<ResultSet>`. | |
| 129 | 189 | This makes the API more friendly if you chain transformations on an async |
| 130 | 190 | query to process all pages (see `AsyncResultSetTest` in the sources for an |
| 131 | 191 | example). |
| 132 | 192 | |
| 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 | |
| 135 | 195 | explanations). So they become purely informational at this stage. |
| 136 | 196 | However it is a good idea to keep using these annotations and make sure |
| 137 | 197 | they match the schema, in anticipation for the schema generation features |