org.apache.calcite.sql.SqlOperator Java Examples

The following examples show how to use org.apache.calcite.sql.SqlOperator. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: RelJson.java    From Bats with Apache License 2.0 6 votes vote down vote up
SqlOperator toOp(RelInput relInput, String op, Map<String, Object> map) {
  // TODO: build a map, for more efficient lookup
  // TODO: look up based on SqlKind
  final List<SqlOperator> operatorList =
      SqlStdOperatorTable.instance().getOperatorList();
  for (SqlOperator operator : operatorList) {
    if (operator.getName().equals(op)) {
      return operator;
    }
  }
  String class_ = (String) map.get("class");
  if (class_ != null) {
    return PluginUtils.instantiatePlugin(SqlOperator.class, class_);
  }
  return null;
}
 
Example #2
Source File: ListSqlOperatorTable.java    From Bats with Apache License 2.0 6 votes vote down vote up
public void lookupOperatorOverloads(SqlIdentifier opName,
    SqlFunctionCategory category,
    SqlSyntax syntax,
    List<SqlOperator> operatorList) {
  for (SqlOperator operator : this.operatorList) {
    if (operator.getSyntax() != syntax) {
      continue;
    }
    if (!opName.isSimple()
        || !operator.isName(opName.getSimple())) {
      continue;
    }
    if (category != null
        && category != category(operator)
        && !category.isUserDefinedNotSpecificFunction()) {
      continue;
    }
    operatorList.add(operator);
  }
}
 
Example #3
Source File: CompositeOperandTypeChecker.java    From Bats with Apache License 2.0 6 votes vote down vote up
public String getAllowedSignatures(SqlOperator op, String opName) {
  if (allowedSignatures != null) {
    return allowedSignatures;
  }
  if (composition == Composition.SEQUENCE) {
    throw new AssertionError(
        "specify allowedSignatures or override getAllowedSignatures");
  }
  StringBuilder ret = new StringBuilder();
  for (Ord<SqlOperandTypeChecker> ord
      : Ord.<SqlOperandTypeChecker>zip(allowedRules)) {
    if (ord.i > 0) {
      ret.append(SqlOperator.NL);
    }
    ret.append(ord.e.getAllowedSignatures(op, opName));
    if (composition == Composition.AND) {
      break;
    }
  }
  return ret.toString();
}
 
Example #4
Source File: SqlValidatorImpl.java    From Flink-CEPplus with Apache License 2.0 6 votes vote down vote up
private SqlNode navigationInMeasure(SqlNode node, boolean allRows) {
	final Set<String> prefix = node.accept(new PatternValidator(true));
	Util.discard(prefix);
	final List<SqlNode> ops = ((SqlCall) node).getOperandList();

	final SqlOperator defaultOp =
		allRows ? SqlStdOperatorTable.RUNNING : SqlStdOperatorTable.FINAL;
	final SqlNode op0 = ops.get(0);
	if (!isRunningOrFinal(op0.getKind())
		|| !allRows && op0.getKind() == SqlKind.RUNNING) {
		SqlNode newNode = defaultOp.createCall(SqlParserPos.ZERO, op0);
		node = SqlStdOperatorTable.AS.createCall(SqlParserPos.ZERO, newNode, ops.get(1));
	}

	node = new NavigationExpander().go(node);
	return node;
}
 
Example #5
Source File: SqlNodeConverter.java    From kylin-on-parquet-v2 with Apache License 2.0 6 votes vote down vote up
private SqlNode convertSqlCall(SqlCall sqlCall) {
    SqlOperator operator = sqlCall.getOperator();
    if (operator != null) {
        Pair<SqlNode, SqlNode> matched = convMaster.matchSqlFunc(sqlCall);

        if (matched != null) {
            Preconditions.checkState(matched.getFirst() instanceof SqlCall);
            SqlCall sourceTmpl = (SqlCall) matched.getFirst();

            Preconditions.checkState(sourceTmpl.operandCount() == sqlCall.operandCount());
            SqlNode targetTmpl = matched.getSecond();

            boolean isWindowCall = sourceTmpl.getOperator() instanceof SqlOverOperator;
            SqlParamsFinder sqlParamsFinder = SqlParamsFinder.newInstance(sourceTmpl, sqlCall, isWindowCall);
            return targetTmpl.accept(new SqlFuncFiller(sqlParamsFinder.getParamNodes(), isWindowCall));
        }
    }
    return null;
}
 
