Elffuss BraidHub

kikocis/java-driver public

2764f2e0c54f · 19.9 KiBRenderedRawPermalink
1## Custom Codecs
2
3Custom codecs support transparent, user-configurable mapping of CQL types to arbitrary Java objects.
4
5Practical 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
16The central piece in the serialization mechanism is [TypeCodec].
17
18Each `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
25Additionally, it implements inspection methods that verify if the codec is suitable for a specific
26CQL type and/or Java object.
27
28`TypeCodec` can be freely subclassed by users willing to implement their own serialization logic.
29However, users are only required to do so when they want to extend
30the driver's default set of codecs by registering additional codecs that handle
31Java types that the driver is otherwise unable to process. For all other users,
32the built-in set of codecs that is bundled with the driver provides
33exactly the same functionality that the driver used to offer so far,
34with out-of-the-box conversion from all CQL types to standard Java equivalents.
35
36Refer to the [javadocs][TypeCodec] of `TypeCodec` for more information.
37
38`TypeCodec`s are centralized in a [CodecRegistry] instance.
39Whenever the driver needs to perform one of the aforementioned operations,
40it 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).
42It also caches codec lookup results for faster execution whenever possible.
43
44Refer to the [javadocs][CodecRegistry] of User `CodecRegistry` for more information.
45
46### Implementing and using custom codecs
47
48Let's consider the following scenario: a user has JSON documents stored in a varchar column, and wants
49the driver to automatically map that column to a Java object using the [Jackson] library,
50instead of returning the raw JSON string.
51
52The (admittedly simplistic) table structure is as follows:
53
54```sql
55CREATE TABLE t (id int PRIMARY KEY, json VARCHAR);
56```
57
58The 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 */
64public class JsonCodec<T> extends TypeCodec<T> {
65
66 private final ObjectMapper objectMapper = new ObjectMapper();
67
68 public JsonCodec(Class<T> javaType) {
69 super(DataType.varchar(), javaType);
70 }
71
72 @Override
73 public ByteBuffer serialize(T value, ProtocolVersion protocolVersion) throws InvalidTypeException {
74 if (value == null)
75 return null;
76 try {
77 return ByteBuffer.wrap(objectMapper.writeValueAsBytes(value));
78 } catch (JsonProcessingException e) {
79 throw new InvalidTypeException(e.getMessage(), e);
80 }
81 }
82
83 @Override
84 @SuppressWarnings("unchecked")
85 public T deserialize(ByteBuffer bytes, ProtocolVersion protocolVersion) throws InvalidTypeException {
86 if (bytes == null)
87 return null;
88 try {
89 byte[] b = new byte[bytes.remaining()];
90 bytes.duplicate().get(b);
91 return (T)objectMapper.readValue(b, toJacksonJavaType());
92 } catch (IOException e) {
93 throw new InvalidTypeException(e.getMessage(), e);
94 }
95 }
96
97 @Override
98 public String format(T value) throws InvalidTypeException {
99 if (value == null)
100 return NULL;
101 String json;
102 try {
103 json = objectMapper.writeValueAsString(value);
104 } catch (IOException e) {
105 throw new InvalidTypeException(e.getMessage(), e);
106 }
107 return '\'' + json.replace("\'", "''") + '\'';
108 }
109
110 @Override
111 @SuppressWarnings("unchecked")
112 public T parse(String value) throws InvalidTypeException {
113 if (value == null || value.isEmpty() || value.equals(NULL))
114 return null;
115 if (value.charAt(0) != '\'' || value.charAt(value.length() - 1) != '\'')
116 throw new InvalidTypeException("JSON strings must be enclosed by single quotes");
117 String json = value.substring(1, value.length() - 1).replace("''", "'");
118 try {
119 return (T)objectMapper.readValue(json, toJacksonJavaType());
120 } catch (IOException e) {
121 throw new InvalidTypeException(e.getMessage(), e);
122 }
123 }
124
125 protected JavaType toJacksonJavaType() {
126 return TypeFactory.defaultInstance().constructType(getJavaType().getType());
127 }
128
129}
130```
131
132A few implementation guidelines:
133
134* Your codecs should be thread-safe, or better yet, immutable;
135* Your codecs should be fast: do not forget that codecs are executed often and are usually very "hot" pieces of code;
136* Your codecs should never block.
137
138The second step is to register your codec with a `CodecRegistry` instance:
139
140```java
141ObjectMapper objectMapper = ...
142JsonCodec<MyPojo> myJsonCodec = new JsonCodec<MyPojo>(MyPojo.class, objectMapper);
143CodecRegistry myCodecRegistry = cluster.getConfiguration().getCodecRegistry();
144myCodecRegistry.register(myJsonCodec);
145```
146
147As you can see, the easiest way to do so is to access the `Cluster`'s `CodecRegistry`.
148By default, `Cluster` instances will use `CodecRegistry.DEFAULT_INSTANCE`,
149which should be adequate for most users.
150
151It is however possible to create a `Cluster` using a different `CodecRegistry`:
152
153```java
154CodecRegistry myCodecRegistry = new CodecRegistry();
155Cluster cluster = new Cluster.builder().withCodecRegistry(myCodecRegistry).build();
156```
157
158Note: when you instantiate a new `CodecRegistry`, it automatically registers all the default codecs used by the driver.
159This ensures that the new registry will not lack of an essential codec. *You cannot deregister default codecs, only
160register new ones*.
161
162From now on, your custom codec is fully operational. It will be used every time the driver encounters
163a `MyPojo` instance when executing queries, or when you ask it to retrieve a `MyPojo` instance from a `ResultSet`.
164
165For example, here is how to save a `MyPojo` object:
166
167```java
168Cluster cluster = ...
169Session session = ...
170MyPojo myPojo = ...
171// Using SimpleStatement
172Statement stmt = session.newSimpleStatement("INSERT INTO t (id, json) VALUES (?, ?)", 42, myPojo));
173// Using the Query Builder
174BuiltStatement insertStmt = new QueryBuilder(cluster).insertInto("t")
175 .value("id", 42)
176 .value("json", myPojo);
177// Using BoundStatements
178PreparedStatement ps = session.prepare("INSERT INTO t (id, json) VALUES (?, ?)");
179BoundStatement bs1 = ps.bind(42, myPojo); // or alternatively...
180BoundStatement bs2 = ps.bind()
181 .setInt(0, 42)
182 .set(1, myPojo, MyPojo.class);
183```
184
185And here is how to retrieve a `MyPojo` object converted from a JSON document:
186
187```java
188ResultSet rows = session.execute(...);
189Row row = one();
190// Let the driver convert the string for you...
191MyPojo myPojo = row.get(1, MyPojo.class);
192// ... or retrieve the raw string if you need it
193String json = row.get(1, String.class); // row.getString(1) would have worked too
194```
195
196Tip: `Row` and `BoundStatement` have several methods to set and retrieve values.
197But if you plan to use custom codecs,
198make sure that you use preferably the `get()` and `set()` methods: they
199avoid any ambiguity by requiring the user to explicitly specify the desired Java type,
200thus forcing the driver to pick the right codec for the right task.
201
202### Support for parameterized types
203
204`get()` and `set()` can even be used to retrieve collections or other
205user-defined parameterized types; simply use the `get()` and `set()` variants that
206take Guava's [TypeToken] parameter:
207
208```java
209Row row = ...
210List<MyPojo> myPojos = row.get("jsonList", new TypeToken<List<MyPojo>>(){});
211// or alternatively, the following also works for collections:
212List<MyPojo> myPojos = row.getList("jsonList", MyPojo.class);
213```
214
215### Support for collections, user types, tuples and Java Enums
216
217`CodecRegistry` instances not only store default codecs and user-defined codecs;
218they can also create new codecs on the fly, based on the set of codecs they currently hold.
219
220* Codecs for [UserType] instances are created on the fly using [UDTCodec];
221* Codecs for [TupleType] instances are created on the fly using [TupleCodec];
222* Codecs for Java Enums are created on the fly using [EnumStringCodec];
223* Codecs for collections are created on the fly using [ListCodec],
224 [SetCodec] and [MapCodec], if their element types can be handled by
225 existing codecs (or codecs that can themselves be generated).
226
227This way, the user does not have to manually register all derived codecs for a given "base" codec.
228However, other combinations of Java and CQL types not listed above cannot have their codecs created on the fly;
229such codecs must be manually registered.
230
231The driver also provides another codec for Enums that converts Enum instances to CQL ints
232representing their ordinal position: [EnumIntCodec]. If you plan to use this codec, make sure to register it
233manually, otherwise Enums would be converted using [EnumStringCodec].
234_It is not possible to mix both codecs in the same `CodecRegistry`_.
235
236Note that the default set of codecs has no support for
237[Cassandra custom types][AbstractType];
238to be able to deserialize values of such types, you need to manually register an appropriate codec.
239
240### Using custom codecs with user types and tuples
241
242By default, the driver maps user-defined type values and tuple values to [UDTValue] and [TupleValue],
243using the built-in codecs [UDTCodec] and [TupleCodec] respectively.
244
245If you want to register a custom codec for a specific user type, follow these steps:
246
247Let's suppose you have a keyspace containing the following type and table:
248
249```sql
250CREATE TYPE address (street VARCHAR, zipcode INT);
251CREATE TABLE users (id UUID PRIMARY KEY, name VARCHAR, address frozen<address>);
252```
253
254And let's suppose that you want to map the type `address` to an `Address` class:
255
256```java
257public class Address {
258
259 private final String street;
260
261 private final int zipcode;
262
263 public Address(String street, int zipcode) {
264 this.street = street;
265 this.zipcode = zipcode;
266 }
267
268 // getters, setters, equals() and hashcode() omitted
269}
270```
271
272First of all, create a codec that knows how to serialize this class; one possible solution
273(but not necessarily the most efficient one) would be to convert `Address` instances into `UDTValue`
274instances, then serialize them with another codec:
275
276
277```java
278public class AddressCodec extends TypeCodec<Address> {
279
280 private final TypeCodec<UDTValue> innerCodec;
281
282 private final UserType userType;
283
284 public AddressCodec(TypeCodec<UDTValue> innerCodec, Class<Address> javaType) {
285 super(innerCodec.getCqlType(), javaType);
286 this.innerCodec = innerCodec;
287 this.userType = (UserType)innerCodec.getCqlType();
288 }
289
290 @Override
291 public ByteBuffer serialize(Address value, ProtocolVersion protocolVersion) throws InvalidTypeException {
292 return innerCodec.serialize(toUDTValue(value), protocolVersion);
293 }
294
295 @Override
296 public Address deserialize(ByteBuffer bytes, ProtocolVersion protocolVersion) throws InvalidTypeException {
297 return toAddress(innerCodec.deserialize(bytes, protocolVersion));
298 }
299
300 @Override
301 public Address parse(String value) throws InvalidTypeException {
302 return value == null || value.isEmpty() || value.equals(NULL) ? null : toAddress(innerCodec.parse(value));
303 }
304
305 @Override
306 public String format(Address value) throws InvalidTypeException {
307 return value == null ? null : innerCodec.format(toUDTValue(value));
308 }
309
310 protected Address toAddress(UDTValue value) {
311 return value == null ? null : new Address(
312 value.getString("street"),
313 value.getInt("zipcode")
314 );
315 }
316
317 protected UDTValue toUDTValue(Address value) {
318 return value == null ? null : userType.newValue()
319 .setString("street", value.getStreet())
320 .setInt("zipcode", value.getZipcode());
321 }
322}
323```
324
325Now (and only if you intend to use your own `CodecRegistry`),
326create it and register it on your `Cluster` instance:
327
328```java
329// only if you do not intend to use CodecRegistry.DEFAULT_INSTANCE
330CodecRegistry codecRegistry = new CodecRegistry();
331Cluster cluster = Cluster.builder()
332 .addContactPoints(...)
333 .withCodecRegistry(codecRegistry)
334 .build();
335```
336
337Now, retrieve the metadata for type `address`:
338
339```java
340UserType addressType = cluster.getMetadata().getKeyspace(...).getUserType("address");
341TypeCodec<UDTValue> addressTypeCodec = codecRegistry.codecFor(addressType);
342```
343
344And finally, register your `AddressCodec` with the `CodecRegistry`. Note that
345your codec simply delegates the hard work to an inner codec that knows how to deal with
346user type values:
347
348```java
349AddressCodec addressCodec = new AddressCodec(addressTypeCodec, Address.class);
350codecRegistry.register(addressCodec);
351```
352
353And voilà! You can now retrieve `address` values as `Address` instances:
354
355```java
356ResultSet rows = session.execute(...);
357Row row = rows.one();
358// let the driver convert it for you...
359Address address = row.get("address", Address.class);
360// ...or access the low-level UDTValue, if you need
361UDTValue addressUdt = row.get("address", UDTValue.class); // row.getUDTValue("address") would have worked too
362```
363
364Note that this solution creates an intermediary `UDTValue` object when
365serializing and deserializing. It's possible to bypass this step with a
366lower-level implementation that manipulates the binary stream directly.
367That's also how the object mapper handles UDTs, and you can rely on the
368mapper to generate UDT codecs for you; see
369[this page](../object_mapper/custom_codecs/#implicit-udt-codecs) for more
370information.
371
372### Limitations
373
374#### Generics
375
376Java generic types are fully supported, through Guava's [TypeToken] API.
377Be sure to only use `get()` and `set()` methods
378that take a `TypeToken` argument:
379
380```java
381// this works
382Foo<Bar> foo = row.get(0, new TypeToken<Foo<Bar>>(){})
383// this does not work due to type erasure
384Foo<Bar> foo = row.get(0, Foo.class);
385```
386
387#### Type inheritance
388
389If a codec accepts a Java type that is assignable to the
390desired Java type, that codec may be returned if it is found first
391in the registry, *even if another codec is a better match*.
392
393As a consequence, type inheritance and interfaces should be used with care.
394Let's consider an example and assume that class `B` extends class `A`:
395
3961) If you register a codec for `A`, you can pass `B` as the target type,
397because `B` instances are assignable to `A`, and the driver is capable
398of detecting that:
399
400```java
401codecRegistry.register(new ACodec());
402// all work
403A a1 = row.get(0, A.class);
404B b = row.get(0, B.class);
405A a2 = row.get(0, B.class);
406```
407
408However, because `List<B>` is *not* assignable to `List<A>`:
409
410```java
411codecRegistry.register(new ACodec());
412// this works
413List<A> as1 = row.getList(0, A.class);
414// but this throws CodecNotFoundException
415List<B> bs = row.getList(0, B.class);
416List<? extends A> as2 = row.getList(0, B.class);
417```
418
4192) If you register a codec for `B`, you can't pass `A` as the target type,
420because no codec matches `A.class` exactly:
421
422```java
423codecRegistry.register(new BCodec());
424// this works
425A a1 = row.get(0, B.class);
426B b = row.get(0, B.class);
427// but this throws CodecNotFoundException
428A a2 = row.get(0, A.class);
429// and with collections, this works
430List<B> bs = row.getList(0, B.class);
431// but this throws CodecNotFoundException
432List<A> as = row.getList(0, A.class);
433```
434
435The same apply for interfaces.
436
437### Performance considerations
438
439A codec lookup operation may be costly; to mitigate this, the `CodecRegistry` caches lookup results whenever possible.
440
441The following situations are exceptions where it is not possible to cache lookup results:
442
443* With [SimpleStatement] instances;
444* With [BuiltStatement] instances (created via the Query Builder).
445
446In these places, the driver has no way to determine the right CQL type to use, so it performs
447a best-effort heuristic to guess which codec to use.
448
449Beware that in these cases, the lookup performs in average 10x worse. If performance is a key factor for your application,
450consider using prepared statements all the time, and avoid calling ambiguous methods (prefer `get()` and `set()`).
451
452[JAVA-721]: https://datastax-oss.atlassian.net/browse/JAVA-721
453[TypeCodec]: http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/core/TypeCodec.html
454[LocalDate]: http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/core/LocalDate.html
455[serialize]: http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/core/TypeCodec.html#serialize(T,%20com.datastax.driver.core.ProtocolVersion)
456[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)
457[TypeCodec.format]: http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/core/TypeCodec.html#format(T)
458[TypeCodec.parse]: http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/core/TypeCodec.html#parse(java.lang.String)
459[CodecRegistry]: http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/core/CodecRegistry.html
460[Jackson]: http://wiki.fasterxml.com/JacksonHome
461[AbstractType]: https://github.com/apache/cassandra/blob/trunk/src/java/org/apache/cassandra/db/marshal/AbstractType.java
462[EnumStringCodec]: http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/core/TypeCodec.EnumStringCodec.html
463[EnumIntCodec]: http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/core/TypeCodec.EnumIntCodec.html
464[UserType]: http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/core/UserType.html
465[UDTValue]: http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/core/UDTValue.html
466[UDTCodec]: http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/core/TypeCodec.UDTCodec.html
467[TupleType]: http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/core/TupleType.html
468[TupleValue]: http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/core/TupleValue.html
469[TupleCodec]: http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/core/TypeCodec.TupleCodec.html
470[ListCodec]: http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/core/TypeCodec.ListCodec.html
471[SetCodec]: http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/core/TypeCodec.SetCodec.html
472[MapCodec]: http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/core/TypeCodec.MapCodec.html
473[TypeToken]: http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/reflect/TypeToken.html
474[MappingCodec]: http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/core/TypeCodec.MappingCodec.html
475[StringParsingCodec]: http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/core/TypeCodec.StringParsingCodec.html
476[SimpleStatement]: http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/core/SimpleStatement.html
477[BuiltStatement]: http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/core/BuiltStatement.html
478[setList]: http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/core/SettableByIndexData.html#setList(int,%20java.util.List)
479[setSet]: http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/core/SettableByIndexData.html#setSet(int,%20java.util.Set)
480[setMap]: http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/core/SettableByIndexData.html#setMap(int,%20java.util.Map)
481[setObject]: http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/core/SettableByIndexData.html#setObject(int,%20V)