Elffuss BraidHub

kikocis/java-driver public

JAVA-1126: JAVA-1126: Handle schema changes in Mapper (#678)

The mapping manager subscribes to schema change events and reacts to
table and UDT removed / modified notifications: a warning is logged and,
for modifications, the manager tries to replace the mapper or codec with
a new one (which may or may not work depending on the nature of the
change and whether client code kept a reference to the old mapper
instance).

In addition, table/UDT names and column/field names are validated
earlier, in a fail-fast attempt to detect wrong configurations.
Changeset66728a15bc919f9b9368ac4f0dad9c551e1e0043c1e5fc7a437a52bce79af6ec
AuthorAlexandre Dutra <adutra@users.noreply.github.com> · 2016-07-08 17:51 +02:00
CommitterOlivier Michallat <olim7t@users.noreply.github.com> · 2016-07-08 08:51 -07:00
Parents48c2cd675808

Browse the files at this changeset

11 files changed

modified changelog/README.md +1 −0
@@ -17,6 +17,7 @@
1717 - [bug] JAVA-1232: Fix NPE in IdempotenceAwareRetryPolicy.isIdempotent.
1818 - [improvement] JAVA-1227: Document "SELECT *" issue with prepared statement.
1919 - [bug] JAVA-1160: Fix NPE in VersionNumber.getPreReleaseLabels().
20+- [improvement] JAVA-1126: Handle schema changes in Mapper.
2021
2122
2223 ### 3.0.2
added driver-core/src/main/java/com/datastax/driver/core/SchemaChangeListenerBase.java +122 −0
@@ -0,0 +1,122 @@
1+/*
2+ * Copyright (C) 2012-2015 DataStax Inc.
3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ */
16+package com.datastax.driver.core;
17+
18+/**
19+ * Base implementation for {@link SchemaChangeListener}.
20+ */
21+public abstract class SchemaChangeListenerBase implements SchemaChangeListener {
22+
23+ @Override
24+ public void onKeyspaceAdded(KeyspaceMetadata keyspace) {
25+
26+ }
27+
28+ @Override
29+ public void onKeyspaceRemoved(KeyspaceMetadata keyspace) {
30+
31+ }
32+
33+ @Override
34+ public void onKeyspaceChanged(KeyspaceMetadata current, KeyspaceMetadata previous) {
35+
36+ }
37+
38+ @Override
39+ public void onTableAdded(TableMetadata table) {
40+
41+ }
42+
43+ @Override
44+ public void onTableRemoved(TableMetadata table) {
45+
46+ }
47+
48+ @Override
49+ public void onTableChanged(TableMetadata current, TableMetadata previous) {
50+
51+ }
52+
53+ @Override
54+ public void onUserTypeAdded(UserType type) {
55+
56+ }
57+
58+ @Override
59+ public void onUserTypeRemoved(UserType type) {
60+
61+ }
62+
63+ @Override
64+ public void onUserTypeChanged(UserType current, UserType previous) {
65+
66+ }
67+
68+ @Override
69+ public void onFunctionAdded(FunctionMetadata function) {
70+
71+ }
72+
73+ @Override
74+ public void onFunctionRemoved(FunctionMetadata function) {
75+
76+ }
77+
78+ @Override
79+ public void onFunctionChanged(FunctionMetadata current, FunctionMetadata previous) {
80+
81+ }
82+
83+ @Override
84+ public void onAggregateAdded(AggregateMetadata aggregate) {
85+
86+ }
87+
88+ @Override
89+ public void onAggregateRemoved(AggregateMetadata aggregate) {
90+
91+ }
92+
93+ @Override
94+ public void onAggregateChanged(AggregateMetadata current, AggregateMetadata previous) {
95+
96+ }
97+
98+ @Override
99+ public void onMaterializedViewAdded(MaterializedViewMetadata view) {
100+
101+ }
102+
103+ @Override
104+ public void onMaterializedViewRemoved(MaterializedViewMetadata view) {
105+
106+ }
107+
108+ @Override
109+ public void onMaterializedViewChanged(MaterializedViewMetadata current, MaterializedViewMetadata previous) {
110+
111+ }
112+
113+ @Override
114+ public void onRegister(Cluster cluster) {
115+
116+ }
117+
118+ @Override
119+ public void onUnregister(Cluster cluster) {
120+
121+ }
122+}
modified driver-mapping/src/main/java/com/datastax/driver/mapping/AnnotationParser.java +29 −11
@@ -16,7 +16,7 @@
1616 package com.datastax.driver.mapping;
1717
1818 import com.datastax.driver.core.ConsistencyLevel;
19-import com.datastax.driver.core.Metadata;
19+import com.datastax.driver.core.TableMetadata;
2020 import com.datastax.driver.core.TypeCodec;
2121 import com.datastax.driver.core.UserType;
2222 import com.datastax.driver.mapping.MethodMapper.ParamMapper;
@@ -31,6 +31,8 @@
3131 import java.util.*;
3232 import java.util.concurrent.atomic.AtomicInteger;
3333
34+import static com.datastax.driver.core.Metadata.quote;
35+
3436 /**
3537 * Static metods that facilitates parsing class annotations into the corresponding {@link EntityMapper}.
3638 */
@@ -66,6 +68,10 @@
6668 }
6769
6870 EntityMapper<T> mapper = factory.create(entityClass, ksName, tableName, writeConsistency, readConsistency);
71+ TableMetadata tableMetadata = mappingManager.getSession().getCluster().getMetadata().getKeyspace(ksName).getTable(tableName);
72+
73+ if (tableMetadata == null)
74+ throw new IllegalArgumentException(String.format("Table %s does not exist in keyspace %s", tableName, ksName));
6975
7076 List<Field> pks = new ArrayList<Field>();
7177 List<Field> ccs = new ArrayList<Field>();
@@ -106,18 +112,24 @@
106112 validateOrder(pks, "@PartitionKey");
107113 validateOrder(ccs, "@ClusteringColumn");
108114
109- mapper.addColumns(createColumnMappers(pks, factory, mapper.entityClass, mappingManager, columnCounter),
110- createColumnMappers(ccs, factory, mapper.entityClass, mappingManager, columnCounter),
111- createColumnMappers(rgs, factory, mapper.entityClass, mappingManager, columnCounter));
115+ mapper.addColumns(
116+ createColumnMappers(pks, factory, mapper.entityClass, mappingManager, columnCounter, tableMetadata, ksName, tableName),
117+ createColumnMappers(ccs, factory, mapper.entityClass, mappingManager, columnCounter, tableMetadata, ksName, tableName),
118+ createColumnMappers(rgs, factory, mapper.entityClass, mappingManager, columnCounter, tableMetadata, ksName, tableName));
112119 return mapper;
113120 }
114121
115- private static <T> List<ColumnMapper<T>> createColumnMappers(List<Field> fields, EntityMapper.Factory factory, Class<T> klass, MappingManager mappingManager, AtomicInteger columnCounter) {
122+ private static <T> List<ColumnMapper<T>> createColumnMappers(List<Field> fields, EntityMapper.Factory factory, Class<T> klass, MappingManager mappingManager, AtomicInteger columnCounter, TableMetadata tableMetadata, String ksName, String tableName) {
116123 List<ColumnMapper<T>> mappers = new ArrayList<ColumnMapper<T>>(fields.size());
117124 for (int i = 0; i < fields.size(); i++) {
118125 Field field = fields.get(i);
119126 int pos = position(field);
120- mappers.add(factory.createColumnMapper(klass, field, pos < 0 ? i : pos, mappingManager, columnCounter));
127+ ColumnMapper<T> columnMapper = factory.createColumnMapper(klass, field, pos < 0 ? i : pos, mappingManager, columnCounter);
128+ if (columnMapper.kind == ColumnMapper.Kind.COMPUTED || tableMetadata.getColumn(columnMapper.getColumnName()) != null)
129+ mappers.add(columnMapper);
130+ else
131+ throw new IllegalArgumentException(String.format("Column %s does not exist in table %s.%s",
132+ columnMapper.getColumnName(), ksName, tableName));
121133 }
122134 return mappers;
123135 }
@@ -126,7 +138,7 @@
126138 UDT udt = AnnotationChecks.getTypeAnnotation(UDT.class, udtClass);
127139
128140 String ksName = udt.caseSensitiveKeyspace() ? udt.keyspace() : udt.keyspace().toLowerCase();
129- String udtName = udt.caseSensitiveType() ? Metadata.quote(udt.name()) : udt.name().toLowerCase();
141+ String udtName = udt.caseSensitiveType() ? quote(udt.name()) : udt.name().toLowerCase();
130142
131143 if (Strings.isNullOrEmpty(udt.keyspace())) {
132144 ksName = mappingManager.getSession().getLoggedKeyspace();
@@ -139,6 +151,8 @@
139151 }
140152
141153 UserType userType = mappingManager.getSession().getCluster().getMetadata().getKeyspace(ksName).getUserType(udtName);
154+ if (userType == null)
155+ throw new IllegalArgumentException(String.format("User type %s does not exist in keyspace %s", udtName, ksName));
142156
143157 List<Field> columns = new ArrayList<Field>();
144158
@@ -163,17 +177,21 @@
163177 break;
164178 }
165179 }
166- Map<String, ColumnMapper<T>> columnMappers = createFieldMappers(columns, factory, udtClass, mappingManager, null);
180+ Map<String, ColumnMapper<T>> columnMappers = createFieldMappers(columns, factory, udtClass, mappingManager, userType, ksName);
167181 return new MappedUDTCodec<T>(userType, udtClass, columnMappers, mappingManager);
168182 }
169183
170- private static <T> Map<String, ColumnMapper<T>> createFieldMappers(List<Field> fields, EntityMapper.Factory factory, Class<T> klass, MappingManager mappingManager, AtomicInteger columnCounter) {
184+ private static <T> Map<String, ColumnMapper<T>> createFieldMappers(List<Field> fields, EntityMapper.Factory factory, Class<T> klass, MappingManager mappingManager, UserType userType, String ksName) {
171185 Map<String, ColumnMapper<T>> mappers = Maps.newHashMapWithExpectedSize(fields.size());
172186 for (int i = 0; i < fields.size(); i++) {
173187 Field field = fields.get(i);
174188 int pos = position(field);
175- ColumnMapper<T> mapper = factory.createColumnMapper(klass, field, pos < 0 ? i : pos, mappingManager, columnCounter);
176- mappers.put(mapper.getColumnName(), mapper);
189+ ColumnMapper<T> mapper = factory.createColumnMapper(klass, field, pos < 0 ? i : pos, mappingManager, null);
190+ if (userType.contains(mapper.getColumnName()))
191+ mappers.put(mapper.getColumnName(), mapper);
192+ else
193+ throw new IllegalArgumentException(String.format("Field %s does not exist in type %s.%s",
194+ mapper.getColumnName(), ksName, userType.getTypeName()));
177195 }
178196 return mappers;
179197 }
modified driver-mapping/src/main/java/com/datastax/driver/mapping/MappedUDTCodec.java +4 −0
@@ -46,6 +46,10 @@
4646 }
4747 }
4848
49+ Class<T> getUdtClass() {
50+ return udtClass;
51+ }
52+
4953 @Override
5054 protected ByteBuffer serializeField(T source, String fieldName, ProtocolVersion protocolVersion) {
5155 // The parent class passes lowercase names unquoted, but in our internal map of mappers they are always quoted
modified driver-mapping/src/main/java/com/datastax/driver/mapping/Mapper.java +9 −5
@@ -141,6 +141,10 @@
141141 return getPreparedQueryAsync(type, Collections.<ColumnMapper<?>>emptySet(), options);
142142 }
143143
144+ Class<T> getMappedClass() {
145+ return klass;
146+ }
147+
144148 /**
145149 * The {@code TableMetadata} for this mapper.
146150 *
@@ -921,7 +925,7 @@
921925
922926 static class Ttl extends Option {
923927
924- private int ttlValue;
928+ private final int ttlValue;
925929
926930 Ttl(int value) {
927931 super(Type.TTL);
@@ -957,7 +961,7 @@
957961
958962 static class Timestamp extends Option {
959963
960- private long tsValue;
964+ private final long tsValue;
961965
962966 Timestamp(long value) {
963967 super(Type.TIMESTAMP);
@@ -993,7 +997,7 @@
993997
994998 static class ConsistencyLevelOption extends Option {
995999
996- private ConsistencyLevel cl;
1000+ private final ConsistencyLevel cl;
9971001
9981002 ConsistencyLevelOption(ConsistencyLevel cl) {
9991003 super(Type.CL);
@@ -1029,7 +1033,7 @@
10291033
10301034 static class Tracing extends Option {
10311035
1032- private boolean tracing;
1036+ private final boolean tracing;
10331037
10341038 Tracing(boolean tracing) {
10351039 super(Type.TRACING);
@@ -1066,7 +1070,7 @@
10661070
10671071 static class SaveNullFields extends Option {
10681072
1069- private boolean saveNullFields;
1073+ private final boolean saveNullFields;
10701074
10711075 SaveNullFields(boolean saveNullFields) {
10721076 super(SAVE_NULL_FIELDS);
modified driver-mapping/src/main/java/com/datastax/driver/mapping/MappingManager.java +78 −6
@@ -15,22 +15,22 @@
1515 */
1616 package com.datastax.driver.mapping;
1717
18-import com.datastax.driver.core.ProtocolVersion;
19-import com.datastax.driver.core.Session;
20-import com.datastax.driver.core.TypeCodec;
18+import com.datastax.driver.core.*;
2119 import com.datastax.driver.mapping.annotations.Accessor;
2220 import com.datastax.driver.mapping.annotations.Table;
2321 import com.datastax.driver.mapping.annotations.UDT;
22+import org.slf4j.Logger;
23+import org.slf4j.LoggerFactory;
2424
25-import java.util.Collections;
26-import java.util.HashMap;
27-import java.util.Map;
25+import java.util.*;
2826
2927 /**
3028 * Mapping manager from which to obtain entity mappers.
3129 */
3230 public class MappingManager {
3331
32+ private static final Logger LOGGER = LoggerFactory.getLogger(MappingManager.class);
33+
3434 private final Session session;
3535 final boolean isCassandraV1;
3636
@@ -74,6 +74,78 @@
7474 // which nodes might join the cluster later.
7575 // At least if protocol >=2 we know there won't be any 1.2 nodes ever.
7676 this.isCassandraV1 = (protocolVersion == ProtocolVersion.V1);
77+ session.getCluster().register(new SchemaChangeListenerBase() {
78+
79+ @Override
80+ public void onTableRemoved(TableMetadata table) {
81+ synchronized (mappers) {
82+ Iterator<Mapper<?>> it = mappers.values().iterator();
83+ while (it.hasNext()) {
84+ Mapper<?> mapper = it.next();
85+ if (mapper.getTableMetadata().equals(table)) {
86+ LOGGER.error("Table {} has been removed; existing mappers for @Entity annotated {} will not work anymore", table.getName(), mapper.getMappedClass());
87+ it.remove();
88+ }
89+ }
90+ }
91+ }
92+
93+ @Override
94+ public void onTableChanged(TableMetadata current, TableMetadata previous) {
95+ synchronized (mappers) {
96+ Iterator<Mapper<?>> it = mappers.values().iterator();
97+ while (it.hasNext()) {
98+ Mapper<?> mapper = it.next();
99+ if (mapper.getTableMetadata().equals(previous)) {
100+ LOGGER.warn("Table {} has been altered; existing mappers for @Entity annotated {} might not work properly anymore",
101+ previous.getName(), mapper.getMappedClass());
102+ it.remove();
103+ }
104+ }
105+ }
106+ }
107+
108+ @Override
109+ public void onUserTypeRemoved(UserType type) {
110+ synchronized (udtCodecs) {
111+ Iterator<MappedUDTCodec<?>> it = udtCodecs.values().iterator();
112+ while (it.hasNext()) {
113+ MappedUDTCodec<?> codec = it.next();
114+ if (type.equals(codec.getCqlType())) {
115+ LOGGER.error("User type {} has been removed; existing mappers for @UDT annotated {} will not work anymore",
116+ type, codec.getUdtClass());
117+ it.remove();
118+ }
119+ }
120+ }
121+ }
122+
123+ @Override
124+ public void onUserTypeChanged(UserType current, UserType previous) {
125+ synchronized (udtCodecs) {
126+ Set<Class<?>> udtClasses = new HashSet<Class<?>>();
127+ Iterator<MappedUDTCodec<?>> it = udtCodecs.values().iterator();
128+ while (it.hasNext()) {
129+ MappedUDTCodec<?> codec = it.next();
130+ if (previous.equals(codec.getCqlType())) {
131+ LOGGER.warn("User type {} has been altered; existing mappers for @UDT annotated {} might not work properly anymore",
132+ previous, codec.getUdtClass());
133+ udtClasses.add(codec.getUdtClass());
134+ it.remove();
135+ }
136+ }
137+ for (Class<?> udtClass : udtClasses) {
138+ // try to register an updated version of the previous codec
139+ try {
140+ getUDTCodec(udtClass);
141+ } catch (Exception e) {
142+ LOGGER.error("Could not update mapping for @UDT annotated " + udtClass, e);
143+ }
144+ }
145+ }
146+ }
147+
148+ });
77149 }
78150
79151 /**
deleted driver-mapping/src/test/java/com/datastax/driver/core/CoreHooks.java +0 −25
@@ -1,25 +0,0 @@
1-/*
2- * Copyright (C) 2012-2015 DataStax Inc.
3- *
4- * Licensed under the Apache License, Version 2.0 (the "License");
5- * you may not use this file except in compliance with the License.
6- * You may obtain a copy of the License at
7- *
8- * http://www.apache.org/licenses/LICENSE-2.0
9- *
10- * Unless required by applicable law or agreed to in writing, software
11- * distributed under the License is distributed on an "AS IS" BASIS,
12- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13- * See the License for the specific language governing permissions and
14- * limitations under the License.
15- */
16-package com.datastax.driver.core;
17-
18-import java.util.Collections;
19-
20-/**
21- * Provides access to package-private members of the core module.
22- */
23-public class CoreHooks {
24- public static UserType MOCK_USER_TYPE = new UserType("mockKs", "mockUDT", Collections.<UserType.Field>emptyList(), TestUtils.getDesiredProtocolVersion(), new CodecRegistry());
25-}
modified driver-mapping/src/test/java/com/datastax/driver/mapping/MapperCompositeKeyTest.java +1 −1
@@ -32,7 +32,7 @@
3232 }
3333
3434 @SuppressWarnings("unused")
35- @Table(keyspace = "ks", name = "test_table")
35+ @Table(name = "test_table")
3636 public static class TestTable {
3737 @PartitionKey(0)
3838 private int pk1;
modified driver-mapping/src/test/java/com/datastax/driver/mapping/MapperComputedFieldsTest.java +3 −14
@@ -17,7 +17,6 @@
1717
1818 import com.datastax.driver.core.*;
1919 import com.datastax.driver.core.exceptions.CodecNotFoundException;
20-import com.datastax.driver.core.exceptions.InvalidQueryException;
2120 import com.datastax.driver.core.utils.CassandraVersion;
2221 import com.datastax.driver.mapping.annotations.*;
2322 import org.testng.SkipException;
@@ -26,7 +25,6 @@
2625
2726 import static com.datastax.driver.core.Assertions.assertThat;
2827 import static com.datastax.driver.core.ProtocolVersion.V1;
29-import static org.assertj.core.api.Assertions.fail;
3028
3129 /**
3230 * Tests to ensure validity of {@link com.datastax.driver.mapping.annotations.Computed}
@@ -54,7 +52,7 @@
5452 userMapper = mappingManager.mapper(User.class);
5553 }
5654
57- @Test(groups = "short", expectedExceptions = {UnsupportedOperationException.class})
55+ @Test(groups = "short", expectedExceptions = UnsupportedOperationException.class)
5856 void should_get_unsupported_operation_exception_on_v1() {
5957 if (protocolVersion.compareTo(V1) > 0)
6058 throw new SkipException("Skipped when protocol version > V1");
@@ -129,19 +127,10 @@
129127 User_WrongComputedType user = mapper.get("testlogin");
130128 }
131129
132- @Test(groups = "short")
130+ @Test(groups = "short", expectedExceptions = IllegalArgumentException.class)
133131 @CassandraVersion(major = 2.0)
134132 void should_fail_if_computed_field_marked_with_column_annotation() {
135- Mapper<User_WrongAnnotationForComputed> mapper = mappingManager.mapper(User_WrongAnnotationForComputed.class);
136- try {
137- mapper.save(new User_WrongAnnotationForComputed("test", "foo"));
138- fail("Expected an InvalidQueryException");
139- } catch (InvalidQueryException e) {/*expected*/}
140-
141- try {
142- User_WrongAnnotationForComputed saved = mapper.get(42);
143- fail("Expected an InvalidQueryException");
144- } catch (InvalidQueryException e) {/*expected*/}
133+ mappingManager.mapper(User_WrongAnnotationForComputed.class);
145134 }
146135
147136 @Table(name = "user")
modified driver-mapping/src/test/java/com/datastax/driver/mapping/MapperTest.java +69 −0
@@ -503,4 +503,73 @@
503503 assertThat(saveQuery.isIdempotent()).isTrue();
504504 }
505505
506+
507+ @Table(name = "users")
508+ public static class UserUnknownColumn {
509+
510+ @PartitionKey
511+ @Column(name = "user_id")
512+ private UUID userId;
513+
514+ @Column(name = "middle_name")
515+ private String middleName;
516+
517+ public UserUnknownColumn() {
518+ }
519+
520+ public UUID getUserId() {
521+ return userId;
522+ }
523+
524+ public void setUserId(UUID userId) {
525+ this.userId = userId;
526+ }
527+
528+ public String getMiddleName() {
529+ return middleName;
530+ }
531+
532+ public void setMiddleName(String middleName) {
533+ this.middleName = middleName;
534+ }
535+ }
536+
537+ /**
538+ * Ensures that when attempting to create a {@link Mapper} from a class that has a field for a
539+ * column that doesn't exist that an {@link IllegalArgumentException} is thrown.
540+ *
541+ * @jira_ticket JAVA-1126
542+ * @test_category object_mapper
543+ */
544+ @Test(groups = "short", expectedExceptions = {IllegalArgumentException.class})
545+ public void should_fail_to_create_mapper_if_class_has_column_not_in_table() {
546+ MappingManager manager = new MappingManager(session());
547+ manager.mapper(UserUnknownColumn.class);
548+ }
549+
550+ @Table(name = "nonexistent")
551+ public static class NonExistentTable {
552+ public String name;
553+
554+ public void setName(String name) {
555+ this.name = name;
556+ }
557+
558+ public String getName() {
559+ return this.name;
560+ }
561+ }
562+
563+ /**
564+ * Ensures that when attempting to create a {@link Mapper} from a class that has a {@link Table} annotation with
565+ * a name that doesn't exist in the current keyspace that an {@link IllegalArgumentException} is thrown.
566+ *
567+ * @jira_ticket JAVA-1126
568+ * @test_category object_mapper
569+ */
570+ @Test(groups = "short", expectedExceptions = {IllegalArgumentException.class})
571+ public void should_fail_to_create_mapper_if_table_does_not_exist() {
572+ MappingManager manager = new MappingManager(session());
573+ manager.mapper(NonExistentTable.class);
574+ }
506575 }
modified driver-mapping/src/test/java/com/datastax/driver/mapping/MapperUDTTest.java +363 −6
@@ -17,34 +17,39 @@
1717
1818 import com.datastax.driver.core.*;
1919 import com.datastax.driver.core.exceptions.CodecNotFoundException;
20+import com.datastax.driver.core.exceptions.InvalidQueryException;
2021 import com.datastax.driver.core.utils.CassandraVersion;
2122 import com.datastax.driver.core.utils.UUIDs;
2223 import com.datastax.driver.mapping.annotations.*;
2324 import com.google.common.base.Objects;
2425 import com.google.common.collect.Maps;
2526 import org.assertj.core.data.MapEntry;
27+import org.testng.annotations.AfterMethod;
2628 import org.testng.annotations.BeforeMethod;
2729 import org.testng.annotations.Test;
2830
2931 import java.util.*;
3032
33+import static com.datastax.driver.core.CreateCCM.TestMode.PER_METHOD;
3134 import static org.assertj.core.api.Assertions.assertThat;
3235 import static org.assertj.core.api.Assertions.fail;
3336 import static org.testng.Assert.*;
3437
35-@SuppressWarnings("unused")
38+@SuppressWarnings({"unused", "WeakerAccess"})
3639 @CassandraVersion(major = 2.1)
40+@CreateCCM(PER_METHOD)
3741 public class MapperUDTTest extends CCMTestsSupport {
3842
39- @Override
40- public void onTestContextInitialized() {
43+ @BeforeMethod(groups = "short")
44+ public void createObjects() {
4145 execute("CREATE TYPE address (street text, city text, \"ZIP_code\" int, phones set<text>)",
4246 "CREATE TABLE users (user_id uuid PRIMARY KEY, name text, mainaddress frozen<address>, other_addresses map<text,frozen<address>>)");
4347 }
4448
45- @BeforeMethod(groups = "short")
46- public void clean() {
47- session().execute("TRUNCATE users");
49+ @AfterMethod(groups = "short")
50+ public void deleteObjects() {
51+ execute("DROP TABLE IF EXISTS users",
52+ "DROP TYPE IF EXISTS address");
4853 }
4954
5055 @Table(name = "users",
@@ -371,4 +376,356 @@
371376 Map<String, Address> otherAddresses = row.getMap("other_addresses", String.class, Address.class);
372377 assertThat(otherAddresses).containsOnly(MapEntry.entry("condo", expectedOtherAddress));
373378 }
379+
380+ /**
381+ * Ensures that if a table is altered after a {@link Mapper} is created that it continues to work as long as
382+ * the change is compatible. A new column is added to the table in this case, which is a compatible change.
383+ * <p>
384+ * It also ensures that after the change is made that requesting a new {@link Mapper} returns a different instance
385+ * instead of the existing one.
386+ *
387+ * @jira_ticket JAVA-1126
388+ * @test_category object_mapper
389+ */
390+ @Test(groups = "short")
391+ public void should_work_normally_when_when_table_is_altered_but_remains_compatible() {
392+ MappingManager manager = new MappingManager(session());
393+ User expected = new User("Paul", new Address("12 4th Street", "Springfield", 12345, "12341343", "435423245"));
394+ Mapper<User> m = manager.mapper(User.class);
395+ Mapper<User> m1 = manager.mapper(User.class);
396+ assertThat(m1).isSameAs(m);
397+ session().execute("ALTER TABLE users ADD foo text");
398+ m.save(expected);
399+ User retrieved = m.get(expected.getUserId());
400+ assertThat(retrieved).isEqualTo(expected);
401+
402+ // Mapper should be recreated since table changed.
403+ Mapper<User> m2 = manager.mapper(User.class);
404+ assertThat(m2).isNotSameAs(m);
405+ }
406+
407+ /**
408+ * Ensures that if a UDT is altered after a {@link Mapper} is created that has a UDT that it continues to work as
409+ * long as the change is compatible. A new field is added to the table in this case, which is a compatible change.
410+ * <p>
411+ * It also ensures that after the change is made that requesting a new {@link TypeCodec} for that UDT and a new
412+ * {@link Mapper} for a table using that UDT returns different instances instead of the existing ones.
413+ *
414+ * @jira_ticket JAVA-1126
415+ * @test_category object_mapper
416+ */
417+ @Test(groups = "short")
418+ public void should_work_normally_when_udt_is_altered_but_remains_compatible() {
419+ MappingManager manager = new MappingManager(session());
420+ User expected = new User("Paul", new Address("12 4th Street", "Springfield", 12345, "12341343", "435423245"));
421+ Mapper<User> m = manager.mapper(User.class);
422+ TypeCodec c = manager.udtCodec(Address.class);
423+ TypeCodec c1 = manager.udtCodec(Address.class);
424+ assertThat(c1).isSameAs(c);
425+ session().execute("ALTER TYPE address ADD foo text");
426+ m.save(expected);
427+ User retrieved = m.get(expected.getUserId());
428+ assertThat(retrieved).isEqualTo(expected);
429+
430+ // Codec should be recreated when requested since UDT and thus the table changed.
431+ Mapper m2 = manager.mapper(User.class);
432+ assertThat(m2).isNotSameAs(m);
433+
434+ // Codec should be recreated when requested since UDT changed.
435+ TypeCodec c2 = manager.udtCodec(Address.class);
436+ assertThat(c2).isNotSameAs(c);
437+ }
438+
439+ /**
440+ * Ensures that if a table is dropped after a {@link Mapper} is created that the {@link Mapper} can no longer
441+ * successfully make queries and that attempting to create a new {@link Mapper} throws an
442+ * {@link IllegalArgumentException}.
443+ * <p>
444+ * It also ensures that requesting a {@link Mapper} fails as the previous {@link Mapper} was evicted and a new
445+ * one cannot be created as the table has been dropped.
446+ *
447+ * @jira_ticket JAVA-1126
448+ * @test_category object_mapper
449+ */
450+ @Test(groups = "short")
451+ public void should_throw_error_when_table_is_dropped() {
452+ User user = new User("Paul", new Address("12 4th Street", "Springfield", 12345, "12341343", "435423245"));
453+ MappingManager manager = new MappingManager(session());
454+ Mapper<User> mapper = manager.mapper(User.class);
455+ session().execute("DROP TABLE users");
456+ // usage of stale mapper
457+ try {
458+ mapper.save(user);
459+ fail("Expected InvalidQueryException");
460+ } catch (InvalidQueryException e) {
461+ assertThat(e.getMessage()).contains("unconfigured", "users");
462+ }
463+ try {
464+ mapper.get(user.getUserId());
465+ fail("Expected InvalidQueryException");
466+ } catch (InvalidQueryException e) {
467+ assertThat(e.getMessage()).contains("unconfigured", "users");
468+ }
469+ // trying to use a new mapper
470+ try {
471+ manager.mapper(User.class);
472+ fail("Expected IllegalArgumentException");
473+ } catch (IllegalArgumentException e) {
474+ assertThat(e.getMessage()).isEqualTo("Table users does not exist in keyspace " + keyspace);
475+ }
476+ }
477+
478+ /**
479+ * Ensures that if a table is altered after a {@link Mapper} is created that it no longer continues to work if
480+ * the change is not compatible. A column is dropped from the table in this case, which is an incompatible change.
481+ * <p>
482+ * It also ensures that requesting a {@link Mapper} fails as the previous {@link Mapper} was evicted and a new
483+ * one cannot be created as a declared column is missing from the schema but is present in the class definition.
484+ *
485+ * @jira_ticket JAVA-1126
486+ * @test_category object_mapper
487+ */
488+ @Test(groups = "short")
489+ public void should_throw_error_when_table_is_altered_and_is_not_compatible_anymore() {
490+ User user = new User("Paul", new Address("12 4th Street", "Springfield", 12345, "12341343", "435423245"));
491+ MappingManager manager = new MappingManager(session());
492+ Mapper<User> mapper = manager.mapper(User.class);
493+ session().execute("ALTER TABLE users DROP mainaddress");
494+ // usage of stale mapper
495+ try {
496+ mapper.save(user);
497+ fail("Expected InvalidQueryException");
498+ } catch (InvalidQueryException e) {
499+ assertThat(e.getMessage()).isEqualTo("Unknown identifier mainaddress");
500+ }
501+ try {
502+ mapper.get(user.getUserId());
503+ fail("Expected InvalidQueryException");
504+ } catch (InvalidQueryException e) {
505+ assertThat(e.getMessage()).isEqualTo("Undefined name mainaddress in selection clause");
506+ }
507+ // trying to use a new mapper
508+ try {
509+ manager.mapper(User.class);
510+ fail("Expected IllegalArgumentException");
511+ } catch (IllegalArgumentException e) {
512+ assertThat(e.getMessage()).isEqualTo(String.format("Column \"mainaddress\" does not exist in table %s.users", keyspace));
513+ }
514+ }
515+
516+ /**
517+ * Ensures that if a UDT is altered after a {@link Mapper} is created that it no longer continues to work if
518+ * the change made to the UDT is not compatible. A field is renamed in the UDT in this case, which is not a
519+ * compatible change.
520+ * <p>
521+ * It also ensures that requesting a {@link Mapper} fails as the previous {@link Mapper} was evicted and a new
522+ * one cannot be created as a declared field is missing from the schema but is present in the class definition.
523+ * <p>
524+ * Also verifies that a {@link TypeCodec} cannot be requested for the UDT as well.
525+ *
526+ * @jira_ticket JAVA-1126
527+ * @test_category object_mapper
528+ */
529+ @Test(groups = "short")
530+ public void should_throw_error_when_udt_is_altered_and_is_not_compatible_anymore() {
531+ User user = new User("Paul", new Address("12 4th Street", "Springfield", 12345, "12341343", "435423245"));
532+ MappingManager manager = new MappingManager(session());
533+ Mapper<User> mapper = manager.mapper(User.class);
534+ session().execute("ALTER TYPE address RENAME \"ZIP_code\" to zip_code");
535+ // usage of stale mapper
536+ try {
537+ mapper.save(user);
538+ fail("Expected CodecNotFoundException");
539+ } catch (CodecNotFoundException e) {
540+ // ok, codec could not be created
541+ }
542+ // insert manually to be able to test retrieval
543+ session().execute("INSERT INTO users (user_id, name, mainaddress) VALUES (?, 'Paul', { street : '12 4th Street', zip_code : 12345 })", user.getUserId());
544+ try {
545+ mapper.get(user.getUserId());
546+ fail("Expected CodecNotFoundException");
547+ } catch (CodecNotFoundException e) {
548+ // ok, codec could not be created
549+ }
550+ // trying to use a new mapper
551+ try {
552+ manager.mapper(User.class);
553+ fail("Expected IllegalArgumentException");
554+ } catch (IllegalArgumentException e) {
555+ assertThat(e.getMessage()).isEqualTo(String.format("Field \"ZIP_code\" does not exist in type %s.address", keyspace));
556+ }
557+ try {
558+ manager.udtCodec(Address.class);
559+ fail("Expected IllegalArgumentException");
560+ } catch (IllegalArgumentException e) {
561+ assertThat(e.getMessage()).isEqualTo(String.format("Field \"ZIP_code\" does not exist in type %s.address", keyspace));
562+ }
563+ }
564+
565+ @UDT(name = "address")
566+ public static class AddressUnknownField {
567+
568+ private String city;
569+
570+ private String street;
571+
572+ @Field(name = "ZIP_code", caseSensitive = true)
573+ private int zipCode;
574+
575+ private Set<String> phones;
576+
577+ public String province;
578+
579+ public AddressUnknownField() {
580+ }
581+
582+ public String getStreet() {
583+ return street;
584+ }
585+
586+ public void setStreet(String street) {
587+ this.street = street;
588+ }
589+
590+ public String getCity() {
591+ return city;
592+ }
593+
594+ public void setCity(String city) {
595+ this.city = city;
596+ }
597+
598+ public int getZipCode() {
599+ return zipCode;
600+ }
601+
602+ public void setZipCode(int zipCode) {
603+ this.zipCode = zipCode;
604+ }
605+
606+ public Set<String> getPhones() {
607+ return phones;
608+ }
609+
610+ public void setPhones(Set<String> phones) {
611+ this.phones = phones;
612+ }
613+
614+ public String getProvince() {
615+ return province;
616+ }
617+
618+ public void setProvince(String province) {
619+ this.province = province;
620+ }
621+ }
622+
623+
624+ /**
625+ * Ensures that when attempting to create a {@link TypeCodec} from a class that has a field that does not exist in
626+ * the UDT that an {@link IllegalArgumentException} is thrown.
627+ *
628+ * @jira_ticket JAVA-1126
629+ * @test_category object_mapper
630+ */
631+ @Test(groups = "short", expectedExceptions = IllegalArgumentException.class)
632+ public void should_fail_to_create_codec_if_class_has_field_not_in_udt() {
633+ MappingManager manager = new MappingManager(session());
634+ manager.getUDTCodec(AddressUnknownField.class);
635+ }
636+
637+ @UDT(name = "nonexistent")
638+ public static class NonExistentUDT {
639+ public String name;
640+
641+ public void setName(String name) {
642+ this.name = name;
643+ }
644+
645+ public String getName() {
646+ return this.name;
647+ }
648+ }
649+
650+ /**
651+ * Ensures that when attempting to create a {@link TypeCodec} from a class that has a {@link UDT} annotation with
652+ * a name that doesn't exist in the current keyspace that an {@link IllegalArgumentException} is thrown.
653+ *
654+ * @jira_ticket JAVA-1126
655+ * @test_category object_mapper
656+ */
657+ @Test(groups = "short", expectedExceptions = IllegalArgumentException.class)
658+ public void should_fail_to_create_codec_if_udt_does_not_exist() {
659+ MappingManager manager = new MappingManager(session());
660+ manager.getUDTCodec(NonExistentUDT.class);
661+ }
662+
663+ @Table(name = "users")
664+ public static class UserWithAddressUnknownField {
665+ @PartitionKey
666+ @Column(name = "user_id")
667+ private UUID userId;
668+
669+ private String name;
670+
671+ @Frozen
672+ private AddressUnknownField mainAddress;
673+
674+ @Column(name = "other_addresses")
675+ @FrozenValue
676+ private Map<String, Address> otherAddresses = Maps.newHashMap();
677+
678+ public UserWithAddressUnknownField() {
679+ }
680+
681+ public UUID getUserId() {
682+ return userId;
683+ }
684+
685+ public void setUserId(UUID userId) {
686+ this.userId = userId;
687+ }
688+
689+ public String getName() {
690+ return name;
691+ }
692+
693+ public void setName(String name) {
694+ this.name = name;
695+ }
696+
697+ public AddressUnknownField getMainAddress() {
698+ return mainAddress;
699+ }
700+
701+ public void setMainAddress(AddressUnknownField address) {
702+ this.mainAddress = address;
703+ }
704+
705+ public Map<String, Address> getOtherAddresses() {
706+ return otherAddresses;
707+ }
708+
709+ public void setOtherAddresses(Map<String, Address> otherAddresses) {
710+ this.otherAddresses = otherAddresses;
711+ }
712+
713+ public void addOtherAddress(String name, Address address) {
714+ this.otherAddresses.put(name, address);
715+ }
716+ }
717+
718+ /**
719+ * Ensures that when attempting to create a {@link Mapper} from a class that has a field that is a class mapping to
720+ * a user type that has a field that does not exist in that UDT that an {@link IllegalArgumentException} is thrown.
721+ *
722+ * @jira_ticket JAVA-1126
723+ * @test_category object_mapper
724+ */
725+ @Test(groups = "short", expectedExceptions = IllegalArgumentException.class)
726+ public void should_fail_to_create_mapper_if_class_has_udt_field_class_that_has_field_not_in_udt() {
727+ MappingManager manager = new MappingManager(session());
728+ manager.mapper(UserWithAddressUnknownField.class);
729+ }
730+
374731 }