Example #6
Source File: FunctionCatalogOperatorTable.java    From flink with Apache License 2.0 6 votes vote down vote up
@Override
public void lookupOperatorOverloads(
		SqlIdentifier opName,
		SqlFunctionCategory category,
		SqlSyntax syntax,
		List<SqlOperator> operatorList,
		SqlNameMatcher nameMatcher) {
	if (opName.isStar()) {
		return;
	}

	final UnresolvedIdentifier identifier = UnresolvedIdentifier.of(opName.names);

	functionCatalog.lookupFunction(identifier)
		.flatMap(lookupResult ->
			convertToSqlFunction(
				category,
				lookupResult.getFunctionIdentifier(),
				lookupResult.getFunctionDefinition()))
		.ifPresent(operatorList::add);
}
 
Example #7
Source File: RelOptUtil.java    From calcite with Apache License 2.0 6 votes vote down vote up
public static SqlOperator op(SqlKind kind, SqlOperator operator) {
  switch (kind) {
  case EQUALS:
    return SqlStdOperatorTable.EQUALS;
  case NOT_EQUALS:
    return SqlStdOperatorTable.NOT_EQUALS;
  case GREATER_THAN:
    return SqlStdOperatorTable.GREATER_THAN;
  case GREATER_THAN_OR_EQUAL:
    return SqlStdOperatorTable.GREATER_THAN_OR_EQUAL;
  case LESS_THAN:
    return SqlStdOperatorTable.LESS_THAN;
  case LESS_THAN_OR_EQUAL:
    return SqlStdOperatorTable.LESS_THAN_OR_EQUAL;
  case IS_DISTINCT_FROM:
    return SqlStdOperatorTable.IS_DISTINCT_FROM;
  case IS_NOT_DISTINCT_FROM:
    return SqlStdOperatorTable.IS_NOT_DISTINCT_FROM;
  default:
    return operator;
  }
}
 
Example #8
Source File: HiveSqlOperatorTable.java    From marble with Apache License 2.0 5 votes vote down vote up
@Override public void lookupOperatorOverloads(final SqlIdentifier opName,
    final SqlFunctionCategory category, final SqlSyntax syntax,
    final List<SqlOperator> operatorList) {
  super.lookupOperatorOverloads(opName, category, syntax, operatorList);
  if (operatorList.size() == 0) {
    SqlStdOperatorTable.instance()
        .lookupOperatorOverloads(opName, category, syntax, operatorList);
  }

}
 
Example #9
Source File: SqlImplementor.java    From Bats with Apache License 2.0 5 votes vote down vote up
private SqlNode createLeftCall(SqlOperator op, List<SqlNode> nodeList) {
    SqlNode node = op.createCall(new SqlNodeList(nodeList.subList(0, 2), POS));
    for (int i = 2; i < nodeList.size(); i++) {
        node = op.createCall(new SqlNodeList(ImmutableList.of(node, nodeList.get(i)), POS));
    }
    return node;
}
 
Example #10
Source File: DruidQuery.java    From calcite with Apache License 2.0 5 votes vote down vote up
/** Creates a DruidQuery. */
public static DruidQuery create(RelOptCluster cluster, RelTraitSet traitSet,
    RelOptTable table, DruidTable druidTable, List<RelNode> rels) {
  final ImmutableMap.Builder<SqlOperator, DruidSqlOperatorConverter> mapBuilder = ImmutableMap
      .builder();
  for (DruidSqlOperatorConverter converter : DEFAULT_OPERATORS_LIST) {
    mapBuilder.put(converter.calciteOperator(), converter);
  }
  return create(cluster, traitSet, table, druidTable, druidTable.intervals, rels,
      mapBuilder.build());
}
 
