Skip to content
Original file line number Diff line number Diff line change
Expand Up @@ -29,11 +29,9 @@
import org.apache.calcite.rex.RexCall;
import org.apache.calcite.rex.RexNode;
import org.apache.calcite.rex.RexShuttle;
import org.apache.calcite.rex.RexUnknownAs;
import org.apache.calcite.rex.RexUtil;
import org.apache.calcite.sql.fun.SqlStdOperatorTable;
import org.apache.hadoop.hive.ql.optimizer.calcite.HiveRelFactories;
import org.apache.hadoop.hive.ql.optimizer.calcite.SearchTransformer;
import org.apache.hadoop.hive.ql.optimizer.calcite.reloperators.HiveIn;
import org.apache.hadoop.hive.ql.optimizer.calcite.translator.RexNodeConverter;

Expand Down Expand Up @@ -152,9 +150,6 @@ private RexInBetweenExpander(RexBuilder rexBuilder) {
@Override
public RexNode visitCall(final RexCall call) {
switch (call.getKind()) {
case SEARCH: {
return new SearchTransformer<>(rexBuilder, call, RexUnknownAs.UNKNOWN).transform().accept(this);
}
case AND: {
boolean[] update = {false};
List<RexNode> newOperands = visitList(call.operands, update);
Expand Down Expand Up @@ -182,16 +177,13 @@ public RexNode visitCall(final RexCall call) {
}
default:
if (HiveIn.INSTANCE.equals(call.op)) {
List<RexNode> newOperands = RexNodeConverter.transformInToOrOperands(call.getOperands(), rexBuilder);
if (newOperands == null) {
RexNode newCall = RexNodeConverter.rewriteInClause(call.getOperands(), rexBuilder);
if (newCall == null) {
// We could not execute transformation, return expression
return call;
}
modified = true;
if (newOperands.size() > 1) {
return rexBuilder.makeCall(SqlStdOperatorTable.OR, newOperands);
}
return newOperands.get(0);
return newCall;
}
return super.visitCall(call);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,8 +39,10 @@
import org.apache.calcite.rex.RexUnknownAs;
import org.apache.calcite.rex.RexUtil;
import org.apache.calcite.sql.SqlKind;
import org.apache.calcite.sql.fun.SqlStdOperatorTable;
import org.apache.calcite.util.Pair;
import org.apache.hadoop.hive.ql.optimizer.calcite.RelOptHiveTable;
import org.apache.hadoop.hive.ql.optimizer.calcite.SearchTransformer;
import org.apache.hadoop.hive.ql.optimizer.calcite.reloperators.HiveIn;
import org.apache.hadoop.hive.ql.plan.ColStatistics;
import org.apache.hadoop.hive.ql.stats.StatsUtils;
Expand Down Expand Up @@ -189,10 +191,14 @@ public RexNode visitCall(RexCall call) {
newOperands.add(operand);
}
}
if (newOperands.size() == 1) {
switch (newOperands.size()) {
case 1:
return rexBuilder.makeLiteral(false);
case 2:
return rexBuilder.makeCall(SqlStdOperatorTable.EQUALS, newOperands);
default:
return rexBuilder.makeCall(HiveIn.INSTANCE, newOperands);
}
return rexBuilder.makeCall(HiveIn.INSTANCE, newOperands);
}
} else if (call.getOperands().get(0).getKind() == SqlKind.ROW) {
// Struct
Expand Down Expand Up @@ -269,6 +275,13 @@ public RexNode visitCall(RexCall call) {
}
}
}
} else if (call.getKind() == SqlKind.SEARCH) {
RexNode expanded = new SearchTransformer<>(rexBuilder, call, RexUnknownAs.UNKNOWN).transform();
RexNode processed = expanded.accept(this);
if (expanded != processed) {
return processed;
}
return call;
}

// If we did not reduce, check the children nodes
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,10 @@
import org.apache.hadoop.hive.common.type.HiveVarchar;
import org.apache.hadoop.hive.common.type.Timestamp;
import org.apache.hadoop.hive.common.type.TimestampTZ;
import org.apache.hadoop.hive.conf.HiveConf;
import org.apache.hadoop.hive.ql.exec.FunctionRegistry;
import org.apache.hadoop.hive.ql.metadata.Hive;
import org.apache.hadoop.hive.ql.metadata.HiveException;
import org.apache.hadoop.hive.ql.optimizer.calcite.CalciteSemanticException;
import org.apache.hadoop.hive.ql.optimizer.calcite.CalciteSemanticException.UnsupportedFeature;
import org.apache.hadoop.hive.ql.optimizer.calcite.HiveCalciteUtil;
Expand Down Expand Up @@ -117,6 +120,16 @@ public class RexNodeConverter {
private final RexBuilder rexBuilder;
private final RelDataTypeFactory typeFactory;

private static final int MAX_NODES_FOR_IN_TO_OR_TRANSFORMATION;

static {
try {
MAX_NODES_FOR_IN_TO_OR_TRANSFORMATION = HiveConf.getIntVar(
Hive.get().getConf(), HiveConf.ConfVars.HIVEOPT_TRANSFORM_IN_MAXNODES);
} catch (HiveException e) {
throw new IllegalStateException(e);
}
}

/**
* Constructor used by HiveRexExecutorImpl.
Expand Down Expand Up @@ -259,19 +272,12 @@ private RexNode convert(ExprNodeGenericFuncDesc func) throws SemanticException {
// If it is a floor <date> operator, we need to rewrite it
childRexNodeLst = rewriteFloorDateChildren(calciteOp, childRexNodeLst, rexBuilder);
} else if (HiveIn.INSTANCE.equals(calciteOp) && isAllPrimitive) {
if (childRexNodeLst.size() == 2) {
// if it is a single item in an IN clause, transform A IN (B) to A = B
// from IN [A,B] => EQUALS [A,B]
// except complex types
calciteOp = SqlStdOperatorTable.EQUALS;
} else if (RexUtil.isReferenceOrAccess(childRexNodeLst.get(0), true)){
// if it is more than an single item in an IN clause,
// transform from IN [A,B,C] => OR [EQUALS [A,B], EQUALS [A,C]]
// except complex types
// Rewrite to OR is done only if number of operands are less than
// the threshold configured
childRexNodeLst = rewriteInClauseChildren(calciteOp, childRexNodeLst, rexBuilder);
calciteOp = SqlStdOperatorTable.OR;
if (childRexNodeLst.size() == 2 || RexUtil.isReferenceOrAccess(childRexNodeLst.get(0), true)) {
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why do we limit the transformation? What are the pros/cons of doing an unconditional rewrite?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just keeping the original logic to minimize the side effects of the change. I'll investigate why this condition was added in the first place and whether it can be removed...

RexNode rewritten = rewriteInClause(childRexNodeLst, rexBuilder);
assert rewritten instanceof RexCall;
RexCall call = (RexCall) rewritten;
calciteOp = call.op;
childRexNodeLst = call.operands;
}
} else if (calciteOp.getKind() == SqlKind.COALESCE &&
childRexNodeLst.size() > 1) {
Expand Down Expand Up @@ -577,17 +583,42 @@ public static List<RexNode> transformInToOrOperands(List<RexNode> operands, RexB
return disjuncts;
}

public static List<RexNode> rewriteInClauseChildren(SqlOperator op, List<RexNode> childRexNodeLst,
RexBuilder rexBuilder) throws SemanticException {
assert op == HiveIn.INSTANCE;
RexNode firstPred = childRexNodeLst.get(0);
List<RexNode> newChildRexNodeLst = new ArrayList<RexNode>();
for (int i = 1; i < childRexNodeLst.size(); i++) {
newChildRexNodeLst.add(
rexBuilder.makeCall(
SqlStdOperatorTable.EQUALS, firstPred, childRexNodeLst.get(i)));
/**
* This method tries to rewrite IN expression arguments into an equivalent call.
* If there are only two elements, generates an EQUALS:
* IN [A,B] => EQUALS [A,B]
* Otherwise, tries to generate a SEARCH:
* IN [A,B,C] => SEARCH(A, SARG([B..B], [C..C]))
* If this is not possible (e.g., argument types not sufficiently compatible to generate a Calcite SEARCH expression),
* tries to generate an OR expression:
* IN [A,B,C] => OR [EQUALS [A,B], EQUALS [A,C]]
* If this is not possible (e.g., non-deterministic calls are found in the expressions), returns null.
*/
public static RexNode rewriteInClause(List<RexNode> childRexNodeLst, RexBuilder rexBuilder) {
if (childRexNodeLst.size() == 2) {
return rexBuilder.makeCall(SqlStdOperatorTable.EQUALS, childRexNodeLst);
}
Comment on lines +598 to +600
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should this become part of RexBuilder#makeIn API if not already the case?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't know... Calcite's code just creates an IN with one element in this case, which is not incorrect (and I guess it's the expected behavior). I've just kept this special case on Hive's side for the moment to minimize side effects by this refactoring.

return newChildRexNodeLst;

RexNode arg = childRexNodeLst.get(0);
List<RexNode> ranges = childRexNodeLst.subList(1, childRexNodeLst.size());
// Avoid SEARCH on rows for the moment (it can lead to issues in Calcite), and check all types are SEARCH-compatible
if (!arg.getType().isStruct() && ranges.stream().allMatch(range -> range.getKind() == SqlKind.LITERAL
&& !RexLiteral.isNullLiteral(range)
&& SqlTypeUtil.inSameFamily(arg.getType(), range.getType()))) {
RexNode search = rexBuilder.makeIn(arg, ranges);
if (search.getKind() == SqlKind.SEARCH) {
return search;
}
}

// Calcite SEARCH conversion was not possible: generate our own OR expression
if (MAX_NODES_FOR_IN_TO_OR_TRANSFORMATION == 0 || childRexNodeLst.size() <= MAX_NODES_FOR_IN_TO_OR_TRANSFORMATION) {
List<RexNode> newInputs = RexNodeConverter.transformInToOrOperands(childRexNodeLst, rexBuilder);
if (newInputs != null) {
return newInputs.size() == 1 ? newInputs.get(0) : rexBuilder.makeCall(SqlStdOperatorTable.OR, newInputs);
}
}
return null;
}

public static List<RexNode> rewriteCoalesceChildren(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,12 +38,9 @@
import org.apache.calcite.sql.SqlOperator;
import org.apache.calcite.sql.fun.SqlStdOperatorTable;
import org.apache.calcite.util.Util;
import org.apache.hadoop.hive.conf.HiveConf;
import org.apache.hadoop.hive.ql.exec.FunctionInfo;
import org.apache.hadoop.hive.ql.exec.FunctionRegistry;
import org.apache.hadoop.hive.ql.exec.HiveFunctionInfo;
import org.apache.hadoop.hive.ql.metadata.Hive;
import org.apache.hadoop.hive.ql.metadata.HiveException;
import org.apache.hadoop.hive.ql.optimizer.calcite.HiveRexExecutorImpl;
import org.apache.hadoop.hive.ql.optimizer.calcite.reloperators.HiveExtractDate;
import org.apache.hadoop.hive.ql.optimizer.calcite.reloperators.HiveFloorDate;
Expand Down Expand Up @@ -102,16 +99,9 @@ public class HiveFunctionHelper implements FunctionHelper {
private static final Logger LOG = LoggerFactory.getLogger(HiveFunctionHelper.class);

private final RexBuilder rexBuilder;
private final int maxNodesForInToOrTransformation;

public HiveFunctionHelper(RexBuilder rexBuilder) {
this.rexBuilder = rexBuilder;
try {
this.maxNodesForInToOrTransformation = HiveConf.getIntVar(
Hive.get().getConf(), HiveConf.ConfVars.HIVEOPT_TRANSFORM_IN_MAXNODES);
} catch (HiveException e) {
throw new IllegalStateException(e);
}
}

/**
Expand Down Expand Up @@ -267,28 +257,12 @@ public RexNode getExpression(String functionText, FunctionInfo fi,
// If it is a floor <date> operator, we need to rewrite it
inputs = RexNodeConverter.rewriteFloorDateChildren(calciteOp, inputs, rexBuilder);
} else if (HiveIn.INSTANCE.equals(calciteOp)) {
// if it is a single item in an IN clause, transform A IN (B) to A = B
// from IN [A,B] => EQUALS [A,B]
// if it is more than an single item in an IN clause,
// transform from IN [A,B,C] => OR [EQUALS [A,B], EQUALS [A,C]]
// Rewrite to OR is done only if number of operands are less than
// the threshold configured
boolean rewriteToOr = true;
if(maxNodesForInToOrTransformation != 0) {
if(inputs.size() > maxNodesForInToOrTransformation) {
rewriteToOr = false;
}
}
if(rewriteToOr) {
// If there are non-deterministic functions, we cannot perform this rewriting
List<RexNode> newInputs = RexNodeConverter.transformInToOrOperands(inputs, rexBuilder);
if (newInputs != null) {
inputs = newInputs;
if (inputs.size() == 1) {
inputs.add(rexBuilder.makeLiteral(false));
}
calciteOp = SqlStdOperatorTable.OR;
}
RexNode rewritten = RexNodeConverter.rewriteInClause(inputs, rexBuilder);
if (rewritten != null) {
assert rewritten instanceof RexCall;
RexCall call = (RexCall) rewritten;
calciteOp = call.op;
inputs = call.operands;
}
} else if (calciteOp.getKind() == SqlKind.COALESCE &&
inputs.size() > 1) {
Expand Down
12 changes: 6 additions & 6 deletions ql/src/test/results/clientpositive/llap/in_typecheck_char.q.out
Original file line number Diff line number Diff line change
Expand Up @@ -238,10 +238,10 @@ STAGE PLANS:
Map Operator Tree:
TableScan
alias: ax
filterExpr: (((CAST( s AS STRING) = 'a') and (CAST( t AS STRING) = 'a')) or (null and (CAST( t AS STRING) = 'bb'))) is null (type: boolean)
filterExpr: ((struct(CAST( s AS STRING),CAST( t AS STRING)) = const struct('a','a')) or (struct(s,CAST( t AS STRING)) = const struct(null,'bb'))) is null (type: boolean)
Statistics: Num rows: 3 Data size: 510 Basic stats: COMPLETE Column stats: COMPLETE
Filter Operator
predicate: (((CAST( s AS STRING) = 'a') and (CAST( t AS STRING) = 'a')) or (null and (CAST( t AS STRING) = 'bb'))) is null (type: boolean)
predicate: ((struct(CAST( s AS STRING),CAST( t AS STRING)) = const struct('a','a')) or (struct(s,CAST( t AS STRING)) = const struct(null,'bb'))) is null (type: boolean)
Statistics: Num rows: 1 Data size: 170 Basic stats: COMPLETE Column stats: COMPLETE
Select Operator
Statistics: Num rows: 1 Data size: 170 Basic stats: COMPLETE Column stats: COMPLETE
Expand Down Expand Up @@ -292,7 +292,7 @@ POSTHOOK: query: select 'expected 1',count(*) from ax where ((s,t) in (('a','a')
POSTHOOK: type: QUERY
POSTHOOK: Input: default@ax
#### A masked pattern was here ####
expected 1 1
expected 1 0
PREHOOK: query: explain cbo select count(*) from ax where t in
('a','bb','aa','bbb','ab','ba','aaa','bbb','abc','bc','ac','bca','cab','cb','ca','cbc','z')
PREHOOK: type: QUERY
Expand Down Expand Up @@ -390,7 +390,7 @@ POSTHOOK: Input: default@ax
CBO PLAN:
HiveProject(_c0=[$0])
HiveAggregate(group=[{}], agg#0=[count()])
HiveFilter(condition=[IN($1, _UTF-16LE'a', _UTF-16LE'aa', _UTF-16LE'aaa', _UTF-16LE'ab', _UTF-16LE'abc', _UTF-16LE'ac', _UTF-16LE'ba', _UTF-16LE'bb', _UTF-16LE'bbb', _UTF-16LE'bc', _UTF-16LE'bca', _UTF-16LE'ca', _UTF-16LE'cab', _UTF-16LE'cb', _UTF-16LE'cbc', _UTF-16LE'z')])
HiveFilter(condition=[IN($1, _UTF-16LE'a ', _UTF-16LE'bb ', _UTF-16LE'aa ', _UTF-16LE'bbb ', _UTF-16LE'ab ', _UTF-16LE'ba ', _UTF-16LE'aaa ', _UTF-16LE'bbb ', _UTF-16LE'abc ', _UTF-16LE'bc ', _UTF-16LE'ac ', _UTF-16LE'bca ', _UTF-16LE'cab ', _UTF-16LE'cb ', _UTF-16LE'ca ', _UTF-16LE'cbc ', _UTF-16LE'z ')])
HiveTableScan(table=[[default, ax]], table:alias=[ax])

PREHOOK: query: explain select count(*) from ax where t in
Expand Down Expand Up @@ -419,10 +419,10 @@ STAGE PLANS:
Map Operator Tree:
TableScan
alias: ax
filterExpr: (t) IN ('a ', 'aa ', 'aaa ', 'ab ', 'abc ', 'ac ', 'ba ', 'bb ', 'bbb ', 'bc ', 'bca ', 'ca ', 'cab ', 'cb ', 'cbc ', 'z ') (type: boolean)
filterExpr: (t) IN ('a ', 'bb ', 'aa ', 'bbb ', 'ab ', 'ba ', 'aaa ', 'bbb ', 'abc ', 'bc ', 'ac ', 'bca ', 'cab ', 'cb ', 'ca ', 'cbc ', 'z ') (type: boolean)
Statistics: Num rows: 3 Data size: 255 Basic stats: COMPLETE Column stats: COMPLETE
Filter Operator
predicate: (t) IN ('a ', 'aa ', 'aaa ', 'ab ', 'abc ', 'ac ', 'ba ', 'bb ', 'bbb ', 'bc ', 'bca ', 'ca ', 'cab ', 'cb ', 'cbc ', 'z ') (type: boolean)
predicate: (t) IN ('a ', 'bb ', 'aa ', 'bbb ', 'ab ', 'ba ', 'aaa ', 'bbb ', 'abc ', 'bc ', 'ac ', 'bca ', 'cab ', 'cb ', 'ca ', 'cbc ', 'z ') (type: boolean)
Statistics: Num rows: 3 Data size: 255 Basic stats: COMPLETE Column stats: COMPLETE
Select Operator
Statistics: Num rows: 3 Data size: 255 Basic stats: COMPLETE Column stats: COMPLETE
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -80,4 +80,4 @@ POSTHOOK: query: select 'expected 1',count(*) from ax where ((s,t) in (('a','a')
POSTHOOK: type: QUERY
POSTHOOK: Input: default@ax
#### A masked pattern was here ####
expected 1 1
expected 1 0
Original file line number Diff line number Diff line change
Expand Up @@ -133,11 +133,11 @@ STAGE PLANS:
Processor Tree:
TableScan
alias: emps_n7
filterExpr: ((deptno = 2) and ((empno + 1) = 3)) (type: boolean)
filterExpr: (struct((empno + 1),deptno) = const struct(3,2)) (type: boolean)
Filter Operator
predicate: ((deptno = 2) and ((empno + 1) = 3)) (type: boolean)
predicate: (struct((empno + 1),deptno) = const struct(3,2)) (type: boolean)
Select Operator
expressions: empno (type: int), 2 (type: int), empname (type: string)
expressions: empno (type: int), deptno (type: int), empname (type: string)
outputColumnNames: _col0, _col1, _col2
ListSink

Expand All @@ -161,9 +161,9 @@ STAGE PLANS:
Processor Tree:
TableScan
alias: emps_n7
filterExpr: ((deptno <> 2) or ((empno + 1) <> 3)) (type: boolean)
filterExpr: (struct((empno + 1),deptno) <> const struct(3,2)) (type: boolean)
Filter Operator
predicate: ((deptno <> 2) or ((empno + 1) <> 3)) (type: boolean)
predicate: (struct((empno + 1),deptno) <> const struct(3,2)) (type: boolean)
Select Operator
expressions: empno (type: int), deptno (type: int), empname (type: string)
outputColumnNames: _col0, _col1, _col2
Expand All @@ -187,11 +187,11 @@ STAGE PLANS:
Processor Tree:
TableScan
alias: emps_n7
filterExpr: ((deptno = 2) and (((empno * 2) | 1) = (empno + 2))) (type: boolean)
filterExpr: (struct(((empno * 2) | 1),deptno) = struct((empno + 2),2)) (type: boolean)
Filter Operator
predicate: ((deptno = 2) and (((empno * 2) | 1) = (empno + 2))) (type: boolean)
predicate: (struct(((empno * 2) | 1),deptno) = struct((empno + 2),2)) (type: boolean)
Select Operator
expressions: empno (type: int), 2 (type: int), empname (type: string)
expressions: empno (type: int), deptno (type: int), empname (type: string)
outputColumnNames: _col0, _col1, _col2
ListSink

Expand Down
Loading
Loading