Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

CASSANDRA-19931: Support OR operator and sub-conditions in query builder #1965

Draft
wants to merge 2 commits into
base: 4.x
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
import com.datastax.oss.driver.api.core.type.codec.registry.CodecRegistry;
import com.datastax.oss.driver.api.querybuilder.delete.DeleteSelection;
import com.datastax.oss.driver.api.querybuilder.insert.InsertInto;
import com.datastax.oss.driver.api.querybuilder.relation.OngoingWhereClause;
import com.datastax.oss.driver.api.querybuilder.relation.Relation;
import com.datastax.oss.driver.api.querybuilder.select.SelectFrom;
import com.datastax.oss.driver.api.querybuilder.select.Selector;
Expand All @@ -43,6 +44,7 @@
import com.datastax.oss.driver.internal.querybuilder.DefaultRaw;
import com.datastax.oss.driver.internal.querybuilder.delete.DefaultDelete;
import com.datastax.oss.driver.internal.querybuilder.insert.DefaultInsert;
import com.datastax.oss.driver.internal.querybuilder.relation.DefaultSubConditionRelation;
import com.datastax.oss.driver.internal.querybuilder.select.DefaultBindMarker;
import com.datastax.oss.driver.internal.querybuilder.select.DefaultSelect;
import com.datastax.oss.driver.internal.querybuilder.term.BinaryArithmeticTerm;
Expand Down Expand Up @@ -538,4 +540,10 @@ public static Truncate truncate(@Nullable String keyspace, @NonNull String table
return truncate(
keyspace == null ? null : CqlIdentifier.fromCql(keyspace), CqlIdentifier.fromCql(table));
}