Example #11
Source File: HiveSqlUDAFReturnTypeInference.java    From marble with Apache License 2.0 5 votes vote down vote up
@Override public RelDataType inferReturnType(
    final SqlOperatorBinding opBinding) {
  try {
    RelDataTypeFactory factory = opBinding.getTypeFactory();
    SqlOperator sqlOperator = opBinding.getOperator();
    String opName = sqlOperator.getName();
    Class hiveUDAFClass = HiveSqlOperatorTable.instance()
        .getHiveUDAFClass(opName);
    List<RelDataTypeHolder> argsType = new ArrayList<>();

    for (int i = 0; i < opBinding.getOperandCount(); i++) {
      RelDataTypeHolder relDataTypeHolder;
      if (TypeInferenceUtil.isOperandConstantForHiveUDAF(hiveUDAFClass, i)) {
        //we use a pre-defined fake value here to getGenericUDAFReturnType
        Object constantValue = TypeInferenceUtil
            .HIVE_UDAF_CONSTANT_OBJECT_INSPECT_CONTEXT_MAP
            .get(hiveUDAFClass).get(i);
        relDataTypeHolder = new RelDataTypeHolder(opBinding.getOperandType(i),
            true, constantValue);
      } else {
        relDataTypeHolder = new RelDataTypeHolder(
            opBinding.getOperandType(i));
      }
      argsType.add(relDataTypeHolder);
    }
    RelDataType resultType = getGenericUDAFReturnType(
        hiveUDAFClass,
        argsType.toArray(new RelDataTypeHolder[0]), factory);
    return resultType;
  } catch (Exception e) {
    throw new RuntimeException(e);
  }
}
 
Example #12
Source File: DrillReduceAggregatesRule.java    From Bats with Apache License 2.0 5 votes vote down vote up
private static boolean isConversionToSumZeroNeeded(SqlOperator sqlOperator, RelDataType type) {
  sqlOperator = DrillCalciteWrapperUtility.extractSqlOperatorFromWrapper(sqlOperator);
  if (sqlOperator instanceof SqlSumAggFunction
      && !type.isNullable()) {
    // If SUM(x) is not nullable, the validator must have determined that
    // nulls are impossible (because the group is never empty and x is never
    // null). Therefore we translate to SUM0(x).
    return true;
  }
  return false;
}
 
Example #13
Source File: ReflectiveConvertletTable.java    From Bats with Apache License 2.0 5 votes vote down vote up
public SqlRexConvertlet get(SqlCall call) {
  SqlRexConvertlet convertlet;
  final SqlOperator op = call.getOperator();

  // Is there a convertlet for this operator
  // (e.g. SqlStdOperatorTable.plusOperator)?
  convertlet = (SqlRexConvertlet) map.get(op);
  if (convertlet != null) {
    return convertlet;
  }

  // Is there a convertlet for this class of operator
  // (e.g. SqlBinaryOperator)?
  Class<?> clazz = op.getClass();
  while (clazz != null) {
    convertlet = (SqlRexConvertlet) map.get(clazz);
    if (convertlet != null) {
      return convertlet;
    }
    clazz = clazz.getSuperclass();
  }

  // Is there a convertlet for this class of expression
  // (e.g. SqlCall)?
  clazz = call.getClass();
  while (clazz != null) {
    convertlet = (SqlRexConvertlet) map.get(clazz);
    if (convertlet != null) {
      return convertlet;
    }
    clazz = clazz.getSuperclass();
  }
  return null;
}
 
