use of org.apache.calcite.sql.SqlCall in project calcite by apache.
the class SqlValidatorImpl method findAllValidFunctionNames.
private static void findAllValidFunctionNames(List<String> names, SqlValidator validator, Collection<SqlMoniker> result, SqlParserPos pos) {
// a function name can only be 1 part
if (names.size() > 1) {
return;
}
for (SqlOperator op : validator.getOperatorTable().getOperatorList()) {
SqlIdentifier curOpId = new SqlIdentifier(op.getName(), pos);
final SqlCall call = SqlUtil.makeCall(validator.getOperatorTable(), curOpId);
if (call != null) {
result.add(new SqlMonikerImpl(op.getName(), SqlMonikerType.FUNCTION));
} else {
if ((op.getSyntax() == SqlSyntax.FUNCTION) || (op.getSyntax() == SqlSyntax.PREFIX)) {
if (op.getOperandTypeChecker() != null) {
String sig = op.getAllowedSignatures();
sig = sig.replaceAll("'", "");
result.add(new SqlMonikerImpl(sig, SqlMonikerType.FUNCTION));
continue;
}
result.add(new SqlMonikerImpl(op.getName(), SqlMonikerType.FUNCTION));
}
}
}
}
use of org.apache.calcite.sql.SqlCall in project calcite by apache.
the class SqlValidatorImpl method inferUnknownTypes.
protected void inferUnknownTypes(RelDataType inferredType, SqlValidatorScope scope, SqlNode node) {
final SqlValidatorScope newScope = scopes.get(node);
if (newScope != null) {
scope = newScope;
}
boolean isNullLiteral = SqlUtil.isNullLiteral(node, false);
if ((node instanceof SqlDynamicParam) || isNullLiteral) {
if (inferredType.equals(unknownType)) {
if (isNullLiteral) {
throw newValidationError(node, RESOURCE.nullIllegal());
} else {
throw newValidationError(node, RESOURCE.dynamicParamIllegal());
}
}
// REVIEW: should dynamic parameter types always be nullable?
RelDataType newInferredType = typeFactory.createTypeWithNullability(inferredType, true);
if (SqlTypeUtil.inCharFamily(inferredType)) {
newInferredType = typeFactory.createTypeWithCharsetAndCollation(newInferredType, inferredType.getCharset(), inferredType.getCollation());
}
setValidatedNodeType(node, newInferredType);
} else if (node instanceof SqlNodeList) {
SqlNodeList nodeList = (SqlNodeList) node;
if (inferredType.isStruct()) {
if (inferredType.getFieldCount() != nodeList.size()) {
// bust out, and the error will be detected higher up
return;
}
}
int i = 0;
for (SqlNode child : nodeList) {
RelDataType type;
if (inferredType.isStruct()) {
type = inferredType.getFieldList().get(i).getType();
++i;
} else {
type = inferredType;
}
inferUnknownTypes(type, scope, child);
}
} else if (node instanceof SqlCase) {
final SqlCase caseCall = (SqlCase) node;
final RelDataType whenType = caseCall.getValueOperand() == null ? booleanType : unknownType;
for (SqlNode sqlNode : caseCall.getWhenOperands().getList()) {
inferUnknownTypes(whenType, scope, sqlNode);
}
RelDataType returnType = deriveType(scope, node);
for (SqlNode sqlNode : caseCall.getThenOperands().getList()) {
inferUnknownTypes(returnType, scope, sqlNode);
}
if (!SqlUtil.isNullLiteral(caseCall.getElseOperand(), false)) {
inferUnknownTypes(returnType, scope, caseCall.getElseOperand());
} else {
setValidatedNodeType(caseCall.getElseOperand(), returnType);
}
} else if (node instanceof SqlCall) {
final SqlCall call = (SqlCall) node;
final SqlOperandTypeInference operandTypeInference = call.getOperator().getOperandTypeInference();
final SqlCallBinding callBinding = new SqlCallBinding(this, scope, call);
final List<SqlNode> operands = callBinding.operands();
final RelDataType[] operandTypes = new RelDataType[operands.size()];
if (operandTypeInference == null) {
// TODO: eventually should assert(operandTypeInference != null)
// instead; for now just eat it
Arrays.fill(operandTypes, unknownType);
} else {
operandTypeInference.inferOperandTypes(callBinding, inferredType, operandTypes);
}
for (int i = 0; i < operands.size(); ++i) {
inferUnknownTypes(operandTypes[i], scope, operands.get(i));
}
}
}
use of org.apache.calcite.sql.SqlCall in project calcite by apache.
the class SqlToRelConverter method convertCursor.
private RelNode convertCursor(Blackboard bb, SubQuery subQuery) {
final SqlCall cursorCall = (SqlCall) subQuery.node;
assert cursorCall.operandCount() == 1;
SqlNode query = cursorCall.operand(0);
RelNode converted = convertQuery(query, false, false).rel;
int iCursor = bb.cursors.size();
bb.cursors.add(converted);
subQuery.expr = new RexInputRef(iCursor, converted.getRowType());
return converted;
}
use of org.apache.calcite.sql.SqlCall in project calcite by apache.
the class SqlToRelConverter method convertToSingleValueSubq.
/**
* Converts the RelNode tree for a select statement to a select that
* produces a single value.
*
* @param query the query
* @param plan the original RelNode tree corresponding to the statement
* @return the converted RelNode tree
*/
public RelNode convertToSingleValueSubq(SqlNode query, RelNode plan) {
// Check whether query is guaranteed to produce a single value.
if (query instanceof SqlSelect) {
SqlSelect select = (SqlSelect) query;
SqlNodeList selectList = select.getSelectList();
SqlNodeList groupList = select.getGroup();
if ((selectList.size() == 1) && ((groupList == null) || (groupList.size() == 0))) {
SqlNode selectExpr = selectList.get(0);
if (selectExpr instanceof SqlCall) {
SqlCall selectExprCall = (SqlCall) selectExpr;
if (Util.isSingleValue(selectExprCall)) {
return plan;
}
}
// it is ensured to produce a single value
if (select.getFetch() != null && select.getFetch() instanceof SqlNumericLiteral) {
SqlNumericLiteral limitNum = (SqlNumericLiteral) select.getFetch();
if (((BigDecimal) limitNum.getValue()).intValue() < 2) {
return plan;
}
}
}
} else if (query instanceof SqlCall) {
// If the query is (values ...),
// it is necessary to look into the operands to determine
// whether SingleValueAgg is necessary
SqlCall exprCall = (SqlCall) query;
if (exprCall.getOperator() instanceof SqlValuesOperator && Util.isSingleValue(exprCall)) {
return plan;
}
}
// If not, project SingleValueAgg
return RelOptUtil.createSingleValueAggRel(cluster, plan);
}
use of org.apache.calcite.sql.SqlCall in project calcite by apache.
the class SqlToRelConverter method convertMatchRecognize.
protected void convertMatchRecognize(Blackboard bb, SqlCall call) {
final SqlMatchRecognize matchRecognize = (SqlMatchRecognize) call;
final SqlValidatorNamespace ns = validator.getNamespace(matchRecognize);
final SqlValidatorScope scope = validator.getMatchRecognizeScope(matchRecognize);
final Blackboard matchBb = createBlackboard(scope, null, false);
final RelDataType rowType = ns.getRowType();
// convert inner query, could be a table name or a derived table
SqlNode expr = matchRecognize.getTableRef();
convertFrom(matchBb, expr);
final RelNode input = matchBb.root;
// PARTITION BY
final SqlNodeList partitionList = matchRecognize.getPartitionList();
final List<RexNode> partitionKeys = new ArrayList<>();
for (SqlNode partition : partitionList) {
RexNode e = matchBb.convertExpression(partition);
partitionKeys.add(e);
}
// ORDER BY
final SqlNodeList orderList = matchRecognize.getOrderList();
final List<RelFieldCollation> orderKeys = new ArrayList<>();
for (SqlNode order : orderList) {
final RelFieldCollation.Direction direction;
switch(order.getKind()) {
case DESCENDING:
direction = RelFieldCollation.Direction.DESCENDING;
order = ((SqlCall) order).operand(0);
break;
case NULLS_FIRST:
case NULLS_LAST:
throw new AssertionError();
default:
direction = RelFieldCollation.Direction.ASCENDING;
break;
}
final RelFieldCollation.NullDirection nullDirection = validator.getDefaultNullCollation().last(desc(direction)) ? RelFieldCollation.NullDirection.LAST : RelFieldCollation.NullDirection.FIRST;
RexNode e = matchBb.convertExpression(order);
orderKeys.add(new RelFieldCollation(((RexInputRef) e).getIndex(), direction, nullDirection));
}
final RelCollation orders = cluster.traitSet().canonize(RelCollations.of(orderKeys));
// convert pattern
final Set<String> patternVarsSet = new HashSet<>();
SqlNode pattern = matchRecognize.getPattern();
final SqlBasicVisitor<RexNode> patternVarVisitor = new SqlBasicVisitor<RexNode>() {
@Override
public RexNode visit(SqlCall call) {
List<SqlNode> operands = call.getOperandList();
List<RexNode> newOperands = Lists.newArrayList();
for (SqlNode node : operands) {
newOperands.add(node.accept(this));
}
return rexBuilder.makeCall(validator.getUnknownType(), call.getOperator(), newOperands);
}
@Override
public RexNode visit(SqlIdentifier id) {
assert id.isSimple();
patternVarsSet.add(id.getSimple());
return rexBuilder.makeLiteral(id.getSimple());
}
@Override
public RexNode visit(SqlLiteral literal) {
if (literal instanceof SqlNumericLiteral) {
return rexBuilder.makeExactLiteral(BigDecimal.valueOf(literal.intValue(true)));
} else {
return rexBuilder.makeLiteral(literal.booleanValue());
}
}
};
final RexNode patternNode = pattern.accept(patternVarVisitor);
SqlLiteral interval = matchRecognize.getInterval();
RexNode intervalNode = null;
if (interval != null) {
intervalNode = matchBb.convertLiteral(interval);
}
// convert subset
final SqlNodeList subsets = matchRecognize.getSubsetList();
final Map<String, TreeSet<String>> subsetMap = Maps.newHashMap();
for (SqlNode node : subsets) {
List<SqlNode> operands = ((SqlCall) node).getOperandList();
SqlIdentifier left = (SqlIdentifier) operands.get(0);
patternVarsSet.add(left.getSimple());
SqlNodeList rights = (SqlNodeList) operands.get(1);
final TreeSet<String> list = new TreeSet<String>();
for (SqlNode right : rights) {
assert right instanceof SqlIdentifier;
list.add(((SqlIdentifier) right).getSimple());
}
subsetMap.put(left.getSimple(), list);
}
SqlNode afterMatch = matchRecognize.getAfter();
if (afterMatch == null) {
afterMatch = SqlMatchRecognize.AfterOption.SKIP_TO_NEXT_ROW.symbol(SqlParserPos.ZERO);
}
final RexNode after;
if (afterMatch instanceof SqlCall) {
List<SqlNode> operands = ((SqlCall) afterMatch).getOperandList();
SqlOperator operator = ((SqlCall) afterMatch).getOperator();
assert operands.size() == 1;
SqlIdentifier id = (SqlIdentifier) operands.get(0);
assert patternVarsSet.contains(id.getSimple()) : id.getSimple() + " not defined in pattern";
RexNode rex = rexBuilder.makeLiteral(id.getSimple());
after = rexBuilder.makeCall(validator.getUnknownType(), operator, ImmutableList.of(rex));
} else {
after = matchBb.convertExpression(afterMatch);
}
matchBb.setPatternVarRef(true);
// convert measures
final ImmutableMap.Builder<String, RexNode> measureNodes = ImmutableMap.builder();
for (SqlNode measure : matchRecognize.getMeasureList()) {
List<SqlNode> operands = ((SqlCall) measure).getOperandList();
String alias = ((SqlIdentifier) operands.get(1)).getSimple();
RexNode rex = matchBb.convertExpression(operands.get(0));
measureNodes.put(alias, rex);
}
// convert definitions
final ImmutableMap.Builder<String, RexNode> definitionNodes = ImmutableMap.builder();
for (SqlNode def : matchRecognize.getPatternDefList()) {
List<SqlNode> operands = ((SqlCall) def).getOperandList();
String alias = ((SqlIdentifier) operands.get(1)).getSimple();
RexNode rex = matchBb.convertExpression(operands.get(0));
definitionNodes.put(alias, rex);
}
final SqlLiteral rowsPerMatch = matchRecognize.getRowsPerMatch();
final boolean allRows = rowsPerMatch != null && rowsPerMatch.getValue() == SqlMatchRecognize.RowsPerMatchOption.ALL_ROWS;
matchBb.setPatternVarRef(false);
final RelFactories.MatchFactory factory = RelFactories.DEFAULT_MATCH_FACTORY;
final RelNode rel = factory.createMatch(input, patternNode, rowType, matchRecognize.getStrictStart().booleanValue(), matchRecognize.getStrictEnd().booleanValue(), definitionNodes.build(), measureNodes.build(), after, subsetMap, allRows, partitionKeys, orders, intervalNode);
bb.setRoot(rel, false);
}
Aggregations