Java Code Examples for org.apache.calcite.sql.SqlOperator

The following examples show how to use org.apache.calcite.sql.SqlOperator. These examples are extracted from open source projects. 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 Project: Bats   Source File: RelJson.java    License: 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 Project: Flink-CEPplus   Source File: SqlValidatorImpl.java    License: 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 3
Source Project: Bats   Source File: ListSqlOperatorTable.java    License: 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 4
Source Project: Bats   Source File: CompositeOperandTypeChecker.java    License: 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 5
Source Project: kylin-on-parquet-v2   Source File: SqlNodeConverter.java    License: 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 Project: flink   Source File: FunctionCatalogOperatorTable.java    License: 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 Project: calcite   Source File: RelOptUtil.java    License: 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 Project: marble   Source File: HiveSqlUDAFReturnTypeInference.java    License: 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 9
Source Project: Bats   Source File: SqlImplementor.java    License: 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 Project: Bats   Source File: ReflectiveConvertletTable.java    License: 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 11
Source Project: streamline   Source File: ExpressionGenerator.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Expression visit(SqlCall call) {
    SqlOperator sqlOperator = call.getOperator();
    if (sqlOperator instanceof SqlBinaryOperator) {
        return visitBinaryOperator((SqlBinaryOperator) sqlOperator, call.getOperandList().get(0),
                call.getOperandList().get(1));
    } else if (sqlOperator instanceof SqlSpecialOperator) {
        return visitSqlSpecialOperator((SqlSpecialOperator) sqlOperator, call.getOperandList());
    } else if (sqlOperator instanceof SqlFunction) {
        SqlFunction sqlFunction = (SqlFunction) sqlOperator;
        if (sqlFunction instanceof SqlAggFunction) {
            return visitAggregateFunction(sqlFunction.getName(), call.getOperandList());
        } else if (sqlFunction instanceof SqlUnresolvedFunction) {
            String udfName = sqlFunction.getName().toUpperCase();
            if (catalogUdfs.containsKey(udfName)) {
                Udf udfInfo = catalogUdfs.get(udfName);
                if (udfInfo.isAggregate()) {
                    return visitUserDefinedAggregateFunction(udfInfo, call.getOperandList());
                } else {
                    return visitUserDefinedFunction(udfInfo, call.getOperandList());
                }
            } else {
                throw new UnsupportedOperationException("Unknown built-in or User defined function '" + udfName + "'");
            }
        } else {
            return visitFunction(sqlFunction.getName(), call.getOperandList());
        }
    } else {
        throw new UnsupportedOperationException("Operator " + sqlOperator.getName() + " is not supported");
    }
}
 
Example 12
Source Project: calcite   Source File: DruidQuery.java    License: 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 13
Source Project: Bats   Source File: DrillReduceAggregatesRule.java    License: 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 14
Source Project: flink   Source File: FlinkSqlOperatorTable.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void lookupOperatorOverloads(
		SqlIdentifier opName,
		SqlFunctionCategory category,
		SqlSyntax syntax,
		List<SqlOperator> operatorList,
		SqlNameMatcher nameMatcher) {
	// set caseSensitive=false to make sure the behavior is same with before.
	super.lookupOperatorOverloads(opName, category, syntax, operatorList, SqlNameMatchers.withCaseSensitive(false));
}
 
Example 15
Source Project: dremio-oss   Source File: DremioCatalogReader.java    License: 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 16
Source Project: calcite   Source File: SplunkPushDownRule.java    License: 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 17
Source Project: dremio-oss   Source File: SqlImplementor.java    License: 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 Project: calcite   Source File: RexUtil.java    License: 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 Project: calcite   Source File: ReflectiveConvertletTable.java    License: 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 Project: marble   Source File: HiveSqlOperatorTable.java    License: 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 21
Source Project: Bats   Source File: SameOperandTypeChecker.java    License: 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 Project: calcite   Source File: RexUtil.java    License: 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 23
Source Project: Bats   Source File: RexUtil.java    License: 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 24
Source Project: calcite   Source File: DruidQuery.java    License: 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 25
Source Project: calcite   Source File: ReflectiveConvertletTable.java    License: 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 26
Source Project: calcite   Source File: ReduceDecimalsRule.java    License: 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 27
Source Project: Bats   Source File: VisitorDataContext.java    License: 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;
}
 
Example 28
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 29
Source Project: calcite   Source File: ChainedSqlOperatorTable.java    License: 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 30
Source Project: calcite   Source File: SqlValidatorUtil.java    License: 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;
}