Example #14
Source File: DremioCatalogReader.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
/**
 * Rest of class is utility functions taken directly from CalciteCatalogReader. This is because that class consider these utilities to be private concerns.
 */
private SqlOperator toOp(SqlIdentifier name, final Function function) {
  List<RelDataType> argTypes = new ArrayList<>();
  List<SqlTypeFamily> typeFamilies = new ArrayList<>();
  for (FunctionParameter o : function.getParameters()) {
    final RelDataType type = o.getType(typeFactory);
    argTypes.add(type);
    typeFamilies.add(
        Util.first(type.getSqlTypeName().getFamily(), SqlTypeFamily.ANY));
  }
  final Predicate<Integer> optional =
      new Predicate<Integer>() {
        @Override
        public boolean apply(Integer input) {
          return function.getParameters().get(input).isOptional();
        }
      };
  final FamilyOperandTypeChecker typeChecker =
      OperandTypes.family(typeFamilies, optional);
  final List<RelDataType> paramTypes = toSql(argTypes);
  if (function instanceof ScalarFunction) {
    return new SqlUserDefinedFunction(name, infer((ScalarFunction) function),
        InferTypes.explicit(argTypes), typeChecker, paramTypes, function);
  } else if (function instanceof AggregateFunction) {
    return new SqlUserDefinedAggFunction(name,
        infer((AggregateFunction) function), InferTypes.explicit(argTypes),
        typeChecker, (AggregateFunction) function, false, false, typeFactory);
  } else if (function instanceof TableMacro) {
    return new SqlUserDefinedTableMacro(name, ReturnTypes.CURSOR,
        InferTypes.explicit(argTypes), typeChecker, paramTypes,
        (TableMacro) function);
  } else if (function instanceof TableFunction) {
    return new SqlUserDefinedTableFunction(name, ReturnTypes.CURSOR,
        InferTypes.explicit(argTypes), typeChecker, paramTypes,
        (TableFunction) function);
  } else {
    throw new AssertionError("unknown function type " + function);
  }
}
 
Example #15
Source File: SplunkPushDownRule.java    From calcite with Apache License 2.0 5 votes vote down vote up
private String toString(SqlOperator op) {
  if (op.equals(SqlStdOperatorTable.LIKE)) {
    return SqlStdOperatorTable.EQUALS.toString();
  } else if (op.equals(SqlStdOperatorTable.NOT_EQUALS)) {
    return "!=";
  }
  return op.toString();
}
 
Example #16
Source File: SqlValidatorImpl.java    From flink with Apache License 2.0 5 votes vote down vote up
@Override public SqlNode visit(SqlIdentifier id) {
	if (id.isSimple()) {
		return id;
	}
	SqlOperator operator = id.names.get(0).equals(alpha)
		? SqlStdOperatorTable.PREV : SqlStdOperatorTable.LAST;

	return operator.createCall(SqlParserPos.ZERO, id,
		SqlLiteral.createExactNumeric("0", SqlParserPos.ZERO));
}
 
Example #17
Source File: SqlImplementor.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
protected SqlNode createLeftCall(SqlOperator op, List<SqlNode> nodeList) {
  if (nodeList.size() == 2) {
    return op.createCall(new SqlNodeList(nodeList, POS));
  }
  final List<SqlNode> butLast = Util.skipLast(nodeList);
  final SqlNode last = nodeList.get(nodeList.size() - 1);
  final SqlNode call = createLeftCall(op, butLast);
  return op.createCall(new SqlNodeList(ImmutableList.of(call, last), POS));
}
 
Example #18
Source File: RexUtil.java    From calcite with Apache License 2.0 5 votes vote down vote up
private static void flattenRecurse(
    List<RexNode> list, List<? extends RexNode> exprs, SqlOperator op) {
  for (RexNode expr : exprs) {
    if (expr instanceof RexCall
        && ((RexCall) expr).getOperator() == op) {
      flattenRecurse(list, ((RexCall) expr).getOperands(), op);
    } else {
      list.add(expr);
    }
  }
}
 
