Search in sources :

Example 1 with TypeCodec

use of com.datastax.oss.driver.api.core.type.codec.TypeCodec in project java-driver by datastax.

the class CachingCodecRegistry method createCodec.

// Try to create a codec when we haven't found it in the cache.
// Variant where the Java type is unknown.
@NonNull
protected TypeCodec<?> createCodec(@NonNull DataType cqlType) {
    if (cqlType instanceof ListType) {
        DataType elementType = ((ListType) cqlType).getElementType();
        TypeCodec<Object> elementCodec = codecFor(elementType);
        return TypeCodecs.listOf(elementCodec);
    } else if (cqlType instanceof SetType) {
        DataType elementType = ((SetType) cqlType).getElementType();
        TypeCodec<Object> elementCodec = codecFor(elementType);
        return TypeCodecs.setOf(elementCodec);
    } else if (cqlType instanceof MapType) {
        DataType keyType = ((MapType) cqlType).getKeyType();
        DataType valueType = ((MapType) cqlType).getValueType();
        TypeCodec<Object> keyCodec = codecFor(keyType);
        TypeCodec<Object> valueCodec = codecFor(valueType);
        return TypeCodecs.mapOf(keyCodec, valueCodec);
    } else if (cqlType instanceof TupleType) {
        return TypeCodecs.tupleOf((TupleType) cqlType);
    } else if (cqlType instanceof UserDefinedType) {
        return TypeCodecs.udtOf((UserDefinedType) cqlType);
    } else if (cqlType instanceof CustomType) {
        return TypeCodecs.custom(cqlType);
    }
    throw new CodecNotFoundException(cqlType, null);
}
Also used : CustomType(com.datastax.oss.driver.api.core.type.CustomType) SetType(com.datastax.oss.driver.api.core.type.SetType) TypeCodec(com.datastax.oss.driver.api.core.type.codec.TypeCodec) ListType(com.datastax.oss.driver.api.core.type.ListType) TupleType(com.datastax.oss.driver.api.core.type.TupleType) DataType(com.datastax.oss.driver.api.core.type.DataType) UserDefinedType(com.datastax.oss.driver.api.core.type.UserDefinedType) CodecNotFoundException(com.datastax.oss.driver.api.core.type.codec.CodecNotFoundException) MapType(com.datastax.oss.driver.api.core.type.MapType) NonNull(edu.umd.cs.findbugs.annotations.NonNull)

Example 2 with TypeCodec

use of com.datastax.oss.driver.api.core.type.codec.TypeCodec in project java-driver by datastax.

the class RelationParser method parseOptions.

protected Map<CqlIdentifier, Object> parseOptions(AdminRow row) {
    ImmutableMap.Builder<CqlIdentifier, Object> builder = ImmutableMap.builder();
    for (Map.Entry<String, TypeCodec<?>> entry : OPTION_CODECS.entrySet()) {
        String name = entry.getKey();
        CqlIdentifier id = CqlIdentifier.fromInternal(name);
        TypeCodec<?> codec = entry.getValue();
        if (name.equals("caching") && row.isString("caching")) {
            // C* <=2.2, caching is stored as a string, and also appears as a string in the WITH clause.
            builder.put(id, row.getString(name));
        } else if (name.equals("compaction_strategy_class")) {
            // C* <=2.2, compaction options split in two columns
            String strategyClass = row.getString(name);
            if (strategyClass != null) {
                builder.put(CqlIdentifier.fromInternal("compaction"), ImmutableMap.<String, String>builder().put("class", strategyClass).putAll(SimpleJsonParser.parseStringMap(row.getString("compaction_strategy_options"))).build());
            }
        } else if (name.equals("compression_parameters")) {
            // C* <=2.2, compression stored as a string
            String compressionParameters = row.getString(name);
            if (compressionParameters != null) {
                builder.put(CqlIdentifier.fromInternal("compression"), ImmutableMap.copyOf(SimpleJsonParser.parseStringMap(row.getString(name))));
            }
        } else if (!isDeprecatedInCassandra4(name)) {
            // Default case, read the value in a generic fashion
            Object value = row.get(name, codec);
            if (value != null) {
                builder.put(id, value);
            }
        }
    }
    return builder.build();
}
Also used : TypeCodec(com.datastax.oss.driver.api.core.type.codec.TypeCodec) CqlIdentifier(com.datastax.oss.driver.api.core.CqlIdentifier) ImmutableMap(com.datastax.oss.driver.shaded.guava.common.collect.ImmutableMap) Map(java.util.Map) ImmutableMap(com.datastax.oss.driver.shaded.guava.common.collect.ImmutableMap)

