adelapena commented on code in PR #2310: URL: https://github.com/apache/cassandra/pull/2310#discussion_r1223187355
########## test/unit/org/apache/cassandra/cql3/RandomSchemaTest.java: ########## @@ -0,0 +1,242 @@ +/* + * 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.cassandra.cql3; + +import java.nio.ByteBuffer; +import java.util.ArrayDeque; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Deque; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Set; +import java.util.stream.Collectors; + +import com.google.common.collect.ImmutableList; +import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import org.apache.cassandra.config.CassandraRelevantProperties; +import org.apache.cassandra.db.marshal.UserType; +import org.apache.cassandra.schema.ColumnMetadata; +import org.apache.cassandra.schema.TableMetadata; +import org.apache.cassandra.utils.AbstractTypeGenerators; +import org.apache.cassandra.utils.AbstractTypeGenerators.TypeGenBuilder; +import org.apache.cassandra.utils.CassandraGenerators; +import org.apache.cassandra.utils.CassandraGenerators.TableMetadataBuilder; +import org.apache.cassandra.utils.FailingConsumer; +import org.quicktheories.core.Gen; +import org.quicktheories.core.RandomnessSource; +import org.quicktheories.generators.SourceDSL; +import org.quicktheories.impl.JavaRandom; + +public class RandomSchemaTest extends CQLTester.InMemory +{ + private static final Logger logger = LoggerFactory.getLogger(RandomSchemaTest.class); + + static + { + // make sure blob is always the same + CassandraRelevantProperties.TEST_BLOB_SHARED_SEED.setInt(42); + } + + { + requireNetwork(); + } + + @Test + public void test() + { + // in accord branch there is a much cleaner api for this pattern... + Gen<AbstractTypeGenerators.ValueDomain> domainGen = SourceDSL.integers().between(1, 100).map(i -> i < 2 ? AbstractTypeGenerators.ValueDomain.NULL : i < 4 ? AbstractTypeGenerators.ValueDomain.EMPTY_BYTES : AbstractTypeGenerators.ValueDomain.NORMAL); + // TODO (seed=1686092282977L) : map() == null, so CQLTEster fails as empty != null.... should/could we move this to AbstractType? + qt().checkAssert(random -> { + TypeGenBuilder withoutUnsafeEquality = AbstractTypeGenerators.withoutUnsafeEquality().withUserTypeKeyspace(KEYSPACE); + TableMetadata metadata = new TableMetadataBuilder() + .withKeyspaceName(KEYSPACE) + .withTableKinds(TableMetadata.Kind.REGULAR) + .withDefaultTypeGen(AbstractTypeGenerators.builder() + .withoutEmpty() + .withUserTypeKeyspace(KEYSPACE) + .withMaxDepth(2) + .withDefaultSetKey(withoutUnsafeEquality) + .withoutTypeKinds(AbstractTypeGenerators.TypeKind.COUNTER) + .build()) + .withPartitionColumnsCount(1) + .withPrimaryColumnTypeGen(new TypeGenBuilder(withoutUnsafeEquality) + .withMaxDepth(2) + .build()) + .withClusteringColumnsBetween(1, 2) + .withRegularColumnsBetween(1, 5) + .withStaticColumnsBetween(0, 2) + .build(random); + maybeCreateUDTs(metadata); + String createTable = metadata.toCqlString(false, false); + // just to make the CREATE TABLE stmt easier to read for CUSTOM types + createTable = createTable.replaceAll("org.apache.cassandra.db.marshal.", ""); + createTable(KEYSPACE, createTable); + + Gen<ByteBuffer[]> dataGen = CassandraGenerators.data(metadata, domainGen); + String insertStmt = insertStmt(metadata); + int primaryColumnCount = primaryColumnCount(metadata); + String selectStmt = selectStmt(metadata); + + for (int i = 0; i < 100; i++) + { + ByteBuffer[] expected = dataGen.generate(random); + try + { + ByteBuffer[] rowKey = Arrays.copyOf(expected, primaryColumnCount); + execute(insertStmt, expected); + // check memtable + assertRows(execute(selectStmt, rowKey), expected); + assertRowsNet(executeNet(selectStmt, rowKey), expected); + + // check sstable + flush(KEYSPACE, metadata.name); + compact(KEYSPACE, metadata.name); + assertRows(execute(selectStmt, rowKey), expected); + assertRowsNet(executeNet(selectStmt, rowKey), expected); + + execute("TRUNCATE " + metadata); + } + catch (Throwable t) + { + Iterator<ColumnMetadata> it = metadata.allColumnsInSelectOrder(); + List<String> literals = new ArrayList<>(expected.length); + for (int idx = 0; idx < expected.length; idx++) + { + assert it.hasNext(); + ColumnMetadata meta = it.next(); + literals.add(!expected[idx].hasRemaining() ? "empty" : meta.type.asCQL3Type().toCQLLiteral(expected[idx])); + } + AssertionError error = new AssertionError(String.format("Failure at attempt %d with schema\n%s\nfor values %s", i, createTable, literals), t); + throw error; Review Comment: We can directly use `throw new AssertionError(...` ########## test/unit/org/apache/cassandra/cql3/CQLTester.java: ########## @@ -2295,6 +2369,28 @@ protected static Gauge<Integer> getPausedConnectionsGauge() return metrics.get(metricName); } + public static class Vector<T> extends AbstractList<T> Review Comment: Nit: can use `@SafeVarargs` ########## test/unit/org/apache/cassandra/cql3/RandomSchemaTest.java: ########## @@ -0,0 +1,242 @@ +/* + * 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.cassandra.cql3; + +import java.nio.ByteBuffer; +import java.util.ArrayDeque; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Deque; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Set; +import java.util.stream.Collectors; + +import com.google.common.collect.ImmutableList; +import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import org.apache.cassandra.config.CassandraRelevantProperties; +import org.apache.cassandra.db.marshal.UserType; +import org.apache.cassandra.schema.ColumnMetadata; +import org.apache.cassandra.schema.TableMetadata; +import org.apache.cassandra.utils.AbstractTypeGenerators; +import org.apache.cassandra.utils.AbstractTypeGenerators.TypeGenBuilder; +import org.apache.cassandra.utils.CassandraGenerators; +import org.apache.cassandra.utils.CassandraGenerators.TableMetadataBuilder; +import org.apache.cassandra.utils.FailingConsumer; +import org.quicktheories.core.Gen; +import org.quicktheories.core.RandomnessSource; +import org.quicktheories.generators.SourceDSL; +import org.quicktheories.impl.JavaRandom; + +public class RandomSchemaTest extends CQLTester.InMemory +{ + private static final Logger logger = LoggerFactory.getLogger(RandomSchemaTest.class); + + static + { + // make sure blob is always the same + CassandraRelevantProperties.TEST_BLOB_SHARED_SEED.setInt(42); + } + + { + requireNetwork(); + } + + @Test + public void test() + { + // in accord branch there is a much cleaner api for this pattern... + Gen<AbstractTypeGenerators.ValueDomain> domainGen = SourceDSL.integers().between(1, 100).map(i -> i < 2 ? AbstractTypeGenerators.ValueDomain.NULL : i < 4 ? AbstractTypeGenerators.ValueDomain.EMPTY_BYTES : AbstractTypeGenerators.ValueDomain.NORMAL); + // TODO (seed=1686092282977L) : map() == null, so CQLTEster fails as empty != null.... should/could we move this to AbstractType? + qt().checkAssert(random -> { + TypeGenBuilder withoutUnsafeEquality = AbstractTypeGenerators.withoutUnsafeEquality().withUserTypeKeyspace(KEYSPACE); + TableMetadata metadata = new TableMetadataBuilder() + .withKeyspaceName(KEYSPACE) + .withTableKinds(TableMetadata.Kind.REGULAR) + .withDefaultTypeGen(AbstractTypeGenerators.builder() + .withoutEmpty() + .withUserTypeKeyspace(KEYSPACE) + .withMaxDepth(2) + .withDefaultSetKey(withoutUnsafeEquality) + .withoutTypeKinds(AbstractTypeGenerators.TypeKind.COUNTER) + .build()) + .withPartitionColumnsCount(1) + .withPrimaryColumnTypeGen(new TypeGenBuilder(withoutUnsafeEquality) + .withMaxDepth(2) + .build()) + .withClusteringColumnsBetween(1, 2) + .withRegularColumnsBetween(1, 5) + .withStaticColumnsBetween(0, 2) + .build(random); + maybeCreateUDTs(metadata); + String createTable = metadata.toCqlString(false, false); + // just to make the CREATE TABLE stmt easier to read for CUSTOM types + createTable = createTable.replaceAll("org.apache.cassandra.db.marshal.", ""); + createTable(KEYSPACE, createTable); + + Gen<ByteBuffer[]> dataGen = CassandraGenerators.data(metadata, domainGen); + String insertStmt = insertStmt(metadata); + int primaryColumnCount = primaryColumnCount(metadata); + String selectStmt = selectStmt(metadata); + + for (int i = 0; i < 100; i++) + { + ByteBuffer[] expected = dataGen.generate(random); + try + { + ByteBuffer[] rowKey = Arrays.copyOf(expected, primaryColumnCount); + execute(insertStmt, expected); + // check memtable + assertRows(execute(selectStmt, rowKey), expected); + assertRowsNet(executeNet(selectStmt, rowKey), expected); + + // check sstable + flush(KEYSPACE, metadata.name); + compact(KEYSPACE, metadata.name); + assertRows(execute(selectStmt, rowKey), expected); + assertRowsNet(executeNet(selectStmt, rowKey), expected); + + execute("TRUNCATE " + metadata); + } + catch (Throwable t) + { + Iterator<ColumnMetadata> it = metadata.allColumnsInSelectOrder(); + List<String> literals = new ArrayList<>(expected.length); + for (int idx = 0; idx < expected.length; idx++) + { + assert it.hasNext(); + ColumnMetadata meta = it.next(); + literals.add(!expected[idx].hasRemaining() ? "empty" : meta.type.asCQL3Type().toCQLLiteral(expected[idx])); + } + AssertionError error = new AssertionError(String.format("Failure at attempt %d with schema\n%s\nfor values %s", i, createTable, literals), t); + throw error; + } + } + }); + } + + private void maybeCreateUDTs(TableMetadata metadata) + { + Set<UserType> udts = CassandraGenerators.extractUDTs(metadata); + if (!udts.isEmpty()) + { + Deque<UserType> pending = new ArrayDeque<>(); + pending.addAll(udts); + Set<ByteBuffer> created = new HashSet<>(); + while (!pending.isEmpty()) + { + UserType next = pending.poll(); + Set<UserType> subTypes = AbstractTypeGenerators.extractUDTs(next); + subTypes.remove(next); // it includes self + if (subTypes.isEmpty() || subTypes.stream().allMatch(t -> created.contains(t.name))) + { + String cql = next.toCqlString(false, false); + logger.warn("Creating UDT {}", cql); + schemaChange(cql); + created.add(next.name); + } + else + { + logger.warn("Unable to create UDT {}; following sub-types still not created: {}", next.getCqlTypeName(), subTypes.stream().filter(t -> !created.contains(t.name)).collect(Collectors.toSet())); Review Comment: We can break the long line: ```suggestion logger.warn("Unable to create UDT {}; following sub-types still not created: {}", next.getCqlTypeName(), subTypes.stream().filter(t -> !created.contains(t.name)).collect(Collectors.toSet())); ``` ########## test/unit/org/apache/cassandra/cql3/RandomSchemaTest.java: ########## @@ -0,0 +1,242 @@ +/* + * 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.cassandra.cql3; + +import java.nio.ByteBuffer; +import java.util.ArrayDeque; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Deque; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Set; +import java.util.stream.Collectors; + +import com.google.common.collect.ImmutableList; +import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import org.apache.cassandra.config.CassandraRelevantProperties; +import org.apache.cassandra.db.marshal.UserType; +import org.apache.cassandra.schema.ColumnMetadata; +import org.apache.cassandra.schema.TableMetadata; +import org.apache.cassandra.utils.AbstractTypeGenerators; +import org.apache.cassandra.utils.AbstractTypeGenerators.TypeGenBuilder; +import org.apache.cassandra.utils.CassandraGenerators; +import org.apache.cassandra.utils.CassandraGenerators.TableMetadataBuilder; +import org.apache.cassandra.utils.FailingConsumer; +import org.quicktheories.core.Gen; +import org.quicktheories.core.RandomnessSource; +import org.quicktheories.generators.SourceDSL; +import org.quicktheories.impl.JavaRandom; + +public class RandomSchemaTest extends CQLTester.InMemory +{ + private static final Logger logger = LoggerFactory.getLogger(RandomSchemaTest.class); + + static + { + // make sure blob is always the same + CassandraRelevantProperties.TEST_BLOB_SHARED_SEED.setInt(42); + } + + { + requireNetwork(); Review Comment: This can go into the static block right above ########## test/unit/org/apache/cassandra/cql3/RandomSchemaTest.java: ########## @@ -0,0 +1,242 @@ +/* + * 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.cassandra.cql3; + +import java.nio.ByteBuffer; +import java.util.ArrayDeque; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Deque; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Set; +import java.util.stream.Collectors; + +import com.google.common.collect.ImmutableList; +import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import org.apache.cassandra.config.CassandraRelevantProperties; +import org.apache.cassandra.db.marshal.UserType; +import org.apache.cassandra.schema.ColumnMetadata; +import org.apache.cassandra.schema.TableMetadata; +import org.apache.cassandra.utils.AbstractTypeGenerators; +import org.apache.cassandra.utils.AbstractTypeGenerators.TypeGenBuilder; +import org.apache.cassandra.utils.CassandraGenerators; +import org.apache.cassandra.utils.CassandraGenerators.TableMetadataBuilder; +import org.apache.cassandra.utils.FailingConsumer; +import org.quicktheories.core.Gen; +import org.quicktheories.core.RandomnessSource; +import org.quicktheories.generators.SourceDSL; +import org.quicktheories.impl.JavaRandom; + +public class RandomSchemaTest extends CQLTester.InMemory +{ + private static final Logger logger = LoggerFactory.getLogger(RandomSchemaTest.class); + + static + { + // make sure blob is always the same + CassandraRelevantProperties.TEST_BLOB_SHARED_SEED.setInt(42); + } + + { + requireNetwork(); + } + + @Test + public void test() + { + // in accord branch there is a much cleaner api for this pattern... + Gen<AbstractTypeGenerators.ValueDomain> domainGen = SourceDSL.integers().between(1, 100).map(i -> i < 2 ? AbstractTypeGenerators.ValueDomain.NULL : i < 4 ? AbstractTypeGenerators.ValueDomain.EMPTY_BYTES : AbstractTypeGenerators.ValueDomain.NORMAL); + // TODO (seed=1686092282977L) : map() == null, so CQLTEster fails as empty != null.... should/could we move this to AbstractType? + qt().checkAssert(random -> { + TypeGenBuilder withoutUnsafeEquality = AbstractTypeGenerators.withoutUnsafeEquality().withUserTypeKeyspace(KEYSPACE); + TableMetadata metadata = new TableMetadataBuilder() + .withKeyspaceName(KEYSPACE) + .withTableKinds(TableMetadata.Kind.REGULAR) + .withDefaultTypeGen(AbstractTypeGenerators.builder() + .withoutEmpty() + .withUserTypeKeyspace(KEYSPACE) + .withMaxDepth(2) + .withDefaultSetKey(withoutUnsafeEquality) + .withoutTypeKinds(AbstractTypeGenerators.TypeKind.COUNTER) + .build()) + .withPartitionColumnsCount(1) + .withPrimaryColumnTypeGen(new TypeGenBuilder(withoutUnsafeEquality) + .withMaxDepth(2) + .build()) + .withClusteringColumnsBetween(1, 2) + .withRegularColumnsBetween(1, 5) + .withStaticColumnsBetween(0, 2) + .build(random); + maybeCreateUDTs(metadata); + String createTable = metadata.toCqlString(false, false); + // just to make the CREATE TABLE stmt easier to read for CUSTOM types + createTable = createTable.replaceAll("org.apache.cassandra.db.marshal.", ""); + createTable(KEYSPACE, createTable); + + Gen<ByteBuffer[]> dataGen = CassandraGenerators.data(metadata, domainGen); + String insertStmt = insertStmt(metadata); + int primaryColumnCount = primaryColumnCount(metadata); + String selectStmt = selectStmt(metadata); + + for (int i = 0; i < 100; i++) + { + ByteBuffer[] expected = dataGen.generate(random); + try + { + ByteBuffer[] rowKey = Arrays.copyOf(expected, primaryColumnCount); + execute(insertStmt, expected); + // check memtable + assertRows(execute(selectStmt, rowKey), expected); + assertRowsNet(executeNet(selectStmt, rowKey), expected); + + // check sstable + flush(KEYSPACE, metadata.name); + compact(KEYSPACE, metadata.name); + assertRows(execute(selectStmt, rowKey), expected); + assertRowsNet(executeNet(selectStmt, rowKey), expected); + + execute("TRUNCATE " + metadata); + } + catch (Throwable t) + { + Iterator<ColumnMetadata> it = metadata.allColumnsInSelectOrder(); + List<String> literals = new ArrayList<>(expected.length); + for (int idx = 0; idx < expected.length; idx++) + { + assert it.hasNext(); + ColumnMetadata meta = it.next(); + literals.add(!expected[idx].hasRemaining() ? "empty" : meta.type.asCQL3Type().toCQLLiteral(expected[idx])); + } + AssertionError error = new AssertionError(String.format("Failure at attempt %d with schema\n%s\nfor values %s", i, createTable, literals), t); + throw error; + } + } + }); + } + + private void maybeCreateUDTs(TableMetadata metadata) + { + Set<UserType> udts = CassandraGenerators.extractUDTs(metadata); + if (!udts.isEmpty()) + { + Deque<UserType> pending = new ArrayDeque<>(); + pending.addAll(udts); + Set<ByteBuffer> created = new HashSet<>(); + while (!pending.isEmpty()) + { + UserType next = pending.poll(); + Set<UserType> subTypes = AbstractTypeGenerators.extractUDTs(next); + subTypes.remove(next); // it includes self + if (subTypes.isEmpty() || subTypes.stream().allMatch(t -> created.contains(t.name))) + { + String cql = next.toCqlString(false, false); + logger.warn("Creating UDT {}", cql); + schemaChange(cql); + created.add(next.name); + } + else + { + logger.warn("Unable to create UDT {}; following sub-types still not created: {}", next.getCqlTypeName(), subTypes.stream().filter(t -> !created.contains(t.name)).collect(Collectors.toSet())); + pending.add(next); + } + } + } + } + + private static int primaryColumnCount(TableMetadata metadata) + { + return metadata.partitionKeyColumns().size() + metadata.clusteringColumns().size(); + } + + private String selectStmt(TableMetadata metadata) + { + StringBuilder sb = new StringBuilder(); + sb.append("SELECT * FROM ").append(metadata).append(" WHERE "); + for (ColumnMetadata column : ImmutableList.<ColumnMetadata>builder().addAll(metadata.partitionKeyColumns()).addAll(metadata.clusteringColumns()).build()) + sb.append(column.name.toCQLString()).append(" = ? AND "); Review Comment: We can break the long line: ```suggestion for (ColumnMetadata column : ImmutableList.<ColumnMetadata>builder() .addAll(metadata.partitionKeyColumns()) .addAll(metadata.clusteringColumns()) .build()) { sb.append(column.name.toCQLString()).append(" = ? AND "); } ``` ########## test/unit/org/apache/cassandra/cql3/RandomSchemaTest.java: ########## @@ -0,0 +1,242 @@ +/* + * 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.cassandra.cql3; + +import java.nio.ByteBuffer; +import java.util.ArrayDeque; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Deque; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Set; +import java.util.stream.Collectors; + +import com.google.common.collect.ImmutableList; +import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import org.apache.cassandra.config.CassandraRelevantProperties; +import org.apache.cassandra.db.marshal.UserType; +import org.apache.cassandra.schema.ColumnMetadata; +import org.apache.cassandra.schema.TableMetadata; +import org.apache.cassandra.utils.AbstractTypeGenerators; +import org.apache.cassandra.utils.AbstractTypeGenerators.TypeGenBuilder; +import org.apache.cassandra.utils.CassandraGenerators; +import org.apache.cassandra.utils.CassandraGenerators.TableMetadataBuilder; +import org.apache.cassandra.utils.FailingConsumer; +import org.quicktheories.core.Gen; +import org.quicktheories.core.RandomnessSource; +import org.quicktheories.generators.SourceDSL; +import org.quicktheories.impl.JavaRandom; + +public class RandomSchemaTest extends CQLTester.InMemory +{ + private static final Logger logger = LoggerFactory.getLogger(RandomSchemaTest.class); + + static + { + // make sure blob is always the same + CassandraRelevantProperties.TEST_BLOB_SHARED_SEED.setInt(42); + } + + { + requireNetwork(); + } + + @Test + public void test() + { + // in accord branch there is a much cleaner api for this pattern... + Gen<AbstractTypeGenerators.ValueDomain> domainGen = SourceDSL.integers().between(1, 100).map(i -> i < 2 ? AbstractTypeGenerators.ValueDomain.NULL : i < 4 ? AbstractTypeGenerators.ValueDomain.EMPTY_BYTES : AbstractTypeGenerators.ValueDomain.NORMAL); + // TODO (seed=1686092282977L) : map() == null, so CQLTEster fails as empty != null.... should/could we move this to AbstractType? + qt().checkAssert(random -> { + TypeGenBuilder withoutUnsafeEquality = AbstractTypeGenerators.withoutUnsafeEquality().withUserTypeKeyspace(KEYSPACE); + TableMetadata metadata = new TableMetadataBuilder() + .withKeyspaceName(KEYSPACE) + .withTableKinds(TableMetadata.Kind.REGULAR) + .withDefaultTypeGen(AbstractTypeGenerators.builder() + .withoutEmpty() + .withUserTypeKeyspace(KEYSPACE) + .withMaxDepth(2) + .withDefaultSetKey(withoutUnsafeEquality) + .withoutTypeKinds(AbstractTypeGenerators.TypeKind.COUNTER) + .build()) + .withPartitionColumnsCount(1) + .withPrimaryColumnTypeGen(new TypeGenBuilder(withoutUnsafeEquality) + .withMaxDepth(2) + .build()) + .withClusteringColumnsBetween(1, 2) + .withRegularColumnsBetween(1, 5) + .withStaticColumnsBetween(0, 2) + .build(random); + maybeCreateUDTs(metadata); + String createTable = metadata.toCqlString(false, false); + // just to make the CREATE TABLE stmt easier to read for CUSTOM types + createTable = createTable.replaceAll("org.apache.cassandra.db.marshal.", ""); + createTable(KEYSPACE, createTable); + + Gen<ByteBuffer[]> dataGen = CassandraGenerators.data(metadata, domainGen); + String insertStmt = insertStmt(metadata); + int primaryColumnCount = primaryColumnCount(metadata); + String selectStmt = selectStmt(metadata); + + for (int i = 0; i < 100; i++) + { + ByteBuffer[] expected = dataGen.generate(random); + try + { + ByteBuffer[] rowKey = Arrays.copyOf(expected, primaryColumnCount); + execute(insertStmt, expected); + // check memtable + assertRows(execute(selectStmt, rowKey), expected); + assertRowsNet(executeNet(selectStmt, rowKey), expected); + + // check sstable + flush(KEYSPACE, metadata.name); + compact(KEYSPACE, metadata.name); + assertRows(execute(selectStmt, rowKey), expected); + assertRowsNet(executeNet(selectStmt, rowKey), expected); + + execute("TRUNCATE " + metadata); + } + catch (Throwable t) + { + Iterator<ColumnMetadata> it = metadata.allColumnsInSelectOrder(); + List<String> literals = new ArrayList<>(expected.length); + for (int idx = 0; idx < expected.length; idx++) + { + assert it.hasNext(); + ColumnMetadata meta = it.next(); + literals.add(!expected[idx].hasRemaining() ? "empty" : meta.type.asCQL3Type().toCQLLiteral(expected[idx])); + } + AssertionError error = new AssertionError(String.format("Failure at attempt %d with schema\n%s\nfor values %s", i, createTable, literals), t); + throw error; + } + } + }); + } + + private void maybeCreateUDTs(TableMetadata metadata) + { + Set<UserType> udts = CassandraGenerators.extractUDTs(metadata); + if (!udts.isEmpty()) + { + Deque<UserType> pending = new ArrayDeque<>(); + pending.addAll(udts); + Set<ByteBuffer> created = new HashSet<>(); + while (!pending.isEmpty()) + { + UserType next = pending.poll(); + Set<UserType> subTypes = AbstractTypeGenerators.extractUDTs(next); + subTypes.remove(next); // it includes self + if (subTypes.isEmpty() || subTypes.stream().allMatch(t -> created.contains(t.name))) + { + String cql = next.toCqlString(false, false); + logger.warn("Creating UDT {}", cql); + schemaChange(cql); + created.add(next.name); + } + else + { + logger.warn("Unable to create UDT {}; following sub-types still not created: {}", next.getCqlTypeName(), subTypes.stream().filter(t -> !created.contains(t.name)).collect(Collectors.toSet())); + pending.add(next); + } + } + } + } + + private static int primaryColumnCount(TableMetadata metadata) + { + return metadata.partitionKeyColumns().size() + metadata.clusteringColumns().size(); + } + + private String selectStmt(TableMetadata metadata) + { + StringBuilder sb = new StringBuilder(); + sb.append("SELECT * FROM ").append(metadata).append(" WHERE "); + for (ColumnMetadata column : ImmutableList.<ColumnMetadata>builder().addAll(metadata.partitionKeyColumns()).addAll(metadata.clusteringColumns()).build()) + sb.append(column.name.toCQLString()).append(" = ? AND "); + sb.setLength(sb.length() - " AND ".length()); + return sb.toString(); + } + + private String insertStmt(TableMetadata metadata) + { + StringBuilder sb = new StringBuilder(); + sb.append("INSERT INTO ").append(metadata.toString()).append(" ("); + Iterator<ColumnMetadata> cols = metadata.allColumnsInSelectOrder(); + while (cols.hasNext()) + sb.append(cols.next().name.toCQLString()).append(", "); + sb.setLength(sb.length() - 2); // remove last ", " + sb.append(") VALUES ("); + for (int i = 0; i < metadata.columns().size(); i++) + { + if (i > 0) + sb.append(", "); + sb.append('?'); + } + sb.append(")"); + return sb.toString(); + } + + private static Builder qt() + { + return new Builder(); + } + + public static class Builder + { + private long seed = System.currentTimeMillis(); Review Comment: Can be `final` ########## test/unit/org/apache/cassandra/cql3/validation/entities/TupleTypeTest.java: ########## @@ -333,7 +336,14 @@ private static Gen<TypeAndRows> typesAndRowsGen() private static Gen<TypeAndRows> typesAndRowsGen(int numRows) { - Gen<TupleType> typeGen = tupleTypeGen(primitiveTypeGen(), SourceDSL.integers().between(1, 10)); + Gen<AbstractType<?>> subTypeGen = AbstractTypeGenerators.builder() + .withTypeKinds(AbstractTypeGenerators.TypeKind.PRIMITIVE) + // ordering doesn't make sense for duration + .withoutPrimitive(DurationType.instance) + // data is "normalzied" causing equality matches to fail Review Comment: Typo: ```suggestion // data is "normalized" causing equality matches to fail ``` ########## test/unit/org/apache/cassandra/cql3/validation/operations/CQLVectorTest.java: ########## @@ -0,0 +1,151 @@ +/* + * 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.cassandra.cql3.validation.operations; + +import org.junit.Test; + +import org.apache.cassandra.cql3.CQLTester; + +public class CQLVectorTest extends CQLTester.InMemory +{ + @Test + public void select() + { + createTable(KEYSPACE, "CREATE TABLE %s (pk vector<int, 2> primary key)"); + + execute("INSERT INTO %s (pk) VALUES ([1, 2])"); + + assertRows(execute("SELECT * FROM %s WHERE pk = [1, 2]"), row(list(1, 2))); Review Comment: `list(1, 2)` and `row(list(1, 2)` are repeated many times across the test. We can put them in a var: ```java Vector<Integer> vector = vector(1, 2); Object[] row = row(vector); assertRows(execute("SELECT * FROM %s WHERE pk = [1, 2]"), row); assertRows(execute("SELECT * FROM %s WHERE pk = ?", vector), row); assertRows(execute("SELECT * FROM %s WHERE pk = [1, 1 + 1]"), row); assertRows(execute("SELECT * FROM %s WHERE pk = [1, ?]", 2), row); ... ``` ########## test/unit/org/apache/cassandra/cql3/validation/operations/InsertInvalidateSizedRecordsTest.java: ########## @@ -0,0 +1,195 @@ +/* + * 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.cassandra.cql3.validation.operations; + +import java.io.BufferedOutputStream; +import java.io.IOException; +import java.io.OutputStreamWriter; +import java.io.Writer; +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.util.UUID; + +import com.google.common.base.StandardSystemProperty; +import org.junit.Test; + +import com.datastax.driver.core.exceptions.InvalidQueryException; +import org.apache.cassandra.cql3.CQLTester; +import org.apache.cassandra.io.util.File; +import org.apache.cassandra.tools.ToolRunner; +import org.apache.cassandra.utils.FBUtilities; +import org.assertj.core.api.Assertions; + +import static org.apache.cassandra.utils.ByteBufferUtil.EMPTY_BYTE_BUFFER; + +public class InsertInvalidateSizedRecordsTest extends CQLTester +{ + private static final ByteBuffer LARGE_BLOB = ByteBuffer.allocate(FBUtilities.MAX_UNSIGNED_SHORT + 1); + private static final ByteBuffer MEDIUM_BLOB = ByteBuffer.allocate(FBUtilities.MAX_UNSIGNED_SHORT / 2 + 10); + + { + requireNetwork(); + } + + @Test + public void singleValuePk() + { + createTable(KEYSPACE, "CREATE TABLE %s (a blob PRIMARY KEY)"); + Assertions.assertThatThrownBy(() -> executeNet("INSERT INTO %s (a) VALUES (?)", LARGE_BLOB)) + .hasRootCauseInstanceOf(InvalidQueryException.class) + .hasRootCauseMessage("Key length of " + LARGE_BLOB.remaining() + " is longer than maximum of 65535"); + + // null / empty checks + Assertions.assertThatThrownBy(() -> executeNet("INSERT INTO %s (a) VALUES (?)", new Object[] {null})) + .hasRootCauseInstanceOf(InvalidQueryException.class) + .hasRootCauseMessage("Invalid null value in condition for column a"); + Assertions.assertThatThrownBy(() -> executeNet("INSERT INTO %s (a) VALUES (?)", EMPTY_BYTE_BUFFER)) + .hasRootCauseInstanceOf(InvalidQueryException.class) + .hasRootCauseMessage("Key may not be empty"); + } + + @Test + public void compositeValuePk() + { + createTable(KEYSPACE, "CREATE TABLE %s (a blob, b blob, PRIMARY KEY ((a, b)))"); + // sum of columns is too large + Assertions.assertThatThrownBy(() -> executeNet("INSERT INTO %s (a, b) VALUES (?, ?)", MEDIUM_BLOB, MEDIUM_BLOB)) + .hasRootCauseInstanceOf(InvalidQueryException.class) + .hasRootCauseMessage("Key length of " + (MEDIUM_BLOB.remaining() * 2) + " is longer than maximum of 65535"); + + // single column is too large + Assertions.assertThatThrownBy(() -> executeNet("INSERT INTO %s (a, b) VALUES (?, ?)", MEDIUM_BLOB, LARGE_BLOB)) + .hasRootCauseInstanceOf(InvalidQueryException.class) + .hasRootCauseMessage("Key length of " + (MEDIUM_BLOB.remaining() + LARGE_BLOB.remaining()) + " is longer than maximum of 65535"); + + // null / empty checks + // this is an inconsistent behavior... null is blocked by org.apache.cassandra.db.MultiCBuilder.OneClusteringBuilder.addElementToAll + // but this does not count empty as null, and doesn't check for this case... We have a requirement in cqlsh that empty is allowed when + // user opts-in to allow it (NULL='-'), so we will find that null is blocked, but empty is allowed! + Assertions.assertThatThrownBy(() -> executeNet("INSERT INTO %s (a, b) VALUES (?, ?)", new Object[] {null, null})) + .hasRootCauseInstanceOf(InvalidQueryException.class) + .hasRootCauseMessage("Invalid null value in condition for column a"); + Assertions.assertThatThrownBy(() -> executeNet("INSERT INTO %s (a, b) VALUES (?, ?)", new Object[] {MEDIUM_BLOB, null})) + .hasRootCauseInstanceOf(InvalidQueryException.class) + .hasRootCauseMessage("Invalid null value in condition for column b"); + Assertions.assertThatThrownBy(() -> executeNet("INSERT INTO %s (a, b) VALUES (?, ?)", new Object[] {null, MEDIUM_BLOB})) + .hasRootCauseInstanceOf(InvalidQueryException.class) + .hasRootCauseMessage("Invalid null value in condition for column a"); + + // empty is allowed when composite partition columns... + executeNet("INSERT INTO %s (a, b) VALUES (?, ?)", EMPTY_BYTE_BUFFER, EMPTY_BYTE_BUFFER); + execute("TRUNCATE %s"); + + executeNet("INSERT INTO %s (a, b) VALUES (?, ?)", MEDIUM_BLOB, EMPTY_BYTE_BUFFER); + execute("TRUNCATE %s"); + + executeNet("INSERT INTO %s (a, b) VALUES (?, ?)", EMPTY_BYTE_BUFFER, MEDIUM_BLOB); + } + + @Test + public void singleValueClustering() + { + createTable(KEYSPACE, "CREATE TABLE %s (a blob, b blob, PRIMARY KEY (a, b))"); + Assertions.assertThatThrownBy(() -> executeNet("INSERT INTO %s (a, b) VALUES (?, ?)", MEDIUM_BLOB, LARGE_BLOB)) + .hasRootCauseInstanceOf(InvalidQueryException.class) + .hasRootCauseMessage("Key length of " + LARGE_BLOB.remaining() + " is longer than maximum of 65535"); + + // null / empty checks + Assertions.assertThatThrownBy(() -> executeNet("INSERT INTO %s (a, b) VALUES (?, ?)", MEDIUM_BLOB, null)) + .hasRootCauseInstanceOf(InvalidQueryException.class) + .hasRootCauseMessage("Invalid null value in condition for column b"); + + // org.apache.cassandra.db.MultiCBuilder.OneClusteringBuilder.addElementToAll defines "null" differently than most of the code; + // most of the code defines null as: + // value == null || accessor.isEmpty(value) + // but the code defines null as + // value == null + // In CASSANDRA-18504 a new isNull method was added to the type, as blob and text both "should" allow empty, but this scattered null logic doesn't allow... + // For backwards compatability reasons, need to keep empty support + executeNet("INSERT INTO %s (a, b) VALUES (?, ?)", MEDIUM_BLOB, EMPTY_BYTE_BUFFER); + } + + @Test + public void compositeValueClustering() + { + createTable(KEYSPACE, "CREATE TABLE %s (a blob, b blob, c blob, PRIMARY KEY (a, b, c))"); + // sum of columns is too large + Assertions.assertThatThrownBy(() -> executeNet("INSERT INTO %s (a, b, c) VALUES (?, ?, ?)", MEDIUM_BLOB, MEDIUM_BLOB, MEDIUM_BLOB)) + .hasRootCauseInstanceOf(InvalidQueryException.class) + .hasRootCauseMessage("Key length of " + (MEDIUM_BLOB.remaining() * 2) + " is longer than maximum of 65535"); + + // single column is too large + // the logic prints the total clustering size and not the single column's size that was too large + Assertions.assertThatThrownBy(() -> executeNet("INSERT INTO %s (a, b, c) VALUES (?, ?, ?)", MEDIUM_BLOB, MEDIUM_BLOB, LARGE_BLOB)) + .hasRootCauseInstanceOf(InvalidQueryException.class) + .hasRootCauseMessage("Key length of " + (MEDIUM_BLOB.remaining() + LARGE_BLOB.remaining()) + " is longer than maximum of 65535"); + } + + @Test + public void singleValueIndex() + { + createTable(KEYSPACE, "CREATE TABLE %s (a blob, b blob, PRIMARY KEY (a))"); + String table = KEYSPACE + "." + currentTable(); + execute("CREATE INDEX single_value_index ON %s (b)"); + Assertions.assertThatThrownBy(() -> executeNet("INSERT INTO %s (a, b) VALUES (?, ?)", MEDIUM_BLOB, LARGE_BLOB)) + .hasRootCauseInstanceOf(InvalidQueryException.class) + .hasRootCauseMessage("Cannot index value of size " + LARGE_BLOB.remaining() + " for index single_value_index on " + table + "(b) (maximum allowed size=65535)"); + } + + /** + * Partial port of cqlsh_tests.test_cqlsh_copy.TestCqlshCopy#test_reading_empty_strings_for_different_types + */ + @Test + public void test_reading_empty_strings_for_different_types() throws IOException Review Comment: I think we can use a camel cased method name, the JavaDoc still makes it easy to find the corresponding Python dtest. ########## test/unit/org/apache/cassandra/cql3/validation/operations/InsertInvalidateSizedRecordsTest.java: ########## @@ -0,0 +1,195 @@ +/* + * 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.cassandra.cql3.validation.operations; + +import java.io.BufferedOutputStream; +import java.io.IOException; +import java.io.OutputStreamWriter; +import java.io.Writer; +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.util.UUID; + +import com.google.common.base.StandardSystemProperty; +import org.junit.Test; + +import com.datastax.driver.core.exceptions.InvalidQueryException; +import org.apache.cassandra.cql3.CQLTester; +import org.apache.cassandra.io.util.File; +import org.apache.cassandra.tools.ToolRunner; +import org.apache.cassandra.utils.FBUtilities; +import org.assertj.core.api.Assertions; + +import static org.apache.cassandra.utils.ByteBufferUtil.EMPTY_BYTE_BUFFER; + +public class InsertInvalidateSizedRecordsTest extends CQLTester +{ + private static final ByteBuffer LARGE_BLOB = ByteBuffer.allocate(FBUtilities.MAX_UNSIGNED_SHORT + 1); + private static final ByteBuffer MEDIUM_BLOB = ByteBuffer.allocate(FBUtilities.MAX_UNSIGNED_SHORT / 2 + 10); + + { + requireNetwork(); + } + + @Test + public void singleValuePk() + { + createTable(KEYSPACE, "CREATE TABLE %s (a blob PRIMARY KEY)"); + Assertions.assertThatThrownBy(() -> executeNet("INSERT INTO %s (a) VALUES (?)", LARGE_BLOB)) + .hasRootCauseInstanceOf(InvalidQueryException.class) + .hasRootCauseMessage("Key length of " + LARGE_BLOB.remaining() + " is longer than maximum of 65535"); + + // null / empty checks + Assertions.assertThatThrownBy(() -> executeNet("INSERT INTO %s (a) VALUES (?)", new Object[] {null})) + .hasRootCauseInstanceOf(InvalidQueryException.class) + .hasRootCauseMessage("Invalid null value in condition for column a"); + Assertions.assertThatThrownBy(() -> executeNet("INSERT INTO %s (a) VALUES (?)", EMPTY_BYTE_BUFFER)) + .hasRootCauseInstanceOf(InvalidQueryException.class) + .hasRootCauseMessage("Key may not be empty"); + } + + @Test + public void compositeValuePk() + { + createTable(KEYSPACE, "CREATE TABLE %s (a blob, b blob, PRIMARY KEY ((a, b)))"); + // sum of columns is too large + Assertions.assertThatThrownBy(() -> executeNet("INSERT INTO %s (a, b) VALUES (?, ?)", MEDIUM_BLOB, MEDIUM_BLOB)) + .hasRootCauseInstanceOf(InvalidQueryException.class) + .hasRootCauseMessage("Key length of " + (MEDIUM_BLOB.remaining() * 2) + " is longer than maximum of 65535"); + + // single column is too large + Assertions.assertThatThrownBy(() -> executeNet("INSERT INTO %s (a, b) VALUES (?, ?)", MEDIUM_BLOB, LARGE_BLOB)) + .hasRootCauseInstanceOf(InvalidQueryException.class) + .hasRootCauseMessage("Key length of " + (MEDIUM_BLOB.remaining() + LARGE_BLOB.remaining()) + " is longer than maximum of 65535"); + + // null / empty checks + // this is an inconsistent behavior... null is blocked by org.apache.cassandra.db.MultiCBuilder.OneClusteringBuilder.addElementToAll + // but this does not count empty as null, and doesn't check for this case... We have a requirement in cqlsh that empty is allowed when + // user opts-in to allow it (NULL='-'), so we will find that null is blocked, but empty is allowed! + Assertions.assertThatThrownBy(() -> executeNet("INSERT INTO %s (a, b) VALUES (?, ?)", new Object[] {null, null})) + .hasRootCauseInstanceOf(InvalidQueryException.class) + .hasRootCauseMessage("Invalid null value in condition for column a"); + Assertions.assertThatThrownBy(() -> executeNet("INSERT INTO %s (a, b) VALUES (?, ?)", new Object[] {MEDIUM_BLOB, null})) + .hasRootCauseInstanceOf(InvalidQueryException.class) + .hasRootCauseMessage("Invalid null value in condition for column b"); + Assertions.assertThatThrownBy(() -> executeNet("INSERT INTO %s (a, b) VALUES (?, ?)", new Object[] {null, MEDIUM_BLOB})) + .hasRootCauseInstanceOf(InvalidQueryException.class) + .hasRootCauseMessage("Invalid null value in condition for column a"); + + // empty is allowed when composite partition columns... + executeNet("INSERT INTO %s (a, b) VALUES (?, ?)", EMPTY_BYTE_BUFFER, EMPTY_BYTE_BUFFER); + execute("TRUNCATE %s"); + + executeNet("INSERT INTO %s (a, b) VALUES (?, ?)", MEDIUM_BLOB, EMPTY_BYTE_BUFFER); + execute("TRUNCATE %s"); + + executeNet("INSERT INTO %s (a, b) VALUES (?, ?)", EMPTY_BYTE_BUFFER, MEDIUM_BLOB); + } + + @Test + public void singleValueClustering() + { + createTable(KEYSPACE, "CREATE TABLE %s (a blob, b blob, PRIMARY KEY (a, b))"); + Assertions.assertThatThrownBy(() -> executeNet("INSERT INTO %s (a, b) VALUES (?, ?)", MEDIUM_BLOB, LARGE_BLOB)) + .hasRootCauseInstanceOf(InvalidQueryException.class) + .hasRootCauseMessage("Key length of " + LARGE_BLOB.remaining() + " is longer than maximum of 65535"); + + // null / empty checks + Assertions.assertThatThrownBy(() -> executeNet("INSERT INTO %s (a, b) VALUES (?, ?)", MEDIUM_BLOB, null)) + .hasRootCauseInstanceOf(InvalidQueryException.class) + .hasRootCauseMessage("Invalid null value in condition for column b"); + + // org.apache.cassandra.db.MultiCBuilder.OneClusteringBuilder.addElementToAll defines "null" differently than most of the code; + // most of the code defines null as: + // value == null || accessor.isEmpty(value) + // but the code defines null as + // value == null + // In CASSANDRA-18504 a new isNull method was added to the type, as blob and text both "should" allow empty, but this scattered null logic doesn't allow... + // For backwards compatability reasons, need to keep empty support + executeNet("INSERT INTO %s (a, b) VALUES (?, ?)", MEDIUM_BLOB, EMPTY_BYTE_BUFFER); + } + + @Test + public void compositeValueClustering() + { + createTable(KEYSPACE, "CREATE TABLE %s (a blob, b blob, c blob, PRIMARY KEY (a, b, c))"); + // sum of columns is too large + Assertions.assertThatThrownBy(() -> executeNet("INSERT INTO %s (a, b, c) VALUES (?, ?, ?)", MEDIUM_BLOB, MEDIUM_BLOB, MEDIUM_BLOB)) + .hasRootCauseInstanceOf(InvalidQueryException.class) + .hasRootCauseMessage("Key length of " + (MEDIUM_BLOB.remaining() * 2) + " is longer than maximum of 65535"); + + // single column is too large + // the logic prints the total clustering size and not the single column's size that was too large + Assertions.assertThatThrownBy(() -> executeNet("INSERT INTO %s (a, b, c) VALUES (?, ?, ?)", MEDIUM_BLOB, MEDIUM_BLOB, LARGE_BLOB)) + .hasRootCauseInstanceOf(InvalidQueryException.class) + .hasRootCauseMessage("Key length of " + (MEDIUM_BLOB.remaining() + LARGE_BLOB.remaining()) + " is longer than maximum of 65535"); + } + + @Test + public void singleValueIndex() + { + createTable(KEYSPACE, "CREATE TABLE %s (a blob, b blob, PRIMARY KEY (a))"); + String table = KEYSPACE + "." + currentTable(); + execute("CREATE INDEX single_value_index ON %s (b)"); + Assertions.assertThatThrownBy(() -> executeNet("INSERT INTO %s (a, b) VALUES (?, ?)", MEDIUM_BLOB, LARGE_BLOB)) + .hasRootCauseInstanceOf(InvalidQueryException.class) + .hasRootCauseMessage("Cannot index value of size " + LARGE_BLOB.remaining() + " for index single_value_index on " + table + "(b) (maximum allowed size=65535)"); + } + + /** + * Partial port of cqlsh_tests.test_cqlsh_copy.TestCqlshCopy#test_reading_empty_strings_for_different_types + */ + @Test + public void test_reading_empty_strings_for_different_types() throws IOException + { + createTable(KEYSPACE, "CREATE TABLE %s (\n" + + " a text,\n" + + " b text,\n" + + " c text,\n" + + " d text,\n" + + " o uuid,\n" + + " i1 bigint,\n" + + " i2 bigint,\n" + + " t text,\n" + + " i3 bigint,\n" + + " PRIMARY KEY ((a, b, c, d), o)\n" + + " )"); + + File csv = new File(Files.createTempFile(new File(StandardSystemProperty.JAVA_IO_TMPDIR.value()).toPath(), "test_reading_empty_strings_for_different_types", ".csv")); + try (Writer out = new OutputStreamWriter(new BufferedOutputStream(csv.newOutputStream(File.WriteMode.OVERWRITE)), StandardCharsets.UTF_8)) + { + out.write(",,,a1,645e7d3c-aef7-4e3c-b834-24b792cf2e55,,,,r1\n"); + } + String table = KEYSPACE + "." + currentTable(); + String template = "COPY %s FROM '%s' WITH NULL='-' AND PREPAREDSTATEMENTS = %s"; + // This is different from cqlsh_tests.test_cqlsh_copy.TestCqlshCopy#test_reading_empty_strings_for_different_types as "false" actually is broken! + // If you do false, then the parsing actually fails... and the test didn't actually check the return code from cqlsh so doesn't detect that it failed! + // What is worse is the test didn't truncate either, which means that the "false" case is reading the "true" case data! + // Rather than try to fix the test and cqlsh... this test only keeps the "true" logic as it is what is needed to make sure CASSANDRA-18504 + // didn't break things. + ToolRunner.invokeCqlsh(String.format(template, table, csv.absolutePath(), true)).assertOnCleanExit(); + assertRowsNet(executeNet("SELECT * FROM %s"), row("", "", "", "a1", UUID.fromString("645e7d3c-aef7-4e3c-b834-24b792cf2e55"), null, null, null, "r1")); + } + + private static int compositeElementCost(int elementSize) Review Comment: Unused method ########## test/unit/org/quicktheories/impl/JavaRandom.java: ########## @@ -0,0 +1,97 @@ +/* + * 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.quicktheories.impl; Review Comment: That could be mentioned in the JavaDoc for the class. ########## test/unit/org/apache/cassandra/cql3/RandomSchemaTest.java: ########## @@ -0,0 +1,242 @@ +/* + * 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.cassandra.cql3; + +import java.nio.ByteBuffer; +import java.util.ArrayDeque; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Deque; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Set; +import java.util.stream.Collectors; + +import com.google.common.collect.ImmutableList; +import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import org.apache.cassandra.config.CassandraRelevantProperties; +import org.apache.cassandra.db.marshal.UserType; +import org.apache.cassandra.schema.ColumnMetadata; +import org.apache.cassandra.schema.TableMetadata; +import org.apache.cassandra.utils.AbstractTypeGenerators; +import org.apache.cassandra.utils.AbstractTypeGenerators.TypeGenBuilder; +import org.apache.cassandra.utils.CassandraGenerators; +import org.apache.cassandra.utils.CassandraGenerators.TableMetadataBuilder; +import org.apache.cassandra.utils.FailingConsumer; +import org.quicktheories.core.Gen; +import org.quicktheories.core.RandomnessSource; +import org.quicktheories.generators.SourceDSL; +import org.quicktheories.impl.JavaRandom; + +public class RandomSchemaTest extends CQLTester.InMemory +{ + private static final Logger logger = LoggerFactory.getLogger(RandomSchemaTest.class); + + static + { + // make sure blob is always the same + CassandraRelevantProperties.TEST_BLOB_SHARED_SEED.setInt(42); + } + + { + requireNetwork(); + } + + @Test + public void test() + { + // in accord branch there is a much cleaner api for this pattern... + Gen<AbstractTypeGenerators.ValueDomain> domainGen = SourceDSL.integers().between(1, 100).map(i -> i < 2 ? AbstractTypeGenerators.ValueDomain.NULL : i < 4 ? AbstractTypeGenerators.ValueDomain.EMPTY_BYTES : AbstractTypeGenerators.ValueDomain.NORMAL); + // TODO (seed=1686092282977L) : map() == null, so CQLTEster fails as empty != null.... should/could we move this to AbstractType? + qt().checkAssert(random -> { + TypeGenBuilder withoutUnsafeEquality = AbstractTypeGenerators.withoutUnsafeEquality().withUserTypeKeyspace(KEYSPACE); + TableMetadata metadata = new TableMetadataBuilder() + .withKeyspaceName(KEYSPACE) + .withTableKinds(TableMetadata.Kind.REGULAR) + .withDefaultTypeGen(AbstractTypeGenerators.builder() + .withoutEmpty() + .withUserTypeKeyspace(KEYSPACE) + .withMaxDepth(2) + .withDefaultSetKey(withoutUnsafeEquality) + .withoutTypeKinds(AbstractTypeGenerators.TypeKind.COUNTER) + .build()) + .withPartitionColumnsCount(1) + .withPrimaryColumnTypeGen(new TypeGenBuilder(withoutUnsafeEquality) + .withMaxDepth(2) + .build()) + .withClusteringColumnsBetween(1, 2) + .withRegularColumnsBetween(1, 5) + .withStaticColumnsBetween(0, 2) + .build(random); + maybeCreateUDTs(metadata); + String createTable = metadata.toCqlString(false, false); + // just to make the CREATE TABLE stmt easier to read for CUSTOM types + createTable = createTable.replaceAll("org.apache.cassandra.db.marshal.", ""); + createTable(KEYSPACE, createTable); + + Gen<ByteBuffer[]> dataGen = CassandraGenerators.data(metadata, domainGen); + String insertStmt = insertStmt(metadata); + int primaryColumnCount = primaryColumnCount(metadata); + String selectStmt = selectStmt(metadata); + + for (int i = 0; i < 100; i++) + { + ByteBuffer[] expected = dataGen.generate(random); + try + { + ByteBuffer[] rowKey = Arrays.copyOf(expected, primaryColumnCount); + execute(insertStmt, expected); + // check memtable + assertRows(execute(selectStmt, rowKey), expected); + assertRowsNet(executeNet(selectStmt, rowKey), expected); + + // check sstable + flush(KEYSPACE, metadata.name); + compact(KEYSPACE, metadata.name); + assertRows(execute(selectStmt, rowKey), expected); + assertRowsNet(executeNet(selectStmt, rowKey), expected); + + execute("TRUNCATE " + metadata); + } + catch (Throwable t) + { + Iterator<ColumnMetadata> it = metadata.allColumnsInSelectOrder(); + List<String> literals = new ArrayList<>(expected.length); + for (int idx = 0; idx < expected.length; idx++) + { + assert it.hasNext(); + ColumnMetadata meta = it.next(); + literals.add(!expected[idx].hasRemaining() ? "empty" : meta.type.asCQL3Type().toCQLLiteral(expected[idx])); + } + AssertionError error = new AssertionError(String.format("Failure at attempt %d with schema\n%s\nfor values %s", i, createTable, literals), t); + throw error; + } + } + }); + } + + private void maybeCreateUDTs(TableMetadata metadata) + { + Set<UserType> udts = CassandraGenerators.extractUDTs(metadata); + if (!udts.isEmpty()) + { + Deque<UserType> pending = new ArrayDeque<>(); + pending.addAll(udts); Review Comment: ```suggestion Deque<UserType> pending = new ArrayDeque<>(udts); ``` ########## test/unit/org/apache/cassandra/cql3/RandomSchemaTest.java: ########## @@ -0,0 +1,242 @@ +/* + * 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.cassandra.cql3; + +import java.nio.ByteBuffer; +import java.util.ArrayDeque; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Deque; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Set; +import java.util.stream.Collectors; + +import com.google.common.collect.ImmutableList; +import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import org.apache.cassandra.config.CassandraRelevantProperties; +import org.apache.cassandra.db.marshal.UserType; +import org.apache.cassandra.schema.ColumnMetadata; +import org.apache.cassandra.schema.TableMetadata; +import org.apache.cassandra.utils.AbstractTypeGenerators; +import org.apache.cassandra.utils.AbstractTypeGenerators.TypeGenBuilder; +import org.apache.cassandra.utils.CassandraGenerators; +import org.apache.cassandra.utils.CassandraGenerators.TableMetadataBuilder; +import org.apache.cassandra.utils.FailingConsumer; +import org.quicktheories.core.Gen; +import org.quicktheories.core.RandomnessSource; +import org.quicktheories.generators.SourceDSL; +import org.quicktheories.impl.JavaRandom; + +public class RandomSchemaTest extends CQLTester.InMemory +{ + private static final Logger logger = LoggerFactory.getLogger(RandomSchemaTest.class); + + static + { + // make sure blob is always the same + CassandraRelevantProperties.TEST_BLOB_SHARED_SEED.setInt(42); + } + + { + requireNetwork(); + } + + @Test + public void test() + { + // in accord branch there is a much cleaner api for this pattern... + Gen<AbstractTypeGenerators.ValueDomain> domainGen = SourceDSL.integers().between(1, 100).map(i -> i < 2 ? AbstractTypeGenerators.ValueDomain.NULL : i < 4 ? AbstractTypeGenerators.ValueDomain.EMPTY_BYTES : AbstractTypeGenerators.ValueDomain.NORMAL); + // TODO (seed=1686092282977L) : map() == null, so CQLTEster fails as empty != null.... should/could we move this to AbstractType? + qt().checkAssert(random -> { + TypeGenBuilder withoutUnsafeEquality = AbstractTypeGenerators.withoutUnsafeEquality().withUserTypeKeyspace(KEYSPACE); + TableMetadata metadata = new TableMetadataBuilder() + .withKeyspaceName(KEYSPACE) + .withTableKinds(TableMetadata.Kind.REGULAR) + .withDefaultTypeGen(AbstractTypeGenerators.builder() + .withoutEmpty() + .withUserTypeKeyspace(KEYSPACE) + .withMaxDepth(2) + .withDefaultSetKey(withoutUnsafeEquality) + .withoutTypeKinds(AbstractTypeGenerators.TypeKind.COUNTER) + .build()) + .withPartitionColumnsCount(1) + .withPrimaryColumnTypeGen(new TypeGenBuilder(withoutUnsafeEquality) + .withMaxDepth(2) + .build()) + .withClusteringColumnsBetween(1, 2) + .withRegularColumnsBetween(1, 5) + .withStaticColumnsBetween(0, 2) + .build(random); + maybeCreateUDTs(metadata); + String createTable = metadata.toCqlString(false, false); + // just to make the CREATE TABLE stmt easier to read for CUSTOM types + createTable = createTable.replaceAll("org.apache.cassandra.db.marshal.", ""); + createTable(KEYSPACE, createTable); + + Gen<ByteBuffer[]> dataGen = CassandraGenerators.data(metadata, domainGen); + String insertStmt = insertStmt(metadata); + int primaryColumnCount = primaryColumnCount(metadata); + String selectStmt = selectStmt(metadata); + + for (int i = 0; i < 100; i++) + { + ByteBuffer[] expected = dataGen.generate(random); + try + { + ByteBuffer[] rowKey = Arrays.copyOf(expected, primaryColumnCount); + execute(insertStmt, expected); + // check memtable + assertRows(execute(selectStmt, rowKey), expected); + assertRowsNet(executeNet(selectStmt, rowKey), expected); + + // check sstable + flush(KEYSPACE, metadata.name); + compact(KEYSPACE, metadata.name); + assertRows(execute(selectStmt, rowKey), expected); + assertRowsNet(executeNet(selectStmt, rowKey), expected); + + execute("TRUNCATE " + metadata); + } + catch (Throwable t) + { + Iterator<ColumnMetadata> it = metadata.allColumnsInSelectOrder(); + List<String> literals = new ArrayList<>(expected.length); + for (int idx = 0; idx < expected.length; idx++) + { + assert it.hasNext(); + ColumnMetadata meta = it.next(); + literals.add(!expected[idx].hasRemaining() ? "empty" : meta.type.asCQL3Type().toCQLLiteral(expected[idx])); + } + AssertionError error = new AssertionError(String.format("Failure at attempt %d with schema\n%s\nfor values %s", i, createTable, literals), t); + throw error; + } + } + }); + } + + private void maybeCreateUDTs(TableMetadata metadata) + { + Set<UserType> udts = CassandraGenerators.extractUDTs(metadata); + if (!udts.isEmpty()) + { + Deque<UserType> pending = new ArrayDeque<>(); + pending.addAll(udts); + Set<ByteBuffer> created = new HashSet<>(); + while (!pending.isEmpty()) + { + UserType next = pending.poll(); + Set<UserType> subTypes = AbstractTypeGenerators.extractUDTs(next); + subTypes.remove(next); // it includes self + if (subTypes.isEmpty() || subTypes.stream().allMatch(t -> created.contains(t.name))) + { + String cql = next.toCqlString(false, false); + logger.warn("Creating UDT {}", cql); + schemaChange(cql); + created.add(next.name); + } + else + { + logger.warn("Unable to create UDT {}; following sub-types still not created: {}", next.getCqlTypeName(), subTypes.stream().filter(t -> !created.contains(t.name)).collect(Collectors.toSet())); + pending.add(next); + } + } + } + } + + private static int primaryColumnCount(TableMetadata metadata) + { + return metadata.partitionKeyColumns().size() + metadata.clusteringColumns().size(); + } + + private String selectStmt(TableMetadata metadata) + { + StringBuilder sb = new StringBuilder(); + sb.append("SELECT * FROM ").append(metadata).append(" WHERE "); + for (ColumnMetadata column : ImmutableList.<ColumnMetadata>builder().addAll(metadata.partitionKeyColumns()).addAll(metadata.clusteringColumns()).build()) + sb.append(column.name.toCQLString()).append(" = ? AND "); + sb.setLength(sb.length() - " AND ".length()); + return sb.toString(); + } + + private String insertStmt(TableMetadata metadata) + { + StringBuilder sb = new StringBuilder(); + sb.append("INSERT INTO ").append(metadata.toString()).append(" ("); + Iterator<ColumnMetadata> cols = metadata.allColumnsInSelectOrder(); + while (cols.hasNext()) + sb.append(cols.next().name.toCQLString()).append(", "); + sb.setLength(sb.length() - 2); // remove last ", " + sb.append(") VALUES ("); + for (int i = 0; i < metadata.columns().size(); i++) + { + if (i > 0) + sb.append(", "); + sb.append('?'); + } + sb.append(")"); + return sb.toString(); + } + + private static Builder qt() + { + return new Builder(); + } + + public static class Builder + { + private long seed = System.currentTimeMillis(); + + public Builder withFixedSeed(long seed) Review Comment: Unused method -- 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] --------------------------------------------------------------------- To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]

