Search in sources :

Example 1 with GenericType

use of com.datastax.oss.driver.api.core.type.reflect.GenericType in project java-driver by datastax.

the class GeometryIT method should_insert_as_field_in_udt.

/**
 * Validates that a geometry value can be inserted as a field in a UDT and verifies that the UDT
 * is stored correctly by retrieving it and ensuring it matches.
 */
@Test
@Ignore
public void should_insert_as_field_in_udt() {
    UUID key = Uuids.random();
    UserDefinedType udtType = sessionRule.session().getMetadata().getKeyspace(sessionRule.session().getKeyspace().orElseThrow(AssertionError::new)).flatMap(ks -> ks.getUserDefinedType(CqlIdentifier.fromInternal("udt1"))).orElseThrow(AssertionError::new);
    assertThat(udtType).isNotNull();
    UdtValue value = udtType.newValue();
    value = value.set("g", sampleData.get(0), genericType);
    PreparedStatement prepared = sessionRule.session().prepare("INSERT INTO tbl (k, u) values (?, ?)");
    BoundStatement bs = prepared.boundStatementBuilder().setUuid(0, key).setUdtValue(1, value).build();
    sessionRule.session().execute(bs);
    ResultSet rs = sessionRule.session().execute(SimpleStatement.builder("SELECT k,u FROM tbl where k=?").addPositionalValues(key).build());
    Row row = rs.iterator().next();
    assertThat(row.getUuid("k")).isEqualTo(key);
    assertThat(row.getUdtValue("u")).isEqualTo(value);
    assertThat(row.getUdtValue(1)).isEqualTo(value);
}
Also used : BatchStatementBuilder(com.datastax.oss.driver.api.core.cql.BatchStatementBuilder) CqlIdentifier(com.datastax.oss.driver.api.core.CqlIdentifier) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) GenericType(com.datastax.oss.driver.api.core.type.reflect.GenericType) SimpleStatement(com.datastax.oss.driver.api.core.cql.SimpleStatement) ParallelizableTests(com.datastax.oss.driver.categories.ParallelizableTests) ImmutableMap(com.datastax.oss.driver.shaded.guava.common.collect.ImmutableMap) CqlSession(com.datastax.oss.driver.api.core.CqlSession) Uuids(com.datastax.oss.driver.api.core.uuid.Uuids) Map(java.util.Map) Row(com.datastax.oss.driver.api.core.cql.Row) DefaultBatchType(com.datastax.oss.driver.api.core.cql.DefaultBatchType) Sets(com.datastax.oss.driver.shaded.guava.common.collect.Sets) ResultSet(com.datastax.oss.driver.api.core.cql.ResultSet) TupleType(com.datastax.oss.driver.api.core.type.TupleType) Preconditions(org.assertj.core.util.Preconditions) Set(java.util.Set) BoundStatement(com.datastax.oss.driver.api.core.cql.BoundStatement) TupleValue(com.datastax.oss.driver.api.core.data.TupleValue) Test(org.junit.Test) UUID(java.util.UUID) BatchStatement(com.datastax.oss.driver.api.core.cql.BatchStatement) PreparedStatement(com.datastax.oss.driver.api.core.cql.PreparedStatement) Category(org.junit.experimental.categories.Category) UdtValue(com.datastax.oss.driver.api.core.data.UdtValue) SessionRule(com.datastax.oss.driver.api.testinfra.session.SessionRule) UserDefinedType(com.datastax.oss.driver.api.core.type.UserDefinedType) List(java.util.List) Ignore(org.junit.Ignore) TypeCodec(com.datastax.oss.driver.api.core.type.codec.TypeCodec) UdtValue(com.datastax.oss.driver.api.core.data.UdtValue) ResultSet(com.datastax.oss.driver.api.core.cql.ResultSet) UserDefinedType(com.datastax.oss.driver.api.core.type.UserDefinedType) PreparedStatement(com.datastax.oss.driver.api.core.cql.PreparedStatement) Row(com.datastax.oss.driver.api.core.cql.Row) UUID(java.util.UUID) BoundStatement(com.datastax.oss.driver.api.core.cql.BoundStatement) Ignore(org.junit.Ignore) Test(org.junit.Test)

Example 2 with GenericType

use of com.datastax.oss.driver.api.core.type.reflect.GenericType in project java-driver by datastax.

the class EntityHelperBaseTest method should_throw_if_there_is_not_matching_cql_column.

@Test
public void should_throw_if_there_is_not_matching_cql_column() {
    // given
    ImmutableMap<CqlIdentifier, GenericType<?>> entityColumns = ImmutableMap.of(CqlIdentifier.fromCql("c1"), GenericType.of(Integer.class));
    ColumnMetadata columnMetadataInt = mock(ColumnMetadata.class);
    when(columnMetadataInt.getType()).thenReturn(DataTypes.INT);
    ImmutableMap<CqlIdentifier, ColumnMetadata> cqlColumns = ImmutableMap.of(CqlIdentifier.fromCql("c2"), columnMetadataInt);
    // when, then
    assertThatThrownBy(() -> EntityHelperBase.findTypeMismatches(entityColumns, cqlColumns, CodecRegistry.DEFAULT)).isInstanceOf(AssertionError.class).hasMessageContaining("There is no cql column for entity column: c1");
}
Also used : GenericType(com.datastax.oss.driver.api.core.type.reflect.GenericType) ColumnMetadata(com.datastax.oss.driver.api.core.metadata.schema.ColumnMetadata) CqlIdentifier(com.datastax.oss.driver.api.core.CqlIdentifier) Test(org.junit.Test)

Example 3 with GenericType

use of com.datastax.oss.driver.api.core.type.reflect.GenericType 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 4 with GenericType

use of com.datastax.oss.driver.api.core.type.reflect.GenericType 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

GenericType (com.datastax.oss.driver.api.core.type.reflect.GenericType)4 UserDefinedType (com.datastax.oss.driver.api.core.type.UserDefinedType)3 TypeCodec (com.datastax.oss.driver.api.core.type.codec.TypeCodec)3 Test (org.junit.Test)3 CqlIdentifier (com.datastax.oss.driver.api.core.CqlIdentifier)2 CqlSession (com.datastax.oss.driver.api.core.CqlSession)2 BoundStatement (com.datastax.oss.driver.api.core.cql.BoundStatement)2 PreparedStatement (com.datastax.oss.driver.api.core.cql.PreparedStatement)2 ResultSet (com.datastax.oss.driver.api.core.cql.ResultSet)2 Row (com.datastax.oss.driver.api.core.cql.Row)2 SimpleStatement (com.datastax.oss.driver.api.core.cql.SimpleStatement)2 TupleValue (com.datastax.oss.driver.api.core.data.TupleValue)2 UdtValue (com.datastax.oss.driver.api.core.data.UdtValue)2 DataType (com.datastax.oss.driver.api.core.type.DataType)2 TupleType (com.datastax.oss.driver.api.core.type.TupleType)2 CodecNotFoundException (com.datastax.oss.driver.api.core.type.codec.CodecNotFoundException)2 SessionRule (com.datastax.oss.driver.api.testinfra.session.SessionRule)2 ParallelizableTests (com.datastax.oss.driver.categories.ParallelizableTests)2 NonNull (edu.umd.cs.findbugs.annotations.NonNull)2 ByteBuffer (java.nio.ByteBuffer)2