Example 3 with TypeCodec

use of com.datastax.oss.driver.api.core.type.codec.TypeCodec in project java-driver by datastax.

the class RelationParser method appendOptions.

public static void appendOptions(Map<CqlIdentifier, Object> options, ScriptBuilder builder) {
    for (Map.Entry<CqlIdentifier, Object> entry : options.entrySet()) {
        CqlIdentifier name = entry.getKey();
        Object value = entry.getValue();
        String formattedValue;
        if (name.asInternal().equals("caching") && value instanceof String) {
            formattedValue = TypeCodecs.TEXT.format((String) value);
        } else {
            @SuppressWarnings("unchecked") TypeCodec<Object> codec = (TypeCodec<Object>) RelationParser.OPTION_CODECS.get(name.asInternal());
            formattedValue = codec.format(value);
        }
        String optionName = name.asCql(true);
        if ("local_read_repair_chance".equals(optionName)) {
            // Another small quirk in C* <= 2.2
            optionName = "dclocal_read_repair_chance";
        }
        builder.andWith().append(optionName).append(" = ").append(formattedValue);
    }
}
Also used : TypeCodec(com.datastax.oss.driver.api.core.type.codec.TypeCodec) ImmutableMap(com.datastax.oss.driver.shaded.guava.common.collect.ImmutableMap) Map(java.util.Map) CqlIdentifier(com.datastax.oss.driver.api.core.CqlIdentifier)

Example 4 with TypeCodec

use of com.datastax.oss.driver.api.core.type.codec.TypeCodec in project java-driver by datastax.

the class CachingCodecRegistry method createCodec.

