| 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 with a `CodecRegistry` instance: |
| 112 | |
| 113 | ```java |
| 114 | ObjectMapper objectMapper = ... |
| 115 | JsonCodec<MyPojo> myJsonCodec = new JsonCodec<MyPojo>(MyPojo.class, objectMapper); |
| 116 | CodecRegistry myCodecRegistry = cluster.getConfiguration().getCodecRegistry(); |
| 117 | myCodecRegistry.register(myJsonCodec); |
| 118 | ``` |
| 119 | |
| 120 | As you can see, the easiest way to do so is to access the `Cluster`'s `CodecRegistry`. |
| 121 | By default, `Cluster` instances will use `CodecRegistry.DEFAULT_INSTANCE`, |
| 122 | which should be adequate for most users. |
| 123 | |
| 124 | It is however possible to create a `Cluster` using a different `CodecRegistry`: |
| 125 | |
| 126 | ```java |
| 127 | CodecRegistry myCodecRegistry = new CodecRegistry(); |
| 128 | Cluster cluster = new Cluster.builder().withCodecRegistry(myCodecRegistry).build(); |
| 129 | ``` |
| 130 | |
| 131 | Note: when you instantiate a new `CodecRegistry`, it automatically registers all the default codecs used by the driver. |
| 132 | This ensures that the new registry will not lack of an essential codec. *You cannot deregister default codecs, only |
| 133 | register new ones*. |
| 134 | |
| 135 | From now on, your custom codec is fully operational. It will be used every time the driver encounters |
| 136 | a `MyPojo` instance when executing queries, or when you ask it to retrieve a `MyPojo` instance from a `ResultSet`. |
| 137 | |
| 138 | For example, here is how to save a `MyPojo` object: |
| 139 | |
| 140 | ```java |
| 141 | Cluster cluster = ... |
| 142 | Session session = ... |
| 143 | MyPojo myPojo = ... |
| 144 | // Using SimpleStatement |
| 145 | Statement stmt = session.newSimpleStatement("INSERT INTO t (id, json) VALUES (?, ?)", 42, myPojo)); |
| 146 | // Using the Query Builder |
| 147 | BuiltStatement insertStmt = new QueryBuilder(cluster).insertInto("t") |
| 148 | .value("id", 42) |
| 149 | .value("json", myPojo); |
| 150 | // Using BoundStatements |
| 151 | PreparedStatement ps = session.prepare("INSERT INTO t (id, json) VALUES (?, ?)"); |
| 152 | BoundStatement bs1 = ps.bind(42, myPojo); // or alternatively... |
| 153 | BoundStatement bs2 = ps.bind() |
| 154 | .setInt(0, 42) |
| 155 | .set(1, myPojo, MyPojo.class); |
| 156 | ``` |
| 157 | |
| 158 | And here is how to retrieve a `MyPojo` object converted from a JSON document: |
| 159 | |
| 160 | ```java |
| 161 | ResultSet rows = session.execute(...); |
| 162 | Row row = one(); |
| 163 | // Let the driver convert the string for you... |
| 164 | MyPojo myPojo = row.get(1, MyPojo.class); |
| 165 | // ... or retrieve the raw string if you need it |
| 166 | String json = row.get(1, String.class); // row.getString(1) would have worked too |
| 167 | ``` |
| 168 | |
| 169 | Tip: `Row` and `BoundStatement` have several methods to set and retrieve values. |
| 170 | But if you plan to use custom codecs, |
| 171 | make sure that you use preferably the `get()` and `set()` methods: they |
| 172 | avoid any ambiguity by requiring the user to explicitly specify the desired Java type, |
| 173 | thus forcing the driver to pick the right codec for the right task. |
| 174 | |
| 175 | ### Support for parameterized types |
| 176 | |
| 177 | `get()` and `set()` can even be used to retrieve collections or other |
| 178 | user-defined parameterized types; simply use the `get()` and `set()` variants that |
| 179 | take Guava's [TypeToken] parameter: |
| 180 | |
| 181 | ```java |
| 182 | Row row = ... |
| 183 | List<MyPojo> myPojos = row.get("jsonList", new TypeToken<List<MyPojo>>(){}); |
| 184 | // or alternatively, the following also works for collections: |
| 185 | List<MyPojo> myPojos = row.getList("jsonList", MyPojo.class); |
| 186 | ``` |
| 187 | |
| 188 | ### Support for collections, user types, tuples and Java Enums |
| 189 | |
| 190 | `CodecRegistry` instances not only store default codecs and user-defined codecs; |
| 191 | they can also create new codecs on the fly, based on the set of codecs they currently hold. |
| 192 | |
| 193 | * Codecs for [UserType] instances are created on the fly using [UDTCodec]; |
| 194 | * Codecs for [TupleType] instances are created on the fly using [TupleCodec]; |
| 195 | * Codecs for Java Enums are created on the fly using [EnumStringCodec]; |
| 196 | * Codecs for collections are created on the fly using [ListCodec], |
| 197 | [SetCodec] and [MapCodec], if their element types can be handled by |
| 198 | existing codecs (or codecs that can themselves be generated). |
| 199 | |
| 200 | This way, the user does not have to manually register all derived codecs for a given "base" codec. |
| 201 | However, other combinations of Java and CQL types not listed above cannot have their codecs created on the fly; |
| 202 | such codecs must be manually registered. |
| 203 | |
| 204 | The driver also provides another codec for Enums that converts Enum instances to CQL ints |
| 205 | representing their ordinal position: [EnumIntCodec]. If you plan to use this codec, make sure to register it |
| 206 | manually, otherwise Enums would be converted using [EnumStringCodec]. |
| 207 | _It is not possible to mix both codecs in the same `CodecRegistry`_. |
| 208 | |
| 209 | Note that the default set of codecs has no support for |
| 210 | [Cassandra custom types][AbstractType]; |
| 211 | to be able to deserialize values of such types, you need to manually register an appropriate codec. |
| 212 | |
| 213 | ### Using custom codecs with user types and tuples |
| 214 | |
| 215 | By default, the driver maps user-defined type values and tuple values to [UDTValue] and [TupleValue], |
| 216 | using the built-in codecs [UDTCodec] and [TupleCodec] respectively. |
| 217 | |
| 218 | If you want to register a custom codec for a specific user type, follow these steps: |
| 219 | |
| 220 | Let's suppose you have a keyspace containing the following type and table: |
| 221 | |
| 222 | ```sql |
| 223 | CREATE TYPE address (street VARCHAR, zipcode INT); |
| 224 | CREATE TABLE users (id UUID PRIMARY KEY, name VARCHAR, address frozen<address>); |
| 225 | ``` |
| 226 | |
| 227 | And let's suppose that you want to map the type `address` to an `Address` class: |
| 228 | |
| 229 | ```java |
| 230 | public class Address { |
| 231 | |
| 232 | private final String street; |
| 233 | |
| 234 | private final int zipcode; |
| 235 | |
| 236 | public Address(String street, int zipcode) { |
| 237 | this.street = street; |
| 238 | this.zipcode = zipcode; |
| 239 | } |
| 240 | |
| 241 | // getters, setters, equals() and hashcode() omitted |
| 242 | } |
| 243 | ``` |
| 244 | |
| 245 | First of all, create a codec for this class: |
| 246 | |
| 247 | ```java |
| 248 | public class AddressCodec extends TypeCodec.MappingCodec<Address, UDTValue> { |
| 249 | |
| 250 | private final UserType userType; |
| 251 | |
| 252 | public AddressCodec(TypeCodec<UDTValue> innerCodec, Class<Address> javaType) { |
| 253 | super(innerCodec, javaType); |
| 254 | userType = (UserType) innerCodec.getCqlType(); |
| 255 | } |
| 256 | |
| 257 | @Override |
| 258 | protected Address deserialize(UDTValue value) { |
| 259 | return value == null ? null : new Address(value.getString("street"), value.getInt("zipcode")); |
| 260 | } |
| 261 | |
| 262 | @Override |
| 263 | protected UDTValue serialize(Address address) { |
| 264 | return address == null ? null : userType.newValue().setString("street", address.getStreet()).setInt("zipcode", address.getZipcode()); |
| 265 | } |
| 266 | } |
| 267 | ``` |
| 268 | |
| 269 | Again, the driver provides a convenient base class: [MappingCodec]. |
| 270 | |
| 271 | Now (and only if you intend to use your own `CodecRegistry`), |
| 272 | create it and register it on your `Cluster` instance: |
| 273 | |
| 274 | ```java |
| 275 | // only if you do not intend to use CodecRegistry.DEFAULT_INSTANCE |
| 276 | CodecRegistry codecRegistry = new CodecRegistry(); |
| 277 | Cluster cluster = Cluster.builder() |
| 278 | .addContactPoints(...) |
| 279 | .withCodecRegistry(codecRegistry) |
| 280 | .build(); |
| 281 | ``` |
| 282 | |
| 283 | Now, retrieve the metadata for type `address`: |
| 284 | |
| 285 | ```java |
| 286 | UserType addressType = cluster.getMetadata().getKeyspace(...).getUserType("address"); |
| 287 | ``` |
| 288 | |
| 289 | And finally, register your `AddressCodec` with the `CodecRegistry`. Note that |
| 290 | your codec simply delegates the hard work to an inner codec that knows how to deal with |
| 291 | user type values: |
| 292 | |
| 293 | ```java |
| 294 | AddressCodec addressCodec = new AddressCodec(new TypeCodec.UDTCodec(addressType), Address.class); |
| 295 | codecRegistry.register(addressCodec); |
| 296 | ``` |
| 297 | |
| 298 | And voilà! You can now retrieve `address` values as `Address` instances: |
| 299 | |
| 300 | ```java |
| 301 | ResultSet rows = session.execute(...); |
| 302 | Row row = rows.one(); |
| 303 | // let the driver convert it for you... |
| 304 | Address address = row.get("address", Address.class); |
| 305 | // ...or access the low-level UDTValue, if you need |
| 306 | UDTValue addressUdt = row.get("address", UDTValue.class); // row.getUDTValue("address") would have worked too |
| 307 | ``` |
| 308 | |
| 309 | Note that this solution creates an intermediary `UDTValue` object when |
| 310 | serializing and deserializing. It's possible to bypass this step with a |
| 311 | lower-level implementation that manipulates the binary stream directly. |
| 312 | That's also how the object mapper handles UDTs, and you can rely on the |
| 313 | mapper to generate UDT codecs for you; see |
| 314 | [this page](../object_mapper/custom_codecs/#implicit-udt-codecs) for more |
| 315 | information. |
| 316 | |
| 317 | ### Limitations |
| 318 | |
| 319 | #### Generics |
| 320 | |
| 321 | Java generic types are fully supported, through Guava's [TypeToken] API. |
| 322 | Be sure to only use `get()` and `set()` methods |
| 323 | that take a `TypeToken` argument: |
| 324 | |
| 325 | ```java |
| 326 | // this works |
| 327 | Foo<Bar> foo = row.get(0, new TypeToken<Foo<Bar>>(){}) |
| 328 | // this does not work due to type erasure |
| 329 | Foo<Bar> foo = row.get(0, Foo.class); |
| 330 | ``` |
| 331 | |
| 332 | #### Type inheritance |
| 333 | |
| 334 | If a codec accepts a Java type that is assignable to the |
| 335 | desired Java type, that codec may be returned if it is found first |
| 336 | in the registry, *even if another codec is a better match*. |
| 337 | |
| 338 | As a consequence, type inheritance and interfaces should be used with care. |
| 339 | Let's consider an example and assume that class `B` extends class `A`: |
| 340 | |
| 341 | 1) If you register a codec for `A`, you can pass `B` as the target type, |
| 342 | because `B` instances are assignable to `A`, and the driver is capable |
| 343 | of detecting that: |
| 344 | |
| 345 | ```java |
| 346 | codecRegistry.register(new ACodec()); |
| 347 | // all work |
| 348 | A a1 = row.get(0, A.class); |
| 349 | B b = row.get(0, B.class); |
| 350 | A a2 = row.get(0, B.class); |
| 351 | ``` |
| 352 | |
| 353 | However, because `List<B>` is *not* assignable to `List<A>`: |
| 354 | |
| 355 | ```java |
| 356 | codecRegistry.register(new ACodec()); |
| 357 | // this works |
| 358 | List<A> as1 = row.getList(0, A.class); |
| 359 | // but this throws CodecNotFoundException |
| 360 | List<B> bs = row.getList(0, B.class); |
| 361 | List<? extends A> as2 = row.getList(0, B.class); |
| 362 | ``` |
| 363 | |
| 364 | 2) If you register a codec for `B`, you can't pass `A` as the target type, |
| 365 | because no codec matches `A.class` exactly: |
| 366 | |
| 367 | ```java |
| 368 | codecRegistry.register(new BCodec()); |
| 369 | // this works |
| 370 | A a1 = row.get(0, B.class); |
| 371 | B b = row.get(0, B.class); |
| 372 | // but this throws CodecNotFoundException |
| 373 | A a2 = row.get(0, A.class); |
| 374 | // and with collections, this works |
| 375 | List<B> bs = row.getList(0, B.class); |
| 376 | // but this throws CodecNotFoundException |
| 377 | List<A> as = row.getList(0, A.class); |
| 378 | ``` |
| 379 | |
| 380 | The same apply for interfaces. |
| 381 | |
| 382 | ### Performance considerations |
| 383 | |
| 384 | A codec lookup operation may be costly; to mitigate this, the `CodecRegistry` caches lookup results whenever possible. |
| 385 | |
| 386 | The following situations are exceptions where it is not possible to cache lookup results: |
| 387 | |
| 388 | * With [SimpleStatement] instances and [BuiltStatement] instances (created via the Query Builder); in these places, the driver has |
| 389 | no way to determine the right CQL type to use, so it performs a best-effort heuristic to guess which codec to use. |
| 390 | * When using "ambiguous" methods of `BoundStatement` and `Row`, such as [setList()][setList], |
| 391 | [setSet()][setSet], [setMap()][setMap], [setObject()][setObject]; |
| 392 | these methods are "ambiguous" because they do not convey enough compile-time information about the object |
| 393 | to serialize, so the driver performs the same heuristic to guess which codec to use. |
| 394 | |
| 395 | Beware that in these cases the lookup performs in average 10x worse. If performance is a key factor for your application, |
| 396 | consider using prepared statements all the time, and avoid calling ambiguous methods (prefer `get()` and `set()`). |
| 397 | |
| 398 | [JAVA-721]: https://datastax-oss.atlassian.net/browse/JAVA-721 |
| 399 | [TypeCodec]: http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/core/TypeCodec.html |
| 400 | [LocalDate]: http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/core/LocalDate.html |
| 401 | [serialize]: http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/core/TypeCodec.html#serialize(T,%20com.datastax.driver.core.ProtocolVersion) |
| 402 | [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) |
| 403 | [TypeCodec.format]: http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/core/TypeCodec.html#format(T) |
| 404 | [TypeCodec.parse]: http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/core/TypeCodec.html#parse(java.lang.String) |
| 405 | [CodecRegistry]: http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/core/CodecRegistry.html |
| 406 | [Jackson]: http://wiki.fasterxml.com/JacksonHome |
| 407 | [AbstractType]: https://github.com/apache/cassandra/blob/trunk/src/java/org/apache/cassandra/db/marshal/AbstractType.java |
| 408 | [EnumStringCodec]: http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/core/TypeCodec.EnumStringCodec.html |
| 409 | [EnumIntCodec]: http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/core/TypeCodec.EnumIntCodec.html |
| 410 | [UserType]: http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/core/UserType.html |
| 411 | [UDTValue]: http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/core/UDTValue.html |
| 412 | [UDTCodec]: http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/core/TypeCodec.UDTCodec.html |
| 413 | [TupleType]: http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/core/TupleType.html |
| 414 | [TupleValue]: http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/core/TupleValue.html |
| 415 | [TupleCodec]: http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/core/TypeCodec.TupleCodec.html |
| 416 | [ListCodec]: http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/core/TypeCodec.ListCodec.html |
| 417 | [SetCodec]: http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/core/TypeCodec.SetCodec.html |
| 418 | [MapCodec]: http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/core/TypeCodec.MapCodec.html |
| 419 | [TypeToken]: http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/reflect/TypeToken.html |
| 420 | [MappingCodec]: http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/core/TypeCodec.MappingCodec.html |
| 421 | [StringParsingCodec]: http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/core/TypeCodec.StringParsingCodec.html |
| 422 | [SimpleStatement]: http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/core/SimpleStatement.html |
| 423 | [BuiltStatement]: http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/core/BuiltStatement.html |
| 424 | [setList]: http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/core/SettableByIndexData.html#setList(int,%20java.util.List) |
| 425 | [setSet]: http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/core/SettableByIndexData.html#setSet(int,%20java.util.Set) |
| 426 | [setMap]: http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/core/SettableByIndexData.html#setMap(int,%20java.util.Map) |
| 427 | [setObject]: http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/core/SettableByIndexData.html#setObject(int,%20V) |