Elffuss BraidHub

kikocis/java-driver public

5366b0f3c217 · 19.6 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 `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 look 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 // always duplicate the ByteBuffer instance before consuming it!
91 bytes.duplicate().get(b);
92 return (T) objectMapper.readValue(b, toJacksonJavaType());
93 } catch (IOException e) {
94 throw new InvalidTypeException(e.getMessage(), e);
95 }
96 }
97
98 @Override
99 public String format(T value) throws InvalidTypeException {
100 if (value == null)
101 return "NULL";
102 String json;
103 try {
104 json = objectMapper.writeValueAsString(value);
105 } catch (IOException e) {
106 throw new InvalidTypeException(e.getMessage(), e);
107 }
108 return '\'' + json.replace("\'", "''") + '\'';
109 }
110
111 @Override
112 @SuppressWarnings("unchecked")
113 public T parse(String value) throws InvalidTypeException {
114 if (value == null || value.isEmpty() || value.equalsIgnoreCase("NULL"))
115 return null;
116 if (value.charAt(0) != '\'' || value.charAt(value.length() - 1) != '\'')
117 throw new InvalidTypeException("JSON strings must be enclosed by single quotes");
118 String json = value.substring(1, value.length() - 1).replace("''", "'");
119 try {
120 return (T) objectMapper.readValue(json, toJacksonJavaType());
121 } catch (IOException e) {
122 throw new InvalidTypeException(e.getMessage(), e);
123 }
124 }
125
126 protected JavaType toJacksonJavaType() {
127 return TypeFactory.defaultInstance().constructType(getJavaType().getType());
128 }
129
130}
131```
132
133A few implementation guidelines:
134
135* Your codecs should be thread-safe, or better yet, immutable;
136* Your codecs should be fast: do not forget that codecs are executed often and are usually very "hot" pieces of code;
137* Your codecs should never block.
138
139The second step is to register your codec with a `CodecRegistry` instance:
140
141```java
142ObjectMapper objectMapper = ...
143JsonCodec<MyPojo> myJsonCodec = new JsonCodec<MyPojo>(MyPojo.class);
144CodecRegistry myCodecRegistry = cluster.getConfiguration().getCodecRegistry();
145myCodecRegistry.register(myJsonCodec);
146```
147
148As you can see, the easiest way to do so is to access the `Cluster`'s `CodecRegistry`.
149By default, `Cluster` instances will use `CodecRegistry.DEFAULT_INSTANCE`,
150which should be adequate for most users.
151
152It is however possible to create a `Cluster` using a different `CodecRegistry`:
153
154```java
155CodecRegistry myCodecRegistry = new CodecRegistry();
156Cluster cluster = new Cluster.builder().withCodecRegistry(myCodecRegistry).build();
157```
158
159Note: when you instantiate a new `CodecRegistry`, it automatically registers all the default codecs used by the driver.
160This ensures that the new registry will not lack of an essential codec. *You cannot deregister nor override
161an already-registered codec, only register new ones*. If you try to register a codec that would override
162an existing one, the driver will log a warning and ignore it.
163
164From now on, your custom codec is fully operational. It will be used every time the driver encounters
165a `MyPojo` instance when executing queries, or when you ask it to retrieve a `MyPojo` instance from a `ResultSet`.
166
167For example, here is how to save a `MyPojo` object:
168
169```java
170Cluster cluster = ...
171Session session = ...
172MyPojo myPojo = ...
173// Using SimpleStatement
174Statement stmt = new SimpleStatement("INSERT INTO t (id, json) VALUES (?, ?)", 42, myPojo));
175// Using the Query Builder
176BuiltStatement insertStmt = QueryBuilder.insertInto("t")
177 .value("id", 42)
178 .value("json", myPojo);
179// Using BoundStatements
180PreparedStatement ps = session.prepare("INSERT INTO t (id, json) VALUES (?, ?)");
181BoundStatement bs1 = ps.bind(42, myPojo); // or alternatively...
182BoundStatement bs2 = ps.bind()
183 .setInt(0, 42)
184 .set(1, myPojo, MyPojo.class);
185```
186
187And here is how to retrieve a `MyPojo` object converted from a JSON document:
188
189```java
190ResultSet rs = session.execute(...);
191Row row = rs.one();
192// Let the driver convert the string for you...
193MyPojo myPojo = row.get(1, MyPojo.class);
194// ... or retrieve the raw string if you need it
195String json = row.get(1, String.class); // row.getString(1) would have worked too
196```
197
198Tip: `Row` and `BoundStatement` have several methods to set and retrieve values.
199But if you plan to use custom codecs,
200make sure that you use preferably the `get()` and `set()` methods: they
201avoid any ambiguity by requiring the user to explicitly specify the desired Java type,
202thus forcing the driver to pick the right codec for the right task.
203
204### On-the-fly codec generation
205
206`CodecRegistry` instances not only store default codecs and user-defined codecs;
207they can also create new codecs on the fly, based on the set of codecs they currently hold.
208They can manage the following mappings:
209
210* Collections (list, sets and maps) of known types. For example, if you registered a `TypeCodec<A>`, you get `List<A>>` handled for free. This works recursively for nested collections;
211* [UserType] instances are automatically mapped to [UDTValue] objects. All registered codecs are available recursively to the UDT's fields;
212* [TupleType] instances are automatically mapped to [TupleValue] objects (with the same rules for nested fields);
213* [CustomType] instances are automatically mapped to [ByteBuffer] instances.
214
215This way, the user does not have to manually register all derived codecs for a given "base" codec.
216However, other combinations of Java and CQL types not listed above cannot have their codecs created on the fly;
217such codecs must be manually registered.
218
219If the codec registry encounters a mapping that it can't handle automatically, a [CodecNotFoundException]
220is thrown.
221
222Thanks to on-the-fly codec generation, it is possible to leverage the `JsonCodec` from our previous
223example to retrieve lists of `MyPojo` objects stored in a CQL column of type `list<text>`, without
224the need to explicitly declare a codec for this specific CQL type:
225
226```java
227JsonCodec<MyPojo> myJsonCodec = new JsonCodec<MyPojo>(MyPojo.class, objectMapper);
228myCodecRegistry.register(myJsonCodec);
229Row row = ...
230List<MyPojo> myPojos = row.getList("jsonList", MyPojo.class); // works out of the box!
231```
232
233### Creating custom codecs for user-defined types (UDTs)
234
235By default, the driver maps user-defined type values to [UDTValue] instances.
236
237If you want to register a custom codec for a specific user-defined type,
238follow these steps:
239
240Let's suppose you have a keyspace containing the following type and table:
241
242```sql
243CREATE TYPE address (street VARCHAR, zipcode INT);
244CREATE TABLE users (id UUID PRIMARY KEY, name VARCHAR, address frozen<address>);
245```
246
247And let's suppose that you want to map the type `address` to an `Address` class:
248
249```java
250public class Address {
251
252 private final String street;
253
254 private final int zipcode;
255
256 public Address(String street, int zipcode) {
257 this.street = street;
258 this.zipcode = zipcode;
259 }
260
261 // getters, setters, equals() and hashcode() omitted
262}
263```
264
265First of all, create a codec that knows how to serialize this class; one possible solution
266(but not necessarily the most efficient one) would be to convert `Address` instances into `UDTValue`
267instances, then serialize them with another codec:
268
269
270```java
271public class AddressCodec extends TypeCodec<Address> {
272
273 private final TypeCodec<UDTValue> innerCodec;
274
275 private final UserType userType;
276
277 public AddressCodec(TypeCodec<UDTValue> innerCodec, Class<Address> javaType) {
278 super(innerCodec.getCqlType(), javaType);
279 this.innerCodec = innerCodec;
280 this.userType = (UserType)innerCodec.getCqlType();
281 }
282
283 @Override
284 public ByteBuffer serialize(Address value, ProtocolVersion protocolVersion) throws InvalidTypeException {
285 return innerCodec.serialize(toUDTValue(value), protocolVersion);
286 }
287
288 @Override
289 public Address deserialize(ByteBuffer bytes, ProtocolVersion protocolVersion) throws InvalidTypeException {
290 return toAddress(innerCodec.deserialize(bytes, protocolVersion));
291 }
292
293 @Override
294 public Address parse(String value) throws InvalidTypeException {
295 return value == null || value.isEmpty() || value.equals(NULL) ? null : toAddress(innerCodec.parse(value));
296 }
297
298 @Override
299 public String format(Address value) throws InvalidTypeException {
300 return value == null ? null : innerCodec.format(toUDTValue(value));
301 }
302
303 protected Address toAddress(UDTValue value) {
304 return value == null ? null : new Address(
305 value.getString("street"),
306 value.getInt("zipcode")
307 );
308 }
309
310 protected UDTValue toUDTValue(Address value) {
311 return value == null ? null : userType.newValue()
312 .setString("street", value.getStreet())
313 .setInt("zipcode", value.getZipcode());
314 }
315}
316```
317
318Now (and only if you intend to use your own `CodecRegistry`),
319create it and register it on your `Cluster` instance:
320
321```java
322// only if you do not intend to use CodecRegistry.DEFAULT_INSTANCE
323CodecRegistry codecRegistry = new CodecRegistry();
324Cluster cluster = Cluster.builder()
325 .addContactPoints(...)
326 .withCodecRegistry(codecRegistry)
327 .build();
328```
329
330Now, retrieve the metadata for type `address`:
331
332```java
333UserType addressType = cluster.getMetadata().getKeyspace(...).getUserType("address");
334TypeCodec<UDTValue> addressTypeCodec = codecRegistry.codecFor(addressType);
335```
336
337And finally, register your `AddressCodec` with the `CodecRegistry`. Note that
338your codec simply delegates the hard work to an inner codec that knows how to deal with
339user type values:
340
341```java
342AddressCodec addressCodec = new AddressCodec(addressTypeCodec, Address.class);
343codecRegistry.register(addressCodec);
344```
345
346And voilà! You can now retrieve `address` values as `Address` instances:
347
348```java
349ResultSet rows = session.execute(...);
350Row row = rows.one();
351// let the driver convert it for you...
352Address address = row.get("address", Address.class);
353// ...or access the low-level UDTValue, if you need
354UDTValue addressUdt = row.get("address", UDTValue.class); // row.getUDTValue("address") would have worked too
355```
356
357Note that this solution creates an intermediary `UDTValue` object when
358serializing and deserializing. It's possible to bypass this step with a
359lower-level implementation that manipulates the binary stream directly.
360That's also how the object mapper handles UDTs, and you can rely on the
361mapper to generate UDT codecs for you; see
362[this page](../object_mapper/custom_codecs/#implicit-udt-codecs) for more
363information.
364
365### Support for generic (parameterized) types
366
367Java generic (parameterized) types are fully supported, through Guava's [TypeToken] API.
368Be sure to only use `get()` and `set()` methods that take a `TypeToken` argument:
369
370```java
371// this works
372Foo<Bar> foo = row.get(0, new TypeToken<Foo<Bar>>(){})
373// this does not work due to type erasure
374Foo<Bar> foo = row.get(0, Foo.class);
375```
376
377### Support for subtype polymorphism
378
379Suppose the following class hierarchy:
380
381```java
382class Animal {}
383class Cat extends Animal {}
384```
385
386By default, a codec will accept to serialize any object that extends or
387implements its declared Java type: a codec such as
388`AnimalCodec extends TypeCodec<Animal>` will accept `Cat` instances as well.
389
390This allows a codec to handle interfaces and superclasses
391in a generic way, regardless of the actual implementation being
392used by client code; for example, the driver has a built-in codec
393that handles `List` instances, and this codec is capable of
394serializing any concrete `List` implementation.
395
396But this has one caveat: when setting or retrieving values
397with `get()` and `set()`, *it is vital to pass the exact
398Java type the codec handles*:
399
400```java
401codecRegistry.register(new AnimalCodec());
402BoundStatement bs = ...
403bs.set(0, new Cat(), Animal.class); // works
404bs.set(0, new Cat(), Cat.class); // throws CodecNotFoundException
405```
406
407The same is valid when retrieving values:
408
409```java
410codecRegistry.register(new AnimalCodec());
411Row row = ...
412Animal animal = row.get(0, Animal.class); // works
413Cat cat = row.get(0, Cat.class); // throws CodecNotFoundException
414```
415
416### Performance considerations
417
418A codec lookup operation may be costly; to mitigate this, the `CodecRegistry`
419caches lookup results whenever possible.
420
421When the cache can be used and the registry looks up a codec, the following rules apply:
422
4231. if a result was previously cached for that mapping, it is returned;
4242. otherwise, the registry checks the list of "basic" codecs: the default ones,
425and the ones that were explicitly registered (in the order that they were registered).
426It calls each codec's [accepts] methods to determine if it can handle the mapping,
427and if so, adds it to the cache and returns it;
4283. otherwise, the registry tries to generate a codec on the fly, according to the rules outlined above;
4294. if the creation succeeds, the registry adds the created codec to the cache and returns it;
4305. otherwise, the registry throws [CodecNotFoundException].
431
432The cache can be used as long as *at least the CQL type is known*. The following situations
433are exceptions where it is *not* possible to cache lookup results:
434
435* With [SimpleStatement] instances;
436* With [BuiltStatement] instances (created via the Query Builder).
437
438In these places, the driver has no way to determine the right CQL type to use, so it performs
439a best-effort heuristic to guess which codec to use. The result of this heuristic is never cached.
440
441Beware that in these cases, the lookup performs in average 10x worse. If performance is a key factor for your application,
442consider using prepared statements all the time.
443
444[JAVA-721]: https://datastax-oss.atlassian.net/browse/JAVA-721
445[TypeCodec]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/TypeCodec.html
446[LocalDate]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/LocalDate.html
447[ByteBuffer]: http://docs.oracle.com/javase/8/docs/api/java/nio/ByteBuffer.html
448[serialize]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/TypeCodec.html#serialize-T-com.datastax.driver.core.ProtocolVersion-
449[deserialize]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/TypeCodec.html#deserialize-java.nio.ByteBuffer-com.datastax.driver.core.ProtocolVersion-
450[TypeCodec.format]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/TypeCodec.html#format-T-
451[TypeCodec.parse]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/TypeCodec.html#parse-java.lang.String-
452[accepts]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/TypeCodec.html#accepts-com.datastax.driver.core.DataType-
453[CodecRegistry]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/CodecRegistry.html
454[CodecNotFoundException]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/exceptions/CodecNotFoundException.html
455[Jackson]: http://wiki.fasterxml.com/JacksonHome
456[AbstractType]: https://github.com/apache/cassandra/blob/trunk/src/java/org/apache/cassandra/db/marshal/AbstractType.java
457[UserType]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/UserType.html
458[UDTValue]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/UDTValue.html
459[TupleType]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/TupleType.html
460[TupleValue]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/TupleValue.html
461[CustomType]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/DataType.CustomType.html
462[TypeToken]: http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/reflect/TypeToken.html
463[SimpleStatement]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/SimpleStatement.html
464[BuiltStatement]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/querybuilder/BuiltStatement.html
465[setList]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/SettableByIndexData.html#setList-int-java.util.List-
466[setSet]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/SettableByIndexData.html#setSet-int-java.util.Set-
467[setMap]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/SettableByIndexData.html#setMap-int-java.util.Map-