// Try to create a codec when we haven't found it in the cache
@NonNull
protected TypeCodec<?> createCodec(@Nullable DataType cqlType, @Nullable GenericType<?> javaType, boolean isJavaCovariant) {
    LOG.trace("[{}] Cache miss, creating codec", logPrefix);
    // Either type can be null, but not both.
    if (javaType == null) {
        assert cqlType != null;
        return createCodec(cqlType);
    } else if (cqlType == null) {
        return createCodec(javaType, isJavaCovariant);
    } else {
        // Both non-null
        TypeToken<?> token = javaType.__getToken();
        if (cqlType instanceof ListType && List.class.isAssignableFrom(token.getRawType())) {
            DataType elementCqlType = ((ListType) cqlType).getElementType();
            TypeCodec<Object> elementCodec;
            if (token.getType() instanceof ParameterizedType) {
                Type[] typeArguments = ((ParameterizedType) token.getType()).getActualTypeArguments();
                GenericType<?> elementJavaType = GenericType.of(typeArguments[0]);
                elementCodec = uncheckedCast(codecFor(elementCqlType, elementJavaType, isJavaCovariant));
            } else {
                elementCodec = codecFor(elementCqlType);
            }
            return TypeCodecs.listOf(elementCodec);
        } else if (cqlType instanceof SetType && Set.class.isAssignableFrom(token.getRawType())) {
            DataType elementCqlType = ((SetType) cqlType).getElementType();
            TypeCodec<Object> elementCodec;
            if (token.getType() instanceof ParameterizedType) {
                Type[] typeArguments = ((ParameterizedType) token.getType()).getActualTypeArguments();
                GenericType<?> elementJavaType = GenericType.of(typeArguments[0]);
                elementCodec = uncheckedCast(codecFor(elementCqlType, elementJavaType, isJavaCovariant));
            } else {
                elementCodec = codecFor(elementCqlType);
            }
            return TypeCodecs.setOf(elementCodec);
        } else if (cqlType instanceof MapType && Map.class.isAssignableFrom(token.getRawType())) {
            DataType keyCqlType = ((MapType) cqlType).getKeyType();
            DataType valueCqlType = ((MapType) cqlType).getValueType();
            TypeCodec<Object> keyCodec;
            TypeCodec<Object> valueCodec;
            if (token.getType() instanceof ParameterizedType) {
                Type[] typeArguments = ((ParameterizedType) token.getType()).getActualTypeArguments();
                GenericType<?> keyJavaType = GenericType.of(typeArguments[0]);
                GenericType<?> valueJavaType = GenericType.of(typeArguments[1]);
                keyCodec = uncheckedCast(codecFor(keyCqlType, keyJavaType, isJavaCovariant));
                valueCodec = uncheckedCast(codecFor(valueCqlType, valueJavaType, isJavaCovariant));
            } else {
                keyCodec = codecFor(keyCqlType);
                valueCodec = codecFor(valueCqlType);
            }
            return TypeCodecs.mapOf(keyCodec, valueCodec);
        } else if (cqlType instanceof TupleType && TupleValue.class.isAssignableFrom(token.getRawType())) {
            return TypeCodecs.tupleOf((TupleType) cqlType);
        } else if (cqlType instanceof UserDefinedType && UdtValue.class.isAssignableFrom(token.getRawType())) {
            return TypeCodecs.udtOf((UserDefinedType) cqlType);
        } else if (cqlType instanceof CustomType && ByteBuffer.class.isAssignableFrom(token.getRawType())) {
            return TypeCodecs.custom(cqlType);
        }
        throw new CodecNotFoundException(cqlType, javaType);
    }
}
Also used : CustomType(com.datastax.oss.driver.api.core.type.CustomType) GenericType(com.datastax.oss.driver.api.core.type.reflect.GenericType) Set(java.util.Set) TypeCodec(com.datastax.oss.driver.api.core.type.codec.TypeCodec) UserDefinedType(com.datastax.oss.driver.api.core.type.UserDefinedType) ByteBuffer(java.nio.ByteBuffer) MapType(com.datastax.oss.driver.api.core.type.MapType) TupleValue(com.datastax.oss.driver.api.core.data.TupleValue) ParameterizedType(java.lang.reflect.ParameterizedType) ListType(com.datastax.oss.driver.api.core.type.ListType) GenericType(com.datastax.oss.driver.api.core.type.reflect.GenericType) MapType(com.datastax.oss.driver.api.core.type.MapType) TupleType(com.datastax.oss.driver.api.core.type.TupleType) DataType(com.datastax.oss.driver.api.core.type.DataType) UserDefinedType(com.datastax.oss.driver.api.core.type.UserDefinedType) ParameterizedType(java.lang.reflect.ParameterizedType) Type(java.lang.reflect.Type) SetType(com.datastax.oss.driver.api.core.type.SetType) CustomType(com.datastax.oss.driver.api.core.type.CustomType) SetType(com.datastax.oss.driver.api.core.type.SetType) TypeToken(com.datastax.oss.driver.shaded.guava.common.reflect.TypeToken) ListType(com.datastax.oss.driver.api.core.type.ListType) TupleType(com.datastax.oss.driver.api.core.type.TupleType) DataType(com.datastax.oss.driver.api.core.type.DataType) CodecNotFoundException(com.datastax.oss.driver.api.core.type.codec.CodecNotFoundException) NonNull(edu.umd.cs.findbugs.annotations.NonNull)

Example 5 with TypeCodec

use of com.datastax.oss.driver.api.core.type.codec.TypeCodec in project java-driver by datastax.