/** Creates new sub-condition in the WHERE clause, surrounded by parenthesis. */
@NonNull
public static OngoingWhereClause<DefaultSubConditionRelation> subCondition() {
return new DefaultSubConditionRelation(true);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
import com.datastax.oss.driver.internal.querybuilder.relation.DefaultColumnRelationBuilder;
import com.datastax.oss.driver.internal.querybuilder.relation.DefaultMultiColumnRelationBuilder;
import com.datastax.oss.driver.internal.querybuilder.relation.DefaultTokenRelationBuilder;
import com.datastax.oss.driver.internal.querybuilder.relation.LogicalRelation;
import edu.umd.cs.findbugs.annotations.CheckReturnValue;
import edu.umd.cs.findbugs.annotations.NonNull;
import java.util.Arrays;
Expand All @@ -47,6 +48,20 @@ public interface OngoingWhereClause<SelfT extends OngoingWhereClause<SelfT>> {
@CheckReturnValue
SelfT where(@NonNull Relation relation);

/** Adds conjunction clause. Next relation is logically joined with AND. */
@NonNull
@CheckReturnValue
default SelfT and() {
return where(LogicalRelation.AND);
}

/** Adds alternative clause. Next relation is logically joined with OR. */
@NonNull
@CheckReturnValue
default SelfT or() {
return where(LogicalRelation.OR);
}

/**
* Adds multiple relations at once. All relations are logically joined with AND.
*
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,161 @@
/*
* 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 com.datastax.oss.driver.internal.querybuilder.relation;

import com.datastax.oss.driver.api.core.cql.SimpleStatement;
import com.datastax.oss.driver.api.core.cql.SimpleStatementBuilder;
import com.datastax.oss.driver.api.querybuilder.BuildableQuery;
import com.datastax.oss.driver.api.querybuilder.CqlSnippet;
import com.datastax.oss.driver.api.querybuilder.relation.OngoingWhereClause;
import com.datastax.oss.driver.api.querybuilder.relation.Relation;
import edu.umd.cs.findbugs.annotations.NonNull;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class DefaultSubConditionRelation
implements OngoingWhereClause<DefaultSubConditionRelation>, BuildableQuery, Relation {

private final List<Relation> relations;
private final boolean isSubCondition;

/** Construct sub-condition relation with empty WHERE clause. */
public DefaultSubConditionRelation(boolean isSubCondition) {
this.relations = new ArrayList<>();
this.isSubCondition = isSubCondition;
}

@NonNull
@Override
public DefaultSubConditionRelation where(@NonNull Relation relation) {
relations.add(relation);
return this;
}

@NonNull
@Override
public DefaultSubConditionRelation where(@NonNull Iterable<Relation> additionalRelations) {
for (Relation relation : additionalRelations) {
relations.add(relation);
}
return this;
}

@NonNull
public DefaultSubConditionRelation withRelations(@NonNull List<Relation> newRelations) {
relations.addAll(newRelations);
return this;
}

@NonNull
@Override
public String asCql() {
StringBuilder builder = new StringBuilder();

if (isSubCondition) {
builder.append("(");
}
appendWhereClause(builder, relations, isSubCondition);
if (isSubCondition) {
builder.append(")");
}

return builder.toString();
}

public static void appendWhereClause(
StringBuilder builder, List<Relation> relations, boolean isSubCondition) {
boolean first = true;
for (int i = 0; i < relations.size(); ++i) {
CqlSnippet snippet = relations.get(i);
if (first && !isSubCondition) {
builder.append(" WHERE ");
}
first = false;

snippet.appendTo(builder);

boolean logicalOperatorAdded = false;
LogicalRelation logicalRelation = lookAheadNextRelation(relations, i, LogicalRelation.class);
if (logicalRelation != null) {
builder.append(" ");
logicalRelation.appendTo(builder);
builder.append(" ");
logicalOperatorAdded = true;
++i;
}
if (!logicalOperatorAdded && i + 1 < relations.size()) {
builder.append(" AND ");
}
}
}

private static <T extends Relation> T lookAheadNextRelation(
List<Relation> relations, int position, Class<T> clazz) {
if (position + 1 >= relations.size()) {
return null;
}
Relation relation = relations.get(position + 1);
if (relation.getClass().isAssignableFrom(clazz)) {
return (T) relation;
}
return null;
}

@NonNull
@Override
public SimpleStatement build() {
return builder().build();
}

@NonNull
@Override
public SimpleStatement build(@NonNull Object... values) {
return builder().addPositionalValues(values).build();
}

@NonNull
@Override
public SimpleStatement build(@NonNull Map<String, Object> namedValues) {
SimpleStatementBuilder builder = builder();
for (Map.Entry<String, Object> entry : namedValues.entrySet()) {
builder.addNamedValue(entry.getKey(), entry.getValue());
}
return builder.build();
}

@Override
public String toString() {
return asCql();
}

@Override
public void appendTo(@NonNull StringBuilder builder) {
builder.append(asCql());
}

@Override
public boolean isIdempotent() {
for (Relation relation : relations) {
if (!relation.isIdempotent()) {
return false;
}
}
return true;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
/*
* 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 com.datastax.oss.driver.internal.querybuilder.relation;

import com.datastax.oss.driver.api.querybuilder.relation.Relation;
import com.datastax.oss.driver.shaded.guava.common.base.Preconditions;
import edu.umd.cs.findbugs.annotations.NonNull;
import net.jcip.annotations.Immutable;

@Immutable
public class LogicalRelation implements Relation {
public static final LogicalRelation AND = new LogicalRelation("AND");
public static final LogicalRelation OR = new LogicalRelation("OR");

private final String operator;

public LogicalRelation(@NonNull String operator) {
Preconditions.checkNotNull(operator);
this.operator = operator;
}

@Override
public void appendTo(@NonNull StringBuilder builder) {
builder.append(operator);
}

@Override
public boolean isIdempotent() {
return true;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
import com.datastax.oss.driver.api.querybuilder.select.Selector;
import com.datastax.oss.driver.internal.querybuilder.CqlHelper;
import com.datastax.oss.driver.internal.querybuilder.ImmutableCollections;
import com.datastax.oss.driver.internal.querybuilder.relation.DefaultSubConditionRelation;
import com.datastax.oss.driver.shaded.guava.common.base.Preconditions;
import com.datastax.oss.driver.shaded.guava.common.collect.ImmutableList;
import com.datastax.oss.driver.shaded.guava.common.collect.ImmutableMap;
Expand Down Expand Up @@ -388,7 +389,8 @@ public String asCql() {
builder.append(" FROM ");
CqlHelper.qualify(keyspace, table, builder);

CqlHelper.append(relations, builder, " WHERE ", " AND ", null);
DefaultSubConditionRelation.appendWhereClause(builder, relations, false);

CqlHelper.append(groupByClauses, builder, " GROUP BY ", ",", null);

boolean first = true;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
import static com.datastax.oss.driver.api.querybuilder.QueryBuilder.function;
import static com.datastax.oss.driver.api.querybuilder.QueryBuilder.insertInto;
import static com.datastax.oss.driver.api.querybuilder.QueryBuilder.selectFrom;
import static com.datastax.oss.driver.api.querybuilder.QueryBuilder.subCondition;
import static com.datastax.oss.driver.api.querybuilder.QueryBuilder.tuple;
import static com.datastax.oss.driver.api.querybuilder.QueryBuilder.update;
import static org.assertj.core.api.Assertions.assertThat;
Expand Down Expand Up @@ -49,6 +50,37 @@ public static Object[][] sampleQueries() {
"SELECT * FROM foo WHERE k=:k",
true
},
{
selectFrom("foo")
.all()
.whereColumn("k")
.isEqualTo(bindMarker("k"))
.or()
.whereColumn("l")
.isEqualTo(bindMarker("l")),
ImmutableMap.of("k", 1, "l", 2),
"SELECT * FROM foo WHERE k=:k OR l=:l",
true
},
{
selectFrom("foo")
.all()
.whereColumn("k")
.isEqualTo(bindMarker("k"))
.and()
.where(
subCondition()
.whereColumn("l")
.isEqualTo(bindMarker("l"))
.or()
.whereColumn("m")
.isEqualTo(bindMarker("m")))
.whereColumn("n")
.isEqualTo(bindMarker("n")),
ImmutableMap.of("k", 1, "l", 2, "m", 3, "n", 4),
"SELECT * FROM foo WHERE k=:k AND (l=:l OR m=:m) AND n=:n",
true
},
{
deleteFrom("foo").whereColumn("k").isEqualTo(bindMarker("k")),
ImmutableMap.of("k", 1),
Expand Down
Loading