You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@cassandra.apache.org by bl...@apache.org on 2024/05/06 17:48:40 UTC
(cassandra) branch trunk updated: Refactor Relation and Restrictions hierachies
This is an automated email from the ASF dual-hosted git repository.
blerer pushed a commit to branch trunk
in repository https://gitbox.apache.org/repos/asf/cassandra.git
The following commit(s) were added to refs/heads/trunk by this push:
new 534da538d2 Refactor Relation and Restrictions hierachies
534da538d2 is described below
commit 534da538d229a5b4fc1d9ef7cc8b37ead455191c
Author: Benjamin Lerer <b....@gmail.com>
AuthorDate: Fri Sep 15 18:05:11 2023 +0200
Refactor Relation and Restrictions hierachies
patch by Benjamin Lerer and Piotr Kołaczkowski; reviewed by Berenguer Blasi, Caleb Rackliffe and Ekaterina Dimitrova for CASSANDRA-19341
Co-authored-by: Piotr Kołaczkowski <pk...@datastax.com>
---
CHANGES.txt | 1 +
src/antlr/Parser.g | 28 +-
.../apache/cassandra/cql3/ColumnsExpression.java | 583 ++++++
.../apache/cassandra/cql3/MultiColumnRelation.java | 231 ---
src/java/org/apache/cassandra/cql3/Operator.java | 484 ++++-
src/java/org/apache/cassandra/cql3/Ordering.java | 7 +-
src/java/org/apache/cassandra/cql3/Relation.java | 288 ++-
.../cassandra/cql3/SingleColumnRelation.java | 294 ---
.../org/apache/cassandra/cql3/TokenRelation.java | 205 --
.../cassandra/cql3/conditions/ColumnCondition.java | 18 +-
.../restrictions/ClusteringColumnRestrictions.java | 72 +-
.../cql3/restrictions/ClusteringElements.java | 473 +++++
.../cassandra/cql3/restrictions/LikePattern.java | 117 ++
.../cql3/restrictions/MergedRestriction.java | 344 ++++
.../cql3/restrictions/MultiColumnRestriction.java | 572 ------
.../restrictions/PartitionKeyRestrictions.java | 345 +++-
.../PartitionKeySingleRestrictionSet.java | 165 --
.../cassandra/cql3/restrictions/Restriction.java | 67 +-
.../cql3/restrictions/RestrictionSet.java | 299 +--
.../cql3/restrictions/RestrictionSetWrapper.java | 75 +-
.../cassandra/cql3/restrictions/Restrictions.java | 59 +-
.../cql3/restrictions/SimpleRestriction.java | 374 ++++
.../cql3/restrictions/SingleColumnRestriction.java | 829 --------
.../cql3/restrictions/SingleRestriction.java | 121 +-
.../cql3/restrictions/StatementRestrictions.java | 259 +--
.../cassandra/cql3/restrictions/TermSlice.java | 180 --
.../cassandra/cql3/restrictions/TokenFilter.java | 336 ----
.../cql3/restrictions/TokenRestriction.java | 341 ----
.../cql3/statements/ModificationStatement.java | 36 +-
.../cassandra/cql3/statements/SelectStatement.java | 36 +-
.../cassandra/cql3/statements/UpdateStatement.java | 4 +-
.../org/apache/cassandra/cql3/terms/InMarker.java | 4 +-
.../org/apache/cassandra/cql3/terms/Marker.java | 11 +-
src/java/org/apache/cassandra/cql3/terms/Term.java | 25 +-
.../org/apache/cassandra/cql3/terms/Terms.java | 96 +-
.../org/apache/cassandra/cql3/terms/Tuples.java | 19 -
.../org/apache/cassandra/db/MultiCBuilder.java | 535 ++---
.../org/apache/cassandra/db/filter/RowFilter.java | 186 +-
.../org/apache/cassandra/index/IndexRegistry.java | 9 +-
.../cassandra/index/sai/StorageAttachedIndex.java | 12 +-
.../apache/cassandra/schema/ColumnMetadata.java | 17 +-
.../org/apache/cassandra/cql3/RelationTest.java | 81 +
.../ClusteringColumnRestrictionsTest.java | 2068 ++++++++++----------
.../cql3/restrictions/ClusteringElementsTest.java | 676 +++++++
.../validation/entities/FrozenCollectionsTest.java | 3 +-
.../cql3/validation/entities/JsonTest.java | 9 +
.../entities/SecondaryIndexOnMapEntriesTest.java | 2 +-
.../operations/CompactStorageSplit1Test.java | 2 +-
.../operations/CompactStorageSplit2Test.java | 184 +-
.../InsertInvalidateSizedRecordsTest.java | 10 +-
.../operations/SelectMultiColumnRelationTest.java | 30 +-
.../operations/SelectOrderedPartitionerTest.java | 24 +-
.../operations/SelectSingleColumnRelationTest.java | 30 +-
.../cql3/validation/operations/SelectTest.java | 154 +-
.../index/sai/cql/CollectionIndexingTest.java | 2 +-
.../index/sai/cql/UnindexedExpressionsTest.java | 2 +-
.../index/sai/cql/VectorInvalidQueryTest.java | 3 +
.../cassandra/io/sstable/CQLSSTableWriterTest.java | 2 +-
58 files changed, 5474 insertions(+), 5965 deletions(-)
diff --git a/CHANGES.txt b/CHANGES.txt
index 6be56fcf3e..6b391cc980 100644
--- a/CHANGES.txt
+++ b/CHANGES.txt
@@ -1,4 +1,5 @@
5.1
+ * Refactor Relation and Restriction hierarchies (CASSANDRA-19341)
* Raise priority of TCM internode messages during critical operations (CASSANDRA-19517)
* Add nodetool command to unregister LEFT nodes (CASSANDRA-19581)
* Add cluster metadata id to gossip syn messages (CASSANDRA-19613)
diff --git a/src/antlr/Parser.g b/src/antlr/Parser.g
index cb5b90c062..3482bf4e95 100644
--- a/src/antlr/Parser.g
+++ b/src/antlr/Parser.g
@@ -1767,36 +1767,36 @@ relationType returns [Operator op]
;
relation[WhereClause.Builder clauses]
- : name=cident type=relationType t=term { $clauses.add(new SingleColumnRelation(name, type, t)); }
- | name=cident K_LIKE t=term { $clauses.add(new SingleColumnRelation(name, Operator.LIKE, t)); }
- | name=cident K_IS K_NOT K_NULL { $clauses.add(new SingleColumnRelation(name, Operator.IS_NOT, Constants.NULL_LITERAL)); }
+ : name=cident type=relationType t=term { $clauses.add(Relation.singleColumn(name, type, t)); }
+ | name=cident K_LIKE t=term { $clauses.add(Relation.singleColumn(name, Operator.LIKE, t)); }
+ | name=cident K_IS K_NOT K_NULL { $clauses.add(Relation.singleColumn(name, Operator.IS_NOT, Constants.NULL_LITERAL)); }
| K_TOKEN l=tupleOfIdentifiers type=relationType t=term
- { $clauses.add(new TokenRelation(l, type, t)); }
+ { $clauses.add(Relation.token(l, type, t)); }
| name=cident K_IN marker=inMarker
- { $clauses.add(new SingleColumnRelation(name, Operator.IN, marker)); }
+ { $clauses.add(Relation.singleColumn(name, Operator.IN, marker)); }
| name=cident K_IN inValues=singleColumnInValues
- { $clauses.add(SingleColumnRelation.createInRelation($name.id, inValues)); }
- | name=cident rt=containsOperator t=term { $clauses.add(new SingleColumnRelation(name, rt, t)); }
- | name=cident '[' key=term ']' type=relationType t=term { $clauses.add(new SingleColumnRelation(name, key, type, t)); }
+ { $clauses.add(Relation.singleColumn($name.id, Operator.IN, inValues)); }
+ | name=cident rt=containsOperator t=term { $clauses.add(Relation.singleColumn(name, rt, t)); }
+ | name=cident '[' key=term ']' type=relationType t=term { $clauses.add(Relation.mapElement(name, key, type, t)); }
| ids=tupleOfIdentifiers
( K_IN
( '(' ')'
- { $clauses.add(MultiColumnRelation.createInRelation(ids, Terms.Raw.of(Collections.emptyList()))); }
+ { $clauses.add(Relation.multiColumn(ids, Operator.IN, Terms.Raw.of(Collections.emptyList()))); }
| tupleInMarker=inMarker /* (a, b, c) IN ? */
- { $clauses.add(MultiColumnRelation.createInRelation(ids, tupleInMarker)); }
+ { $clauses.add(Relation.multiColumn(ids, Operator.IN, tupleInMarker)); }
| literals=tupleOfTupleLiterals /* (a, b, c) IN ((1, 2, 3), (4, 5, 6), ...) */
{
- $clauses.add(MultiColumnRelation.createInRelation(ids, literals));
+ $clauses.add(Relation.multiColumn(ids, Operator.IN, literals));
}
| markers=tupleOfMarkersForTuples /* (a, b, c) IN (?, ?, ...) */
- { $clauses.add(MultiColumnRelation.createInRelation(ids, markers)); }
+ { $clauses.add(Relation.multiColumn(ids, Operator.IN, markers)); }
)
| type=relationType literal=tupleLiteral /* (a, b, c) > (1, 2, 3) or (a, b, c) > (?, ?, ?) */
{
- $clauses.add(MultiColumnRelation.createNonInRelation(ids, type, literal));
+ $clauses.add(Relation.multiColumn(ids, type, literal));
}
| type=relationType tupleMarker=markerForTuple /* (a, b, c) >= ? */
- { $clauses.add(MultiColumnRelation.createNonInRelation(ids, type, tupleMarker)); }
+ { $clauses.add(Relation.multiColumn(ids, type, tupleMarker)); }
)
| '(' relation[$clauses] ')'
;
diff --git a/src/java/org/apache/cassandra/cql3/ColumnsExpression.java b/src/java/org/apache/cassandra/cql3/ColumnsExpression.java
new file mode 100644
index 0000000000..b182d27169
--- /dev/null
+++ b/src/java/org/apache/cassandra/cql3/ColumnsExpression.java
@@ -0,0 +1,583 @@
+/*
+ * 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.ArrayList;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Objects;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+
+import com.google.common.base.Joiner;
+import com.google.common.collect.ImmutableList;
+
+import org.apache.cassandra.cql3.functions.Function;
+import org.apache.cassandra.cql3.terms.Term;
+import org.apache.cassandra.db.marshal.AbstractType;
+import org.apache.cassandra.db.marshal.CollectionType;
+import org.apache.cassandra.db.marshal.ListType;
+import org.apache.cassandra.db.marshal.MapType;
+import org.apache.cassandra.db.marshal.TupleType;
+import org.apache.cassandra.exceptions.InvalidRequestException;
+import org.apache.cassandra.schema.ColumnMetadata;
+import org.apache.cassandra.schema.TableMetadata;
+import org.apache.cassandra.utils.ByteBufferUtil;
+
+import static org.apache.cassandra.cql3.statements.RequestValidations.checkContainsNoDuplicates;
+import static org.apache.cassandra.cql3.statements.RequestValidations.checkContainsOnly;
+import static org.apache.cassandra.cql3.statements.RequestValidations.checkFalse;
+import static org.apache.cassandra.cql3.statements.RequestValidations.checkTrue;
+import static org.apache.cassandra.cql3.statements.RequestValidations.invalidRequest;
+
+/**
+ * An expression including one or several columns.
+ *
+ * <p>This class can be modified to add support for more column expressions like UDT fields, List elements,
+ * functions on columns... </p>
+ */
+public final class ColumnsExpression
+{
+ /**
+ * Represent the expression kind
+ */
+ public enum Kind
+ {
+ /**
+ * Single column expression (e.g. {@code columnA})
+ */
+ SINGLE_COLUMN
+ {
+ @Override
+ void validateColumns(TableMetadata table, List<ColumnMetadata> columns)
+ {
+ }
+
+ @Override
+ AbstractType<?> type(TableMetadata table, List<ColumnMetadata> columns)
+ {
+ return columns.get(0).type;
+ }
+
+ @Override
+ String toCQLString(Stream<String> columns, String mapKey)
+ {
+ return columns.findFirst().orElseThrow();
+ }
+
+ @Override
+ public String toString()
+ {
+ return "single column";
+ }
+ },
+ /**
+ * Multi-column expression (e.g. {@code (columnA, columnB)})
+ */
+ MULTI_COLUMN
+ {
+ @Override
+ protected void validateColumns(TableMetadata table, List<ColumnMetadata> columns)
+ {
+ int previousPosition = -1;
+ for (int i = 0, m = columns.size(); i < m; i++)
+ {
+ ColumnMetadata column = columns.get(i);
+ checkTrue(column.isClusteringColumn(), "Multi-column relations can only be applied to clustering columns but was applied to: %s", column.name);
+ checkFalse(columns.lastIndexOf(column) != i, "Column \"%s\" appeared twice in a relation: %s", column.name, this);
+
+ // check that no clustering columns were skipped
+ checkFalse(previousPosition != -1 && column.position() != previousPosition + 1,
+ "Clustering columns must appear in the PRIMARY KEY order in multi-column relations: %s", toCQLString(columns, null));
+
+ previousPosition = column.position();
+ }
+ }
+
+ @Override
+ AbstractType<?> type(TableMetadata table, List<ColumnMetadata> columns)
+ {
+ return new TupleType(ColumnMetadata.typesOf(columns));
+ }
+
+ @Override
+ String toCQLString(Stream<String> columns, String mapKey)
+ {
+ return columns.collect(Collectors.joining(", ", "(", ")"));
+ }
+
+ @Override
+ public String toString()
+ {
+ return "multi-column";
+ }
+ },
+ /**
+ * Token expression (e.g. {@code token(columnA, columnB)})
+ */
+ TOKEN
+ {
+ @Override
+ protected void validateColumns(TableMetadata table, List<ColumnMetadata> columns)
+ {
+ if (columns.equals(table.partitionKeyColumns()))
+ return;
+
+ // If the columns do not match the partition key columns, let's try to narrow down the problem
+ checkTrue(new HashSet<>(columns).containsAll(table.partitionKeyColumns()),
+ "The token() function must be applied to all partition key components or none of them");
+
+ checkContainsNoDuplicates(columns, "The token() function contains duplicate partition key components");
+
+ checkContainsOnly(columns, table.partitionKeyColumns(), "The token() function must contains only partition key components");
+
+ throw invalidRequest("The token function arguments must be in the partition key order: %s",
+ Joiner.on(", ").join(ColumnMetadata.toIdentifiers(table.partitionKeyColumns())));
+ }
+
+ @Override
+ AbstractType<?> type(TableMetadata table, List<ColumnMetadata> columns)
+ {
+ return table.partitioner.getTokenValidator();
+ }
+
+ @Override
+ String toCQLString(Stream<String> columns, String mapKey)
+ {
+ return columns.collect(Collectors.joining(", ", "token(", ")"));
+ }
+
+ @Override
+ public String toString()
+ {
+ return "token";
+ }
+ },
+ /**
+ * Map element expression (e.g. {@code columnA[?]})
+ */
+ MAP_ELEMENT
+ {
+ @Override
+ void validateColumns(TableMetadata table, List<ColumnMetadata> columns)
+ {
+ ColumnMetadata column = columns.get(0);
+ checkFalse(column.type instanceof ListType, "Indexes on list entries (%s[index] = value) are not supported.", column.name);
+ checkTrue(column.type instanceof MapType, "Column %s cannot be used as a map", column.name);
+ checkTrue(column.type.isMultiCell(), "Map-entry predicates on frozen map column %s are not supported", column.name);
+ }
+
+ @Override
+ AbstractType<?> type(TableMetadata table, List<ColumnMetadata> columns)
+ {
+ return ((MapType<?, ?>) columns.get(0).type).getValuesType();
+ }
+
+ @Override
+ String toCQLString(Stream<String> columns, String mapKey)
+ {
+ return new StringBuilder().append(columns.findFirst().orElseThrow())
+ .append('[')
+ .append(mapKey)
+ .append(']')
+ .toString();
+ }
+
+ @Override
+ public String toString()
+ {
+ return "Map element";
+ }
+ };
+
+ /**
+ * Validates that the specified columns are valid for this kind of expression.
+ * @param table the table metadata
+ * @param columns the expression column
+ */
+ abstract void validateColumns(TableMetadata table, List<ColumnMetadata> columns);
+
+ /**
+ * Returns the expression type.
+ * @param table the table metadata
+ * @param columns the expression columns
+ * @return the expression type
+ */
+ abstract AbstractType<?> type(TableMetadata table, List<ColumnMetadata> columns);
+
+ /**
+ * Returns CQL representation of the expression.
+ * @param columns the expression's columns
+ * @param mapKey the key used to access the map element
+ * @return the CQL representation of the expression.
+ */
+ abstract String toCQLString(Stream<String> columns, String mapKey);
+
+ String toCQLString(List<ColumnMetadata> columns, Term mapKey)
+ {
+ String k = null;
+ if (this == Kind.MAP_ELEMENT)
+ {
+ CQL3Type type = ((MapType<?, ?>) columns.get(0).type).getKeysType().asCQL3Type();
+ // If a Term is not terminal it can be a row marker or a function.
+ // We ignore the fact that it could be a function for now.
+ k = mapKey.isTerminal() ? type.toCQLLiteral(((Term.Terminal) mapKey).get()) : "?";
+ }
+
+ return toCQLString(columns.stream().map(c -> c.name.toCQLString()), k);
+ }
+
+ String toCQLString(List<ColumnIdentifier> identifiers, Term.Raw rawMapKey)
+ {
+ String mapKey = rawMapKey == null ? null : rawMapKey.getText();
+ return toCQLString(identifiers.stream().map(ColumnIdentifier::toCQLString), mapKey);
+ }
+ }
+
+ /**
+ * The kind of columns expression.
+ */
+ private final Kind kind;
+
+ /**
+ * The type represented by this expression. For example, for a single column the type of the expression will
+ * be the one of the column and for a map element expression the type will be the one of the map value.
+ */
+ private final AbstractType<?> type;
+
+ /**
+ * The expression columns
+ */
+ private final List<ColumnMetadata> columns;
+
+ /**
+ * The key used to access the map element if this expression is for a map element,
+ * {@code null} otherwise.
+ */
+ private final Term mapKey;
+
+
+ private ColumnsExpression(Kind kind, AbstractType<?> type, List<ColumnMetadata> columns, Term mapKey)
+ {
+ this.kind = kind;
+ this.type = type;
+ this.columns = columns;
+ this.mapKey = mapKey;
+ }
+
+ /**
+ * Creates an expression for a single column (e.g. {@code columnA}).
+ * @param column the column
+ * @return an expression for a single column.
+ */
+ public static ColumnsExpression singleColumn(ColumnMetadata column)
+ {
+ return new ColumnsExpression(Kind.SINGLE_COLUMN, column.type, ImmutableList.of(column), null);
+ }
+
+ /**
+ * Creates an expression for multi-columns (e.g. {@code (columnA, columnB)}).
+ * @param columns the columns
+ * @return an expression for multi-columns.
+ */
+ public static ColumnsExpression multiColumns(List<ColumnMetadata> columns)
+ {
+ AbstractType<?> type = new TupleType(columns.stream()
+ .map(c -> c.type)
+ .collect(Collectors.toList()));
+ return new ColumnsExpression(Kind.MULTI_COLUMN, type, ImmutableList.copyOf(columns), null);
+ }
+
+ /**
+ * Returns the first column metadata.
+ * @return the first column metadata.
+ */
+ public ColumnMetadata firstColumn()
+ {
+ return columns().get(0);
+ }
+
+ /**
+ * Returns the last column metadata.
+ * @return the last column metadata.
+ */
+ public ColumnMetadata lastColumn()
+ {
+ return columns.get(columns.size() - 1);
+ }
+
+ /**
+ * Returns the columns metadata in position order.
+ * @return the columns metadata in position order.
+ */
+ public List<ColumnMetadata> columns()
+ {
+ return columns;
+ }
+
+ /**
+ * Returns the column kind (partition key, clustering, static or regular).
+ * @return the column kind.
+ */
+ public ColumnMetadata.Kind columnsKind()
+ {
+ // All columns must have the same type.
+ return firstColumn().kind;
+ }
+
+ /**
+ * Returns the expression kind.
+ * @return the expression kind.
+ */
+ public Kind kind()
+ {
+ return kind;
+ }
+
+ public ByteBuffer mapKey(QueryOptions options)
+ {
+ ByteBuffer key = mapKey.bindAndGet(options);
+ if (key == null)
+ throw invalidRequest("Invalid null map key for column %s", firstColumn().name.toCQLString());
+ if (key == ByteBufferUtil.UNSET_BYTE_BUFFER)
+ throw invalidRequest("Invalid unset map key for column %s", firstColumn().name.toCQLString());
+ return key;
+ }
+
+ /**
+ * Collects the column specifications for the bind variables in the map key.
+ * This is obviously a no-op if the expression is not a {@code MAP_ELEMENT} expression.
+ *
+ * @param boundNames the variables specification where to collect the
+ * bind variables of the map key in.
+ */
+ public void collectMarkerSpecification(VariableSpecifications boundNames)
+ {
+ if (mapKey != null)
+ mapKey.collectMarkerSpecification(boundNames);
+ }
+
+ /**
+ * Checks if this instance is a column level expression (single or multi-column expression).
+ * @return {@code true} if this instance is a column level expression, {@code false} otherwise.
+ */
+ public boolean isColumnLevelExpression()
+ {
+ return kind == Kind.SINGLE_COLUMN || kind == Kind.MULTI_COLUMN;
+ }
+
+ /**
+ * Adds all functions (native and user-defined) used by any component of the restriction
+ * to the specified list.
+ * @param functions the list to add to
+ */
+ public void addFunctionsTo(List<Function> functions)
+ {
+ if (mapKey != null)
+ mapKey.addFunctionsTo(functions);
+ }
+
+ /**
+ * Returns CQL representation of this expression.
+ * @return the CQL representation of this expression.
+ */
+ public String toCQLString()
+ {
+ return kind.toCQLString(columns, mapKey);
+ }
+
+ @Override
+ public String toString()
+ {
+ String prefix = kind == Kind.SINGLE_COLUMN ? "column "
+ : kind == Kind.MULTI_COLUMN ? "tuple " : "";
+
+ return prefix + toCQLString();
+ }
+
+ /**
+ * Returns the column specification corresponding to this expression.
+ * @return the column specification corresponding to this expression.
+ */
+ public ColumnSpecification columnSpecification()
+ {
+ ColumnMetadata column = firstColumn();
+ return kind == Kind.SINGLE_COLUMN ? column
+ : new ColumnSpecification(column.ksName, column.cfName, new ColumnIdentifier(toCQLString(), true), type) ;
+ }
+
+ /**
+ * The parsed version of the {@code ColumnsExpression} as outputed by the CQL parser.
+ * {@code Raw.prepare} will be called upon schema binding to create the {@code ColumnsExpression}.
+ */
+ public static final class Raw
+ {
+ private final Kind kind;
+
+ /**
+ * The columns identifiers
+ */
+ private final List<ColumnIdentifier> identifiers;
+
+ private final Term.Raw rawMapKey;
+
+ private Raw(Kind kind, List<ColumnIdentifier> identifiers, Term.Raw mapKey)
+ {
+ this.kind = kind;
+ this.identifiers = identifiers;
+ this.rawMapKey = mapKey;
+ }
+
+ /**
+ * Returns the expression kind.
+ * @return the expression kind.
+ */
+ public Kind kind()
+ {
+ return kind;
+ }
+
+ /**
+ * Creates a raw expression for a single column (e.g. {@code columnA}).
+ * @param identifier the column identifier
+ * @return a raw expression for a single column.
+ */
+ public static Raw singleColumn(ColumnIdentifier identifier)
+ {
+ return new Raw(Kind.SINGLE_COLUMN, ImmutableList.of(identifier), null);
+ }
+
+ /**
+ * Creates a raw expression for multi-column (e.g. {@code (columnA, columnB)}).
+ * @param identifiers the columns identifier
+ * @return a raw expression for multi-column.
+ */
+ public static Raw multiColumn(List<ColumnIdentifier> identifiers)
+ {
+ return new Raw(Kind.MULTI_COLUMN, identifiers, null);
+ }
+
+ /**
+ * Creates a raw expression for token restrictions (e.g. {@code token(columnA, columnB)}).
+ * @param identifiers the columns identifiers
+ * @return a raw token expression.
+ */
+ public static Raw token(List<ColumnIdentifier> identifiers)
+ {
+ return new Raw(Kind.TOKEN, identifiers, null);
+ }
+
+ /**
+ * Creates a raw expression for a map element restrictions (e.g. {@code columnA[?]}).
+ * @param identifier the map column identifier
+ * @param rawMapKey the raw map key
+ * @return a raw element expression.
+ */
+ public static Raw mapElement(ColumnIdentifier identifier, Term.Raw rawMapKey)
+ {
+ return new Raw(Kind.MAP_ELEMENT, ImmutableList.of(identifier), rawMapKey);
+ }
+
+ /**
+ * Renames an identifier in this expression, if applicable.
+ * @param from the old identifier
+ * @param to the new identifier
+ * @return this object, if the old identifier is not in the set of identifiers that this expression covers; otherwise
+ * a new Raw expression with "from" replaced by "to" is returned.
+ */
+ public Raw renameIdentifier(ColumnIdentifier from, ColumnIdentifier to)
+ {
+ if (!identifiers.contains(from))
+ return this;
+
+ List<ColumnIdentifier> newIdentifiers = identifiers.stream()
+ .map(e -> e.equals(from) ? to : e)
+ .collect(Collectors.toList());
+ return new Raw(kind, newIdentifiers, rawMapKey);
+ }
+
+ /**
+ * Bind this {@code Raw} instance to the schema and return the resulting {@code ColumnsExpression}.
+ *
+ * @param table the table schema
+ * @return the {@code ColumnsExpression} resulting from the schema binding
+ */
+ public ColumnsExpression prepare(TableMetadata table)
+ {
+ List<ColumnMetadata> columns = getColumnsMetadata(table, identifiers);
+ kind.validateColumns(table, columns);
+ Term mapKey = prepareMapKey(table, columns);
+ AbstractType<?> type = kind.type(table, columns);
+ return new ColumnsExpression(kind, type, columns, mapKey);
+ }
+
+ private Term prepareMapKey(TableMetadata table, List<ColumnMetadata> columns)
+ {
+ if (kind != Kind.MAP_ELEMENT)
+ return null;
+
+ ColumnSpecification receiver = CollectionType.Kind.MAP.makeCollectionReceiver(columns.get(0), true);
+ return rawMapKey.prepare(table.keyspace, receiver);
+ }
+
+ /**
+ * Returns the columns corresponding to the identifiers.
+ *
+ * @param table the table metadata
+ * @return the definition of the columns to which apply the token restriction.
+ * @throws InvalidRequestException if the entity cannot be resolved
+ */
+ private static List<ColumnMetadata> getColumnsMetadata(TableMetadata table, List<ColumnIdentifier> identifiers)
+ {
+ List<ColumnMetadata> columns = new ArrayList<>(identifiers.size());
+ for (ColumnIdentifier id : identifiers)
+ columns.add(table.getExistingColumn(id));
+ return columns;
+ }
+
+ @Override
+ public int hashCode()
+ {
+ return Objects.hash(kind, identifiers, rawMapKey);
+ }
+
+ @Override
+ public boolean equals(Object o)
+ {
+ if (this == o)
+ return true;
+
+ if (!(o instanceof Raw))
+ return false;
+
+ Raw r = (Raw) o;
+ return kind == r.kind && Objects.equals(identifiers, r.identifiers) && Objects.equals(rawMapKey, r.rawMapKey);
+ }
+
+ /**
+ * Returns CQL representation of this raw expression.
+ * @return the CQL representation of this raw expression.
+ */
+ public String toCQLString()
+ {
+ return kind.toCQLString(identifiers, rawMapKey);
+ }
+ }
+}
diff --git a/src/java/org/apache/cassandra/cql3/MultiColumnRelation.java b/src/java/org/apache/cassandra/cql3/MultiColumnRelation.java
deleted file mode 100644
index 8ea4acc59a..0000000000
--- a/src/java/org/apache/cassandra/cql3/MultiColumnRelation.java
+++ /dev/null
@@ -1,231 +0,0 @@
-/*
- * 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.util.ArrayList;
-import java.util.List;
-import java.util.Objects;
-import java.util.stream.Collectors;
-
-import org.apache.cassandra.cql3.terms.Term;
-import org.apache.cassandra.cql3.terms.Terms;
-import org.apache.cassandra.cql3.terms.Tuples;
-import org.apache.cassandra.schema.ColumnMetadata;
-import org.apache.cassandra.schema.TableMetadata;
-import org.apache.cassandra.cql3.restrictions.MultiColumnRestriction;
-import org.apache.cassandra.cql3.restrictions.Restriction;
-import org.apache.cassandra.cql3.statements.Bound;
-import org.apache.cassandra.exceptions.InvalidRequestException;
-
-import static org.apache.cassandra.cql3.statements.RequestValidations.checkFalse;
-import static org.apache.cassandra.cql3.statements.RequestValidations.checkTrue;
-import static org.apache.cassandra.cql3.statements.RequestValidations.invalidRequest;
-
-/**
- * A relation using the tuple notation, which typically affects multiple columns.
- * Examples:
- * {@code
- * - SELECT ... WHERE (a, b, c) > (1, 'a', 10)
- * - SELECT ... WHERE (a, b, c) IN ((1, 2, 3), (4, 5, 6))
- * - SELECT ... WHERE (a, b) < ?
- * - SELECT ... WHERE (a, b) IN ?
- * }
- */
-public class MultiColumnRelation extends Relation
-{
- private final List<ColumnIdentifier> entities;
-
- /** A literal or raw marker */
- private final Term.Raw value;
-
- /** A list of literals and/or raw markers or an IN raw marker */
- private final Terms.Raw inValues;
-
- private MultiColumnRelation(List<ColumnIdentifier> entities, Operator relationType, Term.Raw value, Terms.Raw inValues)
- {
- this.entities = entities;
- this.operator = relationType;
- this.value = value;
-
- this.inValues = inValues;
- }
-
- /**
- * Creates a multi-column EQ, LT, LTE, GT, or GTE relation.
- * {@code
- * For example: "SELECT ... WHERE (a, b) > (0, 1)"
- * }
- * @param entities the columns on the LHS of the relation
- * @param relationType the relation operator
- * @param value a literal or raw marker
- * @return a new <code>MultiColumnRelation</code> instance
- */
- public static MultiColumnRelation createNonInRelation(List<ColumnIdentifier> entities, Operator relationType, Term.Raw value)
- {
- assert relationType != Operator.IN;
- return new MultiColumnRelation(entities, relationType, value, null);
- }
-
- /**
- * Creates a multi-column IN relation with either a marker for the IN values or a list of IN values or markers.
- * For example: "SELECT ... WHERE (a, b) IN ((0, 1), (2, 3))"
- * @param entities the columns on the LHS of the relation
- * @param inValues the IN values as a {@code Terms.Raw}
- * @return a new <code>MultiColumnRelation</code> instance
- */
- public static MultiColumnRelation createInRelation(List<ColumnIdentifier> entities, Terms.Raw inValues)
- {
- return new MultiColumnRelation(entities, Operator.IN, null, inValues);
- }
-
- public List<ColumnIdentifier> getEntities()
- {
- return entities;
- }
-
- /**
- * For non-IN relations, returns a literal or a raw marker for a single tuple.
- * @return a literal or a raw marker for non-IN relations.
- */
- public Term.Raw getValue()
- {
- return value;
- }
-
- public Terms.Raw getInValues()
- {
- assert operator == Operator.IN;
- return inValues;
- }
-
- @Override
- protected Restriction newEQRestriction(TableMetadata table, VariableSpecifications boundNames)
- {
- List<ColumnMetadata> receivers = receivers(table);
- Term term = toTerm(Tuples.makeReceiver(receivers), getValue(), table.keyspace, boundNames);
- return new MultiColumnRestriction.EQRestriction(receivers, term);
- }
-
- @Override
- protected Restriction newINRestriction(TableMetadata table, VariableSpecifications boundNames)
- {
- List<ColumnMetadata> receivers = receivers(table);
- Terms terms = toTerms(Tuples.makeReceiver(receivers), inValues, table.keyspace, boundNames);
-
- if (terms.containsSingleTerm())
- return new MultiColumnRestriction.EQRestriction(receivers, terms.asSingleTerm());
-
- return new MultiColumnRestriction.INRestriction(receivers, terms);
- }
-
- @Override
- protected Restriction newSliceRestriction(TableMetadata table, VariableSpecifications boundNames, Bound bound, boolean inclusive)
- {
- List<ColumnMetadata> receivers = receivers(table);
- Term term = toTerm(Tuples.makeReceiver(receivers), getValue(), table.keyspace, boundNames);
- return new MultiColumnRestriction.SliceRestriction(receivers, bound, inclusive, term);
- }
-
- @Override
- protected Restriction newContainsRestriction(TableMetadata table, VariableSpecifications boundNames, boolean isKey)
- {
- throw invalidRequest("%s cannot be used for multi-column relations", operator());
- }
-
- @Override
- protected Restriction newIsNotRestriction(TableMetadata table, VariableSpecifications boundNames)
- {
- // this is currently disallowed by the grammar
- throw new AssertionError(String.format("%s cannot be used for multi-column relations", operator()));
- }
-
- @Override
- protected Restriction newLikeRestriction(TableMetadata table, VariableSpecifications boundNames, Operator operator)
- {
- throw invalidRequest("%s cannot be used for multi-column relations", operator());
- }
-
- protected List<ColumnMetadata> receivers(TableMetadata table) throws InvalidRequestException
- {
- List<ColumnMetadata> names = new ArrayList<>(getEntities().size());
- int previousPosition = -1;
- for (ColumnIdentifier id : getEntities())
- {
- ColumnMetadata def = table.getExistingColumn(id);
- checkTrue(def.isClusteringColumn(), "Multi-column relations can only be applied to clustering columns but was applied to: %s", def.name);
- checkFalse(names.contains(def), "Column \"%s\" appeared twice in a relation: %s", def.name, this);
-
- // check that no clustering columns were skipped
- checkFalse(previousPosition != -1 && def.position() != previousPosition + 1,
- "Clustering columns must appear in the PRIMARY KEY order in multi-column relations: %s", this);
-
- names.add(def);
- previousPosition = def.position();
- }
- return names;
- }
-
- @Override
- public Relation renameIdentifier(ColumnIdentifier from, ColumnIdentifier to)
- {
- if (!entities.contains(from))
- return this;
-
- List<ColumnIdentifier> newEntities = entities.stream().map(e -> e.equals(from) ? to : e).collect(Collectors.toList());
- return new MultiColumnRelation(newEntities, operator(), value, inValues);
- }
-
- @Override
- public String toCQLString()
- {
- StringBuilder builder = new StringBuilder(Tuples.tupleToString(entities, ColumnIdentifier::toCQLString));
- if (isIN())
- {
- return builder.append(" IN ")
- .append(inValues.getText())
- .toString();
- }
- return builder.append(' ')
- .append(operator)
- .append(' ')
- .append(value)
- .toString();
- }
-
- @Override
- public int hashCode()
- {
- return Objects.hash(operator, entities, value, inValues);
- }
-
- @Override
- public boolean equals(Object o)
- {
- if (this == o)
- return true;
-
- if (!(o instanceof MultiColumnRelation))
- return false;
-
- MultiColumnRelation mcr = (MultiColumnRelation) o;
- return Objects.equals(entities, mcr.entities)
- && operator == mcr.operator
- && Objects.equals(value, mcr.value)
- && Objects.equals(inValues, mcr.inValues);
- }
-}
diff --git a/src/java/org/apache/cassandra/cql3/Operator.java b/src/java/org/apache/cassandra/cql3/Operator.java
index 55d6779cfe..de372795a1 100644
--- a/src/java/org/apache/cassandra/cql3/Operator.java
+++ b/src/java/org/apache/cassandra/cql3/Operator.java
@@ -21,14 +21,28 @@ import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.nio.ByteBuffer;
+import java.util.Arrays;
import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-import org.apache.cassandra.db.marshal.*;
+import java.util.stream.Collectors;
+
+import com.google.common.collect.RangeSet;
+
+import org.apache.cassandra.cql3.restrictions.ClusteringElements;
+import org.apache.cassandra.db.marshal.AbstractType;
+import org.apache.cassandra.db.marshal.CollectionType;
+import org.apache.cassandra.db.marshal.ListType;
+import org.apache.cassandra.db.marshal.MapType;
+import org.apache.cassandra.db.marshal.SetType;
+import org.apache.cassandra.db.rows.Cell;
+import org.apache.cassandra.db.rows.CellPath;
+import org.apache.cassandra.db.rows.ComplexColumnData;
+import org.apache.cassandra.schema.ColumnMetadata;
import org.apache.cassandra.serializers.ListSerializer;
import org.apache.cassandra.utils.ByteBufferUtil;
+import static org.apache.cassandra.cql3.statements.RequestValidations.checkFalse;
+import static org.apache.cassandra.cql3.statements.RequestValidations.invalidRequest;
+
public enum Operator
{
EQ(0)
@@ -44,6 +58,33 @@ public enum Operator
{
return type.compareForCQL(leftOperand, rightOperand) == 0;
}
+
+ @Override
+ public boolean requiresFilteringOrIndexingFor(ColumnMetadata.Kind columnKind)
+ {
+ return !columnKind.isPrimaryKeyKind();
+ }
+
+ @Override
+ public void restrict(RangeSet<ClusteringElements> rangeSet, List<ClusteringElements> args)
+ {
+ assert args.size() == 1 : this + " accept only one single value";
+ ClusteringElements arg = args.get(0);
+ rangeSet.removeAll(ClusteringElements.lessThan(arg));
+ rangeSet.removeAll(ClusteringElements.greaterThan(arg));
+ }
+
+ @Override
+ public Operator negate()
+ {
+ return NEQ;
+ }
+
+ @Override
+ public boolean canBeUsedWith(ColumnsExpression.Kind kind)
+ {
+ return true;
+ }
},
LT(4)
{
@@ -58,6 +99,37 @@ public enum Operator
{
return type.compareForCQL(leftOperand, rightOperand) < 0;
}
+
+ @Override
+ public boolean requiresFilteringOrIndexingFor(ColumnMetadata.Kind columnKind)
+ {
+ return columnKind != ColumnMetadata.Kind.CLUSTERING;
+ }
+
+ @Override
+ public void restrict(RangeSet<ClusteringElements> rangeSet, List<ClusteringElements> args)
+ {
+ assert args.size() == 1 : this + " accept only one single value";
+ rangeSet.removeAll(ClusteringElements.atLeast(args.get(0)));
+ }
+
+ @Override
+ public Operator negate()
+ {
+ return GTE;
+ }
+
+ @Override
+ public boolean isSlice()
+ {
+ return true;
+ }
+
+ @Override
+ public boolean canBeUsedWith(ColumnsExpression.Kind kind)
+ {
+ return kind != ColumnsExpression.Kind.MAP_ELEMENT;
+ }
},
LTE(3)
{
@@ -72,6 +144,37 @@ public enum Operator
{
return type.compareForCQL(leftOperand, rightOperand) <= 0;
}
+
+ @Override
+ public boolean requiresFilteringOrIndexingFor(ColumnMetadata.Kind columnKind)
+ {
+ return columnKind != ColumnMetadata.Kind.CLUSTERING;
+ }
+
+ @Override
+ public void restrict(RangeSet<ClusteringElements> rangeSet, List<ClusteringElements> args)
+ {
+ assert args.size() == 1 : this + " accept only one single value";
+ rangeSet.removeAll(ClusteringElements.greaterThan(args.get(0)));
+ }
+
+ @Override
+ public Operator negate()
+ {
+ return GT;
+ }
+
+ @Override
+ public boolean isSlice()
+ {
+ return true;
+ }
+
+ @Override
+ public boolean canBeUsedWith(ColumnsExpression.Kind kind)
+ {
+ return kind != ColumnsExpression.Kind.MAP_ELEMENT;
+ }
},
GTE(1)
{
@@ -86,6 +189,37 @@ public enum Operator
{
return type.compareForCQL(leftOperand, rightOperand) >= 0;
}
+
+ @Override
+ public boolean requiresFilteringOrIndexingFor(ColumnMetadata.Kind columnKind)
+ {
+ return columnKind != ColumnMetadata.Kind.CLUSTERING;
+ }
+
+ @Override
+ public void restrict(RangeSet<ClusteringElements> rangeSet, List<ClusteringElements> args)
+ {
+ assert args.size() == 1 : this + " accept only one single value";
+ rangeSet.removeAll(ClusteringElements.lessThan(args.get(0)));
+ }
+
+ @Override
+ public Operator negate()
+ {
+ return LT;
+ }
+
+ @Override
+ public boolean isSlice()
+ {
+ return true;
+ }
+
+ @Override
+ public boolean canBeUsedWith(ColumnsExpression.Kind kind)
+ {
+ return kind != ColumnsExpression.Kind.MAP_ELEMENT;
+ }
},
GT(2)
{
@@ -100,49 +234,107 @@ public enum Operator
{
return type.compareForCQL(leftOperand, rightOperand) > 0;
}
- },
- IN(7)
- {
+
@Override
- public String toString()
+ public boolean requiresFilteringOrIndexingFor(ColumnMetadata.Kind columnKind)
{
- return "IN";
+ return columnKind != ColumnMetadata.Kind.CLUSTERING;
}
+ @Override
+ public void restrict(RangeSet<ClusteringElements> rangeSet, List<ClusteringElements> args)
+ {
+ assert args.size() == 1 : this + " accept only one single value";
+ rangeSet.removeAll(ClusteringElements.atMost(args.get(0)));
+ }
+
+ @Override
+ public Operator negate()
+ {
+ return LTE;
+ }
+
+ @Override
+ public boolean isSlice()
+ {
+ return true;
+ }
+
+ @Override
+ public boolean canBeUsedWith(ColumnsExpression.Kind kind)
+ {
+ return kind != ColumnsExpression.Kind.MAP_ELEMENT;
+ }
+ },
+ IN(7)
+ {
public boolean isSatisfiedBy(AbstractType<?> type, ByteBuffer leftOperand, ByteBuffer rightOperand)
{
ListSerializer<?> serializer = ListType.getInstance(type, false).getSerializer();
return serializer.anyMatch(rightOperand, r -> type.compareForCQL(leftOperand, r) == 0);
}
- },
- CONTAINS(5)
- {
+
@Override
- public String toString()
+ public boolean requiresFilteringOrIndexingFor(ColumnMetadata.Kind columnKind)
{
- return "CONTAINS";
+ return !columnKind.isPrimaryKeyKind();
}
+ @Override
+ public boolean canBeUsedWith(ColumnsExpression.Kind kind)
+ {
+ return kind == ColumnsExpression.Kind.SINGLE_COLUMN || kind == ColumnsExpression.Kind.MULTI_COLUMN;
+ }
+ },
+ CONTAINS(5)
+ {
@Override
public boolean isSatisfiedBy(AbstractType<?> type, ByteBuffer leftOperand, ByteBuffer rightOperand)
{
switch(((CollectionType<?>) type).kind)
{
- case LIST :
+ case LIST:
ListType<?> listType = (ListType<?>) type;
- List<?> list = listType.getSerializer().deserialize(leftOperand);
- return list.contains(listType.getElementsType().getSerializer().deserialize(rightOperand));
+ return listType.compose(leftOperand).contains(listType.getElementsType().compose(rightOperand));
case SET:
SetType<?> setType = (SetType<?>) type;
- Set<?> set = setType.getSerializer().deserialize(leftOperand);
- return set.contains(setType.getElementsType().getSerializer().deserialize(rightOperand));
+ return setType.compose(leftOperand).contains(setType.getElementsType().compose(rightOperand));
case MAP:
MapType<?, ?> mapType = (MapType<?, ?>) type;
- Map<?, ?> map = mapType.getSerializer().deserialize(leftOperand);
- return map.containsValue(mapType.getValuesType().getSerializer().deserialize(rightOperand));
- default:
- throw new AssertionError();
+ return mapType.compose(leftOperand).containsValue(mapType.getValuesType().compose(rightOperand));
+ }
+ throw new AssertionError();
+ }
+
+ @Override
+ public boolean isSatisfiedBy(CollectionType<?> type, ComplexColumnData leftOperand, ByteBuffer rightOperand)
+ {
+ for (Cell<?> cell : leftOperand)
+ {
+ if (type.kind == CollectionType.Kind.SET)
+ {
+ if (type.nameComparator().compare(cell.path().get(0), rightOperand) == 0)
+ return true;
+ }
+ else
+ {
+ if (type.valueComparator().compare(cell.buffer(), rightOperand) == 0)
+ return true;
+ }
}
+ return false;
+ }
+
+ @Override
+ public boolean appliesToColumnValues()
+ {
+ return false;
+ }
+
+ @Override
+ public boolean appliesToCollectionElements()
+ {
+ return true;
}
},
CONTAINS_KEY(6)
@@ -157,8 +349,25 @@ public enum Operator
public boolean isSatisfiedBy(AbstractType<?> type, ByteBuffer leftOperand, ByteBuffer rightOperand)
{
MapType<?, ?> mapType = (MapType<?, ?>) type;
- Map<?, ?> map = mapType.getSerializer().deserialize(leftOperand);
- return map.containsKey(mapType.getKeysType().getSerializer().deserialize(rightOperand));
+ return mapType.compose(leftOperand).containsKey(mapType.getKeysType().compose(rightOperand));
+ }
+
+ @Override
+ public boolean isSatisfiedBy(CollectionType<?> type, ComplexColumnData leftOperand, ByteBuffer rightOperand)
+ {
+ return leftOperand.getCell(CellPath.create(rightOperand)) != null;
+ }
+
+ @Override
+ public boolean appliesToColumnValues()
+ {
+ return false;
+ }
+
+ @Override
+ public boolean appliesToMapKeys()
+ {
+ return true;
}
},
NEQ(8)
@@ -173,7 +382,24 @@ public enum Operator
public boolean isSatisfiedBy(AbstractType<?> type, ByteBuffer leftOperand, ByteBuffer rightOperand)
{
return type.compareForCQL(leftOperand, rightOperand) != 0;
+ }
+
+ @Override
+ public boolean requiresFilteringOrIndexingFor(ColumnMetadata.Kind columnKind)
+ {
+ return !columnKind.isPrimaryKeyKind();
+ }
+ @Override
+ public Operator negate()
+ {
+ return EQ;
+ }
+
+ @Override
+ protected boolean isSupportedByReadPath()
+ {
+ return false;
}
},
IS_NOT(9)
@@ -189,6 +415,12 @@ public enum Operator
{
throw new UnsupportedOperationException();
}
+
+ @Override
+ protected boolean isSupportedByReadPath()
+ {
+ return false;
+ }
},
LIKE_PREFIX(10)
{
@@ -248,31 +480,31 @@ public enum Operator
LIKE(14)
{
@Override
- public String toString()
+ public boolean isSatisfiedBy(AbstractType<?> type, ByteBuffer leftOperand, ByteBuffer rightOperand)
{
- return "LIKE";
+ throw new UnsupportedOperationException();
}
@Override
- public boolean isSatisfiedBy(AbstractType<?> type, ByteBuffer leftOperand, ByteBuffer rightOperand)
+ public boolean requiresIndexing()
{
- throw new UnsupportedOperationException();
+ return true;
}
},
ANN(15)
{
- @Override
- public String toString()
- {
- return "ANN";
- }
-
@Override
public boolean isSatisfiedBy(AbstractType<?> type, ByteBuffer leftOperand, ByteBuffer rightOperand)
{
// The ANN operator is only supported by the vector index so, normally, should never be called directly.
// In networked queries (non-local) the coordinator will end up calling the row filter directly. So, this
// needs to return true so that the returned values are allowed through to the VectorTopKProcessor
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public boolean requiresIndexing()
+ {
return true;
}
};
@@ -283,10 +515,10 @@ public enum Operator
private final int b;
/**
- * Creates a new <code>Operator</code> with the specified binary representation.
- * @param b the binary representation of this <code>Enum</code> value
+ * Creates a new {@code Operator} with the specified binary representation.
+ * @param b the binary representation of this {@code Enum} value
*/
- private Operator(int b)
+ Operator(int b)
{
this.b = b;
}
@@ -299,7 +531,7 @@ public enum Operator
*/
public void writeTo(DataOutput output) throws IOException
{
- output.writeInt(b);
+ output.writeInt(getValue());
}
public int getValue()
@@ -324,23 +556,152 @@ public enum Operator
throw new IOException(String.format("Cannot resolve Relation.Type from binary representation: %s", b));
}
+
/**
* Whether 2 values satisfy this operator (given the type they should be compared with).
*/
public abstract boolean isSatisfiedBy(AbstractType<?> type, ByteBuffer leftOperand, ByteBuffer rightOperand);
- public int serializedSize()
+
+ public boolean isSatisfiedBy(CollectionType<?> type, ComplexColumnData leftOperand, ByteBuffer rightOperand)
+ {
+ throw new UnsupportedOperationException();
+ }
+
+ public static int serializedSize()
{
return 4;
}
+ public void validateFor(ColumnsExpression expression)
+ {
+ if (!canBeUsedWith(expression.kind()))
+ throw invalidRequest("%s cannot be used with %s relations", this, expression);
+
+ switch (expression.kind())
+ {
+ case SINGLE_COLUMN:
+ ColumnMetadata firstColumn = expression.firstColumn();
+ AbstractType<?> columnType = firstColumn.type;
+ if (isSlice())
+ {
+ if (columnType.referencesDuration())
+ {
+ checkFalse(columnType.isCollection(), "Slice restrictions are not supported on collections containing durations");
+ checkFalse(columnType.isTuple(), "Slice restrictions are not supported on tuples containing durations");
+ checkFalse(columnType.isUDT(), "Slice restrictions are not supported on UDTs containing durations");
+ throw invalidRequest("Slice restrictions are not supported on duration columns");
+ }
+ }
+ else
+ {
+ checkFalse(appliesToMapKeys() && !(columnType instanceof MapType), "Cannot use %s on non-map column %s", this, firstColumn.name);
+ checkFalse(appliesToCollectionElements() && !columnType.isCollection(), "Cannot use %s on non-collection column %s", this, firstColumn.name);
+ }
+
+ case MAP_ELEMENT:
+ ColumnMetadata column = expression.firstColumn();
+ AbstractType<?> type = column.type;
+ if (type.isMultiCell())
+ {
+ // Non-frozen UDTs don't support any operator
+ checkFalse(type.isUDT(),
+ "Non-frozen UDT column '%s' (%s) cannot be restricted by any relation",
+ column.name,
+ type.asCQL3Type());
+
+ // We don't support relations against entire collections (unless they're frozen), like "numbers = {1, 2, 3}"
+ checkFalse(type.isCollection()
+ && !this.appliesToMapKeys()
+ && !this.appliesToCollectionElements()
+ && expression.kind() != ColumnsExpression.Kind.MAP_ELEMENT,
+ "Collection column '%s' (%s) cannot be restricted by a '%s' relation",
+ column.name,
+ type.asCQL3Type(),
+ this);
+ }
+ break;
+ }
+ }
+
/**
- * Checks if this operator is a slice operator.
+ * Checks if the specified expression kind can be used with this operator.
+ * @param kind the expression kind
+ * @return {@code true} if the specified expression kind can be used with this operator, {@code false} otherwise.
+ */
+ public boolean canBeUsedWith(ColumnsExpression.Kind kind)
+ {
+ // All operators support single columns
+ return kind == ColumnsExpression.Kind.SINGLE_COLUMN;
+ }
+
+ /**
+ * Checks if this operator applies to non-multicell column values.
+ * @return {@code true} if this operator applies to column values, {@code false} otherwise.
+ */
+ public boolean appliesToColumnValues()
+ {
+ return true;
+ }
+
+ /**
+ * Checks if this operator applies to collection elements (from frozen and non-frozen collections).
+ * @return {@code true} if this operator applies to collection elements, {@code false} otherwise.
+ */
+ public boolean appliesToCollectionElements()
+ {
+ return false;
+ }
+
+ /**
+ * Checks if this operator applies to map keys.
+ * @return {@code true} if this operator applies to map keys, {@code false} otherwise.
+ */
+ public boolean appliesToMapKeys()
+ {
+ return false;
+ }
+
+ /**
+ * Restricts the specified range set based on the operator arguments (optional operation).
+ * @param rangeSet the range set to restrict
+ * @param args the operator arguments
+ */
+ public void restrict(RangeSet<ClusteringElements> rangeSet, List<ClusteringElements> args)
+ {
+ throw new UnsupportedOperationException(this + " is not a range operator");
+ }
+
+ /**
+ * Checks if this operator <b>requires</b> either filtering or indexing for the specified columns kinds.
+ * <p>An operator requires filtering or indexing only if it cannot be executed by other means.
+ * An equal operator on a clustering column for example will return {@code false} even if filtering might be used
+ * because the previous clustering column is not restricted.</p>
+ *
+ * @param columnKind the kind of column being restricted by the operator
+ * @return {@code true} if this operator requires either filtering or indexing, {@code false} otherwise.
+ */
+ public boolean requiresFilteringOrIndexingFor(ColumnMetadata.Kind columnKind)
+ {
+ return true;
+ }
+
+ /**
+ * Checks if this operator requires a secondary index.
+ * @return {@code true} if this operator requires a secondary index, {@code false} otherwise.
+ */
+ public boolean requiresIndexing()
+ {
+ return false;
+ }
+
+ /**
+ * Checks if this operator returning a slice of the data.
* @return {@code true} if this operator is a slice operator, {@code false} otherwise.
*/
public boolean isSlice()
{
- return this == LT || this == LTE || this == GT || this == GTE;
+ return false;
}
@Override
@@ -359,20 +720,43 @@ public enum Operator
}
/**
- * Checks if this operator is CONTAINS operator.
- * @return {@code true} if this operator is a CONTAINS operator, {@code false} otherwise.
+ * Reverse this operator.
+ * @return the reverse operator from this operator.
+ */
+ public Operator negate()
+ {
+ throw new UnsupportedOperationException(this + " does not support negation");
+ }
+
+ /**
+ * Some operators are not supported by the read path because we never fully implemented support for them.
+ * It is the case for {@code IS_NOT} and {@code !=}
+ * @return {@code true} for the operators supported by the read path, {@code false} otherwise.
+ */
+ protected boolean isSupportedByReadPath()
+ {
+ return true;
+ }
+
+ /**
+ * The "LIKE_" operators are not real CQL operators and are simply an internal hack that should be removed at some point.
+ * Therefore, we want to ignore them in the error messages returned to the users.
+ * @return {@code true} for the "LIKE_" operators
*/
- public boolean isContains()
+ private boolean isLikeVariant()
{
- return this == CONTAINS;
+ return this == LIKE_CONTAINS || this == LIKE_PREFIX || this == LIKE_MATCHES || this == LIKE_SUFFIX;
}
/**
- * Checks if this operator is CONTAINS KEY operator.
- * @return {@code true} if this operator is a CONTAINS operator, {@code false} otherwise.
+ * Returns the operators that require an index or filtering for the specified column kind
+ * @param columnKind the column kind
+ * @return the operators that require an index or filtering for the specified column kind
*/
- public boolean isContainsKey()
+ public static List<Operator> operatorsRequiringFilteringOrIndexingFor(ColumnMetadata.Kind columnKind)
{
- return this == CONTAINS_KEY;
+ return Arrays.stream(values())
+ .filter(o -> o.isSupportedByReadPath() && !o.isLikeVariant() && o.requiresFilteringOrIndexingFor(columnKind))
+ .collect(Collectors.toList());
}
}
diff --git a/src/java/org/apache/cassandra/cql3/Ordering.java b/src/java/org/apache/cassandra/cql3/Ordering.java
index 0d8375a133..f05245a2f7 100644
--- a/src/java/org/apache/cassandra/cql3/Ordering.java
+++ b/src/java/org/apache/cassandra/cql3/Ordering.java
@@ -18,9 +18,10 @@
package org.apache.cassandra.cql3;
-import org.apache.cassandra.cql3.restrictions.SingleColumnRestriction;
+import org.apache.cassandra.cql3.restrictions.SimpleRestriction;
import org.apache.cassandra.cql3.restrictions.SingleRestriction;
import org.apache.cassandra.cql3.terms.Term;
+import org.apache.cassandra.cql3.terms.Terms;
import org.apache.cassandra.schema.ColumnMetadata;
import org.apache.cassandra.schema.TableMetadata;
@@ -100,7 +101,9 @@ public class Ordering
@Override
public SingleRestriction toRestriction()
{
- return new SingleColumnRestriction.AnnRestriction(columnMetadata, vectorValue);
+ return new SimpleRestriction(ColumnsExpression.singleColumn(columnMetadata),
+ Operator.ANN,
+ Terms.of(vectorValue));
}
}
diff --git a/src/java/org/apache/cassandra/cql3/Relation.java b/src/java/org/apache/cassandra/cql3/Relation.java
index 20dae5854c..8054639e8c 100644
--- a/src/java/org/apache/cassandra/cql3/Relation.java
+++ b/src/java/org/apache/cassandra/cql3/Relation.java
@@ -17,227 +17,172 @@
*/
package org.apache.cassandra.cql3;
+import java.util.List;
+import java.util.Objects;
+
+import org.apache.cassandra.cql3.restrictions.SimpleRestriction;
+import org.apache.cassandra.cql3.restrictions.SingleRestriction;
import org.apache.cassandra.cql3.terms.Term;
import org.apache.cassandra.cql3.terms.Terms;
+import org.apache.cassandra.db.marshal.CollectionType;
import org.apache.cassandra.schema.TableMetadata;
-import org.apache.cassandra.cql3.restrictions.Restriction;
-import org.apache.cassandra.cql3.statements.Bound;
import org.apache.cassandra.exceptions.InvalidRequestException;
-
import static org.apache.cassandra.cql3.statements.RequestValidations.invalidRequest;
-public abstract class Relation
+/**
+ * The parsed version of a {@code SimpleRestriction} as outputed by the CQL parser.
+ * {@code Relation.prepare} will be called upon schema binding to create a {@code SimpleRestriction}.
+ */
+public final class Relation
{
- protected Operator operator;
-
- public Operator operator()
- {
- return operator;
- }
-
/**
- * Returns the raw value for this relation, or null if this is an IN relation.
+ * The raw columns'expression.
*/
- public abstract Term.Raw getValue();
+ private final ColumnsExpression.Raw rawExpressions;
/**
- * Returns the list of raw IN values for this relation, or null if this is not an IN relation.
+ * The relation operator
*/
- public abstract Terms.Raw getInValues();
+ private final Operator operator;
/**
- * Checks if this relation is a token relation (e.g. <pre>token(a) = token(1)</pre>).
- *
- * @return <code>true</code> if this relation is a token relation, <code>false</code> otherwise.
+ * The raw terms.
*/
- public boolean onToken()
- {
- return false;
- }
+ private final Terms.Raw rawTerms;
- /**
- * Checks if the operator of this relation is a <code>CONTAINS</code>.
- * @return <code>true</code> if the operator of this relation is a <code>CONTAINS</code>, <code>false</code>
- * otherwise.
- */
- public final boolean isContains()
+ private Relation(ColumnsExpression.Raw rawExpressions, Operator operator, Terms.Raw rawTerms)
{
- return operator == Operator.CONTAINS;
+ this.rawExpressions = rawExpressions;
+ this.operator = operator;
+ this.rawTerms = rawTerms;
}
- /**
- * Checks if the operator of this relation is a <code>CONTAINS_KEY</code>.
- * @return <code>true</code> if the operator of this relation is a <code>CONTAINS_KEY</code>, <code>false</code>
- * otherwise.
- */
- public final boolean isContainsKey()
+ public Operator operator()
{
- return operator == Operator.CONTAINS_KEY;
+ return operator;
}
/**
- * Checks if the operator of this relation is a <code>IN</code>.
- * @return <code>true</code> if the operator of this relation is a <code>IN</code>, <code>false</code>
- * otherwise.
+ * Creates a relation for a single column (e.g. {@code columnA = ?} ).
+ *
+ * @param identifier the column identifier to which the relation applies
+ * @param operator the relation operator
+ * @param rawTerm the term to which the column values must be compared
+ * @return a relation for a single column.
*/
- public final boolean isIN()
+ public static Relation singleColumn(ColumnIdentifier identifier, Operator operator, Term.Raw rawTerm)
{
- return operator == Operator.IN;
+ assert operator != Operator.IN;
+ return new Relation(ColumnsExpression.Raw.singleColumn(identifier), operator, Terms.Raw.of(rawTerm));
}
/**
- * Checks if the operator of this relation is a <code>EQ</code>.
- * @return <code>true</code> if the operator of this relation is a <code>EQ</code>, <code>false</code>
- * otherwise.
+ * Creates a relation for a single column (e.g. {@code columnA IN ?} ).
+ *
+ * @param identifier the column identifier to which the relation applies
+ * @param operator the relation operator
+ * @param rawTerms the terms to which the column values must be compared
+ * @return a relation for a single column.
*/
- public final boolean isEQ()
+ public static Relation singleColumn(ColumnIdentifier identifier, Operator operator, Terms.Raw rawTerms)
{
- return operator == Operator.EQ;
- }
-
- public final boolean isLIKE()
- {
- return operator == Operator.LIKE_PREFIX
- || operator == Operator.LIKE_SUFFIX
- || operator == Operator.LIKE_CONTAINS
- || operator == Operator.LIKE_MATCHES
- || operator == Operator.LIKE;
+ return new Relation(ColumnsExpression.Raw.singleColumn(identifier), operator, rawTerms);
}
/**
- * Checks if the operator of this relation is a <code>Slice</code> (GT, GTE, LTE, LT).
+ * Creates a relation for a map element (e.g. {@code columnA[?] = ?}).
*
- * @return <code>true</code> if the operator of this relation is a <code>Slice</code>, <code>false</code> otherwise.
+ * @param identifier the map column identifier
+ * @param rawKey the map element key
+ * @param operator the relation operator
+ * @param rawTerm the term to which the map element must be compared
+ * @return a relation for a map element.
*/
- public final boolean isSlice()
+ public static Relation mapElement(ColumnIdentifier identifier, Term.Raw rawKey, Operator operator, Term.Raw rawTerm)
{
- return operator == Operator.GT
- || operator == Operator.GTE
- || operator == Operator.LTE
- || operator == Operator.LT;
+ return new Relation(ColumnsExpression.Raw.mapElement(identifier, rawKey), operator, Terms.Raw.of(rawTerm));
}
/**
- * Converts this <code>Relation</code> into a <code>Restriction</code>.
+ * Creates a relation for multiple columns (e.g. {@code (columnA, columnB) = (?, ?)}).
*
- * @param table the Column Family meta data
- * @param boundNames the variables specification where to collect the bind variables
- * @return the <code>Restriction</code> corresponding to this <code>Relation</code>
- * @throws InvalidRequestException if this <code>Relation</code> is not valid
+ * @param identifiers the columns identifiers
+ * @param operator the relation operator
+ * @param rawTerm the term (tuple) to which the multiple columns must be compared
+ * @return a relation for multiple columns.
*/
- public final Restriction toRestriction(TableMetadata table, VariableSpecifications boundNames)
+ public static Relation multiColumn(List<ColumnIdentifier> identifiers, Operator operator, Term.Raw rawTerm)
{
- switch (operator)
- {
- case EQ: return newEQRestriction(table, boundNames);
- case LT: return newSliceRestriction(table, boundNames, Bound.END, false);
- case LTE: return newSliceRestriction(table, boundNames, Bound.END, true);
- case GTE: return newSliceRestriction(table, boundNames, Bound.START, true);
- case GT: return newSliceRestriction(table, boundNames, Bound.START, false);
- case IN: return newINRestriction(table, boundNames);
- case CONTAINS: return newContainsRestriction(table, boundNames, false);
- case CONTAINS_KEY: return newContainsRestriction(table, boundNames, true);
- case IS_NOT: return newIsNotRestriction(table, boundNames);
- case LIKE_PREFIX:
- case LIKE_SUFFIX:
- case LIKE_CONTAINS:
- case LIKE_MATCHES:
- case LIKE:
- return newLikeRestriction(table, boundNames, operator);
- case ANN:
- throw invalidRequest("ANN is only supported in ORDER BY");
- default: throw invalidRequest("Unsupported \"!=\" relation: %s", this);
- }
+ assert operator != Operator.IN;
+ return new Relation(ColumnsExpression.Raw.multiColumn(identifiers), operator, Terms.Raw.of(rawTerm));
}
/**
- * Creates a new EQ restriction instance.
+ * Creates a relation for multiple columns (e.g. {@code (columnA, columnB) = (?, ?)}).
*
- * @param table the table meta data
- * @param boundNames the variables specification where to collect the bind variables
- * @return a new EQ restriction instance.
- * @throws InvalidRequestException if the relation cannot be converted into an EQ restriction.
+ * @param identifiers the columns identifiers
+ * @param operator the relation operator
+ * @param rawTerms the terms (tuples) to which the multiple columns must be compared
+ * @return a relation for multiple columns.
*/
- protected abstract Restriction newEQRestriction(TableMetadata table, VariableSpecifications boundNames);
+ public static Relation multiColumn(List<ColumnIdentifier> identifiers, Operator operator, Terms.Raw rawTerms)
+ {
+ return new Relation(ColumnsExpression.Raw.multiColumn(identifiers), operator, rawTerms);
+ }
/**
- * Creates a new IN restriction instance.
+ * Creates a relation for token expression (e.g. {@code token(columnA, columnB) = ?} ).
*
- * @param table the table meta data
- * @param boundNames the variables specification where to collect the bind variables
- * @return a new IN restriction instance
- * @throws InvalidRequestException if the relation cannot be converted into an IN restriction.
+ * @param identifiers the column identifiers for the partition columns
+ * @param operator the relation operator
+ * @param rawTerm the terms to which the token value must be compared
+ * @return a relation for a token expression.
*/
- protected abstract Restriction newINRestriction(TableMetadata table, VariableSpecifications boundNames);
+ public static Relation token(List<ColumnIdentifier> identifiers, Operator operator, Term.Raw rawTerm)
+ {
+ return new Relation(ColumnsExpression.Raw.token(identifiers), operator, Terms.Raw.of(rawTerm));
+ }
/**
- * Creates a new Slice restriction instance.
+ * Checks if this relation is a token relation (e.g. <pre>token(a) = token(1)</pre>).
*
- * @param table the table meta data
- * @param boundNames the variables specification where to collect the bind variables
- * @param bound the slice bound
- * @param inclusive <code>true</code> if the bound is included.
- * @return a new slice restriction instance
- * @throws InvalidRequestException if the <code>Relation</code> is not valid
+ * @return <code>true</code> if this relation is a token relation, <code>false</code> otherwise.
*/
- protected abstract Restriction newSliceRestriction(TableMetadata table,
- VariableSpecifications boundNames,
- Bound bound,
- boolean inclusive);
+ public boolean onToken()
+ {
+ return rawExpressions.kind() == ColumnsExpression.Kind.TOKEN;
+ }
/**
- * Creates a new Contains restriction instance.
+ * Converts this <code>Relation</code> into a <code>Restriction</code>.
*
- * @param table the table meta data
+ * @param table the table metadata
* @param boundNames the variables specification where to collect the bind variables
- * @param isKey <code>true</code> if the restriction to create is a CONTAINS KEY
- * @return a new Contains <code>Restriction</code> instance
- * @throws InvalidRequestException if the <code>Relation</code> is not valid
+ * @return the <code>Restriction</code> corresponding to this <code>Relation</code>
+ * @throws InvalidRequestException if this <code>Relation</code> is not valid
*/
- protected abstract Restriction newContainsRestriction(TableMetadata table, VariableSpecifications boundNames, boolean isKey);
+ public SingleRestriction toRestriction(TableMetadata table, VariableSpecifications boundNames)
+ {
+ if (operator == Operator.NEQ)
+ throw invalidRequest("Unsupported '!=' relation: %s", this);
- protected abstract Restriction newIsNotRestriction(TableMetadata table, VariableSpecifications boundNames);
+ ColumnsExpression expression = rawExpressions.prepare(table);
+ expression.collectMarkerSpecification(boundNames);
- protected abstract Restriction newLikeRestriction(TableMetadata table, VariableSpecifications boundNames, Operator operator);
+ operator.validateFor(expression);
- /**
- * Converts the specified <code>Raw</code> into a <code>Term</code>.
- * @param receiver the column to which the values must be associated at
- * @param raw the raw term to convert
- * @param keyspace the keyspace name
- * @param boundNames the variables specification where to collect the bind variables
- *
- * @return the <code>Term</code> corresponding to the specified <code>Raw</code>
- * @throws InvalidRequestException if the <code>Raw</code> term is not valid
- */
- protected final Term toTerm(ColumnSpecification receiver,
- Term.Raw raw,
- String keyspace,
- VariableSpecifications boundNames)
- {
- Term term = raw.prepare(keyspace, receiver);
- term.collectMarkerSpecification(boundNames);
- return term;
- }
+ ColumnSpecification receiver = expression.columnSpecification();
+ if (!operator.appliesToColumnValues())
+ receiver = ((CollectionType<?>) receiver.type).makeCollectionReceiver(receiver, operator.appliesToMapKeys());
- /**
- * Converts the specified <code>Raw</code> terms into a <code>Terms</code>.
- * @param receiver the column to which the values must be associated at
- * @param raws the raw terms to convert
- * @param keyspace the keyspace name
- * @param boundNames the variables specification where to collect the bind variables
- *
- * @return the <code>Term</code>s corresponding to the specified <code>Raw</code> terms
- * @throws InvalidRequestException if the <code>Raw</code> terms are not valid
- */
- protected final Terms toTerms(ColumnSpecification receiver,
- Terms.Raw raws,
- String keyspace,
- VariableSpecifications boundNames)
- {
- Terms terms = raws.prepare(keyspace, receiver);
+ Terms terms = rawTerms.prepare(table.keyspace, receiver);
terms.collectMarkerSpecification(boundNames);
- return terms;
+
+ // An IN restriction with only one element is the same as an EQ restriction
+ if (operator.isIN() && terms.containsSingleTerm())
+ return new SimpleRestriction(expression, Operator.EQ, terms);
+
+ return new SimpleRestriction(expression, operator, terms);
}
/**
@@ -247,14 +192,41 @@ public abstract class Relation
* @return this object, if the old identifier is not in the set of entities that this relation covers; otherwise
* a new Relation with "from" replaced by "to" is returned.
*/
- public abstract Relation renameIdentifier(ColumnIdentifier from, ColumnIdentifier to);
+ public Relation renameIdentifier(ColumnIdentifier from, ColumnIdentifier to)
+ {
+ return new Relation(rawExpressions.renameIdentifier(from, to), operator, rawTerms);
+ }
+
+ @Override
+ public boolean equals(Object o)
+ {
+ if (this == o)
+ return true;
+
+ if (o == null || getClass() != o.getClass())
+ return false;
+
+ Relation relation = (Relation) o;
+ return Objects.equals(rawExpressions, relation.rawExpressions)
+ && operator == relation.operator
+ && Objects.equals(rawTerms, relation.rawTerms);
+ }
+
+ @Override
+ public int hashCode()
+ {
+ return Objects.hash(rawExpressions, operator, rawTerms);
+ }
/**
* Returns a CQL representation of this relation.
*
* @return a CQL representation of this relation
*/
- public abstract String toCQLString();
+ public String toCQLString()
+ {
+ return String.format("%s %s %s", rawExpressions.toCQLString(), operator, rawTerms.getText());
+ }
@Override
public String toString()
diff --git a/src/java/org/apache/cassandra/cql3/SingleColumnRelation.java b/src/java/org/apache/cassandra/cql3/SingleColumnRelation.java
deleted file mode 100644
index 57c16c31f8..0000000000
--- a/src/java/org/apache/cassandra/cql3/SingleColumnRelation.java
+++ /dev/null
@@ -1,294 +0,0 @@
-/*
- * 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.util.Objects;
-
-import javax.annotation.Nullable;
-
-import org.apache.cassandra.cql3.terms.Constants;
-import org.apache.cassandra.cql3.terms.Term;
-import org.apache.cassandra.cql3.terms.Terms;
-import org.apache.cassandra.schema.ColumnMetadata;
-import org.apache.cassandra.schema.TableMetadata;
-import org.apache.cassandra.cql3.restrictions.Restriction;
-import org.apache.cassandra.cql3.restrictions.SingleColumnRestriction;
-import org.apache.cassandra.cql3.statements.Bound;
-import org.apache.cassandra.db.marshal.CollectionType;
-import org.apache.cassandra.db.marshal.ListType;
-import org.apache.cassandra.db.marshal.MapType;
-import org.apache.cassandra.exceptions.InvalidRequestException;
-
-import static org.apache.cassandra.cql3.statements.RequestValidations.checkFalse;
-import static org.apache.cassandra.cql3.statements.RequestValidations.checkTrue;
-import static org.apache.cassandra.cql3.statements.RequestValidations.invalidRequest;
-
-/**
- * A filter on a column values.
- */
-public final class SingleColumnRelation extends Relation
-{
- private final ColumnIdentifier column;
- private final Term.Raw mapKey;
- private final Term.Raw value;
- private final Terms.Raw inValues;
-
- private SingleColumnRelation(ColumnIdentifier column,
- @Nullable Term.Raw mapKey,
- Operator operator,
- @Nullable Term.Raw value,
- @Nullable Terms.Raw inValues)
- {
- // If mapKey is not null the Operator should be EQ
- assert mapKey == null || operator == Operator.EQ;
-
- this.column = column;
- this.mapKey = mapKey;
- this.operator = operator;
- this.value = value;
- this.inValues = inValues;
-
- assert operator != Operator.IS_NOT || value == Constants.NULL_LITERAL;
- }
-
- /**
- * Creates a new relation.
- *
- * @param column the column that need to be filtered
- * @param mapKey the map key used for filtering map column using key value
- * @param operator the operator used to perform the filtering
- * @param value the value to which the column values must be compared
- */
- public SingleColumnRelation(ColumnIdentifier column, Term.Raw mapKey, Operator operator, Term.Raw value)
- {
- this(column, mapKey, operator, value, null);
- }
-
- /**
- * Creates a new relation.
- *
- * @param column the column that need to be filtered
- * @param operator the operator used to perform the filtering
- * @param value the value to which the column values must be compared
- */
- public SingleColumnRelation(ColumnIdentifier column, Operator operator, Term.Raw value)
- {
- this(column, null, operator, value);
- }
-
- /**
- * Creates a new relation.
- *
- * @param column the column that need to be filtered
- * @param operator the operator used to perform the filtering
- * @param inValues the IN value being compared.
- */
- public SingleColumnRelation(ColumnIdentifier column, Operator operator, Terms.Raw inValues)
- {
- this(column, null, operator, null, inValues);
- }
-
- public Term.Raw getValue()
- {
- return value;
- }
-
- public Terms.Raw getInValues()
- {
- return inValues;
- }
-
- public static SingleColumnRelation createInRelation(ColumnIdentifier column, Terms.Raw inValues)
- {
- return new SingleColumnRelation(column, null, Operator.IN, null, inValues);
- }
-
- public Relation renameIdentifier(ColumnIdentifier from, ColumnIdentifier to)
- {
- return column.equals(from)
- ? new SingleColumnRelation(to, mapKey, operator(), value, inValues)
- : this;
- }
-
- @Override
- public String toCQLString()
- {
- String columnAsString = column.toCQLString();
- if (mapKey != null)
- columnAsString = String.format("%s[%s]", columnAsString, mapKey);
-
- if (isIN())
- return String.format("%s IN %s", columnAsString, inValues);
-
- return String.format("%s %s %s", columnAsString, operator, value);
- }
-
- @Override
- public int hashCode()
- {
- return Objects.hash(operator, column, mapKey, value, inValues);
- }
-
- @Override
- public boolean equals(Object o)
- {
- if (this == o)
- return true;
-
- if (!(o instanceof SingleColumnRelation))
- return false;
-
- SingleColumnRelation scr = (SingleColumnRelation) o;
- return Objects.equals(column, scr.column)
- && operator == scr.operator
- && Objects.equals(mapKey, scr.mapKey)
- && Objects.equals(value, scr.value)
- && Objects.equals(inValues, scr.inValues);
- }
-
- @Override
- protected Restriction newEQRestriction(TableMetadata table, VariableSpecifications boundNames)
- {
- ColumnMetadata column = table.getExistingColumn(this.column);
- validateReceiver(column);
- if (mapKey == null)
- {
- Term term = toTerm(column, value, table.keyspace, boundNames);
- return new SingleColumnRestriction.EQRestriction(column, term);
- }
-
- checkFalse(column.type instanceof ListType, "Indexes on list entries (%s[index] = value) are not supported.", column.name);
- checkTrue(column.type instanceof MapType, "Column %s cannot be used as a map", column.name);
- checkTrue(column.type.isMultiCell(), "Map-entry equality predicates on frozen map column %s are not supported", column.name);
-
- Term entryKey = toTerm(makeCollectionReceiver(column, true), mapKey, table.keyspace, boundNames);
- Term entryValue = toTerm(makeCollectionReceiver(column, false), value, table.keyspace, boundNames);
- return new SingleColumnRestriction.ContainsRestriction(column, entryKey, entryValue);
- }
-
- @Override
- protected Restriction newINRestriction(TableMetadata table, VariableSpecifications boundNames)
- {
- ColumnMetadata column = table.getExistingColumn(this.column);
- validateReceiver(column);
- Terms terms = toTerms(column, inValues, table.keyspace, boundNames);
-
- // An IN restriction with only one element is the same as an EQ restriction
- if (terms.containsSingleTerm())
- return new SingleColumnRestriction.EQRestriction(column, terms.asSingleTerm());
-
- return new SingleColumnRestriction.INRestriction(column, terms);
- }
-
- @Override
- protected Restriction newSliceRestriction(TableMetadata table,
- VariableSpecifications boundNames,
- Bound bound,
- boolean inclusive)
- {
- ColumnMetadata columnDef = table.getExistingColumn(column);
-
- if (columnDef.type.referencesDuration())
- {
- checkFalse(columnDef.type.isCollection(), "Slice restrictions are not supported on collections containing durations");
- checkFalse(columnDef.type.isTuple(), "Slice restrictions are not supported on tuples containing durations");
- checkFalse(columnDef.type.isUDT(), "Slice restrictions are not supported on UDTs containing durations");
- throw invalidRequest("Slice restrictions are not supported on duration columns");
- }
- validateReceiver(columnDef);
-
- Term term = toTerm(columnDef, value, table.keyspace, boundNames);
- return new SingleColumnRestriction.SliceRestriction(columnDef, bound, inclusive, term);
- }
-
- @Override
- protected Restriction newContainsRestriction(TableMetadata table,
- VariableSpecifications boundNames,
- boolean isKey) throws InvalidRequestException
- {
- ColumnMetadata column = table.getExistingColumn(this.column);
-
- checkFalse(isContainsKey() && !(column.type instanceof MapType), "Cannot use CONTAINS KEY on non-map column %s", column.name);
- checkFalse(isContains() && !(column.type.isCollection()), "Cannot use CONTAINS on non-collection column %s", column.name);
- validateReceiver(column);
-
- ColumnSpecification receiver = makeCollectionReceiver(column, isKey);
-
- Term term = toTerm(receiver, value, table.keyspace, boundNames);
- return new SingleColumnRestriction.ContainsRestriction(column, term, isKey);
- }
-
- @Override
- protected Restriction newIsNotRestriction(TableMetadata table,
- VariableSpecifications boundNames) throws InvalidRequestException
- {
- ColumnMetadata columnDef = table.getExistingColumn(column);
- // currently enforced by the grammar
- assert value == Constants.NULL_LITERAL : "Expected null literal for IS NOT relation: " + this.toString();
- return new SingleColumnRestriction.IsNotNullRestriction(columnDef);
- }
-
- @Override
- protected Restriction newLikeRestriction(TableMetadata table, VariableSpecifications boundNames, Operator operator)
- {
- ColumnMetadata column = table.getExistingColumn(this.column);
- validateReceiver(column);
- Term term = toTerm(column, value, table.keyspace, boundNames);
-
- return new SingleColumnRestriction.LikeRestriction(column, operator, term);
- }
-
- /**
- * Validate the receiving column for this relation.
- * @param receiver the column definition
- * @throws InvalidRequestException if the relation is invalid
- */
- private void validateReceiver(ColumnMetadata receiver) throws InvalidRequestException
- {
- if (receiver.type.isMultiCell())
- {
- // Non-frozen UDTs don't support any operator
- checkFalse(receiver.type.isUDT(),
- "Non-frozen UDT column '%s' (%s) cannot be restricted by any relation",
- receiver.name,
- receiver.type.asCQL3Type());
-
- // We don't support relations against entire collections (unless they're frozen), like "numbers = {1, 2, 3}"
- checkFalse(receiver.type.isCollection() && !isLegalRelationForNonFrozenCollection(),
- "Collection column '%s' (%s) cannot be restricted by a '%s' relation",
- receiver.name,
- receiver.type.asCQL3Type(),
- operator());
- }
- }
-
- private static ColumnSpecification makeCollectionReceiver(ColumnSpecification receiver, boolean forKey)
- {
- return ((CollectionType<?>) receiver.type).makeCollectionReceiver(receiver, forKey);
- }
-
- private boolean isLegalRelationForNonFrozenCollection()
- {
- return isContainsKey() || isContains() || isMapEntryEquality();
- }
-
- private boolean isMapEntryEquality()
- {
- return mapKey != null && isEQ();
- }
-}
diff --git a/src/java/org/apache/cassandra/cql3/TokenRelation.java b/src/java/org/apache/cassandra/cql3/TokenRelation.java
deleted file mode 100644
index 58f17d14ba..0000000000
--- a/src/java/org/apache/cassandra/cql3/TokenRelation.java
+++ /dev/null
@@ -1,205 +0,0 @@
-/*
- * 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.util.ArrayList;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Objects;
-import java.util.stream.Collectors;
-
-import com.google.common.base.Joiner;
-
-import org.apache.cassandra.cql3.terms.Term;
-import org.apache.cassandra.cql3.terms.Terms;
-import org.apache.cassandra.cql3.terms.Tuples;
-import org.apache.cassandra.schema.ColumnMetadata;
-import org.apache.cassandra.schema.TableMetadata;
-import org.apache.cassandra.cql3.restrictions.Restriction;
-import org.apache.cassandra.cql3.restrictions.TokenRestriction;
-import org.apache.cassandra.cql3.statements.Bound;
-import org.apache.cassandra.exceptions.InvalidRequestException;
-
-import static org.apache.cassandra.cql3.statements.RequestValidations.checkContainsNoDuplicates;
-import static org.apache.cassandra.cql3.statements.RequestValidations.checkContainsOnly;
-import static org.apache.cassandra.cql3.statements.RequestValidations.checkTrue;
-import static org.apache.cassandra.cql3.statements.RequestValidations.invalidRequest;
-
-/**
- * A relation using the token function.
- * Examples:
- * <ul>
- * <li>SELECT ... WHERE token(a) > token(1)</li>
- * <li>SELECT ... WHERE token(a, b) > token(1, 3)</li>
- * </ul>
- */
-public final class TokenRelation extends Relation
-{
- private final List<ColumnIdentifier> entities;
-
- private final Term.Raw value;
-
- public TokenRelation(List<ColumnIdentifier> entities, Operator type, Term.Raw value)
- {
- this.entities = entities;
- this.operator = type;
- this.value = value;
- }
-
- @Override
- public boolean onToken()
- {
- return true;
- }
-
- public Term.Raw getValue()
- {
- return value;
- }
-
- public Terms.Raw getInValues()
- {
- return null;
- }
-
- @Override
- protected Restriction newEQRestriction(TableMetadata table, VariableSpecifications boundNames)
- {
- List<ColumnMetadata> columnDefs = getColumnDefinitions(table);
- Term term = toTerm(toReceivers(table, columnDefs), value, table.keyspace, boundNames);
- return new TokenRestriction.EQRestriction(table, columnDefs, term);
- }
-
- @Override
- protected Restriction newINRestriction(TableMetadata table, VariableSpecifications boundNames)
- {
- throw invalidRequest("%s cannot be used with the token function", operator());
- }
-
- @Override
- protected Restriction newSliceRestriction(TableMetadata table,
- VariableSpecifications boundNames,
- Bound bound,
- boolean inclusive)
- {
- List<ColumnMetadata> columnDefs = getColumnDefinitions(table);
- Term term = toTerm(toReceivers(table, columnDefs), value, table.keyspace, boundNames);
- return new TokenRestriction.SliceRestriction(table, columnDefs, bound, inclusive, term);
- }
-
- @Override
- protected Restriction newContainsRestriction(TableMetadata table, VariableSpecifications boundNames, boolean isKey)
- {
- throw invalidRequest("%s cannot be used with the token function", operator());
- }
-
- @Override
- protected Restriction newIsNotRestriction(TableMetadata table, VariableSpecifications boundNames)
- {
- throw invalidRequest("%s cannot be used with the token function", operator());
- }
-
- @Override
- protected Restriction newLikeRestriction(TableMetadata table, VariableSpecifications boundNames, Operator operator)
- {
- throw invalidRequest("%s cannot be used with the token function", operator);
- }
-
- @Override
- public Relation renameIdentifier(ColumnIdentifier from, ColumnIdentifier to)
- {
- if (!entities.contains(from))
- return this;
-
- List<ColumnIdentifier> newEntities = entities.stream().map(e -> e.equals(from) ? to : e).collect(Collectors.toList());
- return new TokenRelation(newEntities, operator(), value);
- }
-
- @Override
- public String toCQLString()
- {
- return String.format("token%s %s %s", Tuples.tupleToString(entities, ColumnIdentifier::toCQLString), operator, value);
- }
-
- @Override
- public int hashCode()
- {
- return Objects.hash(operator, entities, value);
- }
-
- @Override
- public boolean equals(Object o)
- {
- if (this == o)
- return true;
-
- if (!(o instanceof TokenRelation))
- return false;
-
- TokenRelation tr = (TokenRelation) o;
- return operator == tr.operator && entities.equals(tr.entities) && value.equals(tr.value);
- }
-
- /**
- * Returns the definition of the columns to which apply the token restriction.
- *
- * @param table the table metadata
- * @return the definition of the columns to which apply the token restriction.
- * @throws InvalidRequestException if the entity cannot be resolved
- */
- private List<ColumnMetadata> getColumnDefinitions(TableMetadata table)
- {
- List<ColumnMetadata> columnDefs = new ArrayList<>(entities.size());
- for (ColumnIdentifier id : entities)
- columnDefs.add(table.getExistingColumn(id));
- return columnDefs;
- }
-
- /**
- * Returns the receiver for this relation.
- *
- * @param table the table meta data
- * @param columnDefs the column definitions
- * @return the receivers for the specified relation.
- * @throws InvalidRequestException if the relation is invalid
- */
- private static ColumnSpecification toReceivers(TableMetadata table,
- List<ColumnMetadata> columnDefs)
- throws InvalidRequestException
- {
-
- if (!columnDefs.equals(table.partitionKeyColumns()))
- {
- checkTrue(new HashSet<>(columnDefs).containsAll(table.partitionKeyColumns()),
- "The token() function must be applied to all partition key components or none of them");
-
- checkContainsNoDuplicates(columnDefs, "The token() function contains duplicate partition key components");
-
- checkContainsOnly(columnDefs, table.partitionKeyColumns(), "The token() function must contains only partition key components");
-
- throw invalidRequest("The token function arguments must be in the partition key order: %s",
- Joiner.on(", ").join(ColumnMetadata.toIdentifiers(table.partitionKeyColumns())));
- }
-
- ColumnMetadata firstColumn = columnDefs.get(0);
- return new ColumnSpecification(firstColumn.ksName,
- firstColumn.cfName,
- new ColumnIdentifier("partition key token", true),
- table.partitioner.getTokenValidator());
- }
-}
diff --git a/src/java/org/apache/cassandra/cql3/conditions/ColumnCondition.java b/src/java/org/apache/cassandra/cql3/conditions/ColumnCondition.java
index 5fce9bcb42..88d54dd79d 100644
--- a/src/java/org/apache/cassandra/cql3/conditions/ColumnCondition.java
+++ b/src/java/org/apache/cassandra/cql3/conditions/ColumnCondition.java
@@ -84,7 +84,7 @@ public abstract class ColumnCondition
{
List<ByteBuffer> buffers = terms.bindAndGet(options);
checkFalse(buffers == null && operator.isIN(), "Invalid null list in IN condition");
- checkFalse(buffers == Terms.UNSET_LIST, "Invalid 'unset' value in condition");
+ checkFalse(buffers == Term.UNSET_LIST, "Invalid 'unset' value in condition");
return filterUnsetValuesIfNeeded(buffers, ByteBufferUtil.UNSET_BYTE_BUFFER);
}
@@ -493,7 +493,7 @@ public abstract class ColumnCondition
if (value == null)
return !iter.hasNext();
- if(operator.isContains() || operator.isContainsKey())
+ if(operator == Operator.CONTAINS || operator == Operator.CONTAINS_KEY)
return containsAppliesTo(type, iter, value.get(), operator);
switch (type.kind)
@@ -583,12 +583,12 @@ public abstract class ColumnCondition
compareType = ((SetType<?>)type).getElementsType();
break;
case MAP:
- compareType = operator.isContainsKey() ? ((MapType<?, ?>)type).getKeysType() : ((MapType<?, ?>)type).getValuesType();
+ compareType = operator == Operator.CONTAINS_KEY ? ((MapType<?, ?>)type).getKeysType() : ((MapType<?, ?>)type).getValuesType();
break;
default:
throw new AssertionError();
}
- boolean appliesToSetOrMapKeys = (type.kind == CollectionType.Kind.SET || type.kind == CollectionType.Kind.MAP && operator.isContainsKey());
+ boolean appliesToSetOrMapKeys = (type.kind == CollectionType.Kind.SET || type.kind == CollectionType.Kind.MAP && operator == Operator.CONTAINS_KEY);
return containsAppliesTo(compareType, iter, value, appliesToSetOrMapKeys);
}
@@ -830,16 +830,18 @@ public abstract class ColumnCondition
private Terms prepareTerms(String keyspace, ColumnSpecification receiver)
{
- checkFalse(operator.isContainsKey() && !(receiver.type instanceof MapType), "Cannot use CONTAINS KEY on non-map column %s", receiver.name);
- checkFalse(operator.isContains() && !(receiver.type.isCollection()), "Cannot use CONTAINS on non-collection column %s", receiver.name);
+ checkFalse(operator == Operator.CONTAINS_KEY && !(receiver.type instanceof MapType),
+ "Cannot use CONTAINS KEY on non-map column %s", receiver.name);
+ checkFalse(operator == Operator.CONTAINS && !(receiver.type.isCollection()),
+ "Cannot use CONTAINS on non-collection column %s", receiver.name);
if (operator.isIN())
{
return inValues.prepare(keyspace, receiver);
}
- if (operator.isContains() || operator.isContainsKey())
- receiver = ((CollectionType<?>) receiver.type).makeCollectionReceiver(receiver, operator.isContainsKey());
+ if (operator == Operator.CONTAINS || operator == Operator.CONTAINS_KEY)
+ receiver = ((CollectionType<?>) receiver.type).makeCollectionReceiver(receiver, operator == Operator.CONTAINS_KEY);
return Terms.of(value.prepare(keyspace, receiver));
}
diff --git a/src/java/org/apache/cassandra/cql3/restrictions/ClusteringColumnRestrictions.java b/src/java/org/apache/cassandra/cql3/restrictions/ClusteringColumnRestrictions.java
index ddd9601c83..10b3864aec 100644
--- a/src/java/org/apache/cassandra/cql3/restrictions/ClusteringColumnRestrictions.java
+++ b/src/java/org/apache/cassandra/cql3/restrictions/ClusteringColumnRestrictions.java
@@ -21,17 +21,17 @@ import java.util.*;
import javax.annotation.Nullable;
+import com.google.common.collect.RangeSet;
+
import org.apache.cassandra.db.guardrails.Guardrails;
import org.apache.cassandra.schema.ColumnMetadata;
import org.apache.cassandra.schema.TableMetadata;
import org.apache.cassandra.cql3.QueryOptions;
-import org.apache.cassandra.cql3.statements.Bound;
import org.apache.cassandra.db.*;
import org.apache.cassandra.db.filter.RowFilter;
import org.apache.cassandra.exceptions.InvalidRequestException;
import org.apache.cassandra.index.IndexRegistry;
import org.apache.cassandra.service.ClientState;
-import org.apache.cassandra.utils.btree.BTreeSet;
import static org.apache.cassandra.cql3.statements.RequestValidations.checkFalse;
import static org.apache.cassandra.cql3.statements.RequestValidations.invalidRequest;
@@ -53,7 +53,7 @@ final class ClusteringColumnRestrictions extends RestrictionSetWrapper
public ClusteringColumnRestrictions(TableMetadata table, boolean allowFiltering)
{
- this(table.comparator, new RestrictionSet(), allowFiltering);
+ this(table.comparator, RestrictionSet.empty(), allowFiltering);
}
private ClusteringColumnRestrictions(ClusteringComparator comparator,
@@ -75,8 +75,8 @@ final class ClusteringColumnRestrictions extends RestrictionSetWrapper
SingleRestriction lastRestriction = restrictions.lastRestriction();
assert lastRestriction != null;
- ColumnMetadata lastRestrictionStart = lastRestriction.getFirstColumn();
- ColumnMetadata newRestrictionStart = restriction.getFirstColumn();
+ ColumnMetadata lastRestrictionStart = lastRestriction.firstColumn();
+ ColumnMetadata newRestrictionStart = restriction.firstColumn();
checkFalse(lastRestriction.isSlice() && newRestrictionStart.position() > lastRestrictionStart.position(),
"Clustering column \"%s\" cannot be restricted (preceding column \"%s\" is restricted by a non-EQ relation)",
@@ -92,24 +92,16 @@ final class ClusteringColumnRestrictions extends RestrictionSetWrapper
return new ClusteringColumnRestrictions(this.comparator, newRestrictionSet, allowFiltering);
}
- private boolean hasMultiColumnSlice()
- {
- for (SingleRestriction restriction : restrictions)
- {
- if (restriction.isMultiColumn() && restriction.isSlice())
- return true;
- }
- return false;
- }
-
public NavigableSet<Clustering<?>> valuesAsClustering(QueryOptions options, ClientState state) throws InvalidRequestException
{
- MultiCBuilder builder = MultiCBuilder.create(comparator, hasIN());
+ MultiCBuilder builder = new MultiCBuilder(comparator);
for (SingleRestriction r : restrictions)
{
- r.appendTo(builder, options);
+ List<ClusteringElements> values = r.values(options);
+ builder.extend(values);
- if (hasIN() && Guardrails.inSelectCartesianProduct.enabled(state))
+ // If values is greater than 1 we know that the restriction is an IN
+ if (values.size() > 1 && Guardrails.inSelectCartesianProduct.enabled(state))
Guardrails.inSelectCartesianProduct.guard(builder.buildSize(), "clustering key", false, state);
if (builder.hasMissingElements())
@@ -118,9 +110,9 @@ final class ClusteringColumnRestrictions extends RestrictionSetWrapper
return builder.build();
}
- public NavigableSet<ClusteringBound<?>> boundsAsClustering(Bound bound, QueryOptions options) throws InvalidRequestException
+ public Slices slices(QueryOptions options) throws InvalidRequestException
{
- MultiCBuilder builder = MultiCBuilder.create(comparator, hasIN() || hasMultiColumnSlice());
+ MultiCBuilder builder = new MultiCBuilder(comparator);
int keyPosition = 0;
for (SingleRestriction r : restrictions)
@@ -130,39 +122,21 @@ final class ClusteringColumnRestrictions extends RestrictionSetWrapper
if (r.isSlice())
{
- r.appendBoundTo(builder, bound, options);
- return builder.buildBoundForSlice(bound.isStart(),
- r.isInclusive(bound),
- r.isInclusive(bound.reverse()),
- r.getColumnDefs());
+ RangeSet<ClusteringElements> rangeSet = ClusteringElements.all();
+ r.restrict(rangeSet, options);
+ return builder.extend(rangeSet).buildSlices();
}
- r.appendBoundTo(builder, bound, options);
+ builder.extend(r.values(options));
if (builder.hasMissingElements())
- return BTreeSet.empty(comparator);
+ break;
- keyPosition = r.getLastColumn().position() + 1;
+ keyPosition = r.lastColumn().position() + 1;
}
// Everything was an equal (or there was nothing)
- return builder.buildBound(bound.isStart(), true);
- }
-
- /**
- * Checks if any of the underlying restriction is a CONTAINS or CONTAINS KEY.
- *
- * @return <code>true</code> if any of the underlying restriction is a CONTAINS or CONTAINS KEY,
- * <code>false</code> otherwise
- */
- public boolean hasContains()
- {
- for (SingleRestriction restriction : restrictions)
- {
- if (restriction.isContains())
- return true;
- }
- return false;
+ return builder.buildSlices();
}
/**
@@ -197,9 +171,9 @@ final class ClusteringColumnRestrictions extends RestrictionSetWrapper
return true;
if (!restriction.isSlice())
- position = restriction.getLastColumn().position() + 1;
+ position = restriction.lastColumn().position() + 1;
}
- return hasContains();
+ return false;
}
@Override
@@ -219,12 +193,12 @@ final class ClusteringColumnRestrictions extends RestrictionSetWrapper
}
if (!restriction.isSlice())
- position = restriction.getLastColumn().position() + 1;
+ position = restriction.lastColumn().position() + 1;
}
}
private boolean handleInFilter(SingleRestriction restriction, int index)
{
- return restriction.isContains() || restriction.isLIKE() || index != restriction.getFirstColumn().position();
+ return restriction.needsFilteringOrIndexing() || index != restriction.firstColumn().position();
}
}
diff --git a/src/java/org/apache/cassandra/cql3/restrictions/ClusteringElements.java b/src/java/org/apache/cassandra/cql3/restrictions/ClusteringElements.java
new file mode 100644
index 0000000000..1467835752
--- /dev/null
+++ b/src/java/org/apache/cassandra/cql3/restrictions/ClusteringElements.java
@@ -0,0 +1,473 @@
+/*
+ * 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.restrictions;
+
+import java.nio.ByteBuffer;
+import java.util.List;
+import java.util.Objects;
+
+import com.google.common.collect.BoundType;
+import com.google.common.collect.ForwardingList;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.Range;
+import com.google.common.collect.RangeSet;
+import com.google.common.collect.TreeRangeSet;
+
+import org.apache.cassandra.cql3.ColumnSpecification;
+import org.apache.cassandra.db.BufferClusteringBound;
+import org.apache.cassandra.db.ClusteringBound;
+import org.apache.cassandra.db.marshal.AbstractType;
+import org.apache.cassandra.schema.ColumnMetadata;
+
+/**
+ * One or more contiguous clusterings elements. A clustering element is composed of a clustering column and its
+ * associated value. In practice, that class is not only used for clustering elements but also for partition key elements
+ * and tokens expression.
+ *
+ * <p>There are some differences between how predicates are represented in a CQL query and how they have to be expressed
+ * internally. Those differences are:
+ * <ul>
+ * <li>The selected partition keys and clustering columns can be expressed with separate predicates in a CQL query
+ * but need to be grouped internally to define exact partition and clustering keys. For example,
+ * <pre>[..] WHERE pk1 = 2 AND pk2 = 3 AND c1 = 5 AND c2 IN (3, 4)</pre> will request 2 rows with clustering (5, 3) and
+ * (5, 4) from the partition (2, 3).</li>
+ * <li>When clustering slices are expressed in a CQL query they are expressed as if all columns were in
+ * ascending order. Internally, the engine handles slice according to the clustering columns real order.
+ * For example, if column c1 is descending and column c2 is ascending the predicate <pre>(c1, c2) >= (1, 2)</pre>
+ * should be translated internally in [(bottom) .. (1, bottom)),[(1, 2, bottom)..(1, top)].</li>
+ * </ul>
+ * This class is used to bridge the gap between the CQL expression and its internal representation. It allows for elements
+ * to be appended together through the {@code extend} method and translate CQL ranges into their internal representation.
+ * </p>
+ * <p>It is important to realize that Guava {@code Range} instances are used in a slightly different way than how they were
+ * designed to be used to deal with the tree model of Clusterings. {@code Range} returned by this class are never
+ * unbounded so the methods {@code hasLowerEndpoint} and {@code hasUpperEndpoint} should not be used on those.
+ * When a range does not have a lower endpoint its lower endpoint value will be (bottom) (e.g. ClusteringElements.of().bottom())
+ * and if it does not have an upper endpoint its upper endpoint value will be (top) (e.g. ClusteringElements.of().top()).
+ * Therefore a missing endpoint will always return {@code true} to {@code isEmpty()}.</p>
+ */
+public class ClusteringElements extends ForwardingList<ByteBuffer> implements Comparable<ClusteringElements>
+{
+ /**
+ * The empty {@code ClusteringElements} instance used to avoid creating unecessary empty instances.
+ */
+ private static final ClusteringElements EMPTY = new ClusteringElements(ImmutableList.of(), ImmutableList.of());
+
+ /**
+ * A range representing all {@code ClusteringElements}.
+ */
+ private static final Range<ClusteringElements> ALL = Range.closed(EMPTY.bottom(), EMPTY.top());
+
+ /**
+ * The elements columns.
+ */
+ // We use ColumnSpecification to allow support for things like Token expressions that do not match real columns directly.
+ private final ImmutableList<? extends ColumnSpecification> columns;
+
+ /**
+ * The elements values.
+ */
+ private final ImmutableList<ByteBuffer> values;
+
+ private ClusteringElements(ImmutableList<? extends ColumnSpecification> columns, ImmutableList<ByteBuffer> values)
+ {
+ if (columns.size() != values.size())
+ throw new IllegalArgumentException("columns and values should have the same size");
+
+ checkColumnsOrder(columns);
+
+ this.columns = columns;
+ this.values = values;
+ }
+
+ private static void checkColumnsOrder(ImmutableList<? extends ColumnSpecification> columns)
+ {
+ if (columns.size() > 1)
+ {
+ // All the columns should be ColumnMetadata for partition key or clustering key
+ int offset = ((ColumnMetadata) columns.get(0)).position();
+ for (int i = 1, m = columns.size(); i < m; i++)
+ {
+ if (((ColumnMetadata) columns.get(i)).position() != (offset + i))
+ throw new IllegalArgumentException("columns should have increasing position");
+ }
+ }
+ }
+
+ private AbstractType<?> columnType(int index)
+ {
+ return columns.get(index).type;
+ }
+
+ @Override
+ protected List<ByteBuffer> delegate()
+ {
+ return values;
+ }
+
+ /**
+ * Returns an empty {@code ClusteringElements}.
+ * @return an empty {@code ClusteringElements}.
+ */
+ public static ClusteringElements of()
+ {
+ return EMPTY;
+ }
+
+ /**
+ * Returns a {@code ClusteringElements} with a single element.
+ * @param column the element column
+ * @param value the element value
+ * @return a {@code ClusteringElements} with a single element.
+ */
+ public static ClusteringElements of(ColumnSpecification column, ByteBuffer value)
+ {
+ return new ClusteringElements(ImmutableList.of(column), ImmutableList.of(value));
+ }
+
+ /**
+ * Returns a {@code ClusteringElements} with the specified elements.
+ * @param columns the elements columns
+ * @param values the elements values
+ * @return a {@code ClusteringElements} with the specified elements.
+ */
+ public static ClusteringElements of(List<? extends ColumnSpecification> columns, List<ByteBuffer> values)
+ {
+ return new ClusteringElements(ImmutableList.copyOf(columns), ImmutableList.copyOf(values));
+ }
+
+ /**
+ * Extends this set of elements with the specified ones. This method should only be called on {@code ClusteringElements}
+ * corresponding to partition key or clustering elements.
+ * <p>If this instance is a range bound (e.g. top or bottom) it cannot be extended. If the extending suffix is a bound
+ * the resulting {@code ClusteringElements} will also be a bound from the same type.</p>
+ *
+ * @param suffix the elements to append to this ones
+ * @return A new {@code ClusteringElements} instance composed of both set of elements
+ * @throws UnsupportedOperationException if this instnace is a range bound (e.g. top or bottom)
+ */
+ public ClusteringElements extend(ClusteringElements suffix)
+ {
+ // We cannot extend a Top or Bottom as those are only used for ranges and ranges endpoint should not be extended
+ if (this instanceof Top || this instanceof Bottom)
+ throw new UnsupportedOperationException("Range endpoints cannot be extended");
+
+ checkSuffix(suffix);
+
+ ImmutableList<? extends ColumnSpecification> newColumns = concat(columns, suffix.columns);
+ ImmutableList<ByteBuffer> newValues = concat(values, suffix.values);
+
+ return suffix instanceof Top ? new Top(newColumns, newValues)
+ : suffix instanceof Bottom ? new Bottom(newColumns, newValues)
+ : new ClusteringElements(newColumns, newValues);
+ }
+
+ private void checkSuffix(ClusteringElements suffix)
+ {
+ // If the columns are not ColumnMetadata instances, we are dealing with a Token representation which cannot be extended
+ if (!(columns.get(0) instanceof ColumnMetadata))
+ throw new UnsupportedOperationException("Non partition key or clustering columns cannot be extended");
+
+ if (!suffix.isEmpty()) // suffix can be empty if equal to (top) or (bottom)
+ {
+ ColumnMetadata lastPrefixElement = ((ColumnMetadata) last(this.columns));
+ ColumnMetadata firstSuffixElement = ((ColumnMetadata) suffix.columns.get(0));
+ if (firstSuffixElement.kind != lastPrefixElement.kind)
+ throw new UnsupportedOperationException("Cannot extend elements with elements of a different kind");
+ if (firstSuffixElement.position() != lastPrefixElement.position() + 1)
+ throw new UnsupportedOperationException("Cannot extend elements with non consecutive elements");
+ }
+ }
+
+ private static <T> ImmutableList<T> concat(ImmutableList<? extends T> prefix, ImmutableList<? extends T> suffix)
+ {
+ return ImmutableList.<T>builderWithExpectedSize(prefix.size() + suffix.size())
+ .addAll(prefix)
+ .addAll(suffix)
+ .build();
+ }
+
+ /**
+ * Returns a {@code RangeSet} representing all the possible {@code ClusteringElements} values.
+ * @return a {@code RangeSet} representing all the possible {@code ClusteringElements} values.
+ */
+ public static RangeSet<ClusteringElements> all()
+ {
+ TreeRangeSet<ClusteringElements> rangeSet = TreeRangeSet.create();
+ rangeSet.add(ALL);
+ return rangeSet;
+ }
+
+ /**
+ * Returns a {@code RangeSet} that contains all values less than or equal to endpoint.
+ * @return a {@code RangeSet} that contains all values less than or equal to endpoint.
+ */
+ public static RangeSet<ClusteringElements> atMost(ClusteringElements endpoint)
+ {
+ return buildRangeSet(endpoint, true, BoundType.CLOSED);
+ }
+
+ /**
+ * Returns a {@code RangeSet} that contains all values less than endpoint.
+ * @return a {@code RangeSet} that contains all values less than endpoint.
+ */
+ public static RangeSet<ClusteringElements> lessThan(ClusteringElements endpoint)
+ {
+ return buildRangeSet(endpoint, true, BoundType.OPEN);
+ }
+
+ /**
+ * Returns a {@code RangeSet} that contains all values greater or equal to endpoint.
+ * @return a {@code RangeSet} that contains all values greater or equal to endpoint.
+ */
+ public static RangeSet<ClusteringElements> atLeast(ClusteringElements endpoint)
+ {
+ return buildRangeSet(endpoint, false, BoundType.CLOSED);
+ }
+
+ /**
+ * Returns a {@code RangeSet} that contains all values greater than endpoint.
+ * @return a {@code RangeSet} that contains all values greater than endpoint.
+ */
+ public static RangeSet<ClusteringElements> greaterThan(ClusteringElements endpoint)
+ {
+ return buildRangeSet(endpoint, false, BoundType.OPEN);
+ }
+
+ private static RangeSet<ClusteringElements> buildRangeSet(ClusteringElements endpoint, boolean upperBound, BoundType boundType)
+ {
+ TreeRangeSet<ClusteringElements> rangeSet = TreeRangeSet.create();
+ boolean reversed = endpoint.columnType(0).isReversed();
+ if (reversed)
+ {
+ upperBound = !upperBound;
+ }
+ ClusteringElements oppositeEndpoint = upperBound ? ClusteringElements.of().bottom()
+ : ClusteringElements.of().top();
+
+ for (int i = 0, m = endpoint.size(); i < m; i++)
+ {
+ AbstractType<?> type = endpoint.columnType(i);
+ if (reversed != type.isReversed())
+ {
+ // The columns are changing directions therefore we need to create the range up to this point
+ // and add it to the range set.
+ // For example if we have c1 ASC and c2 DESC and (c1, c2) <= (1, 2) we should add the [(-∞)..(1))
+ // range at this point. The second and last range: [(1, 2)..(1, -∞]) will be added after the loop.
+ ClusteringElements e = ClusteringElements.of(endpoint.columns.subList(0, i), endpoint.subList(0, i));
+ Range<ClusteringElements> range = upperBound ? Range.closedOpen(oppositeEndpoint, e.bottom())
+ : Range.openClosed(e.top(), oppositeEndpoint);
+
+ rangeSet.add(range);
+ reversed = !reversed;
+ upperBound = !upperBound;
+ oppositeEndpoint = upperBound ? e.bottom() : e.top();
+ }
+ }
+ // We need to add the last range or the only one if there was no change of direction.
+ Range<ClusteringElements> range = upperBound ? Range.range(oppositeEndpoint,
+ BoundType.CLOSED,
+ boundType == BoundType.OPEN ? endpoint.bottom() : endpoint.top(),
+ boundType)
+ : Range.range(boundType == BoundType.OPEN ? endpoint.top() : endpoint.bottom(),
+ boundType,
+ oppositeEndpoint,
+ BoundType.CLOSED);
+ rangeSet.add(range);
+ return rangeSet;
+ }
+
+ /**
+ * Creates a bound representing the top value of this {@code ClusteringElements}.
+ * @return a bound representing the top value of this {@code ClusteringElements}.
+ */
+ public ClusteringElements top()
+ {
+ return new Top(columns, values);
+ }
+
+ /**
+ * Creates a bound representing the bottom value of this {@code ClusteringElements}.
+ * @return a bound representing the bottom value of this {@code ClusteringElements}.
+ */
+ public ClusteringElements bottom()
+ {
+ return new Bottom(columns, values);
+ }
+
+ @Override
+ public int compareTo(ClusteringElements that)
+ {
+ if (that == null)
+ throw new NullPointerException();
+
+ isComparableWith(that);
+
+ int comparison = 0;
+
+ int minSize = Math.min(this.size(), that.size());
+ for (int i = 0; i < minSize; i++)
+ {
+ ByteBuffer thisValue = this.values.get(i);
+ ByteBuffer thatValue = that.values.get(i);
+
+ comparison = this.columnType(i).compare(thisValue, thatValue);
+
+ if (comparison != 0)
+ return comparison;
+ }
+
+ // If both sets of elements have the same size, it could mean:
+ // * that they are equal (e.g. this = (1, 2) and that = (1,2))
+ // * that one of them is a Top or Bottom boundary (e.g. this = (1) and that = (1, +∞))
+ // * that both of them are Top or Bottom boundaries ( e.g. this = (-∞) and that = (+∞)).
+ if (this.size() == that.size())
+ {
+ comparison = Boolean.compare(this instanceof Top, that instanceof Top);
+
+ if (comparison == 0) // either none is a Top or both are Tops
+ {
+ // If none is a Top, one can be a Bottom
+ comparison = Boolean.compare(this instanceof Bottom, that instanceof Bottom);
+ if (comparison == 0)
+ return 0; // this and that are equal
+
+ return comparison > 0 ? -1 : 1; // If this is a Bottom that is greater and if that is a Bottom this is greater
+ }
+
+ // Either this or that is a top
+ return comparison > 0 ? that instanceof Bottom ? 1 : 0 // this is a top
+ : this instanceof Bottom ? -1 : 0; // that is a top
+ }
+
+ // If this size is smaller it means that we have 2 possible cases:
+ // * this with less column than that (e.g. (1) for this and (1, 0) for that)
+ // * a top or bottom for this (e.g. (1, +∞) for this and (1, 0) for that)
+ // If we are in the first case then zero must be returned as that is included in this.
+ if (this.size() < that.size())
+ {
+ return that.columns.get(minSize).type.isReversed() ? this instanceof Bottom ? -1 : 1
+ : this instanceof Top ? 1 : -1;
+ }
+
+ return this.columns.get(minSize).type.isReversed() ? that instanceof Bottom ? 1 : -1
+ : that instanceof Top ? -1 : 1;
+ }
+
+ /**
+ * Checks if this {@code ClusteringElements} is comparable with that other one.
+ * @param that the {@code ClusteringElements} to be compared with.
+ */
+ private void isComparableWith(ClusteringElements that)
+ {
+ int minSize = Math.min(this.columns.size(), that.columns.size());
+
+ if (!this.columns.subList(0, minSize).equals(that.columns.subList(0, minSize)))
+ throw new IllegalStateException("Cannot compare 2 lists containing different types");
+ }
+
+ @Override
+ public boolean equals(Object o)
+ {
+ if (this == o)
+ return true;
+
+ if (o == null || getClass() != o.getClass())
+ return false;
+
+ ClusteringElements that = (ClusteringElements) o;
+ return Objects.equals(columns, that.columns) && Objects.equals(values, that.values);
+ }
+
+ @Override
+ public int hashCode()
+ {
+ return Objects.hash(columns, values);
+ }
+
+ public ClusteringBound<?> toBound(boolean isStart, boolean isInclusive)
+ {
+ return BufferClusteringBound.create(ClusteringBound.boundKind(isStart, isInclusive),
+ values.toArray(new ByteBuffer[values.size()]));
+ }
+
+ @Override
+ public String toString()
+ {
+ StringBuilder builder = new StringBuilder().append('(');
+ for (int i = 0, m = size(); i < m; i++)
+ {
+ if (i != 0)
+ builder.append(", ");
+ builder.append(columnType(i).toCQLString(values.get(i)));
+ }
+
+ if (this instanceof Top || this instanceof Bottom)
+ {
+ if (!isEmpty())
+ builder.append(", ");
+
+ builder.append(this instanceof Top ? "top" : "bottom");
+ }
+ return builder.append(')').toString();
+ }
+
+ private static <E> E last(List<E> elements)
+ {
+ return elements.get(elements.size() - 1);
+ }
+
+ /**
+ * Represents the bottom of a column values. If the column is ascending in value this class will represent -∞.
+ * If the column is descending in value it will represent +∞.
+ * This class is used to define ranges internally.
+ */
+ private static class Bottom extends ClusteringElements
+ {
+ private Bottom(ImmutableList<? extends ColumnSpecification> columns, ImmutableList<ByteBuffer> values)
+ {
+ super(columns, values);
+ }
+
+ @Override
+ public ClusteringBound<?> toBound(boolean isStart, boolean isInclusive)
+ {
+ return isEmpty() ? BufferClusteringBound.BOTTOM : super.toBound(isStart, isInclusive);
+ }
+ }
+
+ /**
+ * Represents the top of a column values. If the column is ascending in value this class will represent +∞.
+ * If the column is descending in value it will represent -∞.
+ * This class is used to define ranges internally.
+ */
+ private static class Top extends ClusteringElements
+ {
+ private Top(ImmutableList<? extends ColumnSpecification> columns, ImmutableList<ByteBuffer> values)
+ {
+ super(columns, values);
+ }
+
+ @Override
+ public ClusteringBound<?> toBound(boolean isStart, boolean isInclusive)
+ {
+ return isEmpty() ? BufferClusteringBound.TOP : super.toBound(isStart, isInclusive);
+ }
+ }
+}
diff --git a/src/java/org/apache/cassandra/cql3/restrictions/LikePattern.java b/src/java/org/apache/cassandra/cql3/restrictions/LikePattern.java
new file mode 100644
index 0000000000..f5ea1e45f4
--- /dev/null
+++ b/src/java/org/apache/cassandra/cql3/restrictions/LikePattern.java
@@ -0,0 +1,117 @@
+/*
+ * 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.restrictions;
+
+import java.nio.ByteBuffer;
+
+import org.apache.cassandra.cql3.Operator;
+import org.apache.cassandra.utils.ByteBufferUtil;
+
+import static org.apache.cassandra.cql3.statements.RequestValidations.invalidRequest;
+
+public final class LikePattern
+{
+ public enum Kind
+ {
+ PREFIX(Operator.LIKE_PREFIX),
+ SUFFIX(Operator.LIKE_SUFFIX),
+ CONTAINS(Operator.LIKE_CONTAINS),
+ MATCHES(Operator.LIKE_MATCHES);
+
+ private final Operator operator;
+
+ Kind(Operator operator)
+ {
+ this.operator = operator;
+ }
+
+ public Operator operator()
+ {
+ return operator;
+ }
+ }
+
+ private static final ByteBuffer WILDCARD = ByteBufferUtil.bytes("%");
+
+ private final Kind kind;
+
+ private final ByteBuffer value;
+
+ private LikePattern(Kind kind, ByteBuffer value)
+ {
+ this.kind = kind;
+ this.value = value;
+ }
+
+ public Kind kind()
+ {
+ return kind;
+ }
+
+ public ByteBuffer value()
+ {
+ return value;
+ }
+
+ /**
+ * As the specific subtype of LIKE (LIKE_PREFIX, LIKE_SUFFIX, LIKE_CONTAINS, LIKE_MATCHES) can only be
+ * determined by examining the value, which in turn can only be known after binding, all LIKE restrictions
+ * are initially created with the generic LIKE operator. This function takes the bound value, trims the
+ * wildcard '%' chars from it and returns a tuple of the inferred operator subtype and the final value
+ * @param value the bound value for the LIKE operation
+ * @return Pair containing the inferred LIKE subtype and the value with wildcards removed
+ */
+ public static LikePattern parse(ByteBuffer value)
+ {
+ Kind kind;
+ int beginIndex = value.position();
+ int endIndex = value.limit() - 1;
+ if (ByteBufferUtil.endsWith(value, WILDCARD))
+ {
+ if (ByteBufferUtil.startsWith(value, WILDCARD))
+ {
+ kind = Kind.CONTAINS;
+ beginIndex =+ 1;
+ }
+ else
+ {
+ kind = Kind.PREFIX;
+ }
+ }
+ else if (ByteBufferUtil.startsWith(value, WILDCARD))
+ {
+ kind = Kind.SUFFIX;
+ beginIndex += 1;
+ endIndex += 1;
+ }
+ else
+ {
+ kind = Kind.MATCHES;
+ endIndex += 1;
+ }
+
+ if (endIndex == 0 || beginIndex == endIndex)
+ throw invalidRequest("LIKE value can't be empty.");
+
+ ByteBuffer newValue = value.duplicate();
+ newValue.position(beginIndex);
+ newValue.limit(endIndex);
+ return new LikePattern(kind, newValue);
+ }
+}
diff --git a/src/java/org/apache/cassandra/cql3/restrictions/MergedRestriction.java b/src/java/org/apache/cassandra/cql3/restrictions/MergedRestriction.java
new file mode 100644
index 0000000000..debbf1f89a
--- /dev/null
+++ b/src/java/org/apache/cassandra/cql3/restrictions/MergedRestriction.java
@@ -0,0 +1,344 @@
+/*
+ * 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.restrictions;
+
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.RangeSet;
+
+import org.apache.cassandra.cql3.Operator;
+import org.apache.cassandra.cql3.QueryOptions;
+import org.apache.cassandra.cql3.functions.Function;
+import org.apache.cassandra.db.filter.RowFilter;
+import org.apache.cassandra.index.Index;
+import org.apache.cassandra.index.IndexRegistry;
+import org.apache.cassandra.schema.ColumnMetadata;
+
+import static org.apache.cassandra.cql3.statements.RequestValidations.invalidRequest;
+
+/**
+ * A {@link SingleRestriction} which is the result of merging multiple {@link SimpleRestriction} applying to
+ * the same set of columns.
+ * <p>For multi-columns restrictions it is possible to merge restrictions applying to different
+ * sets of columns as long as one is a superset of the other and both start with the same set of columns.</p>
+ */
+public final class MergedRestriction implements SingleRestriction
+{
+ /**
+ * The columns to which the restrictions apply.
+ */
+ private final List<ColumnMetadata> columns;
+
+ /**
+ * The restrictions composing this restriction
+ */
+ private final List<SimpleRestriction> restrictions;
+
+ private final boolean isOnToken;
+
+ private final boolean isSlice;
+
+ private final boolean isMultiColumn;
+
+ /**
+ * The number of restrictions that require {@code CONTAINS}, {@code CONTAINS_KEY} and Map equality restrictions.
+ */
+ private final int containsCount;
+
+ public MergedRestriction(SingleRestriction restriction,
+ SimpleRestriction other)
+ {
+ assert restriction.isOnToken() == other.isOnToken();
+
+ this.columns = restriction.columns().size() < other.columns().size()
+ ? other.columns()
+ : restriction.columns();
+
+ ImmutableList.Builder<SimpleRestriction> builder = ImmutableList.builder();
+ int containsCount = 0;
+ if (restriction instanceof MergedRestriction)
+ {
+ MergedRestriction composite = (MergedRestriction) restriction;
+
+ for (SimpleRestriction r : composite.restrictions)
+ {
+ validate(r, other);
+ }
+
+ builder.addAll(composite.restrictions);
+ containsCount = composite.containsCount;
+ }
+ else
+ {
+ SimpleRestriction r = (SimpleRestriction) restriction;
+ validate(r, other);
+ builder.add(r);
+ if (isContains(r))
+ containsCount++;
+ }
+ builder.add(other);
+ if (isContains(restriction))
+ containsCount++;
+
+ this.restrictions = builder.build();
+ this.isOnToken = restriction.isOnToken();
+ this.isSlice = restriction.isSlice() && other.isSlice();
+ this.isMultiColumn = restriction.isMultiColumn() || other.isMultiColumn();
+ this.containsCount = containsCount;
+ }
+
+ @Override
+ public boolean isOnToken()
+ {
+ return isOnToken;
+ }
+
+ @Override
+ public boolean isMultiColumn()
+ {
+ return isMultiColumn;
+ }
+
+ private static void validate(SimpleRestriction restriction, SimpleRestriction other)
+ {
+ checkOperator(restriction);
+ checkOperator(other);
+
+ if (restriction.isContains() != other.isContains())
+ throw invalidRequest("Collection column %s can only be restricted by CONTAINS, CONTAINS KEY," +
+ " or map-entry equality if it already restricted by one of those",
+ restriction.firstColumn().name);
+
+ if (restriction.isSlice() && other.isSlice())
+ {
+ ColumnMetadata firstColumn = restriction.firstColumn();
+ ColumnMetadata otherFirstColumn = other.firstColumn();
+ if (!firstColumn.equals(otherFirstColumn))
+ {
+ ColumnMetadata column = firstColumn.position() > otherFirstColumn.position() ? firstColumn
+ : otherFirstColumn;
+
+ throw invalidRequest("Column \"%s\" cannot be restricted by two inequalities not starting with the same column",
+ column.name);
+ }
+
+ if ((restriction.operator() == Operator.GT || restriction.operator() == Operator.GTE) &&
+ (other.operator() == Operator.GT || other.operator() == Operator.GTE))
+ {
+ throw invalidRequest("More than one restriction was found for the start bound on %s",
+ toCQLString(getColumnsInCommons(restriction, other)));
+ }
+
+ if ((restriction.operator() == Operator.LT || restriction.operator() == Operator.LTE) &&
+ (other.operator() == Operator.LT || other.operator() == Operator.LTE))
+ {
+ throw invalidRequest("More than one restriction was found for the end bound on %s",
+ toCQLString(getColumnsInCommons(restriction, other)));
+ }
+ }
+ }
+
+ private static void checkOperator(SimpleRestriction restriction)
+ {
+ if (restriction.isColumnLevel() || restriction.isOnToken())
+ {
+ if (restriction.isEQ())
+ throw invalidRequest("%s cannot be restricted by more than one relation if it includes an Equal",
+ toCQLString(restriction.columns()));
+
+ if (restriction.isIN())
+ throw invalidRequest("%s cannot be restricted by more than one relation if it includes a IN",
+ toCQLString(restriction.columns()));
+ if (restriction.isANN())
+ throw invalidRequest("%s cannot be restricted by more than one relation in an ANN ordering",
+ toCQLString(restriction.columns()));
+ }
+ }
+
+ /**
+ * Returns the columns that are specified within the 2 {@code Restrictions}.
+ *
+ * @param restriction the first restriction
+ * @param other the other restriction
+ * @return the columns that are specified within the 2 {@code Restrictions}.
+ */
+ private static Set<ColumnMetadata> getColumnsInCommons(Restriction restriction, Restriction other)
+ {
+ Set<ColumnMetadata> commons = new HashSet<>(restriction.columns());
+ commons.retainAll(other.columns());
+ return commons;
+ }
+
+ private static String toCQLString(Iterable<ColumnMetadata> columns)
+ {
+ StringBuilder builder = new StringBuilder();
+ for (ColumnMetadata columnMetadata : columns)
+ {
+ if (builder.length() != 0)
+ builder.append(" ,");
+ builder.append(columnMetadata.name.toCQLString());
+ }
+ return builder.toString();
+ }
+
+ /**
+ * Checks if the restriction operator is a CONTAINS, CONTAINS_KEY or is an equality on a map element.
+ * @param restriction the restriction to check
+ * @return {@code true} if the restriction operator is one of the contains operations, {@code false} otherwise.
+ */
+ private boolean isContains(SingleRestriction restriction)
+ {
+ return restriction instanceof SimpleRestriction && ((SimpleRestriction) restriction).isContains();
+ }
+
+ @Override
+ public boolean isEQ() {
+ return false; // For the moment we do not support merging EQ restriction with anything else.
+ }
+
+ @Override
+ public boolean isIN()
+ {
+ return false; // For the moment we do not support merging IN restriction with anything else.
+ }
+
+ @Override
+ public boolean isANN() {
+ return false; // For the moment we do not support merging ANN restriction with anything else.
+ }
+
+ @Override
+ public boolean isSlice()
+ {
+ return isSlice;
+ }
+
+ @Override
+ public boolean isColumnLevel() {
+ return false;
+ }
+
+ @Override
+ public ColumnMetadata firstColumn()
+ {
+ return columns.get(0);
+ }
+
+ @Override
+ public ColumnMetadata lastColumn()
+ {
+ return columns.get(columns.size() - 1);
+ }
+
+ @Override
+ public List<ColumnMetadata> columns()
+ {
+ return columns;
+ }
+
+ @Override
+ public void addFunctionsTo(List<Function> functions)
+ {
+ for (int i = 0, m = restrictions.size(); i < m; i++)
+ {
+ restrictions.get(i).addFunctionsTo(functions);
+ }
+ }
+
+ @Override
+ public boolean needsFilteringOrIndexing()
+ {
+ for (int i = 0, m = restrictions.size(); i < m; i++)
+ {
+ if (restrictions.get(i).needsFilteringOrIndexing())
+ return true;
+ }
+ return false;
+ }
+
+ @Override
+ public boolean needsFiltering(Index.Group indexGroup)
+ {
+ // multiple contains might require filtering on some indexes, since that is equivalent to a disjunction (or)
+ boolean hasMultipleContains = containsCount > 1;
+
+ for (Index index : indexGroup.getIndexes())
+ {
+ if (isSupportedBy(index) && !(hasMultipleContains && index.filtersMultipleContains()))
+ return false;
+ }
+
+ return true;
+ }
+
+ @Override
+ public Index findSupportingIndex(Iterable<Index> indexes)
+ {
+ for (int i = 0, m = restrictions.size(); i < m; i++)
+ {
+ Index index = restrictions.get(i).findSupportingIndex(indexes);
+ if (index != null)
+ return index;
+ }
+ return null;
+ }
+
+ @Override
+ public boolean isSupportedBy(Index index)
+ {
+ for (SingleRestriction restriction : restrictions)
+ {
+ if (restriction.isSupportedBy(index))
+ return true;
+ }
+ return false;
+ }
+
+ @Override
+ public List<ClusteringElements> values(QueryOptions options)
+ {
+ List<ClusteringElements> values = restrictions.get(0).values(options);
+ for (int i = 1, m = restrictions.size(); i < m; i++)
+ {
+ values.retainAll(restrictions.get(i).values(options));
+ }
+ return values;
+ }
+
+ @Override
+ public void restrict(RangeSet<ClusteringElements> rangeSet, QueryOptions options)
+ {
+ for (int i = 0, m = restrictions.size(); i < m; i++)
+ {
+ restrictions.get(i).restrict(rangeSet, options);
+ }
+ }
+
+ @Override
+ public void addToRowFilter(RowFilter filter, IndexRegistry indexRegistry, QueryOptions options)
+ {
+ for (int i = 0, m = restrictions.size(); i < m; i++)
+ {
+ restrictions.get(i).addToRowFilter(filter, indexRegistry, options);
+ }
+ }
+}
diff --git a/src/java/org/apache/cassandra/cql3/restrictions/MultiColumnRestriction.java b/src/java/org/apache/cassandra/cql3/restrictions/MultiColumnRestriction.java
deleted file mode 100644
index 0ba800cb2e..0000000000
--- a/src/java/org/apache/cassandra/cql3/restrictions/MultiColumnRestriction.java
+++ /dev/null
@@ -1,572 +0,0 @@
-/*
- * 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.restrictions;
-
-import java.nio.ByteBuffer;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.EnumMap;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Set;
-
-import org.apache.commons.lang3.builder.ToStringBuilder;
-import org.apache.commons.lang3.builder.ToStringStyle;
-
-import org.apache.cassandra.cql3.Operator;
-import org.apache.cassandra.cql3.QueryOptions;
-import org.apache.cassandra.cql3.terms.Term;
-import org.apache.cassandra.cql3.terms.Terms;
-import org.apache.cassandra.cql3.terms.Term.Terminal;
-import org.apache.cassandra.cql3.functions.Function;
-import org.apache.cassandra.cql3.statements.Bound;
-import org.apache.cassandra.db.MultiCBuilder;
-import org.apache.cassandra.db.filter.RowFilter;
-import org.apache.cassandra.db.marshal.ListType;
-import org.apache.cassandra.index.Index;
-import org.apache.cassandra.index.IndexRegistry;
-import org.apache.cassandra.schema.ColumnMetadata;
-
-import static org.apache.cassandra.cql3.statements.RequestValidations.checkFalse;
-import static org.apache.cassandra.cql3.statements.RequestValidations.checkNotNull;
-import static org.apache.cassandra.cql3.statements.RequestValidations.checkTrue;
-import static org.apache.cassandra.cql3.statements.RequestValidations.invalidRequest;
-
-public abstract class MultiColumnRestriction implements SingleRestriction
-{
- /**
- * The columns to which the restriction apply.
- */
- protected final List<ColumnMetadata> columnDefs;
-
- public MultiColumnRestriction(List<ColumnMetadata> columnDefs)
- {
- this.columnDefs = columnDefs;
- }
-
- @Override
- public boolean isMultiColumn()
- {
- return true;
- }
-
- @Override
- public ColumnMetadata getFirstColumn()
- {
- return columnDefs.get(0);
- }
-
- @Override
- public ColumnMetadata getLastColumn()
- {
- return columnDefs.get(columnDefs.size() - 1);
- }
-
- @Override
- public List<ColumnMetadata> getColumnDefs()
- {
- return columnDefs;
- }
-
- @Override
- public final SingleRestriction mergeWith(SingleRestriction otherRestriction)
- {
- // We want to allow query like: (b,c) > (?, ?) AND b < ?
- if (!otherRestriction.isMultiColumn()
- && ((SingleColumnRestriction) otherRestriction).canBeConvertedToMultiColumnRestriction())
- {
- return doMergeWith(((SingleColumnRestriction) otherRestriction).toMultiColumnRestriction());
- }
-
- return doMergeWith(otherRestriction);
- }
-
- protected abstract SingleRestriction doMergeWith(SingleRestriction otherRestriction);
-
- /**
- * Returns the names of the columns that are specified within this <code>Restrictions</code> and the other one
- * as a comma separated <code>String</code>.
- *
- * @param otherRestriction the other restrictions
- * @return the names of the columns that are specified within this <code>Restrictions</code> and the other one
- * as a comma separated <code>String</code>.
- */
- protected final String getColumnsInCommons(Restriction otherRestriction)
- {
- Set<ColumnMetadata> commons = new HashSet<>(getColumnDefs());
- commons.retainAll(otherRestriction.getColumnDefs());
- StringBuilder builder = new StringBuilder();
- for (ColumnMetadata columnMetadata : commons)
- {
- if (builder.length() != 0)
- builder.append(" ,");
- builder.append(columnMetadata.name);
- }
- return builder.toString();
- }
-
- @Override
- public final boolean hasSupportingIndex(IndexRegistry indexRegistry)
- {
- for (Index index : indexRegistry.listIndexes())
- if (isSupportedBy(index))
- return true;
-
- return false;
- }
-
- @Override
- public final Index findSupportingIndex(IndexRegistry indexRegistry)
- {
- for (Index index : indexRegistry.listIndexes())
- if (isSupportedBy(index))
- return index;
- return null;
- }
-
- @Override
- public Index findSupportingIndexFromQueryPlan(Index.QueryPlan indexQueryPlan)
- {
- for (Index index : indexQueryPlan.getIndexes())
- if (isSupportedBy(index))
- return index;
- return null;
- }
-
- @Override
- public boolean needsFiltering(Index.Group indexGroup)
- {
- for (ColumnMetadata column : columnDefs)
- {
- if (!isSupportedBy(indexGroup, column))
- return true;
- }
- return false;
- }
-
- private boolean isSupportedBy(Index.Group indexGroup, ColumnMetadata column)
- {
- for (Index index : indexGroup.getIndexes())
- {
- if (isSupportedBy(index, column))
- return true;
- }
- return false;
- }
-
- /**
- * Check if this type of restriction is supported for by the specified index.
- * @param index the secondary index
- *
- * @return <code>true</code> this type of restriction is supported by the specified index,
- * <code>false</code> otherwise.
- */
- private boolean isSupportedBy(Index index)
- {
- for (ColumnMetadata column : columnDefs)
- {
- if (isSupportedBy(index, column))
- return true;
- }
- return false;
- }
-
- protected abstract boolean isSupportedBy(Index index, ColumnMetadata def);
-
- public static class EQRestriction extends MultiColumnRestriction
- {
- protected final Term value;
-
- public EQRestriction(List<ColumnMetadata> columnDefs, Term value)
- {
- super(columnDefs);
- this.value = value;
- }
-
- @Override
- public boolean isEQ()
- {
- return true;
- }
-
- @Override
- public void addFunctionsTo(List<Function> functions)
- {
- value.addFunctionsTo(functions);
- }
-
- @Override
- public String toString()
- {
- return String.format("EQ(%s)", value);
- }
-
- @Override
- public SingleRestriction doMergeWith(SingleRestriction otherRestriction)
- {
- throw invalidRequest("%s cannot be restricted by more than one relation if it includes an Equal",
- getColumnsInCommons(otherRestriction));
- }
-
- @Override
- protected boolean isSupportedBy(Index index, ColumnMetadata column)
- {
- return index.supportsExpression(column, Operator.EQ);
- }
-
- @Override
- public MultiCBuilder appendTo(MultiCBuilder builder, QueryOptions options)
- {
- Term.Terminal t = value.bind(options);
- List<ByteBuffer> values = t.getElements();
- for (int i = 0, m = values.size(); i < m; i++)
- {
- builder.addElementToAll(values.get(i));
- checkFalse(builder.containsNull(), "Invalid null value for column %s", columnDefs.get(i).name);
- }
- return builder;
- }
-
- @Override
- public final void addToRowFilter(RowFilter filter, IndexRegistry indexRegistry, QueryOptions options)
- {
- Term.Terminal t = value.bind(options);
- List<ByteBuffer> values = t.getElements();
-
- for (int i = 0, m = columnDefs.size(); i < m; i++)
- {
- ColumnMetadata columnDef = columnDefs.get(i);
- filter.add(columnDef, Operator.EQ, values.get(i));
- }
- }
- }
-
- public static class INRestriction extends MultiColumnRestriction
- {
- private final Terms values;
-
- public INRestriction(List<ColumnMetadata> columnDefs, Terms values)
- {
- super(columnDefs);
- this.values = values;
- }
-
- @Override
- public void addFunctionsTo(List<Function> functions)
- {
- values.addFunctionsTo(functions);
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public MultiCBuilder appendTo(MultiCBuilder builder, QueryOptions options)
- {
- List<List<ByteBuffer>> elements = values.bindAndGetElements(options);
-
- if (elements == null)
- throw invalidRequest("Invalid null value for in(%s)", ColumnMetadata.toCQLString(columnDefs));
- if (elements == Terms.UNSET_LIST)
- throw invalidRequest("Invalid unset value for in(%s)", ColumnMetadata.toCQLString(columnDefs));
-
- builder.addAllElementsToAll(elements);
-
- if (builder.containsNull())
- throw invalidRequest("Invalid null value in condition for columns: %s", ColumnMetadata.toIdentifiers(columnDefs));
- return builder;
- }
-
- @Override
- public boolean isIN()
- {
- return true;
- }
-
- @Override
- public SingleRestriction doMergeWith(SingleRestriction otherRestriction)
- {
- throw invalidRequest("%s cannot be restricted by more than one relation if it includes a IN",
- getColumnsInCommons(otherRestriction));
- }
-
- @Override
- protected boolean isSupportedBy(Index index, ColumnMetadata column)
- {
- return index.supportsExpression(column, Operator.IN);
- }
-
- @Override
- public final void addToRowFilter(RowFilter filter,
- IndexRegistry indexRegistry,
- QueryOptions options)
- {
- // If the relation is of the type (c) IN ((x),(y),(z)) then it is equivalent to
- // c IN (x, y, z) and we can perform filtering
- if (getColumnDefs().size() == 1)
- {
- List<List<ByteBuffer>> splitValues = values.bindAndGetElements(options);
- List<ByteBuffer> values = new ArrayList<>(splitValues.size());
- for (List<ByteBuffer> splitValue : splitValues)
- values.add(splitValue.get(0));
-
- ListType<?> type = ListType.getInstance(getFirstColumn().type, false);
- ByteBuffer buffer = type.pack(values);
- filter.add(getFirstColumn(), Operator.IN, buffer);
- }
- else
- {
- throw invalidRequest("Multicolumn IN filters are not supported");
- }
- }
- }
-
- public static class SliceRestriction extends MultiColumnRestriction
- {
- private final TermSlice slice;
-
- public SliceRestriction(List<ColumnMetadata> columnDefs, Bound bound, boolean inclusive, Term term)
- {
- this(columnDefs, TermSlice.newInstance(bound, inclusive, term));
- }
-
- SliceRestriction(List<ColumnMetadata> columnDefs, TermSlice slice)
- {
- super(columnDefs);
- this.slice = slice;
- }
-
- @Override
- public boolean isSlice()
- {
- return true;
- }
-
- @Override
- public MultiCBuilder appendTo(MultiCBuilder builder, QueryOptions options)
- {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public MultiCBuilder appendBoundTo(MultiCBuilder builder, Bound bound, QueryOptions options)
- {
- boolean reversed = getFirstColumn().isReversedType();
-
- EnumMap<Bound, List<ByteBuffer>> componentBounds = new EnumMap<>(Bound.class);
- componentBounds.put(Bound.START, componentBounds(Bound.START, options));
- componentBounds.put(Bound.END, componentBounds(Bound.END, options));
-
- List<List<ByteBuffer>> toAdd = new ArrayList<>();
- List<ByteBuffer> values = new ArrayList<>();
-
- for (int i = 0, m = columnDefs.size(); i < m; i++)
- {
- ColumnMetadata column = columnDefs.get(i);
- Bound b = bound.reverseIfNeeded(column);
-
- // For mixed order columns, we need to create additional slices when 2 columns are in reverse order
- if (reversed != column.isReversedType())
- {
- reversed = column.isReversedType();
- // As we are switching direction we need to add the current composite
- toAdd.add(values);
-
- // The new bound side has no value for this component. just stop
- if (!hasComponent(b, i, componentBounds))
- continue;
-
- // The other side has still some components. We need to end the slice that we have just open.
- if (hasComponent(b.reverse(), i, componentBounds))
- toAdd.add(values);
-
- // We need to rebuild where we are in this bound side
- values = new ArrayList<ByteBuffer>();
-
- List<ByteBuffer> vals = componentBounds.get(b);
-
- int n = Math.min(i, vals.size());
- for (int j = 0; j < n; j++)
- {
- ByteBuffer v = checkNotNull(vals.get(j),
- "Invalid null value in condition for column %s",
- columnDefs.get(j).name);
- values.add(v);
- }
- }
-
- if (!hasComponent(b, i, componentBounds))
- continue;
-
- ByteBuffer v = checkNotNull(componentBounds.get(b).get(i), "Invalid null value in condition for column %s", columnDefs.get(i).name);
- values.add(v);
- }
- toAdd.add(values);
-
- if (bound.isEnd())
- Collections.reverse(toAdd);
-
- return builder.addAllElementsToAll(toAdd);
- }
-
- @Override
- protected boolean isSupportedBy(Index index, ColumnMetadata column)
- {
- return slice.isSupportedBy(column, index);
- }
-
- @Override
- public boolean hasBound(Bound bound)
- {
- return slice.hasBound(bound);
- }
-
- @Override
- public void addFunctionsTo(List<Function> functions)
- {
- slice.addFunctionsTo(functions);
- }
-
- @Override
- public boolean isInclusive(Bound bound)
- {
- return slice.isInclusive(bound);
- }
-
- @Override
- public SingleRestriction doMergeWith(SingleRestriction otherRestriction)
- {
- checkTrue(otherRestriction.isSlice(),
- "Column \"%s\" cannot be restricted by both an equality and an inequality relation",
- getColumnsInCommons(otherRestriction));
-
- if (!getFirstColumn().equals(otherRestriction.getFirstColumn()))
- {
- ColumnMetadata column = getFirstColumn().position() > otherRestriction.getFirstColumn().position()
- ? getFirstColumn() : otherRestriction.getFirstColumn();
-
- throw invalidRequest("Column \"%s\" cannot be restricted by two inequalities not starting with the same column",
- column.name);
- }
-
- checkFalse(hasBound(Bound.START) && otherRestriction.hasBound(Bound.START),
- "More than one restriction was found for the start bound on %s",
- getColumnsInCommons(otherRestriction));
- checkFalse(hasBound(Bound.END) && otherRestriction.hasBound(Bound.END),
- "More than one restriction was found for the end bound on %s",
- getColumnsInCommons(otherRestriction));
-
- SliceRestriction otherSlice = (SliceRestriction) otherRestriction;
- List<ColumnMetadata> newColumnDefs = columnDefs.size() >= otherSlice.columnDefs.size() ? columnDefs : otherSlice.columnDefs;
-
- return new SliceRestriction(newColumnDefs, slice.merge(otherSlice.slice));
- }
-
- @Override
- public final void addToRowFilter(RowFilter filter,
- IndexRegistry indexRegistry,
- QueryOptions options)
- {
- throw invalidRequest("Multi-column slice restrictions cannot be used for filtering.");
- }
-
- @Override
- public String toString()
- {
- return "SLICE" + slice;
- }
-
- /**
- * Similar to bounds(), but returns one ByteBuffer per-component in the bound instead of a single
- * ByteBuffer to represent the entire bound.
- * @param b the bound type
- * @param options the query options
- * @return one ByteBuffer per-component in the bound
- */
- private List<ByteBuffer> componentBounds(Bound b, QueryOptions options)
- {
- if (!slice.hasBound(b))
- return Collections.emptyList();
-
- Terminal terminal = slice.bound(b).bind(options);
- return terminal.getElements();
- }
-
- private boolean hasComponent(Bound b, int index, EnumMap<Bound, List<ByteBuffer>> componentBounds)
- {
- return componentBounds.get(b).size() > index;
- }
- }
-
- public static class NotNullRestriction extends MultiColumnRestriction
- {
- public NotNullRestriction(List<ColumnMetadata> columnDefs)
- {
- super(columnDefs);
- assert columnDefs.size() == 1;
- }
-
- @Override
- public void addFunctionsTo(List<Function> functions)
- {
- }
-
- @Override
- public boolean isNotNull()
- {
- return true;
- }
-
- @Override
- public String toString()
- {
- return "IS NOT NULL";
- }
-
- @Override
- public SingleRestriction doMergeWith(SingleRestriction otherRestriction)
- {
- throw invalidRequest("%s cannot be restricted by a relation if it includes an IS NOT NULL clause",
- getColumnsInCommons(otherRestriction));
- }
-
- @Override
- protected boolean isSupportedBy(Index index, ColumnMetadata column)
- {
- return index.supportsExpression(column, Operator.IS_NOT);
- }
-
- @Override
- public MultiCBuilder appendTo(MultiCBuilder builder, QueryOptions options)
- {
- throw new UnsupportedOperationException("Cannot use IS NOT NULL restriction for slicing");
- }
-
- @Override
- public final void addToRowFilter(RowFilter filter, IndexRegistry indexRegistry, QueryOptions options)
- {
- throw new UnsupportedOperationException("Secondary indexes do not support IS NOT NULL restrictions");
- }
- }
-
- @Override
- public String toString()
- {
- return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE);
- }
-}
diff --git a/src/java/org/apache/cassandra/cql3/restrictions/PartitionKeyRestrictions.java b/src/java/org/apache/cassandra/cql3/restrictions/PartitionKeyRestrictions.java
index 822452979e..ce3dfd4eef 100644
--- a/src/java/org/apache/cassandra/cql3/restrictions/PartitionKeyRestrictions.java
+++ b/src/java/org/apache/cassandra/cql3/restrictions/PartitionKeyRestrictions.java
@@ -18,52 +18,359 @@
package org.apache.cassandra.cql3.restrictions;
import java.nio.ByteBuffer;
+import java.util.ArrayList;
import java.util.List;
+import java.util.Set;
+import java.util.SortedSet;
-import org.apache.cassandra.schema.TableMetadata;
+import com.google.common.collect.BoundType;
+import com.google.common.collect.ImmutableRangeSet;
+import com.google.common.collect.Range;
+import com.google.common.collect.RangeSet;
+
+import org.apache.cassandra.cql3.functions.Function;
+import org.apache.cassandra.db.PartitionPosition;
+import org.apache.cassandra.db.guardrails.Guardrails;
+import org.apache.cassandra.dht.AbstractBounds;
+import org.apache.cassandra.dht.Bounds;
+import org.apache.cassandra.dht.IPartitioner;
+import org.apache.cassandra.dht.Token;
+import org.apache.cassandra.dht.Token.TokenFactory;
+import org.apache.cassandra.exceptions.InvalidRequestException;
+import org.apache.cassandra.schema.ColumnMetadata;
import org.apache.cassandra.cql3.QueryOptions;
-import org.apache.cassandra.cql3.statements.Bound;
+import org.apache.cassandra.db.ClusteringComparator;
+import org.apache.cassandra.db.ClusteringPrefix;
+import org.apache.cassandra.db.MultiCBuilder;
import org.apache.cassandra.service.ClientState;
/**
* A set of restrictions on the partition key.
*
*/
-interface PartitionKeyRestrictions extends Restrictions
+final class PartitionKeyRestrictions extends RestrictionSetWrapper
{
- public PartitionKeyRestrictions mergeWith(Restriction restriction);
+ /**
+ * The composite type.
+ */
+ private final ClusteringComparator comparator;
+
+ /**
+ * The token restrictions or {@code null} if there are no restrictions on tokens.
+ */
+ private final SingleRestriction tokenRestrictions;
+
+
+ @Override
+ public boolean isOnToken()
+ {
+ // if all partition key columns have non-token restrictions and do not need filtering,
+ // we can simply use the token range to filter those restrictions and then ignore the token range
+ return tokenRestrictions != null && (restrictions.isEmpty() || needFiltering());
+ }
+
+ public PartitionKeyRestrictions(ClusteringComparator comparator)
+ {
+ super(RestrictionSet.empty());
+ this.comparator = comparator;
+ this.tokenRestrictions = null;
+ }
+
+ private PartitionKeyRestrictions(PartitionKeyRestrictions pkRestrictions,
+ SingleRestriction restriction)
+ {
+ super(restriction.isOnToken() ? pkRestrictions.restrictions
+ : pkRestrictions.restrictions.addRestriction(restriction));
+ this.comparator = pkRestrictions.comparator;
+ this.tokenRestrictions = restriction.isOnToken() ? pkRestrictions.tokenRestrictions == null ? restriction
+ : pkRestrictions.tokenRestrictions.mergeWith(restriction)
+ : pkRestrictions.tokenRestrictions;
+ }
+
+ public PartitionKeyRestrictions mergeWith(Restriction restriction)
+ {
+ return new PartitionKeyRestrictions(this, (SingleRestriction) restriction);
+ }
+
+ @Override
+ public void addFunctionsTo(List<Function> functions)
+ {
+ if (tokenRestrictions != null)
+ tokenRestrictions.addFunctionsTo(functions);
+ super.addFunctionsTo(functions);
+ }
+
+ /**
+ * Returns the partitions selected by this set of restrictions
+ *
+ * @param partitioner the partitioner
+ * @param options the query options
+ * @param state the client state
+ * @return the partitions selected by this set of restrictions
+ */
+ public List<ByteBuffer> values(IPartitioner partitioner, QueryOptions options, ClientState state)
+ {
+ // if we need to perform filtering its means that this query is a partition range query and that
+ // this method should not be called
+ if (isEmpty() || needFiltering())
+ throw new IllegalStateException("the query is a partition range query and this method should not be called");
+
+ List<ByteBuffer> nonTokenRestrictionValues = nonTokenRestrictionValues(options, state);
- public List<ByteBuffer> values(QueryOptions options, ClientState state);
+ if (tokenRestrictions == null)
+ return nonTokenRestrictionValues;
- public List<ByteBuffer> bounds(Bound b, QueryOptions options);
+ return filter(partitioner, nonTokenRestrictionValues, options);
+ }
/**
- * Checks if the specified bound is set or not.
- * @param b the bound type
- * @return <code>true</code> if the specified bound is set, <code>false</code> otherwise
+ * Returns the range of partitions selected by this set of restrictions
+ *
+ * @param partitioner the partitioner
+ * @param options the query options
+ * @return the range of partitions selected by this set of restrictions
*/
- public boolean hasBound(Bound b);
+ public AbstractBounds<PartitionPosition> bounds(IPartitioner partitioner, QueryOptions options)
+ {
+ if (isOnToken())
+ {
+ RangeSet<Token> tokenRangeSet = toRangeSet(partitioner, tokenRestrictions, options);
+ Set<Range<Token>> ranges = tokenRangeSet.asRanges();
+
+ if (ranges.isEmpty())
+ return null;
+
+ assert ranges.size() == 1; // We should only have 1 range.
+ Range<Token> range = ranges.iterator().next();
+ Token startToken = range.hasLowerBound() ? range.lowerEndpoint() : partitioner.getMinimumToken();
+ Token endToken = range.hasUpperBound() ? range.upperEndpoint() : partitioner.getMinimumToken();
+
+ boolean includeStart = range.hasLowerBound() && range.lowerBoundType() == BoundType.CLOSED;
+ boolean includeEnd = range.hasUpperBound() && range.upperBoundType() == BoundType.CLOSED;
+
+ /*
+ * If we ask SP.getRangeSlice() for (token(200), token(200)], it will happily return the whole ring.
+ * However, wrapping range doesn't really make sense for CQL, and we want to return an empty result in that
+ * case (CASSANDRA-5573). So special case to create a range that is guaranteed to be empty.
+ *
+ * In practice, we want to return an empty result set if either startToken > endToken, or both are equal but
+ * one of the bound is excluded (since [a, a] can contain something, but not (a, a], [a, a) or (a, a)).
+ * Note though that in the case where startToken or endToken is the minimum token, then this special case
+ * rule should not apply.
+ */
+ int cmp = startToken.compareTo(endToken);
+ if (!startToken.isMinimum() && !endToken.isMinimum()
+ && (cmp > 0 || (cmp == 0 && (!includeStart || !includeEnd))))
+ return null;
+
+ PartitionPosition start = includeStart ? startToken.minKeyBound() : startToken.maxKeyBound();
+ PartitionPosition end = includeEnd ? endToken.maxKeyBound() : endToken.minKeyBound();
+
+ return new org.apache.cassandra.dht.Range<>(start, end);
+ }
+
+ // If we do not have a token restrictions, we should only end up there if there is no restrictions or filtering is required.
+ if (restrictions.isEmpty())
+ return new Bounds<>(partitioner.getMinimumToken().minKeyBound() , partitioner.getMinimumToken().minKeyBound());
+
+ if (needFiltering())
+ return new org.apache.cassandra.dht.Range<>(partitioner.getMinimumToken().minKeyBound(), partitioner.getMinimumToken().maxKeyBound());
+
+ // the request is for an index query for a single partition
+ ByteBuffer partitionKey = nonTokenRestrictionValues(options, null).get(0);
+ PartitionPosition position = PartitionPosition.ForKey.get(partitionKey, partitioner);
+ return new Bounds<>(position, position);
+ }
/**
- * Checks if the specified bound is inclusive or not.
- * @param b the bound type
- * @return <code>true</code> if the specified bound is inclusive, <code>false</code> otherwise
+ * Computes the partition key values selected by the non-token restrictions.
+ *
+ * @param options the query options
+ * @param state the client state used to check guardrails
+ * @return the partition key values selected by the non-token restrictions.
*/
- public boolean isInclusive(Bound b);
+ private List<ByteBuffer> nonTokenRestrictionValues(QueryOptions options, ClientState state)
+ {
+ MultiCBuilder builder = new MultiCBuilder(comparator);
+ for (SingleRestriction r : restrictions)
+ {
+ builder.extend(r.values(options));
+
+ if (Guardrails.inSelectCartesianProduct.enabled(state))
+ Guardrails.inSelectCartesianProduct.guard(builder.buildSize(), "partition key", false, state);
+
+ if (builder.hasMissingElements())
+ break;
+ }
+ return toByteBuffers(builder.build());
+ }
+
+ private List<ByteBuffer> toByteBuffers(SortedSet<? extends ClusteringPrefix<?>> clusterings)
+ {
+ List<ByteBuffer> l = new ArrayList<>(clusterings.size());
+ for (ClusteringPrefix<?> clustering : clusterings)
+ {
+ // Can not use QueryProcessor.validateKey here to validate each column as that validates that empty are not allowed
+ // but composite partition keys actually allow empty!
+ clustering.validate();
+ l.add(clustering.serializeAsPartitionKey());
+ }
+ return l;
+ }
+
+ @Override
+ public int size()
+ {
+ // If the token restriction is not null we know that all the partition key columns are restricted.
+ return tokenRestrictions == null ? restrictions.size() : comparator.size() ;
+ }
+
+ /**
+ * Use the token restrictions to filter the values returned by the non-token restrictions.
+ *
+ * @param partitioner the partitioner
+ * @param values the values returned by the non-token restrictions
+ * @param options the query options
+ * @return the values matching the token restriction
+ */
+ private List<ByteBuffer> filter(IPartitioner partitioner, List<ByteBuffer> values, QueryOptions options)
+ {
+ RangeSet<Token> rangeSet = tokenRestrictions.isSlice() ? toRangeSet(partitioner, tokenRestrictions, options)
+ : toRangeSet(partitioner, tokenRestrictions.values(options));
+
+ return filterWithRangeSet(partitioner, rangeSet, values);
+ }
+
+ /**
+ * Filter out the values for which the tokens are not included within the specified range.
+ *
+ * @param partitioner the partitioner
+ * @param tokens the tokens range
+ * @param values the restricted values
+ * @return the values for which the tokens are not included within the specified range.
+ */
+ private List<ByteBuffer> filterWithRangeSet(IPartitioner partitioner, RangeSet<Token> tokens, List<ByteBuffer> values)
+ {
+ List<ByteBuffer> remaining = new ArrayList<>();
+
+ for (ByteBuffer value : values)
+ {
+ Token token = partitioner.getToken(value);
+
+ if (!tokens.contains(token))
+ continue;
+
+ remaining.add(value);
+ }
+ return remaining;
+ }
+
+ /**
+ * Converts the specified list into a range set.
+ *
+ * @param partitioner the partitioner
+ * @param values the token restriction values
+ * @return the range set corresponding to the specified list
+ */
+ private RangeSet<Token> toRangeSet(IPartitioner partitioner, List<ClusteringElements> values)
+ {
+ TokenFactory tokenFactory = partitioner.getTokenFactory();
+
+ ImmutableRangeSet.Builder<Token> builder = ImmutableRangeSet.builder();
+
+ for (List<ByteBuffer> value : values)
+ builder.add(Range.singleton(tokenFactory.fromByteArray(value.get(0))));
+
+ return builder.build();
+ }
+
+ /**
+ * Converts the specified slice into a range set.
+ *
+ * @param partitioner the partitioner
+ * @param slice the slice to convert
+ * @param options the query option
+ * @return the range set corresponding to the specified slice
+ * @throws InvalidRequestException if the request is invalid
+ */
+ private RangeSet<Token> toRangeSet(IPartitioner partitioner, SingleRestriction slice, QueryOptions options)
+ {
+ RangeSet<ClusteringElements> rangeSet = ClusteringElements.all();
+ slice.restrict(rangeSet, options);
+
+ ImmutableRangeSet.Builder<Token> builder = ImmutableRangeSet.builder();
+
+ TokenFactory tokenFactory = partitioner.getTokenFactory();
+
+ for (Range<ClusteringElements> range : rangeSet.asRanges())
+ {
+ Range<Token> tokenRange = toTokenRange(tokenFactory, range);
+
+ builder.add(tokenRange);
+ }
+
+ return builder.build();
+ }
+
+ private static Range<Token> toTokenRange(TokenFactory tokenFactory, Range<ClusteringElements> range)
+ {
+ // ValueList ranges always have lower and upper bound but those can be empty (meaning top or bottom) which are
+ // the equivalent to no endpoints.
+ if (range.lowerEndpoint().isEmpty())
+ {
+ return range.upperEndpoint().isEmpty() ? Range.all()
+ : Range.upTo(tokenFactory.fromByteArray(range.upperEndpoint().get(0)),
+ range.upperBoundType());
+ }
+
+ if (range.upperEndpoint().isEmpty())
+ return Range.downTo(tokenFactory.fromByteArray(range.lowerEndpoint().get(0)), range.lowerBoundType());
+
+ return Range.range(tokenFactory.fromByteArray(range.lowerEndpoint().get(0)),
+ range.lowerBoundType(),
+ tokenFactory.fromByteArray(range.upperEndpoint().get(0)),
+ range.upperBoundType());
+ }
+
+ @Override
+ public ColumnMetadata firstColumn()
+ {
+ return isOnToken() ? tokenRestrictions.firstColumn() : restrictions.firstColumn();
+ }
+
+ @Override
+ public ColumnMetadata lastColumn()
+ {
+ return isOnToken() ? tokenRestrictions.lastColumn() : restrictions.lastColumn();
+ }
+
+ @Override
+ public List<ColumnMetadata> columns()
+ {
+ return tokenRestrictions != null ? tokenRestrictions.columns() : restrictions.columns();
+ }
/**
* checks if specified restrictions require filtering
*
- * @param table column family metadata
- * @return <code>true</code> if filtering is required, <code>false</code> otherwise
+ * @return {@code true} if filtering is required, {@code false} otherwise
*/
- public boolean needFiltering(TableMetadata table);
+ public boolean needFiltering()
+ {
+ if (isEmpty())
+ return false;
+
+ // has unrestricted key components or some restrictions that require filtering
+ return hasUnrestrictedPartitionKeyComponents() || restrictions.needsFilteringOrIndexing();
+ }
/**
* Checks if the partition key has unrestricted components.
*
- * @param table column family metadata
* @return <code>true</code> if the partition key has unrestricted components, <code>false</code> otherwise.
*/
- public boolean hasUnrestrictedPartitionKeyComponents(TableMetadata table);
+ public boolean hasUnrestrictedPartitionKeyComponents()
+ {
+ return restrictions.size() < comparator.size();
+ }
}
diff --git a/src/java/org/apache/cassandra/cql3/restrictions/PartitionKeySingleRestrictionSet.java b/src/java/org/apache/cassandra/cql3/restrictions/PartitionKeySingleRestrictionSet.java
deleted file mode 100644
index 914681d691..0000000000
--- a/src/java/org/apache/cassandra/cql3/restrictions/PartitionKeySingleRestrictionSet.java
+++ /dev/null
@@ -1,165 +0,0 @@
-/*
- * 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.restrictions;
-
-import java.nio.ByteBuffer;
-import java.util.*;
-
-import org.apache.cassandra.db.guardrails.Guardrails;
-import org.apache.cassandra.schema.TableMetadata;
-import org.apache.cassandra.cql3.QueryOptions;
-import org.apache.cassandra.cql3.statements.Bound;
-import org.apache.cassandra.db.ClusteringComparator;
-import org.apache.cassandra.db.ClusteringPrefix;
-import org.apache.cassandra.db.MultiCBuilder;
-import org.apache.cassandra.db.filter.RowFilter;
-import org.apache.cassandra.index.IndexRegistry;
-import org.apache.cassandra.service.ClientState;
-
-/**
- * A set of single restrictions on the partition key.
- * <p>This class can only contains <code>SingleRestriction</code> instances. Token restrictions will be handled by
- * <code>TokenRestriction</code> class or by the <code>TokenFilter</code> class if the query contains a mix of token
- * restrictions and single column restrictions on the partition key.
- */
-final class PartitionKeySingleRestrictionSet extends RestrictionSetWrapper implements PartitionKeyRestrictions
-{
- /**
- * The composite type.
- */
- private final ClusteringComparator comparator;
-
- public PartitionKeySingleRestrictionSet(ClusteringComparator comparator)
- {
- super(new RestrictionSet());
- this.comparator = comparator;
- }
-
- private PartitionKeySingleRestrictionSet(PartitionKeySingleRestrictionSet restrictionSet,
- SingleRestriction restriction)
- {
- super(restrictionSet.restrictions.addRestriction(restriction));
- this.comparator = restrictionSet.comparator;
- }
-
- private List<ByteBuffer> toByteBuffers(SortedSet<? extends ClusteringPrefix> clusterings)
- {
- List<ByteBuffer> l = new ArrayList<>(clusterings.size());
- for (ClusteringPrefix clustering : clusterings)
- {
- // Can not use QueryProcessor.validateKey here to validate each column as that validates that empty are not allowed
- // but composite partition keys actually allow empty!
- clustering.validate();
- l.add(clustering.serializeAsPartitionKey());
- }
- return l;
- }
-
- @Override
- public PartitionKeyRestrictions mergeWith(Restriction restriction)
- {
- if (restriction.isOnToken())
- {
- if (isEmpty())
- return (PartitionKeyRestrictions) restriction;
-
- return new TokenFilter(this, (TokenRestriction) restriction);
- }
-
- return new PartitionKeySingleRestrictionSet(this, (SingleRestriction) restriction);
- }
-
- @Override
- public List<ByteBuffer> values(QueryOptions options, ClientState state)
- {
- MultiCBuilder builder = MultiCBuilder.create(comparator, hasIN());
- for (SingleRestriction r : restrictions)
- {
- r.appendTo(builder, options);
-
- if (hasIN() && Guardrails.inSelectCartesianProduct.enabled(state))
- Guardrails.inSelectCartesianProduct.guard(builder.buildSize(), "partition key", false, state);
-
- if (builder.hasMissingElements())
- break;
- }
- return toByteBuffers(builder.build());
- }
-
- @Override
- public List<ByteBuffer> bounds(Bound bound, QueryOptions options)
- {
- MultiCBuilder builder = MultiCBuilder.create(comparator, hasIN());
- for (SingleRestriction r : restrictions)
- {
- r.appendBoundTo(builder, bound, options);
- if (builder.hasMissingElements())
- return Collections.emptyList();
- }
- return toByteBuffers(builder.buildBound(bound.isStart(), true));
- }
-
- @Override
- public boolean hasBound(Bound b)
- {
- if (isEmpty())
- return false;
- return restrictions.lastRestriction().hasBound(b);
- }
-
- @Override
- public boolean isInclusive(Bound b)
- {
- if (isEmpty())
- return false;
- return restrictions.lastRestriction().isInclusive(b);
- }
-
- @Override
- public void addToRowFilter(RowFilter filter,
- IndexRegistry indexRegistry,
- QueryOptions options)
- {
- for (SingleRestriction restriction : restrictions)
- {
- restriction.addToRowFilter(filter, indexRegistry, options);
- }
- }
-
- @Override
- public boolean needFiltering(TableMetadata table)
- {
- if (isEmpty())
- return false;
-
- // slice or has unrestricted key component
- return hasUnrestrictedPartitionKeyComponents(table) || hasSlice() || hasContains();
- }
-
- @Override
- public boolean hasUnrestrictedPartitionKeyComponents(TableMetadata table)
- {
- return size() < table.partitionKeyColumns().size();
- }
-
- @Override
- public boolean hasSlice()
- {
- return restrictions.hasSlice();
- }
-}
diff --git a/src/java/org/apache/cassandra/cql3/restrictions/Restriction.java b/src/java/org/apache/cassandra/cql3/restrictions/Restriction.java
index 7a774bf0d5..125fdf1de3 100644
--- a/src/java/org/apache/cassandra/cql3/restrictions/Restriction.java
+++ b/src/java/org/apache/cassandra/cql3/restrictions/Restriction.java
@@ -31,28 +31,32 @@ import org.apache.cassandra.index.IndexRegistry;
*/
public interface Restriction
{
- public default boolean isOnToken()
+ /**
+ * Checks if this restriction is a token restriction.
+ * @return {@code true} if this restriction is a token restriction, {@code false} otherwise
+ */
+ default boolean isOnToken()
{
return false;
}
/**
- * Returns the definition of the first column.
- * @return the definition of the first column.
+ * Returns the column metadata in position order.
+ * @return the column metadata in position order.
*/
- public ColumnMetadata getFirstColumn();
+ List<ColumnMetadata> columns();
/**
- * Returns the definition of the last column.
- * @return the definition of the last column.
+ * Returns the metadata of the first column.
+ * @return the metadata of the first column.
*/
- public ColumnMetadata getLastColumn();
+ ColumnMetadata firstColumn();
/**
- * Returns the column definitions in position order.
- * @return the column definitions in position order.
+ * Returns the metadata of the last column.
+ * @return the metadata of the last column.
*/
- public List<ColumnMetadata> getColumnDefs();
+ ColumnMetadata lastColumn();
/**
* Adds all functions (native and user-defined) used by any component of the restriction
@@ -62,35 +66,38 @@ public interface Restriction
void addFunctionsTo(List<Function> functions);
/**
- * Check if the restriction is on indexed columns.
- *
- * @param indexRegistry the index registry
- * @return <code>true</code> if the restriction is on indexed columns, <code>false</code>
+ * Checks if this restriction requires filtering or indexing.
+ * @return {@code true} if the restriction will require either filtering or indexing, {@code false} otherwise.
*/
- boolean hasSupportingIndex(IndexRegistry indexRegistry);
+ boolean needsFilteringOrIndexing();
/**
- * Find first supporting index for current restriction
+ * Returns whether this restriction would need filtering if the specified index group were used.
+ * Find the first index supporting this restriction.
*
- * @param indexRegistry the index registry
- * @return <code>index</code> if the restriction is on indexed columns, <code>null</code>
+ * @param indexGroup an index group
+ * @return {@code true} if this would need filtering if {@code indexGroup} were used, {@code false} otherwise
*/
- Index findSupportingIndex(IndexRegistry indexRegistry);
+ boolean needsFiltering(Index.Group indexGroup);
/**
- * Find the first supporting index for the current restriction from an {@link Index.QueryPlan}.
- * @param indexQueryPlan the index query plan
- * @return <code>index</code> if the restriction is on indexed columns, <code>null</code>
+ * Check if the restriction is on indexed columns.
+ *
+ * @param indexes the available indexes
+ * @return <code>true</code> if the restriction is on indexed columns, <code>false</code> otherwise
*/
- Index findSupportingIndexFromQueryPlan(Index.QueryPlan indexQueryPlan);
+ default boolean hasSupportingIndex(Iterable<Index> indexes)
+ {
+ return findSupportingIndex(indexes) != null;
+ }
/**
- * Returns whether this restriction would need filtering if the specified index group were used.
+ * Find the first index supporting this restriction.
*
- * @param indexGroup an index group
- * @return {@code true} if this would need filtering if {@code indexGroup} were used, {@code false} otherwise
+ * @param indexes the available indexes
+ * @return an {@code Index} if the restriction is on indexed columns, {@code null} otherwise.
*/
- boolean needsFiltering(Index.Group indexGroup);
+ Index findSupportingIndex(Iterable<Index> indexes);
/**
* Adds to the specified row filter the expressions corresponding to this <code>Restriction</code>.
@@ -99,7 +106,7 @@ public interface Restriction
* @param indexRegistry the index registry
* @param options the query options
*/
- public void addToRowFilter(RowFilter filter,
- IndexRegistry indexRegistry,
- QueryOptions options);
+ void addToRowFilter(RowFilter filter,
+ IndexRegistry indexRegistry,
+ QueryOptions options);
}
diff --git a/src/java/org/apache/cassandra/cql3/restrictions/RestrictionSet.java b/src/java/org/apache/cassandra/cql3/restrictions/RestrictionSet.java
index 750b728295..9b3c760080 100644
--- a/src/java/org/apache/cassandra/cql3/restrictions/RestrictionSet.java
+++ b/src/java/org/apache/cassandra/cql3/restrictions/RestrictionSet.java
@@ -17,19 +17,25 @@
*/
package org.apache.cassandra.cql3.restrictions;
-import java.util.*;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.NavigableMap;
+import java.util.Set;
+import java.util.TreeMap;
-import com.google.common.collect.AbstractIterator;
-
-import org.apache.cassandra.index.Index;
-import org.apache.cassandra.schema.ColumnMetadata;
import org.apache.cassandra.cql3.QueryOptions;
import org.apache.cassandra.cql3.functions.Function;
import org.apache.cassandra.db.filter.RowFilter;
import org.apache.cassandra.exceptions.InvalidRequestException;
+import org.apache.cassandra.index.Index;
import org.apache.cassandra.index.IndexRegistry;
-import org.apache.commons.lang3.builder.ToStringBuilder;
-import org.apache.commons.lang3.builder.ToStringStyle;
+import org.apache.cassandra.schema.ColumnMetadata;
/**
* Sets of column restrictions.
@@ -51,82 +57,72 @@ final class RestrictionSet implements Restrictions, Iterable<SingleRestriction>
}
};
- private static final TreeMap<ColumnMetadata, SingleRestriction> EMPTY = new TreeMap<>(COLUMN_DEFINITION_COMPARATOR);
+ private static final RestrictionSet EMPTY = new RestrictionSet(Collections.unmodifiableNavigableMap(new TreeMap<>(COLUMN_DEFINITION_COMPARATOR)),
+ false, false, false,false);
/**
* The restrictions per column.
*/
- private final TreeMap<ColumnMetadata, SingleRestriction> restrictions;
+ private final NavigableMap<ColumnMetadata, SingleRestriction> restrictions;
- /**
- * {@code true} if it contains multi-column restrictions, {@code false} otherwise.
- */
- private final boolean hasMultiColumnRestrictions;
+ private final boolean hasSlice;
private final boolean hasIn;
- private final boolean hasContains;
- private final boolean hasSlice;
+
private final boolean hasAnn;
- private final boolean hasOnlyEqualityRestrictions;
- public RestrictionSet()
+ private final boolean needsFilteringOrIndexing;
+
+ /**
+ * Returns an empty {@code RestrictionSet}.
+ * @return an empty {@code RestrictionSet}.
+ */
+ public static RestrictionSet empty()
{
- this(EMPTY, false,
- false,
- false,
- false,
- false,
- true);
+ return EMPTY;
}
- private RestrictionSet(TreeMap<ColumnMetadata, SingleRestriction> restrictions,
- boolean hasMultiColumnRestrictions,
+ private RestrictionSet(NavigableMap<ColumnMetadata, SingleRestriction> restrictions,
boolean hasIn,
- boolean hasContains,
boolean hasSlice,
boolean hasAnn,
- boolean hasOnlyEqualityRestrictions)
+ boolean needsFilteringOrIndexing)
{
this.restrictions = restrictions;
- this.hasMultiColumnRestrictions = hasMultiColumnRestrictions;
this.hasIn = hasIn;
- this.hasContains = hasContains;
this.hasSlice = hasSlice;
this.hasAnn = hasAnn;
- this.hasOnlyEqualityRestrictions = hasOnlyEqualityRestrictions;
+ this.needsFilteringOrIndexing = needsFilteringOrIndexing;
}
@Override
public void addToRowFilter(RowFilter filter, IndexRegistry indexRegistry, QueryOptions options) throws InvalidRequestException
{
- for (Restriction restriction : restrictions.values())
+ for (Restriction restriction : this)
restriction.addToRowFilter(filter, indexRegistry, options);
}
@Override
- public boolean needsFiltering(Index.Group indexGroup)
+ public boolean needsFilteringOrIndexing()
{
- for (SingleRestriction restriction : restrictions.values())
- {
- if (restriction.needsFiltering(indexGroup))
- return true;
- }
- return false;
+ return needsFilteringOrIndexing;
+ }
+
+ public ColumnMetadata firstColumn()
+ {
+ return isEmpty() ? null : this.restrictions.firstKey();
}
@Override
- public List<ColumnMetadata> getColumnDefs()
+ public ColumnMetadata lastColumn()
{
- return new ArrayList<>(restrictions.keySet());
+ return isEmpty() ? null : this.restrictions.lastKey();
}
- /**
- * @return a direct reference to the key set from {@link #restrictions} with no defenseive copying
- */
@Override
- public Collection<ColumnMetadata> getColumnDefinitions()
+ public List<ColumnMetadata> columns()
{
- return restrictions.keySet();
+ return new ArrayList<>(restrictions.keySet());
}
@Override
@@ -137,9 +133,17 @@ final class RestrictionSet implements Restrictions, Iterable<SingleRestriction>
}
@Override
- public boolean isEmpty()
+ public boolean isRestrictedByEquals(ColumnMetadata column)
+ {
+ SingleRestriction restriction = restrictions.get(column);
+ return restriction != null && restriction.isColumnLevel() && restriction.isEQ();
+ }
+
+ @Override
+ public boolean isRestrictedByEqualsOrIN(ColumnMetadata column)
{
- return restrictions.isEmpty();
+ SingleRestriction restriction = restrictions.get(column);
+ return restriction != null && restriction.isColumnLevel() && (restriction.isEQ() || restriction.isIN());
}
@Override
@@ -171,68 +175,59 @@ final class RestrictionSet implements Restrictions, Iterable<SingleRestriction>
*/
public RestrictionSet addRestriction(SingleRestriction restriction)
{
- // RestrictionSet is immutable so we need to clone the restrictions map.
- TreeMap<ColumnMetadata, SingleRestriction> newRestrictions = new TreeMap<>(this.restrictions);
+ // RestrictionSet is immutable. Therefore, we need to clone the restrictions map.
+ NavigableMap<ColumnMetadata, SingleRestriction> newRestricitons = new TreeMap<>(this.restrictions);
- boolean newHasIn = hasIn || restriction.isIN();
- boolean newHasContains = hasContains || restriction.isContains();
+ boolean newHasIN = hasIn || restriction.isIN();
boolean newHasSlice = hasSlice || restriction.isSlice();
- boolean newHasAnn = hasAnn || restriction.isANN();
- boolean newHasOnlyEqualityRestrictions = hasOnlyEqualityRestrictions && (restriction.isEQ() || restriction.isIN());
+ boolean newHasANN = hasAnn || restriction.isANN();
+ boolean newNeedsFilteringOrIndexing = needsFilteringOrIndexing || restriction.needsFilteringOrIndexing();
- return new RestrictionSet(mergeRestrictions(newRestrictions, restriction),
- hasMultiColumnRestrictions || restriction.isMultiColumn(),
- newHasIn,
- newHasContains,
+ return new RestrictionSet(mergeRestrictions(newRestricitons, restriction),
+ newHasIN,
newHasSlice,
- newHasAnn,
- newHasOnlyEqualityRestrictions);
+ newHasANN,
+ newNeedsFilteringOrIndexing);
}
- private TreeMap<ColumnMetadata, SingleRestriction> mergeRestrictions(TreeMap<ColumnMetadata, SingleRestriction> restrictions,
- SingleRestriction restriction)
+ private NavigableMap<ColumnMetadata, SingleRestriction> mergeRestrictions(NavigableMap<ColumnMetadata,SingleRestriction> restrictions,
+ SingleRestriction restriction)
{
- Collection<ColumnMetadata> columnDefs = restriction.getColumnDefs();
- Set<SingleRestriction> existingRestrictions = getRestrictions(columnDefs);
+ Collection<ColumnMetadata> columns = restriction.columns();
+ Set<SingleRestriction> existings = getRestrictions(columns);
- if (existingRestrictions.isEmpty())
+ if (existings.isEmpty())
{
- for (ColumnMetadata columnDef : columnDefs)
- restrictions.put(columnDef, restriction);
+ for (ColumnMetadata column : columns)
+ restrictions.put(column, restriction);
}
else
{
- for (SingleRestriction existing : existingRestrictions)
+ for (SingleRestriction existing : existings)
{
- SingleRestriction newRestriction = mergeRestrictions(existing, restriction);
+ SingleRestriction newRestriction = existing.mergeWith(restriction);
- for (ColumnMetadata columnDef : columnDefs)
- restrictions.put(columnDef, newRestriction);
+ for (ColumnMetadata column : newRestriction.columns())
+ restrictions.put(column, newRestriction);
}
}
return restrictions;
}
- @Override
- public Set<Restriction> getRestrictions(ColumnMetadata columnDef)
- {
- Restriction existing = restrictions.get(columnDef);
- return existing == null ? Collections.emptySet() : Collections.singleton(existing);
- }
/**
* Returns all the restrictions applied to the specified columns.
*
- * @param columnDefs the column definitions
+ * @param columns the column definitions
* @return all the restrictions applied to the specified columns
*/
- private Set<SingleRestriction> getRestrictions(Collection<ColumnMetadata> columnDefs)
+ private Set<SingleRestriction> getRestrictions(Collection<ColumnMetadata> columns)
{
Set<SingleRestriction> set = new HashSet<>();
- for (ColumnMetadata columnDef : columnDefs)
+ for (ColumnMetadata column : columns)
{
- SingleRestriction existing = restrictions.get(columnDef);
+ SingleRestriction existing = restrictions.get(column);
if (existing != null)
set.add(existing);
}
@@ -240,22 +235,11 @@ final class RestrictionSet implements Restrictions, Iterable<SingleRestriction>
}
@Override
- public boolean hasSupportingIndex(IndexRegistry indexRegistry)
- {
- for (Restriction restriction : restrictions.values())
- {
- if (restriction.hasSupportingIndex(indexRegistry))
- return true;
- }
- return false;
- }
-
- @Override
- public Index findSupportingIndex(IndexRegistry indexRegistry)
+ public Index findSupportingIndex(Iterable<Index> indexes)
{
for (SingleRestriction restriction : restrictions.values())
{
- Index index = restriction.findSupportingIndex(indexRegistry);
+ Index index = restriction.findSupportingIndex(indexes);
if (index != null)
return index;
}
@@ -263,87 +247,31 @@ final class RestrictionSet implements Restrictions, Iterable<SingleRestriction>
}
@Override
- public Index findSupportingIndexFromQueryPlan(Index.QueryPlan indexQueryPlan)
+ public boolean needsFiltering(Index.Group indexGroup)
{
- for (SingleRestriction restriction : restrictions.values())
+ for (SingleRestriction restriction : this)
{
- Index index = restriction.findSupportingIndexFromQueryPlan(indexQueryPlan);
- if (index != null)
- return index;
+ if (restriction.needsFiltering(indexGroup))
+ return true;
}
- return null;
- }
-
- /**
- * Returns the column after the specified one.
- *
- * @param columnDef the column for which the next one need to be found
- * @return the column after the specified one.
- */
- ColumnMetadata nextColumn(ColumnMetadata columnDef)
- {
- return restrictions.tailMap(columnDef, false).firstKey();
- }
-
- @Override
- public ColumnMetadata getFirstColumn()
- {
- return isEmpty() ? null : this.restrictions.firstKey();
- }
-
- @Override
- public ColumnMetadata getLastColumn()
- {
- return isEmpty() ? null : this.restrictions.lastKey();
- }
-
- /**
- * Returns the last restriction.
- *
- * @return the last restriction.
- */
- SingleRestriction lastRestriction()
- {
- return isEmpty() ? null : this.restrictions.lastEntry().getValue();
- }
-
- /**
- * Merges the two specified restrictions.
- *
- * @param restriction the first restriction
- * @param otherRestriction the second restriction
- * @return the merged restriction
- * @throws InvalidRequestException if the two restrictions cannot be merged
- */
- private static SingleRestriction mergeRestrictions(SingleRestriction restriction,
- SingleRestriction otherRestriction)
- {
- return restriction == null ? otherRestriction
- : restriction.mergeWith(otherRestriction);
+ return false;
}
@Override
public Iterator<SingleRestriction> iterator()
{
- Iterator<SingleRestriction> iterator = restrictions.values().iterator();
- return hasMultiColumnRestrictions ? new DistinctIterator<>(iterator) : iterator;
+ // We need to eliminate duplicates in the case where we have multi-column restrictions.
+ return new LinkedHashSet<>(restrictions.values()).iterator();
}
- /**
- * Checks if any of the underlying restriction is an IN.
- * @return <code>true</code> if any of the underlying restriction is an IN, <code>false</code> otherwise
- */
- public final boolean hasIN()
+ @Override
+ public boolean hasIN()
{
return hasIn;
}
- public boolean hasContains()
- {
- return hasContains;
- }
-
- public final boolean hasSlice()
+ @Override
+ public boolean hasSlice()
{
return hasSlice;
}
@@ -354,56 +282,23 @@ final class RestrictionSet implements Restrictions, Iterable<SingleRestriction>
}
/**
- * Checks if all of the underlying restrictions are EQ or IN restrictions.
+ * Returns the column after the specified one.
*
- * @return <code>true</code> if all of the underlying restrictions are EQ or IN restrictions,
- * <code>false</code> otherwise
+ * @param columnDef the column for which the next one need to be found
+ * @return the column after the specified one.
*/
- public final boolean hasOnlyEqualityRestrictions()
+ ColumnMetadata nextColumn(ColumnMetadata columnDef)
{
- return hasOnlyEqualityRestrictions;
+ return restrictions.tailMap(columnDef, false).firstKey();
}
/**
- * {@code Iterator} decorator that removes duplicates in an ordered one.
+ * Returns the last restriction.
*
- * @param <E> the iterator element type.
+ * @return the last restriction.
*/
- private static final class DistinctIterator<E> extends AbstractIterator<E>
- {
- /**
- * The decorated iterator.
- */
- private final Iterator<E> iterator;
-
- /**
- * The previous element.
- */
- private E previous;
-
- public DistinctIterator(Iterator<E> iterator)
- {
- this.iterator = iterator;
- }
-
- protected E computeNext()
- {
- while(iterator.hasNext())
- {
- E next = iterator.next();
- if (!next.equals(previous))
- {
- previous = next;
- return next;
- }
- }
- return endOfData();
- }
- }
-
- @Override
- public String toString()
+ SingleRestriction lastRestriction()
{
- return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE);
+ return restrictions.lastEntry().getValue();
}
}
diff --git a/src/java/org/apache/cassandra/cql3/restrictions/RestrictionSetWrapper.java b/src/java/org/apache/cassandra/cql3/restrictions/RestrictionSetWrapper.java
index 049d287cfd..3c3211df62 100644
--- a/src/java/org/apache/cassandra/cql3/restrictions/RestrictionSetWrapper.java
+++ b/src/java/org/apache/cassandra/cql3/restrictions/RestrictionSetWrapper.java
@@ -17,23 +17,21 @@
*/
package org.apache.cassandra.cql3.restrictions;
-import java.util.Collection;
import java.util.List;
-import java.util.Set;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
-import org.apache.cassandra.index.Index;
-import org.apache.cassandra.schema.ColumnMetadata;
import org.apache.cassandra.cql3.QueryOptions;
import org.apache.cassandra.cql3.functions.Function;
import org.apache.cassandra.db.filter.RowFilter;
+import org.apache.cassandra.index.Index;
import org.apache.cassandra.index.IndexRegistry;
+import org.apache.cassandra.schema.ColumnMetadata;
/**
- * A <code>RestrictionSet</code> wrapper that can be extended to allow to modify the <code>RestrictionSet</code>
- * behaviour without breaking its immutability. Sub-classes should be immutables.
+ * A {@link RestrictionSet} wrapper that can be extended to allow to modify the {@code RestrictionSet}
+ * behaviour without breaking its immutability. Subclasses should be immutable.
*/
class RestrictionSetWrapper implements Restrictions
{
@@ -54,25 +52,26 @@ class RestrictionSetWrapper implements Restrictions
restrictions.addToRowFilter(filter, indexRegistry, options);
}
- public List<ColumnMetadata> getColumnDefs()
+ public List<ColumnMetadata> columns()
{
- return restrictions.getColumnDefs();
+ return restrictions.columns();
}
- @Override
- public Collection<ColumnMetadata> getColumnDefinitions()
+ public void addFunctionsTo(List<Function> functions)
{
- return restrictions.getColumnDefinitions();
+ restrictions.addFunctionsTo(functions);
}
- public RestrictionSet getRestrictionSet()
+ @Override
+ public boolean isRestrictedByEquals(ColumnMetadata column)
{
- return restrictions;
+ return restrictions.isRestrictedByEquals(column);
}
- public void addFunctionsTo(List<Function> functions)
+ @Override
+ public boolean isRestrictedByEqualsOrIN(ColumnMetadata column)
{
- restrictions.addFunctionsTo(functions);
+ return restrictions.isRestrictedByEqualsOrIN(column);
}
public boolean isEmpty()
@@ -87,19 +86,13 @@ class RestrictionSetWrapper implements Restrictions
public boolean hasSupportingIndex(IndexRegistry indexRegistry)
{
- return restrictions.hasSupportingIndex(indexRegistry);
+ return restrictions.hasSupportingIndex(indexRegistry.listIndexes());
}
@Override
- public Index findSupportingIndex(IndexRegistry indexRegistry)
+ public Index findSupportingIndex(Iterable<Index> indexes)
{
- return restrictions.findSupportingIndex(indexRegistry);
- }
-
- @Override
- public Index findSupportingIndexFromQueryPlan(Index.QueryPlan indexQueryPlan)
- {
- return restrictions.findSupportingIndexFromQueryPlan(indexQueryPlan);
+ return restrictions.findSupportingIndex(indexes);
}
@Override
@@ -108,24 +101,20 @@ class RestrictionSetWrapper implements Restrictions
return restrictions.needsFiltering(indexGroup);
}
- public ColumnMetadata getFirstColumn()
- {
- return restrictions.getFirstColumn();
- }
-
- public ColumnMetadata getLastColumn()
+ @Override
+ public boolean needsFilteringOrIndexing()
{
- return restrictions.getLastColumn();
+ return restrictions.needsFilteringOrIndexing();
}
- public boolean hasIN()
+ public ColumnMetadata firstColumn()
{
- return restrictions.hasIN();
+ return restrictions.firstColumn();
}
- public boolean hasContains()
+ public ColumnMetadata lastColumn()
{
- return restrictions.hasContains();
+ return restrictions.lastColumn();
}
public boolean hasSlice()
@@ -133,16 +122,22 @@ class RestrictionSetWrapper implements Restrictions
return restrictions.hasSlice();
}
- public boolean hasOnlyEqualityRestrictions()
+ @Override
+ public boolean hasIN()
{
- return restrictions.hasOnlyEqualityRestrictions();
+ return restrictions.hasIN();
}
- public Set<Restriction> getRestrictions(ColumnMetadata columnDef)
+ public boolean hasOnlyEqualityRestrictions()
{
- return restrictions.getRestrictions(columnDef);
+ for (ColumnMetadata column : columns())
+ {
+ if (!isRestrictedByEqualsOrIN(column))
+ return false;
+ }
+ return true;
}
-
+
@Override
public String toString()
{
diff --git a/src/java/org/apache/cassandra/cql3/restrictions/Restrictions.java b/src/java/org/apache/cassandra/cql3/restrictions/Restrictions.java
index 0ad7530e76..e235d5d515 100644
--- a/src/java/org/apache/cassandra/cql3/restrictions/Restrictions.java
+++ b/src/java/org/apache/cassandra/cql3/restrictions/Restrictions.java
@@ -17,9 +17,6 @@
*/
package org.apache.cassandra.cql3.restrictions;
-import java.util.Collection;
-import java.util.Set;
-
import org.apache.cassandra.schema.ColumnMetadata;
/**
@@ -28,58 +25,52 @@ import org.apache.cassandra.schema.ColumnMetadata;
public interface Restrictions extends Restriction
{
/**
- * Returns the restrictions applied to the specified column.
- *
- * @param columnDef the column definition
- * @return the restrictions applied to the specified column
+ * Checks if the specified column is restricted by an equals at the column level.
+ * @return {@code true} if the column is restricted by an equals at the column level, {@code false} otherwise.
*/
- Set<Restriction> getRestrictions(ColumnMetadata columnDef);
+ boolean isRestrictedByEquals(ColumnMetadata column);
/**
- * This method exists in addition to {@link #getColumnDefs()} in case implementations want to
- * provide columns definitions that are not strictly in position order.
+ * Checks if the specified column is restricted by an equals or an IN at the column level.
+ * @return {@code true} if the column is restricted by an equals or an IN at the column level, {@code false} otherwise.
*/
- default Collection<ColumnMetadata> getColumnDefinitions()
- {
- return getColumnDefs();
- }
+ boolean isRestrictedByEqualsOrIN(ColumnMetadata column);
/**
* Checks if this <code>Restrictions</code> is empty or not.
*
* @return <code>true</code> if this <code>Restrictions</code> is empty, <code>false</code> otherwise.
*/
- boolean isEmpty();
+ default boolean isEmpty()
+ {
+ return size() == 0;
+ }
/**
* Returns the number of columns that have a restriction.
*
* @return the number of columns that have a restriction.
*/
- public int size();
+ default int size()
+ {
+ return columns().size();
+ }
/**
- * Checks if any of the underlying restriction is an IN.
- * @return <code>true</code> if any of the underlying restriction is an IN, <code>false</code> otherwise
+ * Checks if any of the underlying restriction use an {@code IN} operator.
+ * @return {@code true} if any of the underlying restriction is an IN, {@code false} otherwise
*/
- public boolean hasIN();
+ default boolean hasIN()
+ {
+ return false;
+ }
- /**
- * Checks if any of the underlying restrictions is a CONTAINS / CONTAINS KEY restriction.
- * @return <code>true</code> if any of the underlying restrictions is CONTAINS, <code>false</code> otherwise
- */
- public boolean hasContains();
/**
* Checks if any of the underlying restrictions is a slice.
- * @return <code>true</code> if any of the underlying restrictions is a slice, <code>false</code> otherwise
+ * @return {@code true} if any of the underlying restrictions is a slice, {@code false} otherwise
*/
- public boolean hasSlice();
-
- /**
- * Checks if all of the underlying restrictions are EQ or IN restrictions.
- *
- * @return <code>true</code> if all of the underlying restrictions are EQ or IN restrictions,
- * <code>false</code> otherwise
- */
- public boolean hasOnlyEqualityRestrictions();
+ default boolean hasSlice()
+ {
+ return false;
+ }
}
diff --git a/src/java/org/apache/cassandra/cql3/restrictions/SimpleRestriction.java b/src/java/org/apache/cassandra/cql3/restrictions/SimpleRestriction.java
new file mode 100644
index 0000000000..1a4a4f3935
--- /dev/null
+++ b/src/java/org/apache/cassandra/cql3/restrictions/SimpleRestriction.java
@@ -0,0 +1,374 @@
+/*
+ * 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.restrictions;
+
+import java.nio.ByteBuffer;
+import java.util.List;
+import java.util.stream.Collectors;
+
+import com.google.common.collect.RangeSet;
+
+import org.apache.cassandra.cql3.ColumnsExpression;
+import org.apache.cassandra.cql3.Operator;
+import org.apache.cassandra.cql3.QueryOptions;
+import org.apache.cassandra.cql3.functions.Function;
+import org.apache.cassandra.cql3.terms.Term;
+import org.apache.cassandra.cql3.terms.Terms;
+import org.apache.cassandra.db.filter.RowFilter;
+import org.apache.cassandra.db.marshal.ListType;
+import org.apache.cassandra.index.Index;
+import org.apache.cassandra.index.IndexRegistry;
+import org.apache.cassandra.schema.ColumnMetadata;
+import org.apache.cassandra.utils.ByteBufferUtil;
+
+import static org.apache.cassandra.cql3.statements.RequestValidations.checkFalse;
+import static org.apache.cassandra.cql3.statements.RequestValidations.invalidRequest;
+
+/**
+ * A simple predicate on a columns expression (e.g. columnA = X).
+ */
+public final class SimpleRestriction implements SingleRestriction
+{
+ /**
+ * The columns expression to which the restriction applies.
+ */
+ private final ColumnsExpression columnsExpression;
+
+ /**
+ * The operator
+ */
+ private final Operator operator;
+
+ /**
+ * The values
+ */
+ private final Terms values;
+
+ public SimpleRestriction(ColumnsExpression columnsExpression, Operator operator, Terms values)
+ {
+ this.columnsExpression = columnsExpression;
+ this.operator = operator;
+ this.values = values;
+ }
+
+ @Override
+ public boolean isOnToken()
+ {
+ return columnsExpression.kind() == ColumnsExpression.Kind.TOKEN;
+ }
+
+ @Override
+ public ColumnMetadata firstColumn()
+ {
+ return columnsExpression.firstColumn();
+ }
+
+ @Override
+ public ColumnMetadata lastColumn()
+ {
+ return columnsExpression.lastColumn();
+ }
+
+ @Override
+ public List<ColumnMetadata> columns()
+ {
+ return columnsExpression.columns();
+ }
+
+ @Override
+ public boolean isMultiColumn()
+ {
+ return columnsExpression.kind() == ColumnsExpression.Kind.MULTI_COLUMN;
+ }
+
+ @Override
+ public boolean isColumnLevel()
+ {
+ return columnsExpression.isColumnLevelExpression();
+ }
+
+ public Operator operator()
+ {
+ return operator;
+ }
+
+ @Override
+ public boolean isANN()
+ {
+ return operator == Operator.ANN;
+ }
+
+ @Override
+ public boolean isEQ()
+ {
+ return operator == Operator.EQ;
+ }
+
+ @Override
+ public boolean isSlice()
+ {
+ return operator.isSlice();
+ }
+
+ @Override
+ public boolean isIN()
+ {
+ return operator == Operator.IN;
+ }
+
+ /**
+ * Checks if this restriction operator is a CONTAINS, CONTAINS_KEY or is an equality on a map element.
+ * @return {@code true} if the restriction operator is one of the contains operations, {@code false} otherwise.
+ */
+ public boolean isContains()
+ {
+ return operator == Operator.CONTAINS
+ || operator == Operator.CONTAINS_KEY
+ || columnsExpression.kind() == ColumnsExpression.Kind.MAP_ELEMENT;
+ }
+
+ @Override
+ public boolean needsFilteringOrIndexing()
+ {
+ // The need for filtering or indexing is a combination of columns expression type and operator
+ // Therefore, we have to take both into account.
+ return columnsExpression.kind() == ColumnsExpression.Kind.MAP_ELEMENT
+ || operator.requiresFilteringOrIndexingFor(columnsExpression.columnsKind());
+ }
+
+ @Override
+ public void addFunctionsTo(List<Function> functions)
+ {
+ columnsExpression.addFunctionsTo(functions);
+ values.addFunctionsTo(functions);
+ }
+
+ @Override
+ public boolean needsFiltering(Index.Group indexGroup)
+ {
+ for (ColumnMetadata column : columns())
+ {
+ if (!isSupportedBy(indexGroup.getIndexes(), column))
+ return true;
+ }
+ return false;
+ }
+
+ private boolean isSupportedBy(Iterable<Index> indexes, ColumnMetadata column)
+ {
+ if (isOnToken())
+ return false;
+
+ for (Index index : indexes)
+ {
+ if (index.supportsExpression(column, operator))
+ return true;
+ }
+ return false;
+ }
+
+ @Override
+ public Index findSupportingIndex(Iterable<Index> indexes)
+ {
+ if (isOnToken())
+ return null;
+
+ for (Index index : indexes)
+ if (isSupportedBy(index))
+ return index;
+ return null;
+ }
+
+ @Override
+ public boolean isSupportedBy(Index index)
+ {
+ if (isOnToken())
+ return false;
+
+ for (ColumnMetadata column : columns())
+ {
+ if (index.supportsExpression(column, operator))
+ return true;
+ }
+ return false;
+ }
+
+ @Override
+ public List<ClusteringElements> values(QueryOptions options)
+ {
+ assert operator == Operator.EQ || operator == Operator.IN || operator == Operator.ANN;
+ return bindAndGetClusteringElements(options);
+ }
+
+ @Override
+ public void restrict(RangeSet<ClusteringElements> rangeSet, QueryOptions options)
+ {
+ assert operator.isSlice() || operator == Operator.EQ;
+ operator.restrict(rangeSet, bindAndGetClusteringElements(options));
+ }
+
+ private List<ClusteringElements> bindAndGetClusteringElements(QueryOptions options)
+ {
+ switch (columnsExpression.kind())
+ {
+ case SINGLE_COLUMN:
+ case TOKEN:
+ return bindAndGet(options).stream()
+ .map(b -> ClusteringElements.of(columnsExpression.columnSpecification(), b))
+ .collect(Collectors.toList());
+ case MULTI_COLUMN:
+ return bindAndGetElements(options).stream()
+ .map(buffers -> ClusteringElements.of(columnsExpression.columns(), buffers))
+ .collect(Collectors.toList());
+ default:
+ throw new UnsupportedOperationException();
+ }
+ }
+
+ private List<ByteBuffer> bindAndGet(QueryOptions options)
+ {
+ List<ByteBuffer> buffers = values.bindAndGet(options);
+ validate(buffers);
+ buffers.forEach(this::validate);
+ return buffers;
+ }
+
+ private List<List<ByteBuffer>> bindAndGetElements(QueryOptions options)
+ {
+ List<List<ByteBuffer>> elementsList = values.bindAndGetElements(options);
+ validate(elementsList);
+ elementsList.forEach(this::validateElements);
+ return elementsList;
+ }
+
+ private void validate(List<?> list)
+ {
+ if (list == null)
+ throw invalidRequest("Invalid null value for %s", columnsExpression);
+ if (list == Term.UNSET_LIST)
+ throw invalidRequest("Invalid unset value for %s", columnsExpression);
+ }
+
+ private void validate(ByteBuffer buffer)
+ {
+ if (buffer == null)
+ throw invalidRequest("Invalid null value for %s", columnsExpression);
+ if (buffer == ByteBufferUtil.UNSET_BYTE_BUFFER)
+ throw invalidRequest("Invalid unset value for %s", columnsExpression);
+ }
+
+ private void validateElements(List<ByteBuffer> elements)
+ {
+ validate(elements);
+
+ List<ColumnMetadata> columns = columns();
+ for (int i = 0, m = columns.size(); i < m; i++)
+ {
+ ColumnMetadata column = columns.get(i);
+ ByteBuffer element = elements.get(i);
+ if (element == null)
+ throw invalidRequest("Invalid null value for %s in %s",
+ column.name.toCQLString(), columnsExpression);
+ if (element == ByteBufferUtil.UNSET_BYTE_BUFFER)
+ throw invalidRequest("Invalid unset value for %s in %s",
+ column.name.toCQLString(), columnsExpression);
+ }
+ }
+
+ @Override
+ public void addToRowFilter(RowFilter filter, IndexRegistry indexRegistry, QueryOptions options)
+ {
+ if (isOnToken())
+ throw new UnsupportedOperationException();
+
+ switch (columnsExpression.kind())
+ {
+ case SINGLE_COLUMN:
+ List<ByteBuffer> buffers = bindAndGet(options);
+
+ ColumnMetadata column = firstColumn();
+ if (operator == Operator.IN)
+ {
+ filter.add(column, operator, inValues(column, buffers));
+ }
+ else if (operator == Operator.LIKE)
+ {
+ LikePattern pattern = LikePattern.parse(buffers.get(0));
+ // there must be a suitable INDEX for LIKE_XXX expressions
+ RowFilter.SimpleExpression expression = filter.add(column, pattern.kind().operator(), pattern.value());
+ indexRegistry.getBestIndexFor(expression)
+ .orElseThrow(() -> invalidRequest("%s is only supported on properly indexed columns",
+ expression));
+ }
+ else
+ {
+ filter.add(column, operator, buffers.get(0));
+ }
+ break;
+ case MULTI_COLUMN:
+ checkFalse(isSlice(), "Multi-column slice restrictions cannot be used for filtering.");
+
+ if (isEQ())
+ {
+ List<ByteBuffer> elements = bindAndGetElements(options).get(0);
+
+ for (int i = 0, m = columns().size(); i < m; i++)
+ {
+ ColumnMetadata columnDef = columns().get(i);
+ filter.add(columnDef, Operator.EQ, elements.get(i));
+ }
+ }
+ else if (isIN())
+ {
+ // If the relation is of the type (c) IN ((x),(y),(z)) then it is equivalent to
+ // c IN (x, y, z) and we can perform filtering
+ if (columns().size() == 1)
+ {
+ List<ByteBuffer> values = bindAndGetElements(options).stream()
+ .map(elements -> elements.get(0))
+ .collect(Collectors.toList());
+
+ filter.add(firstColumn(), Operator.IN, inValues(firstColumn(), values));
+ }
+ else
+ {
+ throw invalidRequest("Multicolumn IN filters are not supported");
+ }
+ }
+ break;
+ case MAP_ELEMENT:
+ ByteBuffer key = columnsExpression.mapKey(options);
+ List<ByteBuffer> values = bindAndGet(options);
+ filter.addMapEquality(firstColumn(), key, operator, values.get(0));
+ break;
+ default: throw new UnsupportedOperationException();
+ }
+ }
+
+ private static ByteBuffer inValues(ColumnMetadata column, List<ByteBuffer> values)
+ {
+ return ListType.getInstance(column.type, false).pack(values);
+ }
+
+ @Override
+ public String toString()
+ {
+ return String.format("%s %s %s", columnsExpression.toCQLString(), operator, values);
+ }
+}
diff --git a/src/java/org/apache/cassandra/cql3/restrictions/SingleColumnRestriction.java b/src/java/org/apache/cassandra/cql3/restrictions/SingleColumnRestriction.java
deleted file mode 100644
index 2a8d58fdfc..0000000000
--- a/src/java/org/apache/cassandra/cql3/restrictions/SingleColumnRestriction.java
+++ /dev/null
@@ -1,829 +0,0 @@
-/*
- * 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.restrictions;
-
-import java.nio.ByteBuffer;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.List;
-
-import org.apache.cassandra.cql3.Operator;
-import org.apache.cassandra.cql3.QueryOptions;
-import org.apache.cassandra.cql3.terms.Term;
-import org.apache.cassandra.cql3.terms.Terms;
-import org.apache.cassandra.db.marshal.ListType;
-import org.apache.cassandra.schema.ColumnMetadata;
-import org.apache.cassandra.cql3.functions.Function;
-import org.apache.cassandra.cql3.statements.Bound;
-import org.apache.cassandra.db.MultiCBuilder;
-import org.apache.cassandra.db.filter.RowFilter;
-import org.apache.cassandra.index.Index;
-import org.apache.cassandra.index.IndexRegistry;
-import org.apache.cassandra.utils.ByteBufferUtil;
-import org.apache.cassandra.utils.Pair;
-
-import static org.apache.cassandra.cql3.statements.RequestValidations.checkBindValueSet;
-import static org.apache.cassandra.cql3.statements.RequestValidations.checkFalse;
-import static org.apache.cassandra.cql3.statements.RequestValidations.checkNotNull;
-import static org.apache.cassandra.cql3.statements.RequestValidations.checkTrue;
-import static org.apache.cassandra.cql3.statements.RequestValidations.invalidRequest;
-
-public abstract class SingleColumnRestriction implements SingleRestriction
-{
- /**
- * The definition of the column to which apply the restriction.
- */
- protected final ColumnMetadata columnDef;
-
- public SingleColumnRestriction(ColumnMetadata columnDef)
- {
- this.columnDef = columnDef;
- }
-
- @Override
- public List<ColumnMetadata> getColumnDefs()
- {
- return Collections.singletonList(columnDef);
- }
-
- @Override
- public ColumnMetadata getFirstColumn()
- {
- return columnDef;
- }
-
- @Override
- public ColumnMetadata getLastColumn()
- {
- return columnDef;
- }
-
- @Override
- public boolean hasSupportingIndex(IndexRegistry indexRegistry)
- {
- for (Index index : indexRegistry.listIndexes())
- if (isSupportedBy(index))
- return true;
-
- return false;
- }
-
- @Override
- public Index findSupportingIndex(IndexRegistry indexRegistry)
- {
- for (Index index : indexRegistry.listIndexes())
- if (isSupportedBy(index))
- return index;
-
- return null;
- }
-
- @Override
- public Index findSupportingIndexFromQueryPlan(Index.QueryPlan indexQueryPlan)
- {
- for (Index index : indexQueryPlan.getIndexes())
- if (isSupportedBy(index))
- return index;
-
- return null;
- }
-
- @Override
- public boolean needsFiltering(Index.Group indexGroup)
- {
- for (Index index : indexGroup.getIndexes())
- if (isSupportedBy(index))
- return false;
-
- return true;
- }
-
- @Override
- public final SingleRestriction mergeWith(SingleRestriction otherRestriction)
- {
- // We want to allow query like: b > ? AND (b,c) < (?, ?)
- if (otherRestriction.isMultiColumn() && canBeConvertedToMultiColumnRestriction())
- {
- return toMultiColumnRestriction().mergeWith(otherRestriction);
- }
-
- return doMergeWith(otherRestriction);
- }
-
- protected abstract SingleRestriction doMergeWith(SingleRestriction otherRestriction);
-
- /**
- * Converts this <code>SingleColumnRestriction</code> into a {@link MultiColumnRestriction}
- *
- * @return the <code>MultiColumnRestriction</code> corresponding to this
- */
- abstract MultiColumnRestriction toMultiColumnRestriction();
-
- /**
- * Checks if this <code>Restriction</code> can be converted into a {@link MultiColumnRestriction}
- *
- * @return <code>true</code> if this <code>Restriction</code> can be converted into a
- * {@link MultiColumnRestriction}, <code>false</code> otherwise.
- */
- boolean canBeConvertedToMultiColumnRestriction()
- {
- return true;
- }
-
- /**
- * Check if this type of restriction is supported by the specified index.
- *
- * @param index the secondary index
- * @return <code>true</code> this type of restriction is supported by the specified index,
- * <code>false</code> otherwise.
- */
- protected abstract boolean isSupportedBy(Index index);
-
- public static final class EQRestriction extends SingleColumnRestriction
- {
- private final Term value;
-
- public EQRestriction(ColumnMetadata columnDef, Term value)
- {
- super(columnDef);
- this.value = value;
- }
-
- @Override
- public void addFunctionsTo(List<Function> functions)
- {
- value.addFunctionsTo(functions);
- }
-
- @Override
- public boolean isEQ()
- {
- return true;
- }
-
- @Override
- MultiColumnRestriction toMultiColumnRestriction()
- {
- return new MultiColumnRestriction.EQRestriction(Collections.singletonList(columnDef), value);
- }
-
- @Override
- public void addToRowFilter(RowFilter filter,
- IndexRegistry indexRegistry,
- QueryOptions options)
- {
- filter.add(columnDef, Operator.EQ, value.bindAndGet(options));
- }
-
- @Override
- public MultiCBuilder appendTo(MultiCBuilder builder, QueryOptions options)
- {
- builder.addElementToAll(value.bindAndGet(options));
- checkFalse(builder.containsNull(), "Invalid null value in condition for column %s", columnDef.name);
- checkFalse(builder.containsUnset(), "Invalid unset value for column %s", columnDef.name);
- return builder;
- }
-
- @Override
- public String toString()
- {
- return String.format("EQ(%s)", value);
- }
-
- @Override
- public SingleRestriction doMergeWith(SingleRestriction otherRestriction)
- {
- throw invalidRequest("%s cannot be restricted by more than one relation if it includes an Equal", columnDef.name);
- }
-
- @Override
- protected boolean isSupportedBy(Index index)
- {
- return index.supportsExpression(columnDef, Operator.EQ);
- }
- }
-
- public static class INRestriction extends SingleColumnRestriction
- {
- private final Terms values;
-
- public INRestriction(ColumnMetadata columnDef, Terms values)
- {
- super(columnDef);
- this.values = values;
- }
-
- @Override
- MultiColumnRestriction toMultiColumnRestriction()
- {
- return new MultiColumnRestriction.INRestriction(Collections.singletonList(columnDef), values);
- }
-
- @Override
- public void addFunctionsTo(List<Function> functions)
- {
- values.addFunctionsTo(functions);
- }
-
- @Override
- public final boolean isIN()
- {
- return true;
- }
-
- @Override
- public final SingleRestriction doMergeWith(SingleRestriction otherRestriction)
- {
- throw invalidRequest("%s cannot be restricted by more than one relation if it includes a IN", columnDef.name);
- }
-
- @Override
- public MultiCBuilder appendTo(MultiCBuilder builder, QueryOptions options)
- {
- List<ByteBuffer> buffers = values.bindAndGet(options);
- checkNotNull(buffers, "Invalid null value for column %s", columnDef.name);
- checkFalse(buffers == Terms.UNSET_LIST, "Invalid unset value for column %s", columnDef.name);
- builder.addEachElementToAll(buffers);
- checkFalse(builder.containsNull(), "Invalid null value in condition for column %s", columnDef.name);
- checkFalse(builder.containsUnset(), "Invalid unset value for column %s", columnDef.name);
- return builder;
- }
-
- @Override
- public void addToRowFilter(RowFilter filter,
- IndexRegistry indexRegistry,
- QueryOptions options)
- {
- List<ByteBuffer> elements = values.bindAndGet(options);
- ListType<?> type = ListType.getInstance(columnDef.type, false);
- ByteBuffer buffer = type.pack(elements);
- filter.add(columnDef, Operator.IN, buffer);
- }
-
- @Override
- protected final boolean isSupportedBy(Index index)
- {
- return index.supportsExpression(columnDef, Operator.IN);
- }
- }
-
- public static class SliceRestriction extends SingleColumnRestriction
- {
- private final TermSlice slice;
-
- public SliceRestriction(ColumnMetadata columnDef, Bound bound, boolean inclusive, Term term)
- {
- super(columnDef);
- slice = TermSlice.newInstance(bound, inclusive, term);
- }
-
- @Override
- public void addFunctionsTo(List<Function> functions)
- {
- slice.addFunctionsTo(functions);
- }
-
- @Override
- MultiColumnRestriction toMultiColumnRestriction()
- {
- return new MultiColumnRestriction.SliceRestriction(Collections.singletonList(columnDef), slice);
- }
-
- @Override
- public boolean isSlice()
- {
- return true;
- }
-
- @Override
- public MultiCBuilder appendTo(MultiCBuilder builder, QueryOptions options)
- {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public boolean hasBound(Bound b)
- {
- return slice.hasBound(b);
- }
-
- @Override
- public MultiCBuilder appendBoundTo(MultiCBuilder builder, Bound bound, QueryOptions options)
- {
- Bound b = bound.reverseIfNeeded(getFirstColumn());
-
- if (!hasBound(b))
- return builder;
-
- ByteBuffer value = slice.bound(b).bindAndGet(options);
- checkBindValueSet(value, "Invalid unset value for column %s", columnDef.name);
- return builder.addElementToAll(value);
-
- }
-
- @Override
- public boolean isInclusive(Bound b)
- {
- return slice.isInclusive(b);
- }
-
- @Override
- public SingleRestriction doMergeWith(SingleRestriction otherRestriction)
- {
- checkTrue(otherRestriction.isSlice(),
- "Column \"%s\" cannot be restricted by both an equality and an inequality relation",
- columnDef.name);
-
- SingleColumnRestriction.SliceRestriction otherSlice = (SingleColumnRestriction.SliceRestriction) otherRestriction;
-
- checkFalse(hasBound(Bound.START) && otherSlice.hasBound(Bound.START),
- "More than one restriction was found for the start bound on %s", columnDef.name);
-
- checkFalse(hasBound(Bound.END) && otherSlice.hasBound(Bound.END),
- "More than one restriction was found for the end bound on %s", columnDef.name);
-
- return new SliceRestriction(columnDef, slice.merge(otherSlice.slice));
- }
-
- @Override
- public void addToRowFilter(RowFilter filter, IndexRegistry indexRegistry, QueryOptions options)
- {
- for (Bound b : Bound.values())
- if (hasBound(b))
- filter.add(columnDef, slice.getIndexOperator(b), slice.bound(b).bindAndGet(options));
- }
-
- @Override
- protected boolean isSupportedBy(Index index)
- {
- return slice.isSupportedBy(columnDef, index);
- }
-
- @Override
- public String toString()
- {
- return String.format("SLICE%s", slice);
- }
-
- private SliceRestriction(ColumnMetadata columnDef, TermSlice slice)
- {
- super(columnDef);
- this.slice = slice;
- }
- }
-
- // This holds CONTAINS, CONTAINS_KEY, and map[key] = value restrictions because we might want to have any combination of them.
- public static final class ContainsRestriction extends SingleColumnRestriction
- {
- private final List<Term> values = new ArrayList<>(); // for CONTAINS
- private final List<Term> keys = new ArrayList<>(); // for CONTAINS_KEY
- private final List<Term> entryKeys = new ArrayList<>(); // for map[key] = value
- private final List<Term> entryValues = new ArrayList<>(); // for map[key] = value
-
- public ContainsRestriction(ColumnMetadata columnDef, Term t, boolean isKey)
- {
- super(columnDef);
- if (isKey)
- keys.add(t);
- else
- values.add(t);
- }
-
- public ContainsRestriction(ColumnMetadata columnDef, Term mapKey, Term mapValue)
- {
- super(columnDef);
- entryKeys.add(mapKey);
- entryValues.add(mapValue);
- }
-
- @Override
- MultiColumnRestriction toMultiColumnRestriction()
- {
- throw new UnsupportedOperationException();
- }
-
- @Override
- boolean canBeConvertedToMultiColumnRestriction()
- {
- return false;
- }
-
- @Override
- public MultiCBuilder appendTo(MultiCBuilder builder, QueryOptions options)
- {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public boolean isContains()
- {
- return true;
- }
-
- @Override
- public SingleRestriction doMergeWith(SingleRestriction otherRestriction)
- {
- checkTrue(otherRestriction.isContains(),
- "Collection column %s can only be restricted by CONTAINS, CONTAINS KEY, or map-entry equality",
- columnDef.name);
-
- SingleColumnRestriction.ContainsRestriction newContains = new ContainsRestriction(columnDef);
-
- copyKeysAndValues(this, newContains);
- copyKeysAndValues((ContainsRestriction) otherRestriction, newContains);
-
- return newContains;
- }
-
- @Override
- public void addToRowFilter(RowFilter filter, IndexRegistry indexRegistry, QueryOptions options)
- {
- for (ByteBuffer value : bindAndGet(values, options))
- filter.add(columnDef, Operator.CONTAINS, value);
- for (ByteBuffer key : bindAndGet(keys, options))
- filter.add(columnDef, Operator.CONTAINS_KEY, key);
-
- List<ByteBuffer> eks = bindAndGet(entryKeys, options);
- List<ByteBuffer> evs = bindAndGet(entryValues, options);
- assert eks.size() == evs.size();
- for (int i = 0; i < eks.size(); i++)
- filter.addMapEquality(columnDef, eks.get(i), Operator.EQ, evs.get(i));
- }
-
- @Override
- protected boolean isSupportedBy(Index index)
- {
- boolean supported = false;
-
- if (numberOfValues() > 0)
- supported |= index.supportsExpression(columnDef, Operator.CONTAINS);
-
- if (numberOfKeys() > 0)
- supported |= index.supportsExpression(columnDef, Operator.CONTAINS_KEY);
-
- if (numberOfEntries() > 0)
- supported |= index.supportsExpression(columnDef, Operator.EQ);
-
- return supported;
- }
-
- @Override
- public boolean needsFiltering(Index.Group indexGroup)
- {
- // multiple contains might require filtering on some indexes, since that is equivalent to a disjunction (or)
- boolean hasMultipleContains = (numberOfValues() + numberOfKeys() + numberOfEntries()) > 1;
-
- for (Index index : indexGroup.getIndexes())
- {
- if (isSupportedBy(index) && !(hasMultipleContains && index.filtersMultipleContains()))
- return false;
- }
-
- return true;
- }
-
- public int numberOfValues()
- {
- return values.size();
- }
-
- public int numberOfKeys()
- {
- return keys.size();
- }
-
- public int numberOfEntries()
- {
- return entryKeys.size();
- }
-
- @Override
- public void addFunctionsTo(List<Function> functions)
- {
- Terms.addFunctions(values, functions);
- Terms.addFunctions(keys, functions);
- Terms.addFunctions(entryKeys, functions);
- Terms.addFunctions(entryValues, functions);
- }
-
- @Override
- public String toString()
- {
- return String.format("CONTAINS(values=%s, keys=%s, entryKeys=%s, entryValues=%s)", values, keys, entryKeys, entryValues);
- }
-
- @Override
- public boolean hasBound(Bound b)
- {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public MultiCBuilder appendBoundTo(MultiCBuilder builder, Bound bound, QueryOptions options)
- {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public boolean isInclusive(Bound b)
- {
- throw new UnsupportedOperationException();
- }
-
- /**
- * Binds the query options to the specified terms and returns the resulting values.
- *
- * @param terms the terms
- * @param options the query options
- * @return the value resulting from binding the query options to the specified terms
- */
- private static List<ByteBuffer> bindAndGet(List<Term> terms, QueryOptions options)
- {
- List<ByteBuffer> buffers = new ArrayList<>(terms.size());
- for (Term value : terms)
- buffers.add(value.bindAndGet(options));
- return buffers;
- }
-
- /**
- * Copies the keys and value from the first <code>Contains</code> to the second one.
- *
- * @param from the <code>Contains</code> to copy from
- * @param to the <code>Contains</code> to copy to
- */
- private static void copyKeysAndValues(ContainsRestriction from, ContainsRestriction to)
- {
- to.values.addAll(from.values);
- to.keys.addAll(from.keys);
- to.entryKeys.addAll(from.entryKeys);
- to.entryValues.addAll(from.entryValues);
- }
-
- private ContainsRestriction(ColumnMetadata columnDef)
- {
- super(columnDef);
- }
- }
-
- public static final class IsNotNullRestriction extends SingleColumnRestriction
- {
- public IsNotNullRestriction(ColumnMetadata columnDef)
- {
- super(columnDef);
- }
-
- @Override
- public void addFunctionsTo(List<Function> functions)
- {
- }
-
- @Override
- public boolean isNotNull()
- {
- return true;
- }
-
- @Override
- MultiColumnRestriction toMultiColumnRestriction()
- {
- return new MultiColumnRestriction.NotNullRestriction(Collections.singletonList(columnDef));
- }
-
- @Override
- public void addToRowFilter(RowFilter filter,
- IndexRegistry indexRegistry,
- QueryOptions options)
- {
- throw new UnsupportedOperationException("Secondary indexes do not support IS NOT NULL restrictions");
- }
-
- @Override
- public MultiCBuilder appendTo(MultiCBuilder builder, QueryOptions options)
- {
- throw new UnsupportedOperationException("Cannot use IS NOT NULL restriction for slicing");
- }
-
- @Override
- public String toString()
- {
- return "IS NOT NULL";
- }
-
- @Override
- public SingleRestriction doMergeWith(SingleRestriction otherRestriction)
- {
- throw invalidRequest("%s cannot be restricted by a relation if it includes an IS NOT NULL", columnDef.name);
- }
-
- @Override
- protected boolean isSupportedBy(Index index)
- {
- return index.supportsExpression(columnDef, Operator.IS_NOT);
- }
- }
-
- public static final class LikeRestriction extends SingleColumnRestriction
- {
- private static final ByteBuffer LIKE_WILDCARD = ByteBufferUtil.bytes("%");
- private final Operator operator;
- private final Term value;
-
- public LikeRestriction(ColumnMetadata columnDef, Operator operator, Term value)
- {
- super(columnDef);
- this.operator = operator;
- this.value = value;
- }
-
- @Override
- public void addFunctionsTo(List<Function> functions)
- {
- value.addFunctionsTo(functions);
- }
-
- @Override
- public boolean isLIKE()
- {
- return true;
- }
-
- @Override
- public boolean canBeConvertedToMultiColumnRestriction()
- {
- return false;
- }
-
- @Override
- MultiColumnRestriction toMultiColumnRestriction()
- {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public void addToRowFilter(RowFilter filter,
- IndexRegistry indexRegistry,
- QueryOptions options)
- {
- Pair<Operator, ByteBuffer> operation = makeSpecific(value.bindAndGet(options));
-
- // there must be a suitable INDEX for LIKE_XXX expressions
- RowFilter.SimpleExpression expression = filter.add(columnDef, operation.left, operation.right);
- indexRegistry.getBestIndexFor(expression)
- .orElseThrow(() -> invalidRequest("%s is only supported on properly indexed columns",
- expression));
- }
-
- @Override
- public MultiCBuilder appendTo(MultiCBuilder builder, QueryOptions options)
- {
- // LIKE can be used with clustering columns, but as it doesn't
- // represent an actual clustering value, it can't be used in a
- // clustering filter.
- throw new UnsupportedOperationException();
- }
-
- @Override
- public String toString()
- {
- return operator.toString();
- }
-
- @Override
- public SingleRestriction doMergeWith(SingleRestriction otherRestriction)
- {
- throw invalidRequest("%s cannot be restricted by more than one relation if it includes a %s", columnDef.name, operator);
- }
-
- @Override
- protected boolean isSupportedBy(Index index)
- {
- return index.supportsExpression(columnDef, operator);
- }
-
- /**
- * As the specific subtype of LIKE (LIKE_PREFIX, LIKE_SUFFIX, LIKE_CONTAINS, LIKE_MATCHES) can only be
- * determined by examining the value, which in turn can only be known after binding, all LIKE restrictions
- * are initially created with the generic LIKE operator. This function takes the bound value, trims the
- * wildcard '%' chars from it and returns a tuple of the inferred operator subtype and the final value
- * @param value the bound value for the LIKE operation
- * @return Pair containing the inferred LIKE subtype and the value with wildcards removed
- */
- private static Pair<Operator, ByteBuffer> makeSpecific(ByteBuffer value)
- {
- Operator operator;
- int beginIndex = value.position();
- int endIndex = value.limit() - 1;
- if (ByteBufferUtil.endsWith(value, LIKE_WILDCARD))
- {
- if (ByteBufferUtil.startsWith(value, LIKE_WILDCARD))
- {
- operator = Operator.LIKE_CONTAINS;
- beginIndex =+ 1;
- }
- else
- {
- operator = Operator.LIKE_PREFIX;
- }
- }
- else if (ByteBufferUtil.startsWith(value, LIKE_WILDCARD))
- {
- operator = Operator.LIKE_SUFFIX;
- beginIndex += 1;
- endIndex += 1;
- }
- else
- {
- operator = Operator.LIKE_MATCHES;
- endIndex += 1;
- }
-
- if (endIndex == 0 || beginIndex == endIndex)
- throw invalidRequest("LIKE value can't be empty.");
-
- ByteBuffer newValue = value.duplicate();
- newValue.position(beginIndex);
- newValue.limit(endIndex);
- return Pair.create(operator, newValue);
- }
- }
- public static final class AnnRestriction extends SingleColumnRestriction
- {
- private final Term value;
-
- public AnnRestriction(ColumnMetadata columnDef, Term value)
- {
- super(columnDef);
- this.value = value;
- }
-
- public ByteBuffer value(QueryOptions options)
- {
- return value.bindAndGet(options);
- }
-
- @Override
- public boolean isANN()
- {
- return true;
- }
-
- @Override
- public void addFunctionsTo(List<Function> functions)
- {
- value.addFunctionsTo(functions);
- }
-
- @Override
- MultiColumnRestriction toMultiColumnRestriction()
- {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public void addToRowFilter(RowFilter filter,
- IndexRegistry indexRegistry,
- QueryOptions options)
- {
- filter.add(columnDef, Operator.ANN, value.bindAndGet(options));
- }
-
- @Override
- public MultiCBuilder appendTo(MultiCBuilder builder, QueryOptions options)
- {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public String toString()
- {
- return String.format("ANN(%s)", value);
- }
-
- @Override
- public SingleRestriction doMergeWith(SingleRestriction otherRestriction)
- {
- throw invalidRequest("%s cannot be restricted by more than one relation in an ANN ordering", columnDef.name);
- }
-
- @Override
- protected boolean isSupportedBy(Index index)
- {
- return index.supportsExpression(columnDef, Operator.ANN);
- }
- }
-}
diff --git a/src/java/org/apache/cassandra/cql3/restrictions/SingleRestriction.java b/src/java/org/apache/cassandra/cql3/restrictions/SingleRestriction.java
index 8f4e2b5de4..e317e8742d 100644
--- a/src/java/org/apache/cassandra/cql3/restrictions/SingleRestriction.java
+++ b/src/java/org/apache/cassandra/cql3/restrictions/SingleRestriction.java
@@ -17,82 +17,62 @@
*/
package org.apache.cassandra.cql3.restrictions;
+import java.util.List;
+
+import com.google.common.collect.RangeSet;
+
import org.apache.cassandra.cql3.QueryOptions;
-import org.apache.cassandra.cql3.statements.Bound;
-import org.apache.cassandra.db.MultiCBuilder;
+import org.apache.cassandra.index.Index;
/**
* A single restriction/clause on one or multiple column.
*/
public interface SingleRestriction extends Restriction
{
- public default boolean isSlice()
- {
- return false;
- }
-
- public default boolean isEQ()
- {
- return false;
- }
-
- public default boolean isLIKE()
- {
- return false;
- }
-
- public default boolean isIN()
- {
- return false;
- }
-
- public default boolean isContains()
- {
- return false;
- }
+ /**
+ * Checks if the restriction applies to the column level.
+ * @return {@code true} if this restriction applies to the column level, {@code false} otherwise.
+ */
+ boolean isColumnLevel();
- public default boolean isANN()
- {
- return false;
- }
+ /**
+ * Checks if this restriction uses an {@code EQ} operator.
+ * @return {@code true} if this restriction uses an {@code EQ} operator, {@code false} otherwise.
+ */
+ boolean isEQ();
/**
- * @return <code>true</code> if this restriction is based on equality comparison rather than a range or negation
+ * Checks if this restriction uses an {@code IN} operator.
+ * @return {@code true} if this restriction uses an {@code IN} operator, {@code false} otherwise.
*/
- default boolean isEqualityBased()
- {
- return isEQ() || isIN();
- }
+ boolean isIN();
- public default boolean isNotNull()
- {
- return false;
- }
+ /**
+ * Checks if this restriction uses an {@code ANN} operator.
+ * @return {@code true} if this restriction uses an {@code ANN} operator, {@code false} otherwise.
+ */
+ boolean isANN();
- public default boolean isMultiColumn()
- {
- return false;
- }
+ /**
+ * Checks if this restriction is selecting a range of values.
+ * @return {@code true} if this restriction is selecting a range of values, {@code false} otherwise.
+ */
+ boolean isSlice();
/**
- * Checks if the specified bound is set or not.
- * @param b the bound type
- * @return <code>true</code> if the specified bound is set, <code>false</code> otherwise
+ * Checks if this restriction is a multi-column restriction.
+ * @return {@code true} if this restriction is a multi-column restriction, {@code false} otherwise.
*/
- public default boolean hasBound(Bound b)
- {
- return true;
- }
+ boolean isMultiColumn();
/**
- * Checks if the specified bound is inclusive or not.
- * @param b the bound type
- * @return <code>true</code> if the specified bound is inclusive, <code>false</code> otherwise
+ * Check if this type of restriction is supported by the specified index.
+ *
+ * @param index the secondary index
+ * @return <code>true</code> this type of restriction is supported by the specified index,
+ * <code>false</code> otherwise.
*/
- public default boolean isInclusive(Bound b)
- {
- return true;
- }
+ boolean isSupportedBy(Index index);
/**
* Merges this restriction with the specified one.
@@ -101,30 +81,29 @@ public interface SingleRestriction extends Restriction
* The reason behind this choice is that it allow a great flexibility in the way the merging can done while
* preventing any side effect.</p>
*
- * @param otherRestriction the restriction to merge into this one
+ * @param other the restriction to merge into this one
* @return the restriction resulting of the merge
*/
- public SingleRestriction mergeWith(SingleRestriction otherRestriction);
+ default SingleRestriction mergeWith(SingleRestriction other)
+ {
+ return new MergedRestriction(this, (SimpleRestriction) other);
+ }
/**
- * Appends the values of this <code>SingleRestriction</code> to the specified builder.
+ * Returns the values selected by this restriction (or by the intersection of merged restrictions) if the operator is an {@code EQ} or an {@code IN}.
*
- * @param builder the <code>MultiCBuilder</code> to append to.
* @param options the query options
- * @return the <code>MultiCBuilder</code>
+ * @return the values selected by this restriction (or by the intersection of merged restrictions) if the operator is an {@code EQ} or an {@code IN}.
+ * @throws UnsupportedOperationException if the operator is not an {@code EQ} or an {@code IN}.
*/
- public MultiCBuilder appendTo(MultiCBuilder builder, QueryOptions options);
+ List<ClusteringElements> values(QueryOptions options);
/**
- * Appends the values of the <code>SingleRestriction</code> for the specified bound to the specified builder.
+ * Removes the ranges of values not selected by this restriction from the specified {@code RangeSet} if the operator is an operator selecting ranges of data.
*
- * @param builder the <code>MultiCBuilder</code> to append to.
- * @param bound the bound
+ * @param rangeSet the range set to add to
* @param options the query options
- * @return the <code>MultiCBuilder</code>
+ * @throws UnsupportedOperationException if the operator is not an operator selecting ranges of data.
*/
- public default MultiCBuilder appendBoundTo(MultiCBuilder builder, Bound bound, QueryOptions options)
- {
- return appendTo(builder, options);
- }
+ void restrict(RangeSet<ClusteringElements> rangeSet, QueryOptions options);
}
diff --git a/src/java/org/apache/cassandra/cql3/restrictions/StatementRestrictions.java b/src/java/org/apache/cassandra/cql3/restrictions/StatementRestrictions.java
index 228ec757da..71958bc61b 100644
--- a/src/java/org/apache/cassandra/cql3/restrictions/StatementRestrictions.java
+++ b/src/java/org/apache/cassandra/cql3/restrictions/StatementRestrictions.java
@@ -23,12 +23,10 @@ import java.util.stream.Collectors;
import java.util.stream.Stream;
import com.google.common.base.Joiner;
-import com.google.common.collect.Iterables;
import com.google.common.collect.Streams;
import org.apache.cassandra.cql3.*;
import org.apache.cassandra.cql3.functions.Function;
-import org.apache.cassandra.cql3.statements.Bound;
import org.apache.cassandra.cql3.statements.StatementType;
import org.apache.cassandra.db.*;
import org.apache.cassandra.db.filter.RowFilter;
@@ -51,7 +49,6 @@ import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import static org.apache.cassandra.cql3.statements.RequestValidations.checkFalse;
-import static org.apache.cassandra.cql3.statements.RequestValidations.checkNotNull;
import static org.apache.cassandra.cql3.statements.RequestValidations.invalidRequest;
/**
@@ -141,9 +138,9 @@ public final class StatementRestrictions
{
this.type = type;
this.table = table;
- this.partitionKeyRestrictions = new PartitionKeySingleRestrictionSet(table.partitionKeyAsClusteringComparator());
+ this.partitionKeyRestrictions = new PartitionKeyRestrictions(table.partitionKeyAsClusteringComparator());
this.clusteringColumnsRestrictions = new ClusteringColumnRestrictions(table, allowFiltering);
- this.nonPrimaryKeyRestrictions = new RestrictionSet();
+ this.nonPrimaryKeyRestrictions = RestrictionSet.empty();
this.notNullColumns = new HashSet<>();
}
@@ -192,26 +189,27 @@ public final class StatementRestrictions
*/
for (Relation relation : whereClause.relations)
{
- if ((relation.isContains() || relation.isContainsKey()) && (type.isUpdate() || type.isDelete()))
+
+ Operator operator = relation.operator();
+ if (operator.requiresFilteringOrIndexingFor(ColumnMetadata.Kind.CLUSTERING) && (type.isUpdate() || type.isDelete()))
{
- throw invalidRequest("Cannot use %s with %s", type, relation.operator());
+ throw invalidRequest("Cannot use %s with %s", type, operator);
}
- if (relation.operator() == Operator.IS_NOT)
+ if (operator == Operator.IS_NOT)
{
if (!forView)
throw new InvalidRequestException("Unsupported restriction: " + relation);
- this.notNullColumns.addAll(relation.toRestriction(table, boundNames).getColumnDefs());
+ this.notNullColumns.addAll(relation.toRestriction(table, boundNames).columns());
}
- else if (relation.isLIKE())
+ else if (operator.requiresIndexing())
{
Restriction restriction = relation.toRestriction(table, boundNames);
if (!type.allowUseOfSecondaryIndices() || !restriction.hasSupportingIndex(indexRegistry))
- throw new InvalidRequestException(String.format("LIKE restriction is only supported on properly " +
- "indexed columns. %s is not valid.",
- relation));
+ throw invalidRequest("%s restriction is only supported on properly " +
+ "indexed columns. %s is not valid.", operator, relation);
addRestriction(restriction, indexRegistry);
}
@@ -247,7 +245,7 @@ public final class StatementRestrictions
// Some but not all of the partition key columns have been specified;
// hence we need turn these restrictions into a row filter.
- if (usesSecondaryIndexing || partitionKeyRestrictions.needFiltering(table))
+ if (usesSecondaryIndexing || partitionKeyRestrictions.needFiltering())
filterRestrictions.add(partitionKeyRestrictions);
if (selectsOnlyStaticColumns && hasClusteringColumnsRestrictions())
@@ -288,42 +286,43 @@ public final class StatementRestrictions
if (!type.allowNonPrimaryKeyInWhereClause())
{
Collection<ColumnIdentifier> nonPrimaryKeyColumns =
- ColumnMetadata.toIdentifiers(nonPrimaryKeyRestrictions.getColumnDefs());
+ ColumnMetadata.toIdentifiers(nonPrimaryKeyRestrictions.columns());
throw invalidRequest("Non PRIMARY KEY columns found in where clause: %s ",
Joiner.on(", ").join(nonPrimaryKeyColumns));
}
- var annRestriction = Streams.stream(nonPrimaryKeyRestrictions).filter(SingleRestriction::isANN).findFirst();
+ Optional<SingleRestriction> annRestriction = Streams.stream(nonPrimaryKeyRestrictions)
+ .filter(SingleRestriction::isANN)
+ .findFirst();
if (annRestriction.isPresent())
{
// If there is an ANN restriction then it must be for a vector<float, n> column, and it must have an index
- var annColumn = annRestriction.get().getFirstColumn();
+ ColumnMetadata annColumn = annRestriction.get().firstColumn();
if (!annColumn.type.isVector() || !(((VectorType<?>)annColumn.type).elementType instanceof FloatType))
- throw invalidRequest(StatementRestrictions.ANN_ONLY_SUPPORTED_ON_VECTOR_MESSAGE);
+ throw invalidRequest(ANN_ONLY_SUPPORTED_ON_VECTOR_MESSAGE);
if (indexRegistry == null || indexRegistry.listIndexes().stream().noneMatch(i -> i.dependsOn(annColumn)))
- throw invalidRequest(StatementRestrictions.ANN_REQUIRES_INDEX_MESSAGE);
+ throw invalidRequest(ANN_REQUIRES_INDEX_MESSAGE);
// We do not allow ANN queries using partition key restrictions that need filtering
- if (partitionKeyRestrictions.needFiltering(table))
- throw invalidRequest(StatementRestrictions.ANN_REQUIRES_INDEXED_FILTERING_MESSAGE);
+ if (partitionKeyRestrictions.needFiltering())
+ throw invalidRequest(ANN_REQUIRES_INDEXED_FILTERING_MESSAGE);
// We do not allow ANN query filtering using non-indexed columns
- var nonAnnColumns = Streams.stream(nonPrimaryKeyRestrictions)
- .filter(r -> !r.isANN())
- .map(Restriction::getFirstColumn)
- .collect(Collectors.toList());
- var clusteringColumns = clusteringColumnsRestrictions.getColumnDefinitions();
+ List<ColumnMetadata> nonAnnColumns = Streams.stream(nonPrimaryKeyRestrictions)
+ .filter(r -> !r.isANN())
+ .map(SingleRestriction::firstColumn)
+ .collect(Collectors.toList());
+ List<ColumnMetadata> clusteringColumns = clusteringColumnsRestrictions.columns();
if (!nonAnnColumns.isEmpty() || !clusteringColumns.isEmpty())
{
- var nonIndexedColumns = Stream.concat(nonAnnColumns.stream(), clusteringColumns.stream())
- .filter(c -> indexRegistry.listIndexes().stream().noneMatch(i -> i.dependsOn(c)))
- .collect(Collectors.toList());
-
+ List<ColumnMetadata> nonIndexedColumns = Stream.concat(nonAnnColumns.stream(), clusteringColumns.stream())
+ .filter(c -> indexRegistry.listIndexes().stream().noneMatch(i -> i.dependsOn(c)))
+ .collect(Collectors.toList());
if (!nonIndexedColumns.isEmpty())
{
// restrictions on non-clustering columns, or clusterings that still need filtering, are invalid
if (!clusteringColumns.containsAll(nonIndexedColumns)
- || partitionKeyRestrictions.hasUnrestrictedPartitionKeyComponents(table)
+ || partitionKeyRestrictions.hasUnrestrictedPartitionKeyComponents()
|| clusteringColumnsRestrictions.needFiltering())
throw invalidRequest(StatementRestrictions.ANN_REQUIRES_INDEXED_FILTERING_MESSAGE);
}
@@ -332,10 +331,10 @@ public final class StatementRestrictions
else
{
// We do not support indexed vector restrictions that are not part of an ANN ordering
- var vectorColumn = nonPrimaryKeyRestrictions.getColumnDefs()
- .stream()
- .filter(c -> c.type.isVector())
- .findFirst();
+ Optional<ColumnMetadata> vectorColumn = nonPrimaryKeyRestrictions.columns()
+ .stream()
+ .filter(c -> c.type.isVector())
+ .findFirst();
if (vectorColumn.isPresent() && indexRegistry.listIndexes().stream().anyMatch(i -> i.dependsOn(vectorColumn.get())))
throw invalidRequest(StatementRestrictions.VECTOR_INDEXES_ANN_ONLY_MESSAGE);
}
@@ -369,7 +368,7 @@ public final class StatementRestrictions
private void addRestriction(Restriction restriction, IndexRegistry indexRegistry)
{
- ColumnMetadata def = restriction.getFirstColumn();
+ ColumnMetadata def = restriction.firstColumn();
if (def.isPartitionKey())
partitionKeyRestrictions = partitionKeyRestrictions.mergeWith(restriction);
else if (def.isClusteringColumn())
@@ -401,7 +400,7 @@ public final class StatementRestrictions
Set<ColumnMetadata> columns = new HashSet<>();
for (Restrictions r : filterRestrictions.getRestrictions())
{
- for (ColumnMetadata def : r.getColumnDefs())
+ for (ColumnMetadata def : r.columns())
if (!def.isPrimaryKeyColumn())
columns.add(def);
}
@@ -418,14 +417,6 @@ public final class StatementRestrictions
return columns;
}
- /**
- * @return the set of columns that have an IS NOT NULL restriction on them
- */
- public Set<ColumnMetadata> notNullColumns()
- {
- return notNullColumns;
- }
-
/**
* @return true if column is restricted by some restriction, false otherwise
*/
@@ -434,7 +425,7 @@ public final class StatementRestrictions
if (notNullColumns.contains(column))
return true;
- return getRestrictions(column.kind).getColumnDefs().contains(column);
+ return getRestrictions(column.kind).columns().contains(column);
}
/**
@@ -461,16 +452,13 @@ public final class StatementRestrictions
/**
* Checks if the specified column is restricted by an EQ restriction.
*
- * @param columnDef the column definition
+ * @param column the column definition
* @return <code>true</code> if the specified column is restricted by an EQ restiction, <code>false</code>
* otherwise.
*/
- public boolean isColumnRestrictedByEq(ColumnMetadata columnDef)
+ public boolean isColumnRestrictedByEq(ColumnMetadata column)
{
- Set<Restriction> restrictions = getRestrictions(columnDef.kind).getRestrictions(columnDef);
- return restrictions.stream()
- .filter(SingleRestriction.class::isInstance)
- .anyMatch(p -> ((SingleRestriction) p).isEQ());
+ return getRestrictions(column.kind).isRestrictedByEquals(column);
}
/**
@@ -484,41 +472,7 @@ public final class StatementRestrictions
*/
public boolean isEqualityRestricted(ColumnMetadata column)
{
- if (column.kind == ColumnMetadata.Kind.PARTITION_KEY)
- {
- if (partitionKeyRestrictions.hasOnlyEqualityRestrictions())
- for (ColumnMetadata restricted : partitionKeyRestrictions.getColumnDefinitions())
- if (restricted.name.equals(column.name))
- return true;
- }
- else if (column.kind == ColumnMetadata.Kind.CLUSTERING)
- {
- if (hasClusteringColumnsRestrictions())
- {
- for (SingleRestriction restriction : clusteringColumnsRestrictions.getRestrictionSet())
- {
- if (restriction.isEqualityBased())
- {
- if (restriction.isMultiColumn())
- {
- for (ColumnMetadata restricted : restriction.getColumnDefs())
- if (restricted.name.equals(column.name))
- return true;
- }
- else if (restriction.getFirstColumn().name.equals(column.name))
- return true;
- }
- }
- }
- }
- else if (hasNonPrimaryKeyRestrictions())
- {
- for (SingleRestriction restriction : nonPrimaryKeyRestrictions)
- if (restriction.getFirstColumn().name.equals(column.name) && restriction.isEqualityBased())
- return true;
- }
-
- return false;
+ return getRestrictions(column.kind).isRestrictedByEqualsOrIN(column);
}
public boolean isTopK()
@@ -578,11 +532,6 @@ public final class StatementRestrictions
return restrictionSet;
}
- private static Iterable<Restriction> allColumnRestrictions(ClusteringColumnRestrictions clusteringColumnsRestrictions, RestrictionSet nonPrimaryKeyRestrictions)
- {
- return Iterables.concat(clusteringColumnsRestrictions.getRestrictionSet(), nonPrimaryKeyRestrictions);
- }
-
private void processPartitionKeyRestrictions(ClientState state, boolean hasQueriableIndex, boolean allowFiltering, boolean forView)
{
if (!type.allowPartitionKeyRanges())
@@ -590,7 +539,7 @@ public final class StatementRestrictions
checkFalse(partitionKeyRestrictions.isOnToken(),
"The token function cannot be used in WHERE clauses for %s statements", type);
- if (partitionKeyRestrictions.hasUnrestrictedPartitionKeyComponents(table))
+ if (partitionKeyRestrictions.hasUnrestrictedPartitionKeyComponents())
throw invalidRequest("Some partition key parts are missing: %s",
Joiner.on(", ").join(getPartitionKeyUnrestrictedComponents()));
@@ -605,7 +554,7 @@ public final class StatementRestrictions
if (partitionKeyRestrictions.isOnToken())
isKeyRange = true;
- if (partitionKeyRestrictions.isEmpty() && partitionKeyRestrictions.hasUnrestrictedPartitionKeyComponents(table))
+ if (partitionKeyRestrictions.isEmpty() && partitionKeyRestrictions.hasUnrestrictedPartitionKeyComponents())
{
isKeyRange = true;
usesSecondaryIndexing = hasQueriableIndex;
@@ -617,7 +566,7 @@ public final class StatementRestrictions
// - Is it queriable without 2ndary index, which is always more efficient
// If a component of the partition key is restricted by a relation, all preceding
// components must have a EQ. Only the last partition key component can be in IN relation.
- if (partitionKeyRestrictions.needFiltering(table))
+ if (partitionKeyRestrictions.needFiltering())
{
if (!allowFiltering && !forView && !hasQueriableIndex && requiresAllowFilteringIfNotSpecified())
throw new InvalidRequestException(allowFilteringMessage(state));
@@ -649,7 +598,7 @@ public final class StatementRestrictions
private Collection<ColumnIdentifier> getPartitionKeyUnrestrictedComponents()
{
List<ColumnMetadata> list = new ArrayList<>(table.partitionKeyColumns());
- list.removeAll(partitionKeyRestrictions.getColumnDefs());
+ list.removeAll(partitionKeyRestrictions.columns());
return ColumnMetadata.toIdentifiers(list);
}
@@ -699,8 +648,13 @@ public final class StatementRestrictions
}
else
{
- checkFalse(clusteringColumnsRestrictions.hasContains() && !hasQueriableIndex && !allowFiltering,
- "Clustering columns can only be restricted with CONTAINS with a secondary index or filtering");
+ if (clusteringColumnsRestrictions.needsFilteringOrIndexing() && !hasQueriableIndex && !allowFiltering)
+ throw invalidRequest("Clustering column restrictions require the use of secondary indices" +
+ " or filtering for map-element restrictions and for the following operators: %s",
+ Operator.operatorsRequiringFilteringOrIndexingFor(ColumnMetadata.Kind.CLUSTERING)
+ .stream()
+ .map(Operator::toString)
+ .collect(Collectors.joining(", ")));
if (hasClusteringColumnsRestrictions() && clusteringColumnsRestrictions.needFiltering())
{
@@ -711,7 +665,7 @@ public final class StatementRestrictions
else if (!allowFiltering)
{
List<ColumnMetadata> clusteringColumns = table.clusteringColumns();
- List<ColumnMetadata> restrictedColumns = new LinkedList<>(clusteringColumnsRestrictions.getColumnDefs());
+ List<ColumnMetadata> restrictedColumns = new ArrayList<>(clusteringColumnsRestrictions.columns());
for (int i = 0, m = restrictedColumns.size(); i < m; i++)
{
@@ -729,7 +683,6 @@ public final class StatementRestrictions
}
}
-
}
/**
@@ -739,7 +692,7 @@ public final class StatementRestrictions
private Collection<ColumnIdentifier> getUnrestrictedClusteringColumns()
{
List<ColumnMetadata> missingClusteringColumns = new ArrayList<>(table.clusteringColumns());
- missingClusteringColumns.removeAll(new LinkedList<>(clusteringColumnsRestrictions.getColumnDefs()));
+ missingClusteringColumns.removeAll(new LinkedList<>(clusteringColumnsRestrictions.columns()));
return ColumnMetadata.toIdentifiers(missingClusteringColumns);
}
@@ -811,20 +764,7 @@ public final class StatementRestrictions
*/
public List<ByteBuffer> getPartitionKeys(final QueryOptions options, ClientState state)
{
- return partitionKeyRestrictions.values(options, state);
- }
-
- /**
- * Returns the specified bound of the partition key.
- *
- * @param b the boundary type
- * @param options the query options
- * @return the specified bound of the partition key
- */
- private ByteBuffer getPartitionKeyBound(Bound b, QueryOptions options)
- {
- // We deal with IN queries for keys in other places, so we know buildBound will return only one result
- return partitionKeyRestrictions.bounds(b, options).get(0);
+ return partitionKeyRestrictions.values(table.partitioner, options, state);
}
/**
@@ -835,83 +775,7 @@ public final class StatementRestrictions
*/
public AbstractBounds<PartitionPosition> getPartitionKeyBounds(QueryOptions options)
{
- IPartitioner p = table.partitioner;
-
- if (partitionKeyRestrictions.isOnToken())
- {
- return getPartitionKeyBoundsForTokenRestrictions(p, options);
- }
-
- return getPartitionKeyBounds(p, options);
- }
-
- private AbstractBounds<PartitionPosition> getPartitionKeyBounds(IPartitioner p,
- QueryOptions options)
- {
- // Deal with unrestricted partition key components (special-casing is required to deal with 2i queries on the
- // first component of a composite partition key) queries that filter on the partition key.
- if (partitionKeyRestrictions.needFiltering(table))
- return new Range<>(p.getMinimumToken().minKeyBound(), p.getMinimumToken().maxKeyBound());
-
- ByteBuffer startKeyBytes = getPartitionKeyBound(Bound.START, options);
- ByteBuffer finishKeyBytes = getPartitionKeyBound(Bound.END, options);
-
- PartitionPosition startKey = PartitionPosition.ForKey.get(startKeyBytes, p);
- PartitionPosition finishKey = PartitionPosition.ForKey.get(finishKeyBytes, p);
-
- if (startKey.compareTo(finishKey) > 0 && !finishKey.isMinimum())
- return null;
-
- if (partitionKeyRestrictions.isInclusive(Bound.START))
- {
- return partitionKeyRestrictions.isInclusive(Bound.END)
- ? new Bounds<>(startKey, finishKey)
- : new IncludingExcludingBounds<>(startKey, finishKey);
- }
-
- return partitionKeyRestrictions.isInclusive(Bound.END)
- ? new Range<>(startKey, finishKey)
- : new ExcludingBounds<>(startKey, finishKey);
- }
-
- private AbstractBounds<PartitionPosition> getPartitionKeyBoundsForTokenRestrictions(IPartitioner p,
- QueryOptions options)
- {
- Token startToken = getTokenBound(Bound.START, options, p);
- Token endToken = getTokenBound(Bound.END, options, p);
-
- boolean includeStart = partitionKeyRestrictions.isInclusive(Bound.START);
- boolean includeEnd = partitionKeyRestrictions.isInclusive(Bound.END);
-
- /*
- * If we ask SP.getRangeSlice() for (token(200), token(200)], it will happily return the whole ring.
- * However, wrapping range doesn't really make sense for CQL, and we want to return an empty result in that
- * case (CASSANDRA-5573). So special case to create a range that is guaranteed to be empty.
- *
- * In practice, we want to return an empty result set if either startToken > endToken, or both are equal but
- * one of the bound is excluded (since [a, a] can contains something, but not (a, a], [a, a) or (a, a)).
- * Note though that in the case where startToken or endToken is the minimum token, then this special case
- * rule should not apply.
- */
- int cmp = startToken.compareTo(endToken);
- if (!startToken.isMinimum() && !endToken.isMinimum()
- && (cmp > 0 || (cmp == 0 && (!includeStart || !includeEnd))))
- return null;
-
- PartitionPosition start = includeStart ? startToken.minKeyBound() : startToken.maxKeyBound();
- PartitionPosition end = includeEnd ? endToken.maxKeyBound() : endToken.minKeyBound();
-
- return new Range<>(start, end);
- }
-
- private Token getTokenBound(Bound b, QueryOptions options, IPartitioner p)
- {
- if (!partitionKeyRestrictions.hasBound(b))
- return p.getMinimumToken();
-
- ByteBuffer value = partitionKeyRestrictions.bounds(b, options).get(0);
- checkNotNull(value, "Invalid null token value");
- return p.getTokenFactory().fromByteArray(value);
+ return partitionKeyRestrictions.bounds(table.partitioner, options);
}
/**
@@ -944,15 +808,14 @@ public final class StatementRestrictions
}
/**
- * Returns the bounds (start or end) of the clustering columns.
+ * Returns the clustering columns slices.
*
- * @param b the bound type
* @param options the query options
- * @return the bounds (start or end) of the clustering columns
+ * @return the clustering columns slices
*/
- public NavigableSet<ClusteringBound<?>> getClusteringColumnsBounds(Bound b, QueryOptions options)
+ public Slices getSlices(QueryOptions options)
{
- return clusteringColumnsRestrictions.boundsAsClustering(b, options);
+ return clusteringColumnsRestrictions.slices(options);
}
/**
@@ -1008,7 +871,7 @@ public final class StatementRestrictions
public boolean hasAllPKColumnsRestrictedByEqualities()
{
return !isPartitionKeyRestrictionsOnToken()
- && !partitionKeyRestrictions.hasUnrestrictedPartitionKeyComponents(table)
+ && !partitionKeyRestrictions.hasUnrestrictedPartitionKeyComponents()
&& (partitionKeyRestrictions.hasOnlyEqualityRestrictions())
&& !hasUnrestrictedClusteringColumns()
&& (clusteringColumnsRestrictions.hasOnlyEqualityRestrictions());
diff --git a/src/java/org/apache/cassandra/cql3/restrictions/TermSlice.java b/src/java/org/apache/cassandra/cql3/restrictions/TermSlice.java
deleted file mode 100644
index 4e2d70d1aa..0000000000
--- a/src/java/org/apache/cassandra/cql3/restrictions/TermSlice.java
+++ /dev/null
@@ -1,180 +0,0 @@
-/*
- * 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.restrictions;
-
-import java.util.List;
-
-import org.apache.cassandra.schema.ColumnMetadata;
-import org.apache.cassandra.cql3.Operator;
-import org.apache.cassandra.cql3.terms.Term;
-import org.apache.cassandra.cql3.functions.Function;
-import org.apache.cassandra.cql3.statements.Bound;
-import org.apache.cassandra.index.Index;
-
-final class TermSlice
-{
- /**
- * The slice boundaries.
- */
- private final Term[] bounds;
-
- /**
- * Specifies if a slice boundary is inclusive or not.
- */
- private final boolean[] boundInclusive;
-
- /**
- * Creates a new <code>TermSlice</code> with the specified boundaries.
- *
- * @param start the lower boundary
- * @param includeStart <code>true</code> if the lower boundary is inclusive
- * @param end the upper boundary
- * @param includeEnd <code>true</code> if the upper boundary is inclusive
- */
- private TermSlice(Term start, boolean includeStart, Term end, boolean includeEnd)
- {
- bounds = new Term[]{start, end};
- boundInclusive = new boolean[]{includeStart, includeEnd};
- }
-
- /**
- * Creates a new <code>TermSlice</code> with the specified boundary.
- *
- * @param bound the boundary type
- * @param include <code>true</code> if the boundary is inclusive
- * @param term the value
- * @return a new <code>TermSlice</code> instance
- */
- public static TermSlice newInstance(Bound bound, boolean include, Term term)
- {
- return bound.isStart() ? new TermSlice(term, include, null, false)
- : new TermSlice(null, false, term, include);
- }
-
- /**
- * Returns the boundary value.
- *
- * @param bound the boundary type
- * @return the boundary value
- */
- public Term bound(Bound bound)
- {
- return bounds[bound.idx];
- }
-
- /**
- * Checks if this slice has a boundary for the specified type.
- *
- * @param b the boundary type
- * @return <code>true</code> if this slice has a boundary for the specified type, <code>false</code> otherwise.
- */
- public boolean hasBound(Bound b)
- {
- return bounds[b.idx] != null;
- }
-
- /**
- * Checks if this slice boundary is inclusive for the specified type.
- *
- * @param b the boundary type
- * @return <code>true</code> if this slice boundary is inclusive for the specified type,
- * <code>false</code> otherwise.
- */
- public boolean isInclusive(Bound b)
- {
- return bounds[b.idx] == null || boundInclusive[b.idx];
- }
-
- /**
- * Merges this slice with the specified one.
- *
- * @param otherSlice the slice to merge to
- * @return the new slice resulting from the merge
- */
- public TermSlice merge(TermSlice otherSlice)
- {
- if (hasBound(Bound.START))
- {
- assert !otherSlice.hasBound(Bound.START);
-
- return new TermSlice(bound(Bound.START),
- isInclusive(Bound.START),
- otherSlice.bound(Bound.END),
- otherSlice.isInclusive(Bound.END));
- }
- assert !otherSlice.hasBound(Bound.END);
-
- return new TermSlice(otherSlice.bound(Bound.START),
- otherSlice.isInclusive(Bound.START),
- bound(Bound.END),
- isInclusive(Bound.END));
- }
-
- @Override
- public String toString()
- {
- return String.format("(%s %s, %s %s)", boundInclusive[0] ? ">=" : ">",
- bounds[0],
- boundInclusive[1] ? "<=" : "<",
- bounds[1]);
- }
-
- /**
- * Returns the index operator corresponding to the specified boundary.
- *
- * @param b the boundary type
- * @return the index operator corresponding to the specified boundary
- */
- public Operator getIndexOperator(Bound b)
- {
- if (b.isStart())
- return boundInclusive[b.idx] ? Operator.GTE : Operator.GT;
-
- return boundInclusive[b.idx] ? Operator.LTE : Operator.LT;
- }
-
- /**
- * Check if this <code>TermSlice</code> is supported by the specified index.
- *
- * @param index the secondary index
- * @return <code>true</code> this type of <code>TermSlice</code> is supported by the specified index,
- * <code>false</code> otherwise.
- */
- public boolean isSupportedBy(ColumnMetadata column, Index index)
- {
- boolean supported = false;
-
- if (hasBound(Bound.START))
- supported |= isInclusive(Bound.START) ? index.supportsExpression(column, Operator.GTE)
- : index.supportsExpression(column, Operator.GT);
- if (hasBound(Bound.END))
- supported |= isInclusive(Bound.END) ? index.supportsExpression(column, Operator.LTE)
- : index.supportsExpression(column, Operator.LT);
-
- return supported;
- }
-
- public void addFunctionsTo(List<Function> functions)
- {
- if (hasBound(Bound.START))
- bound(Bound.START).addFunctionsTo(functions);
-
- if (hasBound(Bound.END))
- bound(Bound.END).addFunctionsTo(functions);
- }
-}
diff --git a/src/java/org/apache/cassandra/cql3/restrictions/TokenFilter.java b/src/java/org/apache/cassandra/cql3/restrictions/TokenFilter.java
deleted file mode 100644
index 74ad7b51a4..0000000000
--- a/src/java/org/apache/cassandra/cql3/restrictions/TokenFilter.java
+++ /dev/null
@@ -1,336 +0,0 @@
-/*
- * 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.restrictions;
-
-import java.nio.ByteBuffer;
-import java.util.*;
-
-import com.google.common.collect.BoundType;
-import com.google.common.collect.ImmutableRangeSet;
-import com.google.common.collect.Range;
-import com.google.common.collect.RangeSet;
-
-import org.apache.cassandra.index.Index;
-import org.apache.cassandra.schema.ColumnMetadata;
-import org.apache.cassandra.schema.TableMetadata;
-import org.apache.cassandra.cql3.QueryOptions;
-import org.apache.cassandra.cql3.functions.Function;
-import org.apache.cassandra.cql3.statements.Bound;
-import org.apache.cassandra.db.filter.RowFilter;
-import org.apache.cassandra.dht.IPartitioner;
-import org.apache.cassandra.dht.Token;
-import org.apache.cassandra.exceptions.InvalidRequestException;
-import org.apache.cassandra.index.IndexRegistry;
-import org.apache.cassandra.service.ClientState;
-
-import static org.apache.cassandra.cql3.statements.Bound.END;
-import static org.apache.cassandra.cql3.statements.Bound.START;
-
-/**
- * <code>Restriction</code> decorator used to merge non-token restriction and token restriction on partition keys.
- *
- * <p>If all partition key columns have non-token restrictions and do not need filtering, they take precedence
- * when calculating bounds, incusiveness etc (see CASSANDRA-12149).</p>
- */
-final class TokenFilter implements PartitionKeyRestrictions
-{
- /**
- * The decorated restriction
- */
- private final PartitionKeyRestrictions restrictions;
-
- /**
- * The restriction on the token
- */
- private final TokenRestriction tokenRestriction;
-
- /**
- * Partitioner to manage tokens, extracted from tokenRestriction metadata.
- */
- private final IPartitioner partitioner;
-
- public boolean hasIN()
- {
- return isOnToken() ? false : restrictions.hasIN();
- }
-
- public boolean hasContains()
- {
- return isOnToken() ? false : restrictions.hasContains();
- }
-
- public boolean hasOnlyEqualityRestrictions()
- {
- return isOnToken() ? false : restrictions.hasOnlyEqualityRestrictions();
- }
-
- @Override
- public Set<Restriction> getRestrictions(ColumnMetadata columnDef)
- {
- Set<Restriction> set = new HashSet<>();
- set.addAll(restrictions.getRestrictions(columnDef));
- set.addAll(tokenRestriction.getRestrictions(columnDef));
- return set;
- }
-
- @Override
- public boolean isOnToken()
- {
- // if all partition key columns have non-token restrictions and do not need filtering,
- // we can simply use the token range to filter those restrictions and then ignore the token range
- return needFiltering(tokenRestriction.metadata) || restrictions.size() < tokenRestriction.size();
- }
-
- public TokenFilter(PartitionKeyRestrictions restrictions, TokenRestriction tokenRestriction)
- {
- this.restrictions = restrictions;
- this.tokenRestriction = tokenRestriction;
- this.partitioner = tokenRestriction.metadata.partitioner;
- }
-
- @Override
- public List<ByteBuffer> values(QueryOptions options, ClientState state) throws InvalidRequestException
- {
- return filter(restrictions.values(options, state), options, state);
- }
-
- @Override
- public PartitionKeyRestrictions mergeWith(Restriction restriction) throws InvalidRequestException
- {
- if (restriction.isOnToken())
- return new TokenFilter(restrictions, (TokenRestriction) tokenRestriction.mergeWith(restriction));
-
- return new TokenFilter(restrictions.mergeWith(restriction), tokenRestriction);
- }
-
- @Override
- public boolean isInclusive(Bound bound)
- {
- return isOnToken() ? tokenRestriction.isInclusive(bound) : restrictions.isInclusive(bound);
- }
-
- @Override
- public boolean hasBound(Bound bound)
- {
- return isOnToken() ? tokenRestriction.hasBound(bound) : restrictions.hasBound(bound);
- }
-
- @Override
- public List<ByteBuffer> bounds(Bound bound, QueryOptions options) throws InvalidRequestException
- {
- return isOnToken() ? tokenRestriction.bounds(bound, options) : restrictions.bounds(bound, options);
- }
-
- /**
- * Filter the values returned by the restriction.
- *
- * @param values the values returned by the decorated restriction
- * @param options the query options
- * @param state the client state
- * @return the values matching the token restriction
- * @throws InvalidRequestException if the request is invalid
- */
- private List<ByteBuffer> filter(List<ByteBuffer> values, QueryOptions options, ClientState state) throws InvalidRequestException
- {
- RangeSet<Token> rangeSet = tokenRestriction.hasSlice() ? toRangeSet(tokenRestriction, options)
- : toRangeSet(tokenRestriction.values(options, state));
-
- return filterWithRangeSet(rangeSet, values);
- }
-
- /**
- * Filter out the values for which the tokens are not included within the specified range.
- *
- * @param tokens the tokens range
- * @param values the restricted values
- * @return the values for which the tokens are not included within the specified range.
- */
- private List<ByteBuffer> filterWithRangeSet(RangeSet<Token> tokens, List<ByteBuffer> values)
- {
- List<ByteBuffer> remaining = new ArrayList<>();
-
- for (ByteBuffer value : values)
- {
- Token token = partitioner.getToken(value);
-
- if (!tokens.contains(token))
- continue;
-
- remaining.add(value);
- }
- return remaining;
- }
-
- /**
- * Converts the specified list into a range set.
- *
- * @param buffers the token restriction values
- * @return the range set corresponding to the specified list
- */
- private RangeSet<Token> toRangeSet(List<ByteBuffer> buffers)
- {
- ImmutableRangeSet.Builder<Token> builder = ImmutableRangeSet.builder();
-
- for (ByteBuffer buffer : buffers)
- builder.add(Range.singleton(deserializeToken(buffer)));
-
- return builder.build();
- }
-
- /**
- * Converts the specified slice into a range set.
- *
- * @param slice the slice to convert
- * @param options the query option
- * @return the range set corresponding to the specified slice
- * @throws InvalidRequestException if the request is invalid
- */
- private RangeSet<Token> toRangeSet(TokenRestriction slice, QueryOptions options) throws InvalidRequestException
- {
- if (slice.hasBound(START))
- {
- Token start = deserializeToken(slice.bounds(START, options).get(0));
-
- BoundType startBoundType = toBoundType(slice.isInclusive(START));
-
- if (slice.hasBound(END))
- {
- BoundType endBoundType = toBoundType(slice.isInclusive(END));
- Token end = deserializeToken(slice.bounds(END, options).get(0));
-
- if (start.equals(end) && (BoundType.OPEN == startBoundType || BoundType.OPEN == endBoundType))
- return ImmutableRangeSet.of();
-
- if (start.compareTo(end) <= 0)
- return ImmutableRangeSet.of(Range.range(start,
- startBoundType,
- end,
- endBoundType));
-
- return ImmutableRangeSet.<Token> builder()
- .add(Range.upTo(end, endBoundType))
- .add(Range.downTo(start, startBoundType))
- .build();
- }
- return ImmutableRangeSet.of(Range.downTo(start,
- startBoundType));
- }
- Token end = deserializeToken(slice.bounds(END, options).get(0));
- return ImmutableRangeSet.of(Range.upTo(end, toBoundType(slice.isInclusive(END))));
- }
-
- /**
- * Deserializes the token corresponding to the specified buffer.
- *
- * @param buffer the buffer
- * @return the token corresponding to the specified buffer
- */
- private Token deserializeToken(ByteBuffer buffer)
- {
- return partitioner.getTokenFactory().fromByteArray(buffer);
- }
-
- private static BoundType toBoundType(boolean inclusive)
- {
- return inclusive ? BoundType.CLOSED : BoundType.OPEN;
- }
-
- @Override
- public ColumnMetadata getFirstColumn()
- {
- return restrictions.getFirstColumn();
- }
-
- @Override
- public ColumnMetadata getLastColumn()
- {
- return restrictions.getLastColumn();
- }
-
- @Override
- public List<ColumnMetadata> getColumnDefs()
- {
- return restrictions.getColumnDefs();
- }
-
- @Override
- public void addFunctionsTo(List<Function> functions)
- {
- restrictions.addFunctionsTo(functions);
- }
-
- @Override
- public boolean hasSupportingIndex(IndexRegistry indexRegistry)
- {
- return restrictions.hasSupportingIndex(indexRegistry);
- }
-
- @Override
- public void addToRowFilter(RowFilter filter, IndexRegistry indexRegistry, QueryOptions options)
- {
- restrictions.addToRowFilter(filter, indexRegistry, options);
- }
-
- @Override
- public Index findSupportingIndex(IndexRegistry indexRegistry)
- {
- return restrictions.findSupportingIndex(indexRegistry);
- }
-
- @Override
- public Index findSupportingIndexFromQueryPlan(Index.QueryPlan indexQueryPlan)
- {
- return restrictions.findSupportingIndexFromQueryPlan(indexQueryPlan);
- }
-
- @Override
- public boolean needsFiltering(Index.Group indexGroup)
- {
- return restrictions.needsFiltering(indexGroup);
- }
-
- @Override
- public boolean isEmpty()
- {
- return restrictions.isEmpty();
- }
-
- @Override
- public int size()
- {
- return restrictions.size();
- }
-
- @Override
- public boolean needFiltering(TableMetadata table)
- {
- return restrictions.needFiltering(table);
- }
-
- @Override
- public boolean hasUnrestrictedPartitionKeyComponents(TableMetadata table)
- {
- return restrictions.hasUnrestrictedPartitionKeyComponents(table);
- }
-
- @Override
- public boolean hasSlice()
- {
- return restrictions.hasSlice();
- }
-}
diff --git a/src/java/org/apache/cassandra/cql3/restrictions/TokenRestriction.java b/src/java/org/apache/cassandra/cql3/restrictions/TokenRestriction.java
deleted file mode 100644
index 99104d19e5..0000000000
--- a/src/java/org/apache/cassandra/cql3/restrictions/TokenRestriction.java
+++ /dev/null
@@ -1,341 +0,0 @@
-/*
- * 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.restrictions;
-
-import java.nio.ByteBuffer;
-import java.util.*;
-
-import com.google.common.base.Joiner;
-
-import org.apache.cassandra.index.Index;
-import org.apache.cassandra.schema.ColumnMetadata;
-import org.apache.cassandra.schema.TableMetadata;
-import org.apache.cassandra.cql3.QueryOptions;
-import org.apache.cassandra.cql3.terms.Term;
-import org.apache.cassandra.cql3.functions.Function;
-import org.apache.cassandra.cql3.statements.Bound;
-import org.apache.cassandra.db.filter.RowFilter;
-import org.apache.cassandra.exceptions.InvalidRequestException;
-import org.apache.cassandra.index.IndexRegistry;
-import org.apache.cassandra.service.ClientState;
-
-import static org.apache.cassandra.cql3.statements.RequestValidations.invalidRequest;
-
-/**
- * <code>Restriction</code> using the token function.
- */
-public abstract class TokenRestriction implements PartitionKeyRestrictions
-{
- /**
- * The definition of the columns to which apply the token restriction.
- */
- protected final List<ColumnMetadata> columnDefs;
-
- protected final TableMetadata metadata;
-
- /**
- * Creates a new <code>TokenRestriction</code> that apply to the specified columns.
- *
- * @param columnDefs the definition of the columns to which apply the token restriction
- */
- public TokenRestriction(TableMetadata metadata, List<ColumnMetadata> columnDefs)
- {
- this.columnDefs = columnDefs;
- this.metadata = metadata;
- }
-
- public boolean hasIN()
- {
- return false;
- }
-
- public boolean hasOnlyEqualityRestrictions()
- {
- return false;
- }
-
- @Override
- public Set<Restriction> getRestrictions(ColumnMetadata columnDef)
- {
- return Collections.singleton(this);
- }
-
- @Override
- public final boolean isOnToken()
- {
- return true;
- }
-
- @Override
- public boolean needFiltering(TableMetadata table)
- {
- return false;
- }
-
- @Override
- public boolean hasSlice()
- {
- return false;
- }
-
- @Override
- public boolean hasUnrestrictedPartitionKeyComponents(TableMetadata table)
- {
- return false;
- }
-
- @Override
- public List<ColumnMetadata> getColumnDefs()
- {
- return columnDefs;
- }
-
- @Override
- public ColumnMetadata getFirstColumn()
- {
- return columnDefs.get(0);
- }
-
- @Override
- public ColumnMetadata getLastColumn()
- {
- return columnDefs.get(columnDefs.size() - 1);
- }
-
- @Override
- public boolean hasSupportingIndex(IndexRegistry indexRegistry)
- {
- return false;
- }
-
- @Override
- public void addToRowFilter(RowFilter filter, IndexRegistry indexRegistry, QueryOptions options)
- {
- throw new UnsupportedOperationException("Index expression cannot be created for token restriction");
- }
-
- @Override
- public Index findSupportingIndex(IndexRegistry indexRegistry)
- {
- return null;
- }
-
- @Override
- public Index findSupportingIndexFromQueryPlan(Index.QueryPlan indexQueryPlan)
- {
- return null;
- }
-
- @Override
- public boolean needsFiltering(Index.Group indexGroup)
- {
- return false;
- }
-
- @Override
- public final boolean isEmpty()
- {
- return getColumnDefs().isEmpty();
- }
-
- @Override
- public final int size()
- {
- return getColumnDefs().size();
- }
-
- /**
- * Returns the column names as a comma separated <code>String</code>.
- *
- * @return the column names as a comma separated <code>String</code>.
- */
- protected final String getColumnNamesAsString()
- {
- return Joiner.on(", ").join(ColumnMetadata.toIdentifiers(columnDefs));
- }
-
- @Override
- public final PartitionKeyRestrictions mergeWith(Restriction otherRestriction) throws InvalidRequestException
- {
- if (!otherRestriction.isOnToken())
- return new TokenFilter(toPartitionKeyRestrictions(otherRestriction), this);
-
- return doMergeWith((TokenRestriction) otherRestriction);
- }
-
- /**
- * Merges this restriction with the specified <code>TokenRestriction</code>.
- * @param otherRestriction the <code>TokenRestriction</code> to merge with.
- */
- protected abstract PartitionKeyRestrictions doMergeWith(TokenRestriction otherRestriction) throws InvalidRequestException;
-
- /**
- * Converts the specified restriction into a <code>PartitionKeyRestrictions</code>.
- *
- * @param restriction the restriction to convert
- * @return a <code>PartitionKeyRestrictions</code>
- * @throws InvalidRequestException if a problem occurs while converting the restriction
- */
- private PartitionKeyRestrictions toPartitionKeyRestrictions(Restriction restriction) throws InvalidRequestException
- {
- if (restriction instanceof PartitionKeyRestrictions)
- return (PartitionKeyRestrictions) restriction;
-
- return new PartitionKeySingleRestrictionSet(metadata.partitionKeyAsClusteringComparator()).mergeWith(restriction);
- }
-
- public static final class EQRestriction extends TokenRestriction
- {
- private final Term value;
-
- public EQRestriction(TableMetadata table, List<ColumnMetadata> columnDefs, Term value)
- {
- super(table, columnDefs);
- this.value = value;
- }
-
- @Override
- public void addFunctionsTo(List<Function> functions)
- {
- value.addFunctionsTo(functions);
- }
-
- @Override
- protected PartitionKeyRestrictions doMergeWith(TokenRestriction otherRestriction) throws InvalidRequestException
- {
- throw invalidRequest("%s cannot be restricted by more than one relation if it includes an Equal",
- Joiner.on(", ").join(ColumnMetadata.toIdentifiers(columnDefs)));
- }
-
- @Override
- public List<ByteBuffer> bounds(Bound b, QueryOptions options) throws InvalidRequestException
- {
- // ClientState is used by inSelectCartesianProduct guardrail to skip non-ordinary users.
- // Passing null here to avoid polluting too many methods, because in case of EQ token restriction,
- // it won't generate high cartesian product.
- return values(options, null);
- }
-
- @Override
- public boolean hasBound(Bound b)
- {
- return true;
- }
-
- @Override
- public boolean isInclusive(Bound b)
- {
- return true;
- }
-
- @Override
- public List<ByteBuffer> values(QueryOptions options, ClientState state) throws InvalidRequestException
- {
- return Collections.singletonList(value.bindAndGet(options));
- }
-
- public boolean hasContains()
- {
- return false;
- }
- }
-
- public static class SliceRestriction extends TokenRestriction
- {
- private final TermSlice slice;
-
- public SliceRestriction(TableMetadata table, List<ColumnMetadata> columnDefs, Bound bound, boolean inclusive, Term term)
- {
- super(table, columnDefs);
- slice = TermSlice.newInstance(bound, inclusive, term);
- }
-
- public boolean hasContains()
- {
- return false;
- }
-
- @Override
- public boolean hasSlice()
- {
- return true;
- }
-
- @Override
- public List<ByteBuffer> values(QueryOptions options, ClientState state) throws InvalidRequestException
- {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public boolean hasBound(Bound b)
- {
- return slice.hasBound(b);
- }
-
- @Override
- public List<ByteBuffer> bounds(Bound b, QueryOptions options) throws InvalidRequestException
- {
- return Collections.singletonList(slice.bound(b).bindAndGet(options));
- }
-
- @Override
- public void addFunctionsTo(List<Function> functions)
- {
- slice.addFunctionsTo(functions);
- }
-
- @Override
- public boolean isInclusive(Bound b)
- {
- return slice.isInclusive(b);
- }
-
- @Override
- protected PartitionKeyRestrictions doMergeWith(TokenRestriction otherRestriction)
- throws InvalidRequestException
- {
- if (!(otherRestriction instanceof SliceRestriction))
- throw invalidRequest("Columns \"%s\" cannot be restricted by both an equality and an inequality relation",
- getColumnNamesAsString());
-
- TokenRestriction.SliceRestriction otherSlice = (TokenRestriction.SliceRestriction) otherRestriction;
-
- if (hasBound(Bound.START) && otherSlice.hasBound(Bound.START))
- throw invalidRequest("More than one restriction was found for the start bound on %s",
- getColumnNamesAsString());
-
- if (hasBound(Bound.END) && otherSlice.hasBound(Bound.END))
- throw invalidRequest("More than one restriction was found for the end bound on %s",
- getColumnNamesAsString());
-
- return new SliceRestriction(metadata, columnDefs, slice.merge(otherSlice.slice));
- }
-
- @Override
- public String toString()
- {
- return String.format("SLICE%s", slice);
- }
- private SliceRestriction(TableMetadata table, List<ColumnMetadata> columnDefs, TermSlice slice)
- {
- super(table, columnDefs);
- this.slice = slice;
- }
- }
-}
diff --git a/src/java/org/apache/cassandra/cql3/statements/ModificationStatement.java b/src/java/org/apache/cassandra/cql3/statements/ModificationStatement.java
index 61fbd6f391..4cf3de117d 100644
--- a/src/java/org/apache/cassandra/cql3/statements/ModificationStatement.java
+++ b/src/java/org/apache/cassandra/cql3/statements/ModificationStatement.java
@@ -822,10 +822,7 @@ public abstract class ModificationStatement implements CQLStatement.SingleKeyspa
public Slices createSlices(QueryOptions options)
{
- SortedSet<ClusteringBound<?>> startBounds = restrictions.getClusteringColumnsBounds(Bound.START, options);
- SortedSet<ClusteringBound<?>> endBounds = restrictions.getClusteringColumnsBounds(Bound.END, options);
-
- return toSlices(startBounds, endBounds);
+ return restrictions.getSlices(options);
}
private UpdateParameters makeUpdateParameters(Collection<ByteBuffer> keys,
@@ -889,37 +886,6 @@ public abstract class ModificationStatement implements CQLStatement.SingleKeyspa
lists);
}
- private Slices toSlices(SortedSet<ClusteringBound<?>> startBounds, SortedSet<ClusteringBound<?>> endBounds)
- {
- return toSlices(metadata, startBounds, endBounds);
- }
-
- public static Slices toSlices(TableMetadata metadata, SortedSet<ClusteringBound<?>> startBounds, SortedSet<ClusteringBound<?>> endBounds)
- {
- return toSlices(metadata.comparator, startBounds, endBounds);
- }
-
- public static Slices toSlices(ClusteringComparator comparator, SortedSet<ClusteringBound<?>> startBounds, SortedSet<ClusteringBound<?>> endBounds)
- {
- assert startBounds.size() == endBounds.size();
-
- Slices.Builder builder = new Slices.Builder(comparator);
-
- Iterator<ClusteringBound<?>> starts = startBounds.iterator();
- Iterator<ClusteringBound<?>> ends = endBounds.iterator();
-
- while (starts.hasNext())
- {
- Slice slice = Slice.make(starts.next(), ends.next());
- if (!slice.isEmpty(comparator))
- {
- builder.add(slice);
- }
- }
-
- return builder.build();
- }
-
public static abstract class Parsed extends QualifiedStatement
{
protected final StatementType type;
diff --git a/src/java/org/apache/cassandra/cql3/statements/SelectStatement.java b/src/java/org/apache/cassandra/cql3/statements/SelectStatement.java
index e2723df3ab..d3fe533a39 100644
--- a/src/java/org/apache/cassandra/cql3/statements/SelectStatement.java
+++ b/src/java/org/apache/cassandra/cql3/statements/SelectStatement.java
@@ -838,39 +838,9 @@ public class SelectStatement implements CQLStatement.SingleKeyspaceCqlStatement
}
@VisibleForTesting
- public Slices makeSlices(QueryOptions options)
- throws InvalidRequestException
+ public Slices makeSlices(QueryOptions options) throws InvalidRequestException
{
- SortedSet<ClusteringBound<?>> startBounds = restrictions.getClusteringColumnsBounds(Bound.START, options);
- SortedSet<ClusteringBound<?>> endBounds = restrictions.getClusteringColumnsBounds(Bound.END, options);
- assert startBounds.size() == endBounds.size();
-
- // The case where startBounds == 1 is common enough that it's worth optimizing
- if (startBounds.size() == 1)
- {
- ClusteringBound<?> start = startBounds.first();
- ClusteringBound<?> end = endBounds.first();
- return Slice.isEmpty(table.comparator, start, end)
- ? Slices.NONE
- : Slices.with(table.comparator, Slice.make(start, end));
- }
-
- Slices.Builder builder = new Slices.Builder(table.comparator, startBounds.size());
- Iterator<ClusteringBound<?>> startIter = startBounds.iterator();
- Iterator<ClusteringBound<?>> endIter = endBounds.iterator();
- while (startIter.hasNext() && endIter.hasNext())
- {
- ClusteringBound<?> start = startIter.next();
- ClusteringBound<?> end = endIter.next();
-
- // Ignore slices that are nonsensical
- if (Slice.isEmpty(table.comparator, start, end))
- continue;
-
- builder.add(start, end);
- }
-
- return builder.build();
+ return restrictions.getSlices(options);
}
private DataLimits getDataLimits(int userLimit,
@@ -1744,7 +1714,7 @@ public class SelectStatement implements CQLStatement.SingleKeyspaceCqlStatement
Index.QueryPlan indexQueryPlan = Keyspace.openAndGetStore(table).indexManager.getBestIndexQueryPlanFor(rowFilter);
- Index index = restriction.findSupportingIndexFromQueryPlan(indexQueryPlan);
+ Index index = restriction.findSupportingIndex(indexQueryPlan.getIndexes());
assert index != null;
Comparator<ByteBuffer> comparator = index.getPostQueryOrdering(restriction, options);
return (a, b) -> compare(comparator, a.get(columnIndex), b.get(columnIndex));
diff --git a/src/java/org/apache/cassandra/cql3/statements/UpdateStatement.java b/src/java/org/apache/cassandra/cql3/statements/UpdateStatement.java
index 0fba12ef50..b7d38bc291 100644
--- a/src/java/org/apache/cassandra/cql3/statements/UpdateStatement.java
+++ b/src/java/org/apache/cassandra/cql3/statements/UpdateStatement.java
@@ -168,7 +168,7 @@ public class UpdateStatement extends ModificationStatement
if (def.isPrimaryKeyColumn())
{
- whereClause.add(new SingleColumnRelation(columnNames.get(i), Operator.EQ, value));
+ whereClause.add(Relation.singleColumn(columnNames.get(i), Operator.EQ, value));
}
else
{
@@ -239,7 +239,7 @@ public class UpdateStatement extends ModificationStatement
Term.Raw raw = prepared.getRawTermForColumn(def, defaultUnset);
if (def.isPrimaryKeyColumn())
{
- whereClause.add(new SingleColumnRelation(def.name, Operator.EQ, raw));
+ whereClause.add(Relation.singleColumn(def.name, Operator.EQ, raw));
}
else
{
diff --git a/src/java/org/apache/cassandra/cql3/terms/InMarker.java b/src/java/org/apache/cassandra/cql3/terms/InMarker.java
index afc22dd1de..452856e284 100644
--- a/src/java/org/apache/cassandra/cql3/terms/InMarker.java
+++ b/src/java/org/apache/cassandra/cql3/terms/InMarker.java
@@ -115,9 +115,9 @@ public final class InMarker extends Terms.NonTerminals
}
@Override
- public Term asSingleTerm()
+ public String toString()
{
- throw new UnsupportedOperationException();
+ return "?";
}
/**
diff --git a/src/java/org/apache/cassandra/cql3/terms/Marker.java b/src/java/org/apache/cassandra/cql3/terms/Marker.java
index ff0702fbc3..2befe633ce 100644
--- a/src/java/org/apache/cassandra/cql3/terms/Marker.java
+++ b/src/java/org/apache/cassandra/cql3/terms/Marker.java
@@ -31,8 +31,6 @@ import org.apache.cassandra.exceptions.InvalidRequestException;
import org.apache.cassandra.serializers.MarshalException;
import org.apache.cassandra.utils.ByteBufferUtil;
-import static org.apache.cassandra.cql3.statements.RequestValidations.checkFalse;
-
/**
* A placeholder, also called bind marker, for a single value represented in CQL as {@code ?} for an unnamed marker or {@code :<name>} for a named marker.
* For example, {@code SELECT ... WHERE pk = ?} or {@code SELECT ... WHERE pk = :myKey}.
@@ -81,10 +79,7 @@ public final class Marker extends Term.NonTerminal
return null;
if (bytes == ByteBufferUtil.UNSET_BYTE_BUFFER)
- {
- checkFalse(receiver.type.isTuple(), "Invalid unset value for tuple %s", receiver.name);
return Constants.UNSET_VALUE;
- }
if (receiver.type instanceof MultiElementType<?>)
return MultiElements.Value.fromSerialized(bytes, (MultiElementType<?>) receiver.type);
@@ -98,6 +93,12 @@ public final class Marker extends Term.NonTerminal
}
}
+ @Override
+ public String toString()
+ {
+ return "?";
+ }
+
/**
* A parsed, but non prepared, bind marker.
*/
diff --git a/src/java/org/apache/cassandra/cql3/terms/Term.java b/src/java/org/apache/cassandra/cql3/terms/Term.java
index 494a2c1473..36b96a88cd 100644
--- a/src/java/org/apache/cassandra/cql3/terms/Term.java
+++ b/src/java/org/apache/cassandra/cql3/terms/Term.java
@@ -18,6 +18,7 @@
package org.apache.cassandra.cql3.terms;
import java.nio.ByteBuffer;
+import java.util.AbstractList;
import java.util.Collections;
import java.util.List;
@@ -32,6 +33,7 @@ import org.apache.cassandra.cql3.functions.Function;
import org.apache.cassandra.db.marshal.AbstractType;
import org.apache.cassandra.exceptions.InvalidRequestException;
import org.apache.cassandra.schema.SchemaConstants;
+import org.apache.cassandra.utils.ByteBufferUtil;
/**
* A CQL3 term, i.e. a column value with or without bind variables.
@@ -42,6 +44,25 @@ import org.apache.cassandra.schema.SchemaConstants;
*/
public interface Term
{
+ /**
+ * The {@code List} returned when the list was not set.
+ */
+ @SuppressWarnings("rawtypes")
+ List UNSET_LIST = Collections.unmodifiableList(new AbstractList()
+ {
+ @Override
+ public ByteBuffer get(int index)
+ {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public int size()
+ {
+ throw new UnsupportedOperationException();
+ }
+ });
+
/**
* Collects the column specification for the bind variables in this Term.
* This is obviously a no-op if the term is Terminal.
@@ -236,7 +257,9 @@ public interface Term
public List<ByteBuffer> getElements()
{
ByteBuffer value = get();
- return value == null ? Collections.emptyList() : Collections.singletonList(value);
+ return value == null ? Collections.emptyList()
+ : value == ByteBufferUtil.UNSET_BYTE_BUFFER ? UNSET_LIST
+ : Collections.singletonList(value);
}
@Override
diff --git a/src/java/org/apache/cassandra/cql3/terms/Terms.java b/src/java/org/apache/cassandra/cql3/terms/Terms.java
index 0ebb78a615..8a78ef9bfd 100644
--- a/src/java/org/apache/cassandra/cql3/terms/Terms.java
+++ b/src/java/org/apache/cassandra/cql3/terms/Terms.java
@@ -36,25 +36,6 @@ import org.apache.cassandra.exceptions.InvalidRequestException;
*/
public interface Terms
{
- /**
- * The {@code List} returned when the list was not set.
- */
- @SuppressWarnings("rawtypes")
- List UNSET_LIST = new AbstractList()
- {
- @Override
- public Object get(int index)
- {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public int size()
- {
- throw new UnsupportedOperationException();
- }
- };
-
/**
* The terminals returned when they were unset.
*/
@@ -64,14 +45,14 @@ public interface Terms
@SuppressWarnings("unchecked")
public List<ByteBuffer> get()
{
- return (List<ByteBuffer>) UNSET_LIST;
+ return Term.UNSET_LIST;
}
@Override
@SuppressWarnings("unchecked")
public List<List<ByteBuffer>> getElements()
{
- return (List<List<ByteBuffer>>) UNSET_LIST;
+ return Term.UNSET_LIST;
}
@Override
@@ -92,9 +73,9 @@ public interface Terms
}
@Override
- public Term asSingleTerm()
+ public String toString()
{
- throw new UnsupportedOperationException();
+ return "UNSET";
}
};
@@ -185,13 +166,6 @@ public interface Terms
*/
boolean containsSingleTerm();
- /**
- * If this {@code terms} contains a single term it will be returned otherwise an UnsupportedOperationException will be thrown.
- * @return a single term representing the single element of this {@code terms}.
- * @throws UnsupportedOperationException if this term does not know how many terms it contains or contains more than one term
- */
- Term asSingleTerm();
-
/**
* Adds all functions (native and user-defined) of the specified terms to the list.
* @param functions the list to add to
@@ -225,6 +199,18 @@ public interface Terms
*/
public abstract String getText();
+ @Override
+ public int hashCode()
+ {
+ return getText().hashCode();
+ }
+
+ @Override
+ public boolean equals(Object o)
+ {
+ return this == o || (o instanceof Terms.Raw && getText().equals(((Terms.Raw) o).getText()));
+ }
+
/**
* The type of the {@code Terms} if it can be inferred.
*
@@ -283,6 +269,36 @@ public interface Terms
}
};
}
+
+ public static Raw of(Term.Raw raw)
+ {
+ return new Raw()
+ {
+ @Override
+ public Terms prepare(String keyspace, ColumnSpecification receiver) throws InvalidRequestException
+ {
+ return Terms.of(raw.prepare(keyspace, receiver));
+ }
+
+ @Override
+ public String getText()
+ {
+ return raw.getText();
+ }
+
+ @Override
+ public AbstractType<?> getExactTypeIfKnown(String keyspace)
+ {
+ return raw.getExactTypeIfKnown(keyspace);
+ }
+
+ @Override
+ public TestResult testAssignment(String keyspace, ColumnSpecification receiver)
+ {
+ return raw.testAssignment(keyspace, receiver);
+ }
+ };
+ }
}
/**
@@ -370,9 +386,9 @@ public interface Terms
}
@Override
- public Term asSingleTerm()
+ public String toString()
{
- return terminal;
+ return terminal.toString();
}
};
}
@@ -426,11 +442,9 @@ public interface Terms
}
@Override
- public Terminal asSingleTerm()
+ public String toString()
{
- if (!containsSingleTerm())
- throw new UnsupportedOperationException("This terms content cannot be converted in a single term");
- return terminals.get(0);
+ return terminals.stream().map(Objects::toString).collect(Collectors.joining(", ", "(", ")"));
}
};
}
@@ -482,9 +496,9 @@ public interface Terms
}
@Override
- public Term.NonTerminal asSingleTerm()
+ public String toString()
{
- return term;
+ return term.toString();
}
};
}
@@ -555,11 +569,9 @@ public interface Terms
}
@Override
- public Term asSingleTerm()
+ public String toString()
{
- if (!containsSingleTerm())
- throw new UnsupportedOperationException("This Terms cannot be converted in a single Term");
- return terms.get(0);
+ return terms.stream().map(Objects::toString).collect(Collectors.joining(", ", "(", ")"));
}
};
}
diff --git a/src/java/org/apache/cassandra/cql3/terms/Tuples.java b/src/java/org/apache/cassandra/cql3/terms/Tuples.java
index 9458335677..6825a16b98 100644
--- a/src/java/org/apache/cassandra/cql3/terms/Tuples.java
+++ b/src/java/org/apache/cassandra/cql3/terms/Tuples.java
@@ -48,25 +48,6 @@ public final class Tuples
(getTupleType(column.type)).type(component));
}
- public static ColumnSpecification makeReceiver(List<? extends ColumnSpecification> receivers)
- {
- List<AbstractType<?>> types = new ArrayList<>(receivers.size());
- StringBuilder inName = new StringBuilder("(");
- for (int i = 0; i < receivers.size(); i++)
- {
- ColumnSpecification receiver = receivers.get(i);
- inName.append(receiver.name);
- if (i < receivers.size() - 1)
- inName.append(',');
- types.add(receiver.type);
- }
- inName.append(')');
-
- ColumnIdentifier identifier = new ColumnIdentifier(inName.toString(), true);
- TupleType type = new TupleType(types);
- return new ColumnSpecification(receivers.get(0).ksName, receivers.get(0).cfName, identifier, type);
- }
-
/**
* A raw, literal tuple. When prepared, this will become a Tuples.Value or Tuples.DelayedValue, depending
* on whether the tuple holds NonTerminals.
diff --git a/src/java/org/apache/cassandra/db/MultiCBuilder.java b/src/java/org/apache/cassandra/db/MultiCBuilder.java
index 435e418eb3..99bbc64a65 100644
--- a/src/java/org/apache/cassandra/db/MultiCBuilder.java
+++ b/src/java/org/apache/cassandra/db/MultiCBuilder.java
@@ -17,148 +17,160 @@
*/
package org.apache.cassandra.db;
-import java.nio.ByteBuffer;
-import java.util.ArrayList;
-import java.util.Arrays;
import java.util.List;
import java.util.NavigableSet;
+import java.util.Set;
-import org.apache.cassandra.schema.ColumnMetadata;
-import org.apache.cassandra.utils.ByteBufferUtil;
+import com.google.common.collect.BoundType;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableRangeSet;
+import com.google.common.collect.Range;
+import com.google.common.collect.RangeSet;
+
+import org.apache.cassandra.cql3.restrictions.ClusteringElements;
import org.apache.cassandra.utils.btree.BTreeSet;
/**
- * Builder that allow to build multiple Clustering/ClusteringBound at the same time.
+ * Builder that allows to build multiple Clusterings/Slices at the same time.
*/
-public abstract class MultiCBuilder
+public final class MultiCBuilder
{
/**
* The table comparator.
*/
- protected final ClusteringComparator comparator;
+ private final ClusteringComparator comparator;
/**
- * The number of clustering elements that have been added.
+ * {@code true} if the clusterings have been build, <code>false</code> otherwise.
*/
- protected int size;
+ private boolean built;
/**
- * <code>true</code> if the clusterings have been build, <code>false</code> otherwise.
+ * The clusterings set.
*/
- protected boolean built;
+ private List<ClusteringElements> clusterings = ImmutableList.of();
/**
- * <code>true</code> if the clusterings contains some <code>null</code> elements.
+ * The clustering ranges.
*/
- protected boolean containsNull;
+ private RangeSet<ClusteringElements> clusteringsRanges;
/**
- * <code>true</code> if the composites contains some <code>unset</code> elements.
+ * Track if some elements are missing. This can happen with a <pre>WHERE c IN ()</pre>.
+ * making the query not returning any results.
*/
- protected boolean containsUnset;
+ private boolean hasMissingElements;
- /**
- * <code>true</code> if some empty collection have been added.
- */
- protected boolean hasMissingElements;
- protected MultiCBuilder(ClusteringComparator comparator)
+ public MultiCBuilder(ClusteringComparator comparator)
{
this.comparator = comparator;
}
/**
- * Creates a new empty {@code MultiCBuilder}.
- */
- public static MultiCBuilder create(ClusteringComparator comparator, boolean forMultipleValues)
- {
- return forMultipleValues
- ? new MultiClusteringBuilder(comparator)
- : new OneClusteringBuilder(comparator);
- }
-
- /**
- * Adds the specified element to all the clusterings.
- * <p>
- * If this builder contains 2 clustering: A-B and A-C a call to this method to add D will result in the clusterings:
- * A-B-D and A-C-D.
- * </p>
+ * Adds individually each of the specified elements to the end of all the existing clusterings.
+ * The number of result clusterings is the product of the number of current clusterings and the number
+ * of elements added.
*
- * @param value the value of the next element
- * @return this <code>MulitCBuilder</code>
- */
- public abstract MultiCBuilder addElementToAll(ByteBuffer value);
-
- /**
- * Adds individually each of the specified elements to the end of all of the existing clusterings.
* <p>
- * If this builder contains 2 clusterings: A-B and A-C a call to this method to add D and E will result in the 4
+ * If this builder contains 2 composites: A-B and A-C a call to this method to add D and E will result in the 4
* clusterings: A-B-D, A-B-E, A-C-D and A-C-E.
* </p>
*
- * @param values the elements to add
- * @return this <code>CompositeBuilder</code>
- */
- public abstract MultiCBuilder addEachElementToAll(List<ByteBuffer> values);
-
- /**
- * Adds individually each of the specified list of elements to the end of all of the existing composites.
* <p>
- * If this builder contains 2 composites: A-B and A-C a call to this method to add [[D, E], [F, G]] will result in the 4
- * composites: A-B-D-E, A-B-F-G, A-C-D-E and A-C-F-G.
+ * Added elements can be composites as well.
+ * If this builder contains 2 composites: A-B and A-C a call to this method to add [[D, E], [F, G]] will result in
+ * 4 composites: A-B-D-E, A-B-F-G, A-C-D-E and A-C-F-G.
* </p>
*
- * @param values the elements to add
- * @return this <code>CompositeBuilder</code>
+ * @param suffixes the elements to add
+ * @return this <code>MultiCBuilder</code>
*/
- public abstract MultiCBuilder addAllElementsToAll(List<List<ByteBuffer>> values);
-
- protected void checkUpdateable()
+ public MultiCBuilder extend(List<ClusteringElements> suffixes)
{
- if (!hasRemaining() || built)
- throw new IllegalStateException("this builder cannot be updated anymore");
+ checkUpdateable();
+
+ if (suffixes.isEmpty())
+ {
+ hasMissingElements = true;
+ return this;
+ }
+ this.clusterings = this.clusterings.isEmpty() ? suffixes : cartesianProduct(clusterings, suffixes);
+ return this;
}
/**
- * Returns the number of elements that can be added to the clusterings.
+ * Adds individually each of the specified elements ranges to the end of all the existing clusterings.
+ * The number of result clusterings is the product of the number of current clusterings and the number
+ * of range added.
*
- * @return the number of elements that can be added to the clusterings.
+ * <p>
+ * If this builder contains 2 composites: A-B and A-C a call to this method to add [D..E) and (F..G] will result in the 4
+ * clusterings range : [A-B-D..A-B-E), (A-B-F..A-B-G], [A-C-D..A-C-E) and (A-C-F..A-C-G].
+ * </p>
+ *
+ * <p>
+ * Added elements can be composites as well.
+ * If this builder contains 2 composites: A-B and A-C a call to this method to add [[D-E..F-G), (H-I..J-K]] will result in
+ * 4 composites: [A-B-D-E..A-B-F-G), (A-B-H-I..A-B-J-K], [A-C-D-E..A-C-F-G) and (A-C-H-I..A-C-J-K].
+ * </p>
+ *
+ * @param suffixes the ranges to add
+ * @return this <code>MultiCBuilder</code>
*/
- public int remainingCount()
+ public MultiCBuilder extend(RangeSet<ClusteringElements> suffixes)
{
- return comparator.size() - size;
+ checkUpdateable();
+
+ this.clusteringsRanges = this.clusterings.isEmpty() ? suffixes : cartesianProduct(clusterings, suffixes);
+ this.clusterings = null;
+ return this;
}
- /**
- * Returns the current number of results when {@link #build()} is called
- *
- * @return the current number of build results
- */
- public abstract int buildSize();
+ private static RangeSet<ClusteringElements> cartesianProduct(List<ClusteringElements> prefixes, RangeSet<ClusteringElements> suffixes)
+ {
+ ImmutableRangeSet.Builder<ClusteringElements> builder = ImmutableRangeSet.builder();
+ for (ClusteringElements prefix: prefixes)
+ {
+ for (Range<ClusteringElements> suffix : suffixes.asRanges())
+ {
+ builder.add(Range.range(prefix.extend(suffix.lowerEndpoint()),
+ suffix.lowerBoundType(),
+ prefix.extend(suffix.upperEndpoint()),
+ suffix.upperBoundType()));
+ }
+ }
+ return builder.build();
+ }
- /**
- * Checks if the clusterings contains null elements.
- *
- * @return <code>true</code> if the clusterings contains <code>null</code> elements, <code>false</code> otherwise.
- */
- public boolean containsNull()
+ private static List<ClusteringElements> cartesianProduct(List<ClusteringElements> prefixes, List<ClusteringElements> suffixes)
{
- return containsNull;
+ ImmutableList.Builder<ClusteringElements> builder = ImmutableList.builderWithExpectedSize(prefixes.size() * suffixes.size());
+ for (ClusteringElements prefix: prefixes)
+ {
+ for (ClusteringElements suffix: suffixes)
+ {
+ builder.add(prefix.extend(suffix));
+ }
+ }
+ return builder.build();
}
/**
- * Checks if the clusterings contains unset elements.
+ * Returns the current number of results when {@link #build()} is called
*
- * @return <code>true</code> if the clusterings contains <code>unset</code> elements, <code>false</code> otherwise.
+ * @return the current number of build results
*/
- public boolean containsUnset()
+ public int buildSize()
{
- return containsUnset;
+ return hasMissingElements ? 0
+ : clusterings != null ? clusterings.size()
+ : clusteringsRanges.asRanges().size();
}
/**
- * Checks if some empty list of values have been added
- * @return <code>true</code> if the clusterings have some missing elements, <code>false</code> otherwise.
+ * Checks if some clusterings have some missing elements due to a <pre>WHERE c IN ()</pre>.
+ * @return {@code true} if the clusterings have some missing elements, {@code false} otherwise.
*/
public boolean hasMissingElements()
{
@@ -170,345 +182,72 @@ public abstract class MultiCBuilder
*
* @return the clusterings
*/
- public abstract NavigableSet<Clustering<?>> build();
-
- /**
- * Builds the <code>ClusteringBound</code>s for slice restrictions.
- *
- * @param isStart specify if the bound is a start one
- * @param isInclusive specify if the bound is inclusive or not
- * @param isOtherBoundInclusive specify if the other bound is inclusive or not
- * @param columnDefs the columns of the slice restriction
- * @return the <code>ClusteringBound</code>s
- */
- public abstract NavigableSet<ClusteringBound<?>> buildBoundForSlice(boolean isStart,
- boolean isInclusive,
- boolean isOtherBoundInclusive,
- List<ColumnMetadata> columnDefs);
-
- /**
- * Builds the <code>ClusteringBound</code>s
- *
- * @param isStart specify if the bound is a start one
- * @param isInclusive specify if the bound is inclusive or not
- * @return the <code>ClusteringBound</code>s
- */
- public abstract NavigableSet<ClusteringBound<?>> buildBound(boolean isStart, boolean isInclusive);
-
- /**
- * Checks if some elements can still be added to the clusterings.
- *
- * @return <code>true</code> if it is possible to add more elements to the clusterings, <code>false</code> otherwise.
- */
- public boolean hasRemaining()
+ public NavigableSet<Clustering<?>> build()
{
- return remainingCount() > 0;
- }
-
- /**
- * Specialization of MultiCBuilder when we know only one clustering/bound is created.
- */
- private static class OneClusteringBuilder extends MultiCBuilder
- {
- /**
- * The elements of the clusterings
- */
- private final ByteBuffer[] elements;
-
- public OneClusteringBuilder(ClusteringComparator comparator)
- {
- super(comparator);
- this.elements = new ByteBuffer[comparator.size()];
- }
-
- public MultiCBuilder addElementToAll(ByteBuffer value)
- {
- checkUpdateable();
-
- if (value == null)
- containsNull = true;
- if (value == ByteBufferUtil.UNSET_BYTE_BUFFER)
- containsUnset = true;
-
- elements[size++] = value;
- return this;
- }
-
- public MultiCBuilder addEachElementToAll(List<ByteBuffer> values)
- {
- if (values.isEmpty())
- {
- hasMissingElements = true;
- return this;
- }
-
- assert values.size() == 1;
-
- return addElementToAll(values.get(0));
- }
-
- public MultiCBuilder addAllElementsToAll(List<List<ByteBuffer>> values)
- {
- if (values.isEmpty())
- {
- hasMissingElements = true;
- return this;
- }
+ assert clusteringsRanges == null;
+ built = true;
- assert values.size() == 1;
- return addEachElementToAll(values.get(0));
- }
+ if (hasMissingElements)
+ return BTreeSet.empty(comparator);
- @Override
- public int buildSize()
- {
- return hasMissingElements ? 0 : 1;
- }
+ if (clusterings.isEmpty())
+ return BTreeSet.of(comparator, Clustering.EMPTY);
- public NavigableSet<Clustering<?>> build()
- {
- built = true;
-
- if (hasMissingElements)
- return BTreeSet.empty(comparator);
-
- return BTreeSet.of(comparator, size == 0 ? Clustering.EMPTY : Clustering.make(elements));
- }
+ CBuilder builder = CBuilder.create(comparator);
- @Override
- public NavigableSet<ClusteringBound<?>> buildBoundForSlice(boolean isStart,
- boolean isInclusive,
- boolean isOtherBoundInclusive,
- List<ColumnMetadata> columnDefs)
+ BTreeSet.Builder<Clustering<?>> set = BTreeSet.builder(builder.comparator());
+ for (ClusteringElements clustering : clusterings)
{
- return buildBound(isStart, columnDefs.get(0).isReversedType() ? isOtherBoundInclusive : isInclusive);
- }
-
- public NavigableSet<ClusteringBound<?>> buildBound(boolean isStart, boolean isInclusive)
- {
- built = true;
-
- if (hasMissingElements)
- return BTreeSet.empty(comparator);
-
- if (size == 0)
- return BTreeSet.of(comparator, isStart ? BufferClusteringBound.BOTTOM : BufferClusteringBound.TOP);
-
- ByteBuffer[] newValues = size == elements.length
- ? elements
- : Arrays.copyOf(elements, size);
-
- return BTreeSet.of(comparator, BufferClusteringBound.create(ClusteringBound.boundKind(isStart, isInclusive), newValues));
+ set.add(builder.buildWith(clustering));
}
+ return set.build();
}
- /**
- * MultiCBuilder implementation actually supporting the creation of multiple clustering/bound.
- */
- private static class MultiClusteringBuilder extends MultiCBuilder
+ public Slices buildSlices()
{
- /**
- * The elements of the clusterings
- */
- private final List<List<ByteBuffer>> elementsList = new ArrayList<>();
-
- public MultiClusteringBuilder(ClusteringComparator comparator)
- {
- super(comparator);
- }
-
- public MultiCBuilder addElementToAll(ByteBuffer value)
- {
- checkUpdateable();
-
- if (elementsList.isEmpty())
- elementsList.add(new ArrayList<>());
-
- if (value == null)
- containsNull = true;
- else if (value == ByteBufferUtil.UNSET_BYTE_BUFFER)
- containsUnset = true;
-
- for (int i = 0, m = elementsList.size(); i < m; i++)
- elementsList.get(i).add(value);
-
- size++;
- return this;
- }
-
- public MultiCBuilder addEachElementToAll(List<ByteBuffer> values)
- {
- checkUpdateable();
-
- if (elementsList.isEmpty())
- elementsList.add(new ArrayList<>());
-
- if (values.isEmpty())
- {
- hasMissingElements = true;
- }
- else
- {
- for (int i = 0, m = elementsList.size(); i < m; i++)
- {
- List<ByteBuffer> oldComposite = elementsList.remove(0);
-
- for (int j = 0, n = values.size(); j < n; j++)
- {
- List<ByteBuffer> newComposite = new ArrayList<>(oldComposite);
- elementsList.add(newComposite);
-
- ByteBuffer value = values.get(j);
-
- if (value == null)
- containsNull = true;
- if (value == ByteBufferUtil.UNSET_BYTE_BUFFER)
- containsUnset = true;
-
- newComposite.add(values.get(j));
- }
- }
- }
- size++;
- return this;
- }
-
- public MultiCBuilder addAllElementsToAll(List<List<ByteBuffer>> values)
+ if (clusterings != null)
{
- checkUpdateable();
-
- if (elementsList.isEmpty())
- elementsList.add(new ArrayList<>());
-
- if (values.isEmpty())
- {
- hasMissingElements = true;
- }
- else
- {
- for (int i = 0, m = elementsList.size(); i < m; i++)
- {
- List<ByteBuffer> oldComposite = elementsList.remove(0);
-
- for (int j = 0, n = values.size(); j < n; j++)
- {
- List<ByteBuffer> newComposite = new ArrayList<>(oldComposite);
- elementsList.add(newComposite);
-
- List<ByteBuffer> value = values.get(j);
-
- if (value.contains(null))
- containsNull = true;
- if (value.contains(ByteBufferUtil.UNSET_BYTE_BUFFER))
- containsUnset = true;
-
- newComposite.addAll(value);
- }
- }
- size += values.get(0).size();
- }
- return this;
- }
-
- @Override
- public int buildSize()
- {
- return hasMissingElements ? 0 : elementsList.size();
- }
-
- public NavigableSet<Clustering<?>> build()
- {
- built = true;
-
if (hasMissingElements)
- return BTreeSet.empty(comparator);
+ return Slices.NONE;
- CBuilder builder = CBuilder.create(comparator);
+ if (clusterings.isEmpty())
+ return Slices.ALL;
- if (elementsList.isEmpty())
- return BTreeSet.of(builder.comparator(), builder.build());
+ Slices.Builder builder = new Slices.Builder(comparator, clusterings.size());
- BTreeSet.Builder<Clustering<?>> set = BTreeSet.builder(builder.comparator());
- for (int i = 0, m = elementsList.size(); i < m; i++)
+ for (ClusteringElements clustering : clusterings)
{
- List<ByteBuffer> elements = elementsList.get(i);
- set.add(builder.buildWith(elements));
+ builder.add(clustering.toBound(true, true),
+ clustering.toBound(false, true));
}
- return set.build();
+ return builder.build();
}
- public NavigableSet<ClusteringBound<?>> buildBoundForSlice(boolean isStart,
- boolean isInclusive,
- boolean isOtherBoundInclusive,
- List<ColumnMetadata> columnDefs)
- {
- built = true;
+ Set<Range<ClusteringElements>> ranges = clusteringsRanges.asRanges();
- if (hasMissingElements)
- return BTreeSet.empty(comparator);
-
- CBuilder builder = CBuilder.create(comparator);
-
- if (elementsList.isEmpty())
- return BTreeSet.of(comparator, builder.buildBound(isStart, isInclusive));
-
- // Use a TreeSet to sort and eliminate duplicates
- BTreeSet.Builder<ClusteringBound<?>> set = BTreeSet.builder(comparator);
-
- // The first column of the slice might not be the first clustering column (e.g. clustering_0 = ? AND (clustering_1, clustering_2) >= (?, ?)
- int offset = columnDefs.get(0).position();
-
- for (int i = 0, m = elementsList.size(); i < m; i++)
- {
- List<ByteBuffer> elements = elementsList.get(i);
-
- // Handle the no bound case
- if (elements.size() == offset)
- {
- set.add(builder.buildBoundWith(elements, isStart, true));
- continue;
- }
-
- // In the case of mixed order columns, we will have some extra slices where the columns change directions.
- // For example: if we have clustering_0 DESC and clustering_1 ASC a slice like (clustering_0, clustering_1) > (1, 2)
- // will produce 2 slices: [BOTTOM, 1) and (1.2, 1]
- // So, the END bound will return 2 bounds with the same values 1
- ColumnMetadata lastColumn = columnDefs.get(columnDefs.size() - 1);
- if (elements.size() <= lastColumn.position() && i < m - 1 && elements.equals(elementsList.get(i + 1)))
- {
- set.add(builder.buildBoundWith(elements, isStart, false));
- set.add(builder.buildBoundWith(elementsList.get(i++), isStart, true));
- continue;
- }
-
- // Handle the normal bounds
- ColumnMetadata column = columnDefs.get(elements.size() - 1 - offset);
- set.add(builder.buildBoundWith(elements, isStart, column.isReversedType() ? isOtherBoundInclusive : isInclusive));
- }
- return set.build();
- }
-
- public NavigableSet<ClusteringBound<?>> buildBound(boolean isStart, boolean isInclusive)
+ Slices.Builder builder = new Slices.Builder(comparator, ranges.size());
+ for (Range<ClusteringElements> range : ranges)
{
- built = true;
-
- if (hasMissingElements)
- return BTreeSet.empty(comparator);
+ builder.add(range.lowerEndpoint().toBound(true, isInclusive(range.lowerBoundType())),
+ range.upperEndpoint().toBound(false, isInclusive(range.upperBoundType())));
+ }
+ return builder.build();
+ }
- CBuilder builder = CBuilder.create(comparator);
+ private boolean isInclusive(BoundType boundType)
+ {
+ return boundType == BoundType.CLOSED;
+ }
- if (elementsList.isEmpty())
- return BTreeSet.of(comparator, builder.buildBound(isStart, isInclusive));
+ private void checkUpdateable()
+ {
+ if (built)
+ throw new IllegalStateException("This builder cannot be updated anymore");
- // Use a TreeSet to sort and eliminate duplicates
- BTreeSet.Builder<ClusteringBound<?>> set = BTreeSet.builder(comparator);
+ if (clusteringsRanges != null)
+ throw new IllegalStateException("Cannot extend clusterings that contain ranges");
- for (int i = 0, m = elementsList.size(); i < m; i++)
- {
- List<ByteBuffer> elements = elementsList.get(i);
- set.add(builder.buildBoundWith(elements, isStart, isInclusive));
- }
- return set.build();
- }
+ if (hasMissingElements)
+ throw new IllegalStateException("Cannot extend clusterings with missing elements");
}
}
diff --git a/src/java/org/apache/cassandra/db/filter/RowFilter.java b/src/java/org/apache/cassandra/db/filter/RowFilter.java
index beb3edfcd7..60b019d077 100644
--- a/src/java/org/apache/cassandra/db/filter/RowFilter.java
+++ b/src/java/org/apache/cassandra/db/filter/RowFilter.java
@@ -49,7 +49,6 @@ import org.apache.cassandra.db.marshal.CompositeType;
import org.apache.cassandra.db.marshal.ListType;
import org.apache.cassandra.db.marshal.LongType;
import org.apache.cassandra.db.marshal.MapType;
-import org.apache.cassandra.db.marshal.SetType;
import org.apache.cassandra.db.marshal.UTF8Type;
import org.apache.cassandra.db.partitions.PartitionIterator;
import org.apache.cassandra.db.partitions.UnfilteredPartitionIterator;
@@ -125,7 +124,7 @@ public class RowFilter implements Iterable<RowFilter.Expression>
public void addMapEquality(ColumnMetadata def, ByteBuffer key, Operator op, ByteBuffer value)
{
- add(new MapEqualityExpression(def, key, op, value));
+ add(new MapElementExpression(def, key, op, value));
}
public void addCustomIndexExpression(TableMetadata metadata, IndexMetadata targetIndex, ByteBuffer value)
@@ -440,7 +439,7 @@ public class RowFilter implements Iterable<RowFilter.Expression>
// and this is why we have some UNUSEDX for values we don't use anymore
// (we could clean those on a major protocol update, but it's not worth
// the trouble for now)
- protected enum Kind { SIMPLE, MAP_EQUALITY, UNUSED1, CUSTOM, USER }
+ protected enum Kind { SIMPLE, MAP_ELEMENT, UNUSED1, CUSTOM, USER }
protected abstract Kind kind();
protected final ColumnMetadata column;
@@ -474,28 +473,6 @@ public class RowFilter implements Iterable<RowFilter.Expression>
return operator;
}
- /**
- * Checks if the operator of this <code>IndexExpression</code> is a <code>CONTAINS</code> operator.
- *
- * @return <code>true</code> if the operator of this <code>IndexExpression</code> is a <code>CONTAINS</code>
- * operator, <code>false</code> otherwise.
- */
- public boolean isContains()
- {
- return Operator.CONTAINS == operator;
- }
-
- /**
- * Checks if the operator of this <code>IndexExpression</code> is a <code>CONTAINS_KEY</code> operator.
- *
- * @return <code>true</code> if the operator of this <code>IndexExpression</code> is a <code>CONTAINS_KEY</code>
- * operator, <code>false</code> otherwise.
- */
- public boolean isContainsKey()
- {
- return Operator.CONTAINS_KEY == operator;
- }
-
/**
* If this expression is used to query an index, the value to use as
* partition key for that index query.
@@ -617,8 +594,8 @@ public class RowFilter implements Iterable<RowFilter.Expression>
case SIMPLE:
ByteBufferUtil.writeWithShortLength(expression.value, out);
break;
- case MAP_EQUALITY:
- MapEqualityExpression mexpr = (MapEqualityExpression)expression;
+ case MAP_ELEMENT:
+ MapElementExpression mexpr = (MapElementExpression)expression;
ByteBufferUtil.writeWithShortLength(mexpr.key, out);
ByteBufferUtil.writeWithShortLength(mexpr.value, out);
break;
@@ -653,10 +630,10 @@ public class RowFilter implements Iterable<RowFilter.Expression>
{
case SIMPLE:
return new SimpleExpression(column, operator, ByteBufferUtil.readWithShortLength(in));
- case MAP_EQUALITY:
+ case MAP_ELEMENT:
ByteBuffer key = ByteBufferUtil.readWithShortLength(in);
ByteBuffer value = ByteBufferUtil.readWithShortLength(in);
- return new MapEqualityExpression(column, key, operator, value);
+ return new MapElementExpression(column, key, operator, value);
}
throw new AssertionError();
}
@@ -669,15 +646,15 @@ public class RowFilter implements Iterable<RowFilter.Expression>
// other expressions do.
if (expression.kind() != Kind.CUSTOM && expression.kind() != Kind.USER)
size += ByteBufferUtil.serializedSizeWithShortLength(expression.column().name.bytes)
- + expression.operator.serializedSize();
+ + Operator.serializedSize();
switch (expression.kind())
{
case SIMPLE:
size += ByteBufferUtil.serializedSizeWithShortLength(((SimpleExpression)expression).value);
break;
- case MAP_EQUALITY:
- MapEqualityExpression mexpr = (MapEqualityExpression)expression;
+ case MAP_ELEMENT:
+ MapElementExpression mexpr = (MapElementExpression)expression;
size += ByteBufferUtil.serializedSizeWithShortLength(mexpr.key)
+ ByteBufferUtil.serializedSizeWithShortLength(mexpr.value);
break;
@@ -710,103 +687,42 @@ public class RowFilter implements Iterable<RowFilter.Expression>
// TODO: we should try to merge both code someday.
assert value != null;
- switch (operator)
+ if (operator.appliesToColumnValues())
{
- case EQ:
- case IN:
- case LT:
- case LTE:
- case GTE:
- case GT:
- {
- assert !column.isComplex() : "Only CONTAINS and CONTAINS_KEY are supported for collection types";
-
- // In order to support operators on Counter types, their value has to be extracted from internal
- // representation. See CASSANDRA-11629
- if (column.type.isCounter())
- {
- ByteBuffer foundValue = getValue(metadata, partitionKey, row);
- if (foundValue == null)
- return false;
-
- ByteBuffer counterValue = LongType.instance.decompose(CounterContext.instance().total(foundValue, ByteBufferAccessor.instance));
- return operator.isSatisfiedBy(LongType.instance, counterValue, value);
- }
- else
- {
- // Note that CQL expression are always of the form 'x < 4', i.e. the tested value is on the left.
- ByteBuffer foundValue = getValue(metadata, partitionKey, row);
- return foundValue != null && operator.isSatisfiedBy(column.type, foundValue, value);
- }
- }
- case NEQ:
- case LIKE_PREFIX:
- case LIKE_SUFFIX:
- case LIKE_CONTAINS:
- case LIKE_MATCHES:
- case ANN:
- {
- assert !column.isComplex() : "Only CONTAINS and CONTAINS_KEY are supported for collection types";
- ByteBuffer foundValue = getValue(metadata, partitionKey, row);
- // Note that CQL expression are always of the form 'x < 4', i.e. the tested value is on the left.
- return foundValue != null && operator.isSatisfiedBy(column.type, foundValue, value);
- }
- case CONTAINS:
- assert column.type.isCollection();
- CollectionType<?> type = (CollectionType<?>)column.type;
- if (column.isComplex())
- {
- ComplexColumnData complexData = row.getComplexColumnData(column);
- if (complexData != null)
- {
- for (Cell<?> cell : complexData)
- {
- if (type.kind == CollectionType.Kind.SET)
- {
- if (type.nameComparator().compare(cell.path().get(0), value) == 0)
- return true;
- }
- else
- {
- if (type.valueComparator().compare(cell.buffer(), value) == 0)
- return true;
- }
- }
- }
+ assert !column.isComplex() : "Only CONTAINS and CONTAINS_KEY are supported for 'complex' types";
+
+ // In order to support operators on Counter types, their value has to be extracted from internal
+ // representation. See CASSANDRA-11629
+ if (column.type.isCounter())
+ {
+ ByteBuffer foundValue = getValue(metadata, partitionKey, row);
+ if (foundValue == null)
return false;
- }
- else
- {
- ByteBuffer foundValue = getValue(metadata, partitionKey, row);
- if (foundValue == null)
- return false;
-
- switch (type.kind)
- {
- case LIST:
- ListType<?> listType = (ListType<?>)type;
- return listType.compose(foundValue).contains(listType.getElementsType().compose(value));
- case SET:
- SetType<?> setType = (SetType<?>)type;
- return setType.compose(foundValue).contains(setType.getElementsType().compose(value));
- case MAP:
- MapType<?,?> mapType = (MapType<?, ?>)type;
- return mapType.compose(foundValue).containsValue(mapType.getValuesType().compose(value));
- }
- throw new AssertionError();
- }
- case CONTAINS_KEY:
- assert column.type.isCollection() && column.type instanceof MapType;
- MapType<?, ?> mapType = (MapType<?, ?>)column.type;
- if (column.isComplex())
- {
- return row.getCell(column, CellPath.create(value)) != null;
- }
- else
- {
- ByteBuffer foundValue = getValue(metadata, partitionKey, row);
- return foundValue != null && mapType.getSerializer().getSerializedValue(foundValue, value, mapType.getKeysType()) != null;
- }
+
+ ByteBuffer counterValue = LongType.instance.decompose(CounterContext.instance().total(foundValue, ByteBufferAccessor.instance));
+ return operator.isSatisfiedBy(LongType.instance, counterValue, value);
+ }
+ else
+ {
+ // Note that CQL expression are always of the form 'x < 4', i.e. the tested value is on the left.
+ ByteBuffer foundValue = getValue(metadata, partitionKey, row);
+ return foundValue != null && operator.isSatisfiedBy(column.type, foundValue, value);
+ }
+ }
+ else if (operator.appliesToCollectionElements() || operator.appliesToMapKeys())
+ {
+ assert column.type.isCollection();
+ CollectionType<?> type = (CollectionType<?>) column.type;
+ if (column.isComplex())
+ {
+ ComplexColumnData complexData = row.getComplexColumnData(column);
+ return complexData != null && operator.isSatisfiedBy(type, complexData, value);
+ }
+ else
+ {
+ ByteBuffer foundValue = getValue(metadata, partitionKey, row);
+ return foundValue != null && operator.isSatisfiedBy(column.type, foundValue, value);
+ }
}
throw new AssertionError();
}
@@ -848,11 +764,11 @@ public class RowFilter implements Iterable<RowFilter.Expression>
* An expression of the form 'column' ['key'] = 'value' (which is only
* supported when 'column' is a map).
*/
- private static class MapEqualityExpression extends Expression
+ private static class MapElementExpression extends Expression
{
private final ByteBuffer key;
- public MapEqualityExpression(ColumnMetadata column, ByteBuffer key, Operator operator, ByteBuffer value)
+ public MapElementExpression(ColumnMetadata column, ByteBuffer key, Operator operator, ByteBuffer value)
{
super(column, operator, value);
assert column.type instanceof MapType && operator == Operator.EQ;
@@ -884,11 +800,11 @@ public class RowFilter implements Iterable<RowFilter.Expression>
if (row.isStatic() != column.isStatic())
return true;
- MapType<?, ?> mt = (MapType<?, ?>)column.type;
+ MapType<?, ?> mt = (MapType<?, ?>) column.type;
if (column.isComplex())
{
Cell<?> cell = row.getCell(column, CellPath.create(key));
- return cell != null && mt.valueComparator().compare(cell.buffer(), value) == 0;
+ return cell != null && operator.isSatisfiedBy(mt.getValuesType(), cell.buffer(), value);
}
else
{
@@ -897,7 +813,7 @@ public class RowFilter implements Iterable<RowFilter.Expression>
return false;
ByteBuffer foundValue = mt.getSerializer().getSerializedValue(serializedMap, key, mt.getKeysType());
- return foundValue != null && mt.valueComparator().compare(foundValue, value) == 0;
+ return foundValue != null && operator.isSatisfiedBy(mt.getValuesType(), foundValue, value);
}
}
@@ -918,10 +834,10 @@ public class RowFilter implements Iterable<RowFilter.Expression>
if (this == o)
return true;
- if (!(o instanceof MapEqualityExpression))
+ if (!(o instanceof MapElementExpression))
return false;
- MapEqualityExpression that = (MapEqualityExpression)o;
+ MapElementExpression that = (MapElementExpression)o;
return Objects.equal(this.column.name, that.column.name)
&& Objects.equal(this.operator, that.operator)
@@ -938,7 +854,7 @@ public class RowFilter implements Iterable<RowFilter.Expression>
@Override
protected Kind kind()
{
- return Kind.MAP_EQUALITY;
+ return Kind.MAP_ELEMENT;
}
}
diff --git a/src/java/org/apache/cassandra/index/IndexRegistry.java b/src/java/org/apache/cassandra/index/IndexRegistry.java
index d29bb11db4..5fa91ca092 100644
--- a/src/java/org/apache/cassandra/index/IndexRegistry.java
+++ b/src/java/org/apache/cassandra/index/IndexRegistry.java
@@ -22,6 +22,7 @@ package org.apache.cassandra.index;
import java.util.Collection;
import java.util.Collections;
+import java.util.Iterator;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.Callable;
@@ -57,7 +58,7 @@ import org.apache.cassandra.service.ClientState;
* i) subscribe to the stream of updates being applied to partitions in the base table
* ii) provide searchers to support queries with the relevant search predicates
*/
-public interface IndexRegistry
+public interface IndexRegistry extends Iterable<Index>
{
/**
* An empty {@code IndexRegistry}
@@ -315,6 +316,12 @@ public interface IndexRegistry
Index getIndex(IndexMetadata indexMetadata);
Collection<Index> listIndexes();
+ @Override
+ default Iterator<Index> iterator()
+ {
+ return listIndexes().iterator();
+ }
+
Optional<Index> getBestIndexFor(RowFilter.Expression expression);
/**
diff --git a/src/java/org/apache/cassandra/index/sai/StorageAttachedIndex.java b/src/java/org/apache/cassandra/index/sai/StorageAttachedIndex.java
index b42a165f11..98a48b02e2 100644
--- a/src/java/org/apache/cassandra/index/sai/StorageAttachedIndex.java
+++ b/src/java/org/apache/cassandra/index/sai/StorageAttachedIndex.java
@@ -53,7 +53,8 @@ import org.apache.cassandra.cql3.CqlBuilder;
import org.apache.cassandra.cql3.Operator;
import org.apache.cassandra.cql3.QueryOptions;
import org.apache.cassandra.cql3.restrictions.Restriction;
-import org.apache.cassandra.cql3.restrictions.SingleColumnRestriction;
+import org.apache.cassandra.cql3.restrictions.SimpleRestriction;
+import org.apache.cassandra.cql3.restrictions.ClusteringElements;
import org.apache.cassandra.cql3.statements.schema.IndexTarget;
import org.apache.cassandra.db.CassandraWriteContext;
import org.apache.cassandra.db.ColumnFamilyStore;
@@ -453,14 +454,17 @@ public class StorageAttachedIndex implements Index
public Comparator<ByteBuffer> getPostQueryOrdering(Restriction restriction, QueryOptions options)
{
// For now, only support ANN
- assert restriction instanceof SingleColumnRestriction.AnnRestriction;
+ assert restriction instanceof SimpleRestriction
+ && ((SimpleRestriction) restriction).operator() == Operator.ANN;
Preconditions.checkState(indexTermType.isVector());
- SingleColumnRestriction.AnnRestriction annRestriction = (SingleColumnRestriction.AnnRestriction) restriction;
+ SimpleRestriction annRestriction = (SimpleRestriction) restriction;
VectorSimilarityFunction function = indexWriterConfig.getSimilarityFunction();
- float[] target = indexTermType.decomposeVector(annRestriction.value(options).duplicate());
+ List<ClusteringElements> elementsList = annRestriction.values(options);
+ ByteBuffer serializedVector = elementsList.get(0).get(0).duplicate();
+ float[] target = indexTermType.decomposeVector(serializedVector);
return (leftBuf, rightBuf) -> {
float[] left = indexTermType.decomposeVector(leftBuf.duplicate());
diff --git a/src/java/org/apache/cassandra/schema/ColumnMetadata.java b/src/java/org/apache/cassandra/schema/ColumnMetadata.java
index f6c5bf0ced..682db5124d 100644
--- a/src/java/org/apache/cassandra/schema/ColumnMetadata.java
+++ b/src/java/org/apache/cassandra/schema/ColumnMetadata.java
@@ -512,7 +512,6 @@ public final class ColumnMetadata extends ColumnSpecification implements Selecta
return sb.toString();
}
-
public void appendNameAndOrderTo(CqlBuilder builder)
{
builder.append(name.toCQLString())
@@ -556,6 +555,22 @@ public final class ColumnMetadata extends ColumnSpecification implements Selecta
return type;
}
+ /**
+ * Returns the types of the differents columns.
+ *
+ * @param columns the columns for which the types must be returned.
+ * @return the types of the differents columns.
+ */
+ public static List<AbstractType<?>> typesOf(List<ColumnMetadata> columns)
+ {
+ List<AbstractType<?>> types = new ArrayList<>(columns.size());
+ for (ColumnMetadata column : columns)
+ {
+ types.add(column.type);
+ }
+ return types;
+ }
+
public static class Serializer implements UDTAndFunctionsAwareMetadataSerializer<ColumnMetadata>
{
public void serialize(ColumnMetadata t, DataOutputPlus out, Version version) throws IOException
diff --git a/test/unit/org/apache/cassandra/cql3/RelationTest.java b/test/unit/org/apache/cassandra/cql3/RelationTest.java
new file mode 100644
index 0000000000..4d59b1c884
--- /dev/null
+++ b/test/unit/org/apache/cassandra/cql3/RelationTest.java
@@ -0,0 +1,81 @@
+/*
+ * 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.util.List;
+
+import org.junit.Test;
+
+import org.apache.cassandra.cql3.functions.FunctionCall;
+import org.apache.cassandra.cql3.functions.FunctionName;
+import org.apache.cassandra.cql3.terms.Constants;
+import org.apache.cassandra.cql3.terms.InMarker;
+import org.apache.cassandra.cql3.terms.Marker;
+import org.apache.cassandra.cql3.terms.Term;
+import org.apache.cassandra.cql3.terms.Terms;
+import org.apache.cassandra.cql3.terms.Tuples;
+
+import static java.util.Arrays.asList;
+import static org.apache.cassandra.cql3.Relation.mapElement;
+import static org.apache.cassandra.cql3.Relation.multiColumn;
+import static org.apache.cassandra.cql3.Relation.singleColumn;
+import static org.apache.cassandra.cql3.Relation.token;
+import static org.junit.Assert.assertEquals;
+
+public class RelationTest
+{
+ @Test
+ public void toCQLStringTest()
+ {
+ ColumnIdentifier col = new ColumnIdentifier("col", false);
+ ColumnIdentifier col2 = new ColumnIdentifier("col2", false);
+ Marker.Raw marker = new Marker.Raw(0);
+ InMarker.Raw inMarker = new InMarker.Raw(0);
+ Term.Raw one = Constants.Literal.integer("1");
+ Term.Raw two = Constants.Literal.integer("2");
+ Term.Raw three = Constants.Literal.integer("3");
+ Terms.Raw oneTwo = Terms.Raw.of(asList(one, two));
+ Term.Raw text = Constants.Literal.string("text");
+
+ assertEquals("col = ?", singleColumn(col, Operator.EQ, marker).toCQLString());
+ assertEquals("col = 2", singleColumn(col, Operator.EQ, two).toCQLString());
+ assertEquals("col = 'text'", singleColumn(col, Operator.EQ, text).toCQLString());
+ assertEquals("col >= ?", singleColumn(col, Operator.GTE, marker).toCQLString());
+ assertEquals("col IN ?", singleColumn(col, Operator.IN, inMarker).toCQLString());
+ assertEquals("col IN (1, 2)", singleColumn(col, Operator.IN, oneTwo).toCQLString());
+ assertEquals("col IN (1)", singleColumn(col, Operator.IN, Terms.Raw.of(List.of(one))).toCQLString());
+
+ Term.Raw tuple1 = new Tuples.Literal(asList(one, two));
+ Term.Raw tuple2 = new Tuples.Literal(asList(two, three));
+ Terms.Raw tuples = Terms.Raw.of(asList(tuple1, tuple2));
+
+ assertEquals("(col, col2) = ?", multiColumn(asList(col, col2), Operator.EQ, marker).toCQLString());
+ assertEquals("(col, col2) = (1, 2)", multiColumn(asList(col, col2), Operator.EQ, tuple1).toCQLString());
+ assertEquals("(col, col2) IN ((1, 2), (2, 3))", multiColumn(asList(col, col2), Operator.IN, tuples).toCQLString());
+ assertEquals("(col, col2) IN ?", multiColumn(asList(col, col2), Operator.IN, inMarker).toCQLString());
+
+ Term.Raw tokenCall = new FunctionCall.Raw(FunctionName.nativeFunction("token"), asList(one, two));
+
+ assertEquals("token(col, col2) = ?", token(asList(col, col2), Operator.EQ, marker).toCQLString());
+ assertEquals("token(col, col2) = token(1, 2)", token(asList(col, col2), Operator.EQ, tokenCall).toCQLString());
+
+ assertEquals("col['text'] = ?", mapElement(col, text, Operator.EQ, marker).toCQLString());
+ assertEquals("col[?] = ?", mapElement(col, marker, Operator.EQ, marker).toCQLString());
+ }
+}
diff --git a/test/unit/org/apache/cassandra/cql3/restrictions/ClusteringColumnRestrictionsTest.java b/test/unit/org/apache/cassandra/cql3/restrictions/ClusteringColumnRestrictionsTest.java
index 815e5aca45..a8fda344bc 100644
--- a/test/unit/org/apache/cassandra/cql3/restrictions/ClusteringColumnRestrictionsTest.java
+++ b/test/unit/org/apache/cassandra/cql3/restrictions/ClusteringColumnRestrictionsTest.java
@@ -20,7 +20,6 @@ package org.apache.cassandra.cql3.restrictions;
import java.nio.ByteBuffer;
import java.util.*;
-import com.google.common.collect.Iterables;
import org.junit.BeforeClass;
import org.junit.Test;
@@ -33,7 +32,6 @@ import org.apache.cassandra.schema.ColumnMetadata;
import org.apache.cassandra.schema.TableMetadata;
import org.apache.cassandra.config.DatabaseDescriptor;
import org.apache.cassandra.cql3.*;
-import org.apache.cassandra.cql3.statements.Bound;
import org.apache.cassandra.db.*;
import org.apache.cassandra.db.marshal.AbstractType;
@@ -60,13 +58,9 @@ public class ClusteringColumnRestrictionsTest
ClusteringColumnRestrictions restrictions = restrictions(tableMetadata);
- SortedSet<ClusteringBound<?>> bounds = restrictions.boundsAsClustering(Bound.START, QueryOptions.DEFAULT);
- assertEquals(1, bounds.size());
... 4397 lines suppressed ...
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@cassandra.apache.org
For additional commands, e-mail: commits-help@cassandra.apache.org