the class CodecRegistryIT method should_register_and_use_custom_codec_for_user_defined_type.

@Test
public void should_register_and_use_custom_codec_for_user_defined_type() {
    Map<String, Coordinates> coordinatesMap = ImmutableMap.of("home", new Coordinates(12, 34));
    GenericType<Map<String, Coordinates>> coordinatesMapType = GenericType.mapOf(String.class, Coordinates.class);
    // Still create a separate session because we don't want to interfere with other tests
    try (CqlSession session = SessionUtils.newSession(CCM_RULE, SESSION_RULE.keyspace())) {
        // register the mapping codec for UDT coordinates
        UserDefinedType coordinatesUdt = session.getMetadata().getKeyspace(SESSION_RULE.keyspace()).flatMap(ks -> ks.getUserDefinedType("coordinates")).orElseThrow(IllegalStateException::new);
        MutableCodecRegistry codecRegistry = (MutableCodecRegistry) session.getContext().getCodecRegistry();
        // Retrieve the inner codec
        TypeCodec<UdtValue> innerCodec = codecRegistry.codecFor(coordinatesUdt);
        assertThat(innerCodec).isInstanceOf(UdtCodec.class);
        // Create the "outer" codec and register it
        CoordinatesCodec coordinatesCodec = new CoordinatesCodec(innerCodec);
        codecRegistry.register(coordinatesCodec);
        // Test that the codec will be used to create on-the-fly codecs
        assertThat(codecRegistry.codecFor(Coordinates.class)).isSameAs(coordinatesCodec);
        assertThat(codecRegistry.codecFor(coordinatesMapType).accepts(coordinatesMap)).isTrue();
        // test insertion
        PreparedStatement prepared = session.prepare("INSERT INTO test3 (k0, k1, v) values (?, ?, ?)");
        BoundStatement insert = prepared.boundStatementBuilder().setString(0, name.getMethodName()).setInt(1, 0).set(2, coordinatesMap, // use java type so has to be looked up in registry.
        coordinatesMapType).build();
        session.execute(insert);
        // test retrieval
        ResultSet result = session.execute(SimpleStatement.builder("SELECT v from test3 where k0 = ? AND k1 = ?").addPositionalValues(name.getMethodName(), 0).build());
        List<Row> rows = result.all();
        assertThat(rows).hasSize(1);
        Row row = rows.get(0);
        assertThat(row.get(0, coordinatesMapType)).isEqualTo(coordinatesMap);
        assertThat(row.getMap(0, String.class, Coordinates.class)).isEqualTo(coordinatesMap);
    }
}
Also used : Maps(org.assertj.core.util.Maps) BeforeClass(org.junit.BeforeClass) MappingCodec(com.datastax.oss.driver.api.core.type.codec.MappingCodec) TestRule(org.junit.rules.TestRule) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) GenericType(com.datastax.oss.driver.api.core.type.reflect.GenericType) CcmRule(com.datastax.oss.driver.api.testinfra.ccm.CcmRule) HashMap(java.util.HashMap) SimpleStatement(com.datastax.oss.driver.api.core.cql.SimpleStatement) ParallelizableTests(com.datastax.oss.driver.categories.ParallelizableTests) ByteBuffer(java.nio.ByteBuffer) CqlSession(com.datastax.oss.driver.api.core.CqlSession) TestName(org.junit.rules.TestName) NonNull(edu.umd.cs.findbugs.annotations.NonNull) Map(java.util.Map) Assertions.catchThrowable(org.assertj.core.api.Assertions.catchThrowable) ClassRule(org.junit.ClassRule) ProtocolVersion(com.datastax.oss.driver.api.core.ProtocolVersion) Row(com.datastax.oss.driver.api.core.cql.Row) OptionalCodec(com.datastax.oss.driver.internal.core.type.codec.extras.OptionalCodec) Iterator(java.util.Iterator) ResultSet(com.datastax.oss.driver.api.core.cql.ResultSet) ImmutableMap(com.google.common.collect.ImmutableMap) SessionUtils(com.datastax.oss.driver.api.testinfra.session.SessionUtils) DataType(com.datastax.oss.driver.api.core.type.DataType) BoundStatement(com.datastax.oss.driver.api.core.cql.BoundStatement) Test(org.junit.Test) PreparedStatement(com.datastax.oss.driver.api.core.cql.PreparedStatement) Category(org.junit.experimental.categories.Category) UdtValue(com.datastax.oss.driver.api.core.data.UdtValue) TypeCodecs(com.datastax.oss.driver.api.core.type.codec.TypeCodecs) SessionRule(com.datastax.oss.driver.api.testinfra.session.SessionRule) Objects(java.util.Objects) RuleChain(org.junit.rules.RuleChain) UserDefinedType(com.datastax.oss.driver.api.core.type.UserDefinedType) DataTypes(com.datastax.oss.driver.api.core.type.DataTypes) List(java.util.List) Rule(org.junit.Rule) CodecNotFoundException(com.datastax.oss.driver.api.core.type.codec.CodecNotFoundException) UdtCodec(com.datastax.oss.driver.internal.core.type.codec.UdtCodec) TypeCodec(com.datastax.oss.driver.api.core.type.codec.TypeCodec) Nullable(edu.umd.cs.findbugs.annotations.Nullable) Optional(java.util.Optional) MutableCodecRegistry(com.datastax.oss.driver.api.core.type.codec.registry.MutableCodecRegistry) IntCodec(com.datastax.oss.driver.internal.core.type.codec.IntCodec) UdtValue(com.datastax.oss.driver.api.core.data.UdtValue) UserDefinedType(com.datastax.oss.driver.api.core.type.UserDefinedType) PreparedStatement(com.datastax.oss.driver.api.core.cql.PreparedStatement) CqlSession(com.datastax.oss.driver.api.core.CqlSession) MutableCodecRegistry(com.datastax.oss.driver.api.core.type.codec.registry.MutableCodecRegistry) ResultSet(com.datastax.oss.driver.api.core.cql.ResultSet) Row(com.datastax.oss.driver.api.core.cql.Row) HashMap(java.util.HashMap) Map(java.util.Map) ImmutableMap(com.google.common.collect.ImmutableMap) BoundStatement(com.datastax.oss.driver.api.core.cql.BoundStatement) Test(org.junit.Test)

