|
| 1 | +package org.springframework.data.cassandra.config; |
| 2 | + |
| 3 | +import java.util.Collection; |
| 4 | +import java.util.LinkedList; |
| 5 | +import java.util.List; |
| 6 | +import java.util.Objects; |
| 7 | +import java.util.Optional; |
| 8 | + |
| 9 | +import org.apache.commons.logging.Log; |
| 10 | +import org.apache.commons.logging.LogFactory; |
| 11 | +import org.springframework.beans.factory.SmartInitializingSingleton; |
| 12 | +import org.springframework.data.cassandra.CassandraKeyspaceDoesNotExistsException; |
| 13 | +import org.springframework.data.cassandra.CassandraNoActiveKeyspaceSetForCqlSessionException; |
| 14 | +import org.springframework.data.cassandra.CassandraSchemaValidationException; |
| 15 | +import org.springframework.data.cassandra.core.mapping.BasicCassandraPersistentEntity; |
| 16 | +import org.springframework.data.cassandra.core.mapping.CassandraMappingContext; |
| 17 | +import org.springframework.data.cassandra.core.mapping.CassandraPersistentEntity; |
| 18 | +import org.springframework.data.cassandra.core.mapping.CassandraPersistentProperty; |
| 19 | +import org.springframework.data.cassandra.core.mapping.CassandraSimpleTypeHolder; |
| 20 | +import org.springframework.data.mapping.PropertyHandler; |
| 21 | +import org.springframework.util.Assert; |
| 22 | + |
| 23 | +import com.datastax.oss.driver.api.core.CqlIdentifier; |
| 24 | +import com.datastax.oss.driver.api.core.CqlSession; |
| 25 | +import com.datastax.oss.driver.api.core.metadata.schema.ColumnMetadata; |
| 26 | +import com.datastax.oss.driver.api.core.metadata.schema.KeyspaceMetadata; |
| 27 | +import com.datastax.oss.driver.api.core.metadata.schema.TableMetadata; |
| 28 | +import com.datastax.oss.driver.api.core.type.DataType; |
| 29 | + |
| 30 | +/** |
| 31 | + * Class that is responsible to validate cassandra schema inside {@link CqlSession} keyspace. |
| 32 | + * |
| 33 | + * @author Mikhail Polivakha |
| 34 | + */ |
| 35 | +public class CassandraSchemaValidator implements SmartInitializingSingleton { |
| 36 | + |
| 37 | + private static final Log logger = LogFactory.getLog(CassandraSchemaValidator.class); |
| 38 | + |
| 39 | + private final CqlSessionFactoryBean cqlSessionFactoryBean; |
| 40 | + |
| 41 | + private final CassandraMappingContext cassandraMappingContext; |
| 42 | + |
| 43 | + private final boolean strictValidation; |
| 44 | + |
| 45 | + public CassandraSchemaValidator( |
| 46 | + CqlSessionFactoryBean cqlSessionFactoryBean, |
| 47 | + CassandraMappingContext cassandraMappingContext, |
| 48 | + boolean strictValidation |
| 49 | + ) { |
| 50 | + this.strictValidation = strictValidation; |
| 51 | + this.cqlSessionFactoryBean = cqlSessionFactoryBean; |
| 52 | + this.cassandraMappingContext = cassandraMappingContext; |
| 53 | + } |
| 54 | + |
| 55 | + /** |
| 56 | + * Here, we only consider {@link CqlSession#getKeyspace() current session keyspace}, |
| 57 | + * because for now there is no way to customize keyspace for {@link CassandraPersistentEntity}. |
| 58 | + * <p> |
| 59 | + * See <a href="https://github.com/spring-projects/spring-data-cassandra/issues/921">related issue</a> |
| 60 | + */ |
| 61 | + @Override |
| 62 | + public void afterSingletonsInstantiated() { |
| 63 | + CqlSession session = cqlSessionFactoryBean.getSession(); |
| 64 | + |
| 65 | + CqlIdentifier activeKeyspace = session |
| 66 | + .getKeyspace() |
| 67 | + .orElseThrow(CassandraNoActiveKeyspaceSetForCqlSessionException::new); |
| 68 | + |
| 69 | + KeyspaceMetadata keyspaceMetadata = session |
| 70 | + .getMetadata() |
| 71 | + .getKeyspace(activeKeyspace) |
| 72 | + .orElseThrow(() -> new CassandraKeyspaceDoesNotExistsException(activeKeyspace.asInternal())); |
| 73 | + |
| 74 | + Collection<BasicCassandraPersistentEntity<?>> persistentEntities = cassandraMappingContext.getPersistentEntities(); |
| 75 | + |
| 76 | + CassandraSchemaValidationProfile validationProfile = CassandraSchemaValidationProfile.empty(); |
| 77 | + |
| 78 | + for (BasicCassandraPersistentEntity<?> persistentEntity : persistentEntities) { |
| 79 | + validationProfile.addValidationErrors(validatePersistentEntity(keyspaceMetadata, persistentEntity)); |
| 80 | + } |
| 81 | + |
| 82 | + evaluateValidationResult(validationProfile); |
| 83 | + } |
| 84 | + |
| 85 | + private void evaluateValidationResult(CassandraSchemaValidationProfile validationProfile) { |
| 86 | + if (validationProfile.validationFailed()) { |
| 87 | + if (strictValidation) { |
| 88 | + throw new CassandraSchemaValidationException(validationProfile.renderExceptionMessage()); |
| 89 | + } else { |
| 90 | + if (logger.isErrorEnabled()) { |
| 91 | + logger.error(validationProfile.renderExceptionMessage()); |
| 92 | + } |
| 93 | + } |
| 94 | + } else { |
| 95 | + if (logger.isDebugEnabled()) { |
| 96 | + logger.debug("Cassandra schema validation completed successfully"); |
| 97 | + } |
| 98 | + } |
| 99 | + } |
| 100 | + |
| 101 | + private List<String> validatePersistentEntity( |
| 102 | + KeyspaceMetadata keyspaceMetadata, |
| 103 | + BasicCassandraPersistentEntity<?> entity |
| 104 | + ) { |
| 105 | + |
| 106 | + if (entity.isTupleType() || entity.isUserDefinedType()) { |
| 107 | + return List.of(); |
| 108 | + } |
| 109 | + |
| 110 | + if (logger.isDebugEnabled()) { |
| 111 | + logger.debug("Validating persistent entity '%s'".formatted(keyspaceMetadata.getName())); |
| 112 | + } |
| 113 | + |
| 114 | + Optional<TableMetadata> table = keyspaceMetadata.getTable(entity.getTableName()); |
| 115 | + |
| 116 | + if (table.isPresent()) { |
| 117 | + return this.validateProperties(table.get(), entity); |
| 118 | + } else { |
| 119 | + return List.of( |
| 120 | + "Unable to locate target table for persistent entity '%s'. Expected table name is '%s', but no such table in keyspace '%s'".formatted( |
| 121 | + entity.getName(), |
| 122 | + entity.getTableName(), |
| 123 | + keyspaceMetadata.getName() |
| 124 | + ) |
| 125 | + ); |
| 126 | + } |
| 127 | + } |
| 128 | + |
| 129 | + private List<String> validateProperties(TableMetadata tableMetadata, BasicCassandraPersistentEntity<?> entity) { |
| 130 | + |
| 131 | + List<String> validationErrors = new LinkedList<>(); |
| 132 | + |
| 133 | + entity.doWithProperties((PropertyHandler<CassandraPersistentProperty>) persistentProperty -> { |
| 134 | + CqlIdentifier expectedColumnName = persistentProperty.getColumnName(); |
| 135 | + |
| 136 | + Assert.notNull(expectedColumnName, "Column cannot not be null at this point"); |
| 137 | + |
| 138 | + Optional<ColumnMetadata> column = tableMetadata.getColumn(expectedColumnName); |
| 139 | + |
| 140 | + if (column.isPresent()) { |
| 141 | + ColumnMetadata columnMetadata = column.get(); |
| 142 | + DataType dataTypeExpected = CassandraSimpleTypeHolder.getDataTypeFor(persistentProperty.getRawType()); |
| 143 | + |
| 144 | + if (dataTypeExpected == null) { |
| 145 | + validationErrors.add( |
| 146 | + "Unable to deduce cassandra data type for property '%s' inside the persistent entity '%s'".formatted( |
| 147 | + persistentProperty.getName(), |
| 148 | + entity.getName() |
| 149 | + ) |
| 150 | + ); |
| 151 | + } else { |
| 152 | + if (!Objects.equals(dataTypeExpected.getProtocolCode(), columnMetadata.getType().getProtocolCode())) { |
| 153 | + validationErrors.add( |
| 154 | + "Expected '%s' data type for '%s' property in the '%s' persistent entity, but actual data type is '%s'".formatted( |
| 155 | + dataTypeExpected, |
| 156 | + persistentProperty.getName(), |
| 157 | + entity.getName(), |
| 158 | + columnMetadata.getType() |
| 159 | + ) |
| 160 | + ); |
| 161 | + } |
| 162 | + } |
| 163 | + } else { |
| 164 | + validationErrors.add( |
| 165 | + "Unable to locate target column for persistent property '%s' in persistent entity '%s'. Expected to see column with name '%s', but there is no such column in table '%s'".formatted( |
| 166 | + persistentProperty.getName(), |
| 167 | + entity.getName(), |
| 168 | + expectedColumnName, |
| 169 | + entity.getTableName() |
| 170 | + ) |
| 171 | + ); |
| 172 | + } |
| 173 | + }); |
| 174 | + |
| 175 | + return validationErrors; |
| 176 | + } |
| 177 | + |
| 178 | + public boolean isStrictValidation() { |
| 179 | + return strictValidation; |
| 180 | + } |
| 181 | +} |
0 commit comments