MartijnVisser commented on code in PR #53: URL: https://github.com/apache/flink-connector-cassandra/pull/53#discussion_r4694567118
########## flink-connector-cassandra/src/main/java/org/apache/flink/connector/cassandra/mapper/PojoMapper.java: ########## @@ -0,0 +1,563 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.flink.connector.cassandra.mapper; + +import org.apache.flink.annotation.Internal; +import org.apache.flink.connector.cassandra.CassandraMapperOptions; +import org.apache.flink.util.FlinkRuntimeException; +import org.apache.flink.util.Preconditions; + +import com.datastax.oss.driver.api.core.CqlIdentifier; +import com.datastax.oss.driver.api.core.cql.BoundStatement; +import com.datastax.oss.driver.api.core.cql.BoundStatementBuilder; +import com.datastax.oss.driver.api.core.cql.PreparedStatement; +import com.datastax.oss.driver.api.core.cql.Row; +import com.datastax.oss.driver.api.core.cql.SimpleStatement; +import com.datastax.oss.driver.api.core.data.GettableById; +import com.datastax.oss.driver.api.core.data.UdtValue; +import com.datastax.oss.driver.api.core.type.DataType; +import com.datastax.oss.driver.api.core.type.UserDefinedType; +import com.datastax.oss.driver.api.core.type.reflect.GenericType; +import com.datastax.oss.driver.api.mapper.annotations.Computed; +import com.datastax.oss.driver.api.mapper.annotations.CqlName; +import com.datastax.oss.driver.api.mapper.annotations.Entity; +import com.datastax.oss.driver.api.mapper.annotations.HierarchyScanStrategy; +import com.datastax.oss.driver.api.mapper.annotations.NamingStrategy; +import com.datastax.oss.driver.api.mapper.annotations.PropertyStrategy; +import com.datastax.oss.driver.api.mapper.annotations.Transient; +import com.datastax.oss.driver.api.mapper.annotations.TransientProperties; +import com.datastax.oss.driver.api.mapper.entity.naming.NameConverter; +import com.datastax.oss.driver.api.mapper.entity.naming.NamingConvention; +import com.datastax.oss.driver.api.querybuilder.QueryBuilder; +import com.datastax.oss.driver.api.querybuilder.insert.Insert; +import com.datastax.oss.driver.api.querybuilder.insert.InsertInto; +import com.datastax.oss.driver.api.querybuilder.insert.RegularInsert; + +import javax.annotation.Nullable; + +import java.beans.IntrospectionException; +import java.beans.Introspector; +import java.beans.PropertyDescriptor; +import java.lang.annotation.Annotation; +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.lang.reflect.ParameterizedType; +import java.lang.reflect.Type; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.function.Predicate; +import java.util.stream.Collectors; + +/** + * Maps POJOs annotated with {@link Entity} to and from Cassandra at runtime. + * + * <p>The mapper of the Cassandra driver generates its code with an annotation processor at compile + * time, so it cannot map a class that is only known at runtime. This class supports the subset of + * the driver mapper annotations that the connector needs: {@link Entity}, {@link CqlName}, {@link + * NamingStrategy}, {@link Transient}, {@link TransientProperties} and {@link Computed}. A property + * whose type is itself annotated with {@link Entity} is mapped to a user defined type. + * + * @param <T> the type of the mapped POJO + */ +@Internal +public final class PojoMapper<T> { + + private final Class<T> pojoClass; + @Nullable private final CqlIdentifier keyspace; + private final CqlIdentifier table; + private final List<Property> properties; + private final List<Property> writableProperties; + + private PojoMapper( + Class<T> pojoClass, + @Nullable CqlIdentifier keyspace, + CqlIdentifier table, + List<Property> properties) { + this.pojoClass = pojoClass; + this.keyspace = keyspace; + this.table = table; + this.properties = properties; + this.writableProperties = + properties.stream().filter(p -> !p.computed).collect(Collectors.toList()); + } + + /** + * Creates the mapper of a class annotated with {@link Entity}. + * + * @param pojoClass the class to map + * @param <T> the type of the mapped POJO + * @return the mapper + */ + public static <T> PojoMapper<T> create(Class<T> pojoClass) { + return create(pojoClass, new HashSet<>()); + } + + private static <T> PojoMapper<T> create(Class<T> pojoClass, Set<Class<?>> visiting) { + Preconditions.checkNotNull(pojoClass, "The POJO class must not be null."); + final Entity entity = pojoClass.getAnnotation(Entity.class); + Preconditions.checkArgument( + entity != null, + "%s must be annotated with %s.", + pojoClass.getName(), + Entity.class.getName()); + Preconditions.checkArgument( + visiting.add(pojoClass), + "%s references itself, recursive entities are not supported.", + pojoClass.getName()); + + checkNoUnsupportedAnnotation(pojoClass, pojoClass.getAnnotations()); + final NameConverter nameConverter = createNameConverter(pojoClass); + final CqlName tableName = pojoClass.getAnnotation(CqlName.class); + final CqlIdentifier table = + CqlIdentifier.fromCql( + tableName != null + ? tableName.value() + : nameConverter.toCassandraName( + Introspector.decapitalize(pojoClass.getSimpleName()))); + final CqlIdentifier keyspace = + entity.defaultKeyspace().isEmpty() + ? null + : CqlIdentifier.fromCql(entity.defaultKeyspace()); + + final TransientProperties transientProperties = + pojoClass.getAnnotation(TransientProperties.class); + final Set<String> transientNames = + transientProperties == null + ? new HashSet<>() + : new HashSet<>(Arrays.asList(transientProperties.value())); + + final List<Property> properties = new ArrayList<>(); + for (PropertyDescriptor descriptor : getPropertyDescriptors(pojoClass)) { Review Comment: The driver's annotation processor maps 7 of 19 test entities differently: `Boolean isX()` and protected getters are dropped, and `@CqlName`, `@Transient`, `@NamingStrategy` and `@TransientProperties` on a superclass or interface are ignored. On reads that leaves fields unset without an error. Can the scan follow the processor, with it as the oracle in `PojoMapperTest`? ########## flink-connector-cassandra/src/main/java/org/apache/flink/connector/cassandra/source/CassandraSource.java: ########## @@ -190,35 +191,41 @@ public static CassandraSourceBuilder builder() { maxSplitMemorySize, MIN_SPLIT_MEMORY_SIZE); this.maxSplitMemorySize = maxSplitMemorySize; - final QueryValidator queryValidator = new QueryValidator(clusterBuilder); + final QueryValidator queryValidator = new QueryValidator(sessionBuilder); final Matcher queryMatcher = queryValidator.checkQueryValidity(query); this.query = query; this.keyspace = queryMatcher.group(1); this.table = queryMatcher.group(2); - this.clusterBuilder = clusterBuilder; - ClosureCleaner.clean(clusterBuilder, ExecutionConfig.ClosureCleanerLevel.RECURSIVE, true); + this.sessionBuilder = sessionBuilder; + ClosureCleaner.clean(sessionBuilder, ExecutionConfig.ClosureCleanerLevel.RECURSIVE, true); this.rowToTypeConverter = rowToTypeConverter; } /** @deprecated Use {@link #builder()} instead. */ @Deprecated Review Comment: These signatures change anyway, so I'd drop the deprecated constructors in 4.0 instead of porting them. ########## flink-connector-cassandra/src/main/java/org/apache/flink/connector/cassandra/mapper/PojoMapper.java: ########## @@ -0,0 +1,563 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.flink.connector.cassandra.mapper; + +import org.apache.flink.annotation.Internal; +import org.apache.flink.connector.cassandra.CassandraMapperOptions; +import org.apache.flink.util.FlinkRuntimeException; +import org.apache.flink.util.Preconditions; + +import com.datastax.oss.driver.api.core.CqlIdentifier; +import com.datastax.oss.driver.api.core.cql.BoundStatement; +import com.datastax.oss.driver.api.core.cql.BoundStatementBuilder; +import com.datastax.oss.driver.api.core.cql.PreparedStatement; +import com.datastax.oss.driver.api.core.cql.Row; +import com.datastax.oss.driver.api.core.cql.SimpleStatement; +import com.datastax.oss.driver.api.core.data.GettableById; +import com.datastax.oss.driver.api.core.data.UdtValue; +import com.datastax.oss.driver.api.core.type.DataType; +import com.datastax.oss.driver.api.core.type.UserDefinedType; +import com.datastax.oss.driver.api.core.type.reflect.GenericType; +import com.datastax.oss.driver.api.mapper.annotations.Computed; +import com.datastax.oss.driver.api.mapper.annotations.CqlName; +import com.datastax.oss.driver.api.mapper.annotations.Entity; +import com.datastax.oss.driver.api.mapper.annotations.HierarchyScanStrategy; +import com.datastax.oss.driver.api.mapper.annotations.NamingStrategy; +import com.datastax.oss.driver.api.mapper.annotations.PropertyStrategy; +import com.datastax.oss.driver.api.mapper.annotations.Transient; +import com.datastax.oss.driver.api.mapper.annotations.TransientProperties; +import com.datastax.oss.driver.api.mapper.entity.naming.NameConverter; +import com.datastax.oss.driver.api.mapper.entity.naming.NamingConvention; +import com.datastax.oss.driver.api.querybuilder.QueryBuilder; +import com.datastax.oss.driver.api.querybuilder.insert.Insert; +import com.datastax.oss.driver.api.querybuilder.insert.InsertInto; +import com.datastax.oss.driver.api.querybuilder.insert.RegularInsert; + +import javax.annotation.Nullable; + +import java.beans.IntrospectionException; +import java.beans.Introspector; +import java.beans.PropertyDescriptor; +import java.lang.annotation.Annotation; +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.lang.reflect.ParameterizedType; +import java.lang.reflect.Type; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.function.Predicate; +import java.util.stream.Collectors; + +/** + * Maps POJOs annotated with {@link Entity} to and from Cassandra at runtime. + * + * <p>The mapper of the Cassandra driver generates its code with an annotation processor at compile + * time, so it cannot map a class that is only known at runtime. This class supports the subset of + * the driver mapper annotations that the connector needs: {@link Entity}, {@link CqlName}, {@link + * NamingStrategy}, {@link Transient}, {@link TransientProperties} and {@link Computed}. A property + * whose type is itself annotated with {@link Entity} is mapped to a user defined type. + * + * @param <T> the type of the mapped POJO + */ +@Internal +public final class PojoMapper<T> { + + private final Class<T> pojoClass; + @Nullable private final CqlIdentifier keyspace; + private final CqlIdentifier table; + private final List<Property> properties; + private final List<Property> writableProperties; + + private PojoMapper( + Class<T> pojoClass, + @Nullable CqlIdentifier keyspace, + CqlIdentifier table, + List<Property> properties) { + this.pojoClass = pojoClass; + this.keyspace = keyspace; + this.table = table; + this.properties = properties; + this.writableProperties = + properties.stream().filter(p -> !p.computed).collect(Collectors.toList()); + } + + /** + * Creates the mapper of a class annotated with {@link Entity}. + * + * @param pojoClass the class to map + * @param <T> the type of the mapped POJO + * @return the mapper + */ + public static <T> PojoMapper<T> create(Class<T> pojoClass) { + return create(pojoClass, new HashSet<>()); + } + + private static <T> PojoMapper<T> create(Class<T> pojoClass, Set<Class<?>> visiting) { + Preconditions.checkNotNull(pojoClass, "The POJO class must not be null."); + final Entity entity = pojoClass.getAnnotation(Entity.class); + Preconditions.checkArgument( + entity != null, + "%s must be annotated with %s.", + pojoClass.getName(), + Entity.class.getName()); + Preconditions.checkArgument( + visiting.add(pojoClass), + "%s references itself, recursive entities are not supported.", + pojoClass.getName()); + + checkNoUnsupportedAnnotation(pojoClass, pojoClass.getAnnotations()); + final NameConverter nameConverter = createNameConverter(pojoClass); + final CqlName tableName = pojoClass.getAnnotation(CqlName.class); + final CqlIdentifier table = + CqlIdentifier.fromCql( + tableName != null + ? tableName.value() + : nameConverter.toCassandraName( + Introspector.decapitalize(pojoClass.getSimpleName()))); + final CqlIdentifier keyspace = + entity.defaultKeyspace().isEmpty() + ? null + : CqlIdentifier.fromCql(entity.defaultKeyspace()); + + final TransientProperties transientProperties = + pojoClass.getAnnotation(TransientProperties.class); + final Set<String> transientNames = + transientProperties == null + ? new HashSet<>() + : new HashSet<>(Arrays.asList(transientProperties.value())); + + final List<Property> properties = new ArrayList<>(); + for (PropertyDescriptor descriptor : getPropertyDescriptors(pojoClass)) { + final Method getter = descriptor.getReadMethod(); + final Method setter = descriptor.getWriteMethod(); + if (getter == null || getter.getDeclaringClass() == Object.class) { + continue; + } + final String name = descriptor.getName(); + final Field field = findField(pojoClass, name); + checkNoUnsupportedAnnotation(pojoClass, getter.getAnnotations()); Review Comment: Only the class-level check is tested, `PojoMapperTest` stays green with the getter, setter and field checks removed. ########## docs/content/docs/connectors/datastream/cassandra.md: ########## @@ -140,6 +143,100 @@ With checkpointing enabled, Cassandra Sink guarantees at-least-once delivery of More details on [checkpoints docs]({{< ref "docs/dev/datastream/fault-tolerance/checkpointing" >}}) and [fault tolerance guarantee docs]({{< ref "docs/connectors/datastream/guarantees" >}}) +## Connecting to Cassandra + +The sources and the sinks create their connection with a `CassandraSessionBuilder`. Its `buildSession` method +receives the `CqlSessionBuilder` of the driver and returns the `CqlSession`: + +```java +CassandraSessionBuilder sessionBuilder = new CassandraSessionBuilder() { + @Override + protected CqlSession buildSession(CqlSessionBuilder builder) { + return builder.addContactPoint(new InetSocketAddress("127.0.0.1", 9042)) + .withLocalDatacenter("datacenter1") + .withAuthCredentials("user", "password") + .build(); + } +}; +``` + +The driver requires the local datacenter when contact points are set, it only sends requests to the nodes of this +datacenter. `CassandraSink#setHost` and the SQL connector infer the datacenter from the contact points when +`setLocalDatacenter` or the `local-datacenter` option is not set. + +### Driver configuration + +All the options of the driver (timeouts, consistency levels, execution profiles, load balancing, retries, +address translation, request throttling, SSL, ...) are described in the +[configuration manual](https://apache.github.io/cassandra-java-driver/4.19.0/core/configuration/) of the driver. They can be set in several ways: + +* programmatically in `buildSession`, with `builder.withConfigLoader(DriverConfigLoader.programmaticBuilder()...build())`, +* with an `application.conf` file in the classpath of the job, +* with system properties prefixed by `datastax-java-driver.`, +* for the SQL connector, with table options prefixed by `driver.`, for example `'driver.basic.request.page-size' = '1000'`. + Options whose value is a list cannot be set this way. + +The metrics of the driver are disabled by default and are not integrated with Flink metrics. + +### Connecting to a cloud database + +A cloud database such as [**DataStax Astra**](https://docs.datastax.com/en/astra-db-serverless/index.html) is reached with its secure connect bundle, which contains the contact +points, the local datacenter and the certificates of the database. The bundle is set with +`builder.withCloudSecureConnectBundle(...)` in `buildSession`, or with the `secure-connect-bundle` option of the +SQL connector, as a path of the local filesystem or a URL. It must be accessible from all the nodes of the Flink cluster. + +```java +CassandraSessionBuilder sessionBuilder = new CassandraSessionBuilder() { + @Override + protected CqlSession buildSession(CqlSessionBuilder builder) { + return builder.withCloudSecureConnectBundle(Paths.get("/path/to/secure-connect-database_name.zip")) + .withAuthCredentials("token", "AstraCS:redacted") + .build(); + } +}; +``` + +When a bundle is provided, the contact points and the local datacenter are ignored, including the `hosts`, `port` and +`local-datacenter` options of the SQL connector. The SSL connection is configured from the bundle and the default +consistency level of the driver becomes `LOCAL_QUORUM`. + +## Mapping POJOs + +The POJO source, the POJO sink and the POJO input and output formats map classes annotated with the +[mapper annotations](https://apache.github.io/cassandra-java-driver/4.19.0/mapper/entities/) of the driver. The connector maps the classes at runtime, +the annotation processor of the driver mapper is not needed. The following annotations are supported: + +* `@Entity` is required on the class, `defaultKeyspace` sets the keyspace of the table. +* `@CqlName` sets the name of the table on the class and the name of a column on a field or a getter. +* `@NamingStrategy` sets how the names without `@CqlName` are derived from the Java names. By default, + they are converted to snake case, for example the property `batchId` is mapped to the column `batch_id`. +* `@Transient` and `@TransientProperties` exclude properties. +* `@Computed` marks a property that is read but never written. + +The class must have a public no-argument constructor and each mapped property needs a getter and a setter. +A property whose type is itself annotated with `@Entity` is mapped to a user defined type, collections of +such types are not supported. Custom codecs are registered in `buildSession` with `builder.addTypeCodecs(...)`. + +## Migrating from the version 3 of the driver + +The versions of the connector up to 3.x use the version 3 of the driver, which has a different API. +The following changes are needed when upgrading: + +* `ClusterBuilder#buildCluster(Cluster.Builder)` is replaced by `CassandraSessionBuilder#buildSession(CqlSessionBuilder)` + and `setClusterBuilder` by `setSessionBuilder`. The SQL option `cluster-builder-class` is renamed to `session-builder-class`. +* The local datacenter has to be set when contact points are set, see [Connecting to Cassandra](#connecting-to-cassandra). +* `MapperOptions` and `SimpleMapperOptions` are replaced by `CassandraMapperOptions`. +* The mapper annotations `@Table` and `@Column` are replaced by `@Entity` and `@CqlName`. A column without `@CqlName` + is now named after the property converted to snake case. +* CQL `date`, `time` and `timestamp` are mapped to `java.time.LocalDate`, `java.time.LocalTime` and `java.time.Instant`, + see [temporal types](https://apache.github.io/cassandra-java-driver/4.19.0/core/temporal_types/). `java.util.Date` is still supported for `timestamp` columns. + Tuples read with `CassandraInputFormat` contain the `java.time` types. +* The request timeout of the driver, set by the SQL option `read-timeout`, now covers a request including its retries. Review Comment: `setHost` and custom builders go from driver 3's 12 s read timeout to a 2 s request timeout, I think that belongs here too. ########## flink-connector-cassandra/src/main/resources/META-INF/NOTICE: ########## @@ -6,6 +6,15 @@ The Apache Software Foundation (http://www.apache.org/). This project bundles the following dependencies under the Apache Software License 2.0. (http://www.apache.org/licenses/LICENSE-2.0.txt) -- com.datastax.cassandra:cassandra-driver-core:shaded:3.11.2 -- com.datastax.cassandra:cassandra-driver-mapping:3.11.2 -- com.google.guava:guava:19.0 +- com.datastax.oss:native-protocol:1.5.2 +- com.typesafe:config:1.4.1 +- io.dropwizard.metrics:metrics-core:4.1.18 +- org.apache.cassandra:java-driver-core-shaded:4.19.4 Review Comment: The shaded driver bundles relocated netty 4.1.138 and jackson 2.20.1, those need listing, and its BSD Protocol Buffers code needs `licenses/LICENSE.protobuf`. ########## flink-connector-cassandra/src/main/java/org/apache/flink/connector/cassandra/mapper/PojoMapper.java: ########## @@ -0,0 +1,563 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.flink.connector.cassandra.mapper; + +import org.apache.flink.annotation.Internal; +import org.apache.flink.connector.cassandra.CassandraMapperOptions; +import org.apache.flink.util.FlinkRuntimeException; +import org.apache.flink.util.Preconditions; + +import com.datastax.oss.driver.api.core.CqlIdentifier; +import com.datastax.oss.driver.api.core.cql.BoundStatement; +import com.datastax.oss.driver.api.core.cql.BoundStatementBuilder; +import com.datastax.oss.driver.api.core.cql.PreparedStatement; +import com.datastax.oss.driver.api.core.cql.Row; +import com.datastax.oss.driver.api.core.cql.SimpleStatement; +import com.datastax.oss.driver.api.core.data.GettableById; +import com.datastax.oss.driver.api.core.data.UdtValue; +import com.datastax.oss.driver.api.core.type.DataType; +import com.datastax.oss.driver.api.core.type.UserDefinedType; +import com.datastax.oss.driver.api.core.type.reflect.GenericType; +import com.datastax.oss.driver.api.mapper.annotations.Computed; +import com.datastax.oss.driver.api.mapper.annotations.CqlName; +import com.datastax.oss.driver.api.mapper.annotations.Entity; +import com.datastax.oss.driver.api.mapper.annotations.HierarchyScanStrategy; +import com.datastax.oss.driver.api.mapper.annotations.NamingStrategy; +import com.datastax.oss.driver.api.mapper.annotations.PropertyStrategy; +import com.datastax.oss.driver.api.mapper.annotations.Transient; +import com.datastax.oss.driver.api.mapper.annotations.TransientProperties; +import com.datastax.oss.driver.api.mapper.entity.naming.NameConverter; +import com.datastax.oss.driver.api.mapper.entity.naming.NamingConvention; +import com.datastax.oss.driver.api.querybuilder.QueryBuilder; +import com.datastax.oss.driver.api.querybuilder.insert.Insert; +import com.datastax.oss.driver.api.querybuilder.insert.InsertInto; +import com.datastax.oss.driver.api.querybuilder.insert.RegularInsert; + +import javax.annotation.Nullable; + +import java.beans.IntrospectionException; +import java.beans.Introspector; +import java.beans.PropertyDescriptor; +import java.lang.annotation.Annotation; +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.lang.reflect.ParameterizedType; +import java.lang.reflect.Type; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.function.Predicate; +import java.util.stream.Collectors; + +/** + * Maps POJOs annotated with {@link Entity} to and from Cassandra at runtime. + * + * <p>The mapper of the Cassandra driver generates its code with an annotation processor at compile + * time, so it cannot map a class that is only known at runtime. This class supports the subset of + * the driver mapper annotations that the connector needs: {@link Entity}, {@link CqlName}, {@link + * NamingStrategy}, {@link Transient}, {@link TransientProperties} and {@link Computed}. A property + * whose type is itself annotated with {@link Entity} is mapped to a user defined type. + * + * @param <T> the type of the mapped POJO + */ +@Internal +public final class PojoMapper<T> { + + private final Class<T> pojoClass; + @Nullable private final CqlIdentifier keyspace; + private final CqlIdentifier table; + private final List<Property> properties; + private final List<Property> writableProperties; + + private PojoMapper( + Class<T> pojoClass, + @Nullable CqlIdentifier keyspace, + CqlIdentifier table, + List<Property> properties) { + this.pojoClass = pojoClass; + this.keyspace = keyspace; + this.table = table; + this.properties = properties; + this.writableProperties = + properties.stream().filter(p -> !p.computed).collect(Collectors.toList()); + } + + /** + * Creates the mapper of a class annotated with {@link Entity}. + * + * @param pojoClass the class to map + * @param <T> the type of the mapped POJO + * @return the mapper + */ + public static <T> PojoMapper<T> create(Class<T> pojoClass) { + return create(pojoClass, new HashSet<>()); + } + + private static <T> PojoMapper<T> create(Class<T> pojoClass, Set<Class<?>> visiting) { + Preconditions.checkNotNull(pojoClass, "The POJO class must not be null."); + final Entity entity = pojoClass.getAnnotation(Entity.class); + Preconditions.checkArgument( + entity != null, + "%s must be annotated with %s.", + pojoClass.getName(), + Entity.class.getName()); + Preconditions.checkArgument( + visiting.add(pojoClass), + "%s references itself, recursive entities are not supported.", + pojoClass.getName()); + + checkNoUnsupportedAnnotation(pojoClass, pojoClass.getAnnotations()); + final NameConverter nameConverter = createNameConverter(pojoClass); + final CqlName tableName = pojoClass.getAnnotation(CqlName.class); + final CqlIdentifier table = + CqlIdentifier.fromCql( + tableName != null + ? tableName.value() + : nameConverter.toCassandraName( + Introspector.decapitalize(pojoClass.getSimpleName()))); + final CqlIdentifier keyspace = + entity.defaultKeyspace().isEmpty() + ? null + : CqlIdentifier.fromCql(entity.defaultKeyspace()); + + final TransientProperties transientProperties = + pojoClass.getAnnotation(TransientProperties.class); + final Set<String> transientNames = + transientProperties == null + ? new HashSet<>() + : new HashSet<>(Arrays.asList(transientProperties.value())); + + final List<Property> properties = new ArrayList<>(); + for (PropertyDescriptor descriptor : getPropertyDescriptors(pojoClass)) { + final Method getter = descriptor.getReadMethod(); + final Method setter = descriptor.getWriteMethod(); + if (getter == null || getter.getDeclaringClass() == Object.class) { + continue; + } + final String name = descriptor.getName(); + final Field field = findField(pojoClass, name); + checkNoUnsupportedAnnotation(pojoClass, getter.getAnnotations()); + if (setter != null) { + checkNoUnsupportedAnnotation(pojoClass, setter.getAnnotations()); + } + if (field != null) { + checkNoUnsupportedAnnotation(pojoClass, field.getAnnotations()); + } + if (transientNames.contains(name) + || isAnnotated(Transient.class, getter, field) + || (field != null + && java.lang.reflect.Modifier.isTransient(field.getModifiers()))) { + continue; + } + final Computed computed = getAnnotation(Computed.class, getter, field); + if (setter == null) { + throw new IllegalArgumentException( + String.format( + "Property %s of %s has no setter. Add a setter or annotate the property with %s.", + name, pojoClass.getName(), Transient.class.getName())); + } + getter.setAccessible(true); + setter.setAccessible(true); + final CqlName cqlName = getAnnotation(CqlName.class, getter, field); + final CqlIdentifier column = + CqlIdentifier.fromCql( + cqlName != null + ? cqlName.value() + : nameConverter.toCassandraName(name)); + final Type type = getter.getGenericReturnType(); + final Class<?> rawType = getter.getReturnType(); + final PojoMapper<?> udtMapper; + if (rawType.isAnnotationPresent(Entity.class)) { + udtMapper = create(rawType, visiting); + } else { + checkNoNestedEntity(pojoClass, name, type); + udtMapper = null; + } + properties.add( + new Property( + name, + column, + getter, + setter, + GenericType.of(type).wrap(), + rawType.isPrimitive(), + computed != null, + udtMapper)); + } + Preconditions.checkArgument( + !properties.isEmpty(), "%s has no mapped property.", pojoClass.getName()); + visiting.remove(pojoClass); + return new PojoMapper<>(pojoClass, keyspace, table, properties); + } + + /** + * The driver mapper annotations that change how an entity is mapped but that this mapper does + * not implement. They are rejected instead of being silently ignored. + */ + private static final List<Class<? extends Annotation>> UNSUPPORTED_ANNOTATIONS = + Arrays.asList(HierarchyScanStrategy.class, PropertyStrategy.class); + + private static void checkNoUnsupportedAnnotation(Class<?> pojoClass, Annotation[] annotations) { + for (Annotation annotation : annotations) { + for (Class<? extends Annotation> unsupported : UNSUPPORTED_ANNOTATIONS) { + if (unsupported.isInstance(annotation)) { + throw new IllegalArgumentException( + String.format( + "%s of %s is not supported by the POJO mapper of the connector.", + unsupported.getName(), pojoClass.getName())); + } + } + } + } + + /** + * Builds the statement inserting an instance of the mapped class. The statement contains one + * positional bind marker per mapped property, to bind with {@link #bind(PreparedStatement, + * Object, CassandraMapperOptions)}. + * + * @param defaultKeyspace the keyspace to use instead of the one of the {@link Entity} + * annotation, when null the keyspace of the annotation or of the session is used + * @param options the mapper options + * @return the insert statement + */ + public SimpleStatement buildInsert( + @Nullable String defaultKeyspace, CassandraMapperOptions options) { + Preconditions.checkState( + !writableProperties.isEmpty(), "%s has no property to save.", pojoClass.getName()); + final CqlIdentifier insertKeyspace = + defaultKeyspace == null || defaultKeyspace.isEmpty() + ? keyspace + : CqlIdentifier.fromCql(defaultKeyspace); + final InsertInto insertInto = + insertKeyspace == null + ? QueryBuilder.insertInto(table) + : QueryBuilder.insertInto(insertKeyspace, table); + RegularInsert regularInsert = null; + for (Property property : writableProperties) { + regularInsert = + (regularInsert == null ? insertInto : regularInsert) + .value(property.column, QueryBuilder.bindMarker()); + } + Insert insert = regularInsert; + if (options.isIfNotExists()) { + insert = insert.ifNotExists(); + } + if (options.getTimestamp() != null) { + insert = insert.usingTimestamp(options.getTimestamp()); + } + if (options.getTtl() != null) { + insert = insert.usingTtl(options.getTtl()); + } + return insert.build(); + } + + /** + * Binds an instance of the mapped class to a statement prepared from {@link + * #buildInsert(String, CassandraMapperOptions)}. + * + * @param preparedStatement the prepared insert statement + * @param pojo the instance to save + * @param options the mapper options + * @return the bound statement + */ + public BoundStatement bind( + PreparedStatement preparedStatement, T pojo, CassandraMapperOptions options) { + BoundStatementBuilder builder = preparedStatement.boundStatementBuilder(); + for (int i = 0; i < writableProperties.size(); i++) { + final Property property = writableProperties.get(i); + final Object value = property.get(pojo); + if (value == null) { + if (options.isSaveNullFields()) { + builder = builder.setToNull(i); + } + } else if (property.udtMapper != null) { + builder = + builder.setUdtValue( + i, + property.udtMapper.toUdtValue( + value, + preparedStatement + .getVariableDefinitions() + .get(i) + .getType())); + } else { + builder = builder.set(i, value, property.type); + } + } + if (options.getConsistencyLevel() != null) { + builder = builder.setConsistencyLevel(options.getConsistencyLevel()); + } + if (options.isTracing()) { + builder = builder.setTracing(true); + } + return builder.build(); + } + + /** + * Creates an instance of the mapped class from a row. The columns of the row that do not match + * a property are ignored and the properties that do not match a column are left unset. + * + * @param row the row to map + * @return the mapped instance + */ + public T map(Row row) { + return map(row, column -> row.getColumnDefinitions().contains(column)); + } + + private T map(GettableById source, Predicate<CqlIdentifier> contains) { + final T pojo; + try { + pojo = pojoClass.getDeclaredConstructor().newInstance(); + } catch (ReflectiveOperationException e) { + throw new FlinkRuntimeException( + String.format( + "Cannot instantiate %s, it must have a public no-argument constructor.", + pojoClass.getName()), + e); + } + for (Property property : properties) { + if (!contains.test(property.column)) { + continue; + } + if (source.isNull(property.column)) { + if (!property.primitive) { + property.set(pojo, null); + } + } else if (property.udtMapper != null) { + property.set( + pojo, property.udtMapper.fromUdtValue(source.getUdtValue(property.column))); + } else { + property.set(pojo, source.get(property.column, property.type)); + } + } + return pojo; + } + + private T fromUdtValue(UdtValue udtValue) { + return map(udtValue, field -> udtValue.getType().contains(field)); + } + + private UdtValue toUdtValue(Object pojo, DataType dataType) { + Preconditions.checkArgument( + dataType instanceof UserDefinedType, + "%s is mapped as a user defined type but the type of the column is %s.", + pojoClass.getName(), + dataType); + final UserDefinedType userDefinedType = (UserDefinedType) dataType; + UdtValue udtValue = userDefinedType.newValue(); + for (Property property : writableProperties) { + final int index = userDefinedType.firstIndexOf(property.column); + Preconditions.checkArgument( + index >= 0, + "%s is not a field of the user defined type %s.", + property.column, + userDefinedType.getName()); + final Object value = property.get(pojo); + if (value == null) { + udtValue = udtValue.setToNull(index); + } else if (property.udtMapper != null) { + udtValue = + udtValue.setUdtValue( + index, + property.udtMapper.toUdtValue( + value, userDefinedType.getFieldTypes().get(index))); + } else { + udtValue = udtValue.set(index, value, property.type); + } + } + return udtValue; + } + + private static NameConverter createNameConverter(Class<?> pojoClass) { + final NamingStrategy namingStrategy = pojoClass.getAnnotation(NamingStrategy.class); + if (namingStrategy == null) { + return name -> toCassandraName(name, NamingConvention.SNAKE_CASE_INSENSITIVE); + } + final NamingConvention[] conventions = namingStrategy.convention(); + final Class<? extends NameConverter>[] converters = namingStrategy.customConverterClass(); + Preconditions.checkArgument( + conventions.length + converters.length == 1, + "%s on %s must have exactly one convention or one custom converter class.", + NamingStrategy.class.getSimpleName(), + pojoClass.getName()); + if (conventions.length == 1) { + return name -> toCassandraName(name, conventions[0]); + } + try { + return converters[0].getDeclaredConstructor().newInstance(); + } catch (ReflectiveOperationException e) { + throw new IllegalArgumentException( + String.format( + "Cannot instantiate %s, it must have a public no-argument constructor.", + converters[0].getName()), + e); + } + } + + /** Converts a Java name to a CQL name the same way the driver mapper does. */ + static String toCassandraName(String javaName, NamingConvention convention) { + switch (convention) { + case CASE_INSENSITIVE: + return javaName; + case EXACT_CASE: + return doubleQuote(javaName); + case LOWER_CAMEL_CASE: + return doubleQuote( + Character.toLowerCase(javaName.charAt(0)) + javaName.substring(1)); + case UPPER_CAMEL_CASE: + return doubleQuote( + Character.toUpperCase(javaName.charAt(0)) + javaName.substring(1)); + case SNAKE_CASE_INSENSITIVE: + return toSnakeCase(javaName).toLowerCase(); Review Comment: This needs `Locale.ROOT`, with a Turkish default locale `userId` becomes `user_ıd` and the mapper throws. ########## flink-connector-cassandra/src/main/java/org/apache/flink/connector/cassandra/mapper/PojoMapper.java: ########## @@ -0,0 +1,563 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.flink.connector.cassandra.mapper; + +import org.apache.flink.annotation.Internal; +import org.apache.flink.connector.cassandra.CassandraMapperOptions; +import org.apache.flink.util.FlinkRuntimeException; +import org.apache.flink.util.Preconditions; + +import com.datastax.oss.driver.api.core.CqlIdentifier; +import com.datastax.oss.driver.api.core.cql.BoundStatement; +import com.datastax.oss.driver.api.core.cql.BoundStatementBuilder; +import com.datastax.oss.driver.api.core.cql.PreparedStatement; +import com.datastax.oss.driver.api.core.cql.Row; +import com.datastax.oss.driver.api.core.cql.SimpleStatement; +import com.datastax.oss.driver.api.core.data.GettableById; +import com.datastax.oss.driver.api.core.data.UdtValue; +import com.datastax.oss.driver.api.core.type.DataType; +import com.datastax.oss.driver.api.core.type.UserDefinedType; +import com.datastax.oss.driver.api.core.type.reflect.GenericType; +import com.datastax.oss.driver.api.mapper.annotations.Computed; +import com.datastax.oss.driver.api.mapper.annotations.CqlName; +import com.datastax.oss.driver.api.mapper.annotations.Entity; +import com.datastax.oss.driver.api.mapper.annotations.HierarchyScanStrategy; +import com.datastax.oss.driver.api.mapper.annotations.NamingStrategy; +import com.datastax.oss.driver.api.mapper.annotations.PropertyStrategy; +import com.datastax.oss.driver.api.mapper.annotations.Transient; +import com.datastax.oss.driver.api.mapper.annotations.TransientProperties; +import com.datastax.oss.driver.api.mapper.entity.naming.NameConverter; +import com.datastax.oss.driver.api.mapper.entity.naming.NamingConvention; +import com.datastax.oss.driver.api.querybuilder.QueryBuilder; +import com.datastax.oss.driver.api.querybuilder.insert.Insert; +import com.datastax.oss.driver.api.querybuilder.insert.InsertInto; +import com.datastax.oss.driver.api.querybuilder.insert.RegularInsert; + +import javax.annotation.Nullable; + +import java.beans.IntrospectionException; +import java.beans.Introspector; +import java.beans.PropertyDescriptor; +import java.lang.annotation.Annotation; +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.lang.reflect.ParameterizedType; +import java.lang.reflect.Type; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.function.Predicate; +import java.util.stream.Collectors; + +/** + * Maps POJOs annotated with {@link Entity} to and from Cassandra at runtime. + * + * <p>The mapper of the Cassandra driver generates its code with an annotation processor at compile + * time, so it cannot map a class that is only known at runtime. This class supports the subset of + * the driver mapper annotations that the connector needs: {@link Entity}, {@link CqlName}, {@link + * NamingStrategy}, {@link Transient}, {@link TransientProperties} and {@link Computed}. A property + * whose type is itself annotated with {@link Entity} is mapped to a user defined type. + * + * @param <T> the type of the mapped POJO + */ +@Internal +public final class PojoMapper<T> { + + private final Class<T> pojoClass; + @Nullable private final CqlIdentifier keyspace; + private final CqlIdentifier table; + private final List<Property> properties; + private final List<Property> writableProperties; + + private PojoMapper( + Class<T> pojoClass, + @Nullable CqlIdentifier keyspace, + CqlIdentifier table, + List<Property> properties) { + this.pojoClass = pojoClass; + this.keyspace = keyspace; + this.table = table; + this.properties = properties; + this.writableProperties = + properties.stream().filter(p -> !p.computed).collect(Collectors.toList()); + } + + /** + * Creates the mapper of a class annotated with {@link Entity}. + * + * @param pojoClass the class to map + * @param <T> the type of the mapped POJO + * @return the mapper + */ + public static <T> PojoMapper<T> create(Class<T> pojoClass) { + return create(pojoClass, new HashSet<>()); + } + + private static <T> PojoMapper<T> create(Class<T> pojoClass, Set<Class<?>> visiting) { + Preconditions.checkNotNull(pojoClass, "The POJO class must not be null."); + final Entity entity = pojoClass.getAnnotation(Entity.class); + Preconditions.checkArgument( + entity != null, + "%s must be annotated with %s.", + pojoClass.getName(), + Entity.class.getName()); + Preconditions.checkArgument( + visiting.add(pojoClass), + "%s references itself, recursive entities are not supported.", + pojoClass.getName()); + + checkNoUnsupportedAnnotation(pojoClass, pojoClass.getAnnotations()); + final NameConverter nameConverter = createNameConverter(pojoClass); + final CqlName tableName = pojoClass.getAnnotation(CqlName.class); + final CqlIdentifier table = + CqlIdentifier.fromCql( + tableName != null + ? tableName.value() + : nameConverter.toCassandraName( + Introspector.decapitalize(pojoClass.getSimpleName()))); + final CqlIdentifier keyspace = + entity.defaultKeyspace().isEmpty() + ? null + : CqlIdentifier.fromCql(entity.defaultKeyspace()); + + final TransientProperties transientProperties = + pojoClass.getAnnotation(TransientProperties.class); + final Set<String> transientNames = + transientProperties == null + ? new HashSet<>() + : new HashSet<>(Arrays.asList(transientProperties.value())); + + final List<Property> properties = new ArrayList<>(); + for (PropertyDescriptor descriptor : getPropertyDescriptors(pojoClass)) { + final Method getter = descriptor.getReadMethod(); + final Method setter = descriptor.getWriteMethod(); + if (getter == null || getter.getDeclaringClass() == Object.class) { + continue; + } + final String name = descriptor.getName(); + final Field field = findField(pojoClass, name); + checkNoUnsupportedAnnotation(pojoClass, getter.getAnnotations()); + if (setter != null) { + checkNoUnsupportedAnnotation(pojoClass, setter.getAnnotations()); + } + if (field != null) { + checkNoUnsupportedAnnotation(pojoClass, field.getAnnotations()); + } + if (transientNames.contains(name) + || isAnnotated(Transient.class, getter, field) + || (field != null + && java.lang.reflect.Modifier.isTransient(field.getModifiers()))) { + continue; + } + final Computed computed = getAnnotation(Computed.class, getter, field); + if (setter == null) { Review Comment: The driver skips a getter without a setter, a derived `getFullName()` fails only here. -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected]