Example #19
Source File: ReflectiveConvertletTable.java    From calcite with Apache License 2.0 5 votes vote down vote up
/**
 * Registers that one operator is an alias for another.
 *
 * @param alias  Operator which is alias
 * @param target Operator to translate calls to
 */
protected void addAlias(final SqlOperator alias, final SqlOperator target) {
  map.put(
      alias, (SqlRexConvertlet) (cx, call) -> {
        Preconditions.checkArgument(call.getOperator() == alias,
            "call to wrong operator");
        final SqlCall newCall =
            target.createCall(SqlParserPos.ZERO, call.getOperandList());
        return cx.convertExpression(newCall);
      });
}
 
Example #20
Source File: SameOperandTypeExceptLastOperandChecker.java    From calcite with Apache License 2.0 5 votes vote down vote up
public String getAllowedSignatures(SqlOperator op, String opName) {
  final String typeName = getTypeName();
  if (nOperands == -1) {
    return SqlUtil.getAliasedSignature(op, opName,
        ImmutableList.of(typeName, typeName, "..."));
  } else {
    List<String> types = Collections.nCopies(nOperands - 1, typeName);
    types.add(lastOperandTypeName);
    return SqlUtil.getAliasedSignature(op, opName, types);
  }
}
 
Example #21
Source File: SameOperandTypeChecker.java    From Bats with Apache License 2.0 5 votes vote down vote up
public String getAllowedSignatures(SqlOperator op, String opName) {
  final String typeName = getTypeName();
  return SqlUtil.getAliasedSignature(op, opName,
      nOperands == -1
          ? ImmutableList.of(typeName, typeName, "...")
          : Collections.nCopies(nOperands, typeName));
}
 
Example #22
Source File: RexCallBinding.java    From Bats with Apache License 2.0 5 votes vote down vote up
public RexCallBinding(
    RelDataTypeFactory typeFactory,
    SqlOperator sqlOperator,
    List<? extends RexNode> operands,
    List<RelCollation> inputCollations) {
  super(typeFactory, sqlOperator);
  this.operands = ImmutableList.copyOf(operands);
  this.inputCollations = ImmutableList.copyOf(inputCollations);
}
 
Example #23
Source File: SqlValidatorUtil.java    From calcite with Apache License 2.0 5 votes vote down vote up
/**
 * Lookup sql function by sql identifier and function category.
 *
 * @param opTab    operator table to look up
 * @param funName  function name
 * @param funcType function category
 * @return A sql function if and only if there is one operator matches, else null
 */
public static SqlOperator lookupSqlFunctionByID(SqlOperatorTable opTab,
    SqlIdentifier funName,
    SqlFunctionCategory funcType) {
  if (funName.isSimple()) {
    final List<SqlOperator> list = new ArrayList<>();
    opTab.lookupOperatorOverloads(funName, funcType, SqlSyntax.FUNCTION, list,
        SqlNameMatchers.withCaseSensitive(funName.isComponentQuoted(0)));
    if (list.size() == 1) {
      return list.get(0);
    }
  }
  return null;
}
 
Example #24
Source File: RexUtil.java    From calcite with Apache License 2.0 5 votes vote down vote up
public static RexNode negate(RexBuilder rexBuilder, RexCall call) {
  switch (call.getKind()) {
  case EQUALS:
  case NOT_EQUALS:
  case LESS_THAN:
  case GREATER_THAN:
  case LESS_THAN_OR_EQUAL:
  case GREATER_THAN_OR_EQUAL:
    final SqlOperator op = op(call.getKind().negateNullSafe());
    return rexBuilder.makeCall(op, call.getOperands());
  }
  return null;
}
 