Aggregations

TypeCodec (com.datastax.oss.driver.api.core.type.codec.TypeCodec)5 DataType (com.datastax.oss.driver.api.core.type.DataType)3 UserDefinedType (com.datastax.oss.driver.api.core.type.UserDefinedType)3 CodecNotFoundException (com.datastax.oss.driver.api.core.type.codec.CodecNotFoundException)3 NonNull (edu.umd.cs.findbugs.annotations.NonNull)3 Map (java.util.Map)3 CqlIdentifier (com.datastax.oss.driver.api.core.CqlIdentifier)2 CustomType (com.datastax.oss.driver.api.core.type.CustomType)2 ListType (com.datastax.oss.driver.api.core.type.ListType)2 MapType (com.datastax.oss.driver.api.core.type.MapType)2 SetType (com.datastax.oss.driver.api.core.type.SetType)2 TupleType (com.datastax.oss.driver.api.core.type.TupleType)2 GenericType (com.datastax.oss.driver.api.core.type.reflect.GenericType)2 ImmutableMap (com.datastax.oss.driver.shaded.guava.common.collect.ImmutableMap)2 ByteBuffer (java.nio.ByteBuffer)2 CqlSession (com.datastax.oss.driver.api.core.CqlSession)1 ProtocolVersion (com.datastax.oss.driver.api.core.ProtocolVersion)1 BoundStatement (com.datastax.oss.driver.api.core.cql.BoundStatement)1 PreparedStatement (com.datastax.oss.driver.api.core.cql.PreparedStatement)1 ResultSet (com.datastax.oss.driver.api.core.cql.ResultSet)1