Example #25
Source File: RexUtil.java    From Bats with Apache License 2.0 5 votes vote down vote up
public static RexNode negate(RexBuilder rexBuilder, RexCall call) {
    switch (call.getKind()) {
    case EQUALS:
    case NOT_EQUALS:
    case LESS_THAN:
    case GREATER_THAN:
    case LESS_THAN_OR_EQUAL:
    case GREATER_THAN_OR_EQUAL:
        final SqlOperator op = op(call.getKind().negateNullSafe());
        return rexBuilder.makeCall(op, call.getOperands());
    }
    return null;
}
 
Example #26
Source File: DruidQuery.java    From calcite with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a DruidQuery.
 */
private static DruidQuery create(RelOptCluster cluster, RelTraitSet traitSet,
    RelOptTable table, DruidTable druidTable, List<Interval> intervals,
    List<RelNode> rels, Map<SqlOperator, DruidSqlOperatorConverter> converterOperatorMap) {
  return new DruidQuery(cluster, traitSet, table, druidTable, intervals, rels,
      converterOperatorMap);
}
 
Example #27
Source File: ChainedSqlOperatorTable.java    From calcite with Apache License 2.0 5 votes vote down vote up
public void lookupOperatorOverloads(SqlIdentifier opName,
    SqlFunctionCategory category, SqlSyntax syntax,
    List<SqlOperator> operatorList, SqlNameMatcher nameMatcher) {
  for (SqlOperatorTable table : tableList) {
    table.lookupOperatorOverloads(opName, category, syntax, operatorList,
        nameMatcher);
  }
}
 
Example #28
Source File: ReflectiveConvertletTable.java    From calcite with Apache License 2.0 5 votes vote down vote up
/**
 * Registers method if it: a. is public, and b. is named "convertXxx", and
 * c. has a return type of "RexNode" or a subtype d. has a 3 parameters with
 * types: ConvertletContext; SqlOperator (or a subtype), SqlCall (or a
 * subtype).
 */
private void registerOpTypeMethod(final Method method) {
  if (!Modifier.isPublic(method.getModifiers())) {
    return;
  }
  if (!method.getName().startsWith("convert")) {
    return;
  }
  if (!RexNode.class.isAssignableFrom(method.getReturnType())) {
    return;
  }
  final Class[] parameterTypes = method.getParameterTypes();
  if (parameterTypes.length != 3) {
    return;
  }
  if (parameterTypes[0] != SqlRexContext.class) {
    return;
  }
  final Class opClass = parameterTypes[1];
  if (!SqlOperator.class.isAssignableFrom(opClass)) {
    return;
  }
  final Class parameterType = parameterTypes[2];
  if (!SqlCall.class.isAssignableFrom(parameterType)) {
    return;
  }
  map.put(opClass, (SqlRexConvertlet) (cx, call) -> {
    try {
      return (RexNode) method.invoke(ReflectiveConvertletTable.this,
          cx, call.getOperator(), call);
    } catch (IllegalAccessException | InvocationTargetException e) {
      throw new RuntimeException("while converting " + call, e);
    }
  });
}
 
Example #29
Source File: ReduceDecimalsRule.java    From calcite with Apache License 2.0 5 votes vote down vote up
/**
 * Rewrites a call, if required, or returns the original call
 */
private RexNode rewriteCall(RexCall call) {
  SqlOperator operator = call.getOperator();
  if (!operator.requiresDecimalExpansion()) {
    return call;
  }

  RexExpander expander = getExpander(call);
  if (expander.canExpand(call)) {
    return expander.expand(call);
  }
  return call;
}
 
Example #30
Source File: VisitorDataContext.java    From Bats with Apache License 2.0 5 votes vote down vote up
private static RexNode removeCast(RexNode inputRef) {
  if (inputRef instanceof RexCall) {
    final RexCall castedRef = (RexCall) inputRef;
    final SqlOperator operator = castedRef.getOperator();
    if (operator instanceof SqlCastFunction) {
      inputRef = castedRef.getOperands().get(0);
    }
  }
  return inputRef;
}