Search in sources :

Example 16 with SqlNode

use of org.apache.calcite.sql.SqlNode in project druid by druid-io.

the class DruidPlanner method plan.

public PlannerResult plan(final String sql) throws SqlParseException, ValidationException, RelConversionException {
    SqlExplain explain = null;
    SqlNode parsed = planner.parse(sql);
    if (parsed.getKind() == SqlKind.EXPLAIN) {
        explain = (SqlExplain) parsed;
        parsed = explain.getExplicandum();
    }
    final SqlNode validated = planner.validate(parsed);
    final RelRoot root = planner.rel(validated);
    try {
        return planWithDruidConvention(explain, root);
    } catch (RelOptPlanner.CannotPlanException e) {
        // Try again with BINDABLE convention. Used for querying Values, metadata tables, and fallback.
        try {
            return planWithBindableConvention(explain, root);
        } catch (Exception e2) {
            e.addSuppressed(e2);
            throw e;
        }
    }
}
Also used : SqlExplain(org.apache.calcite.sql.SqlExplain) RelRoot(org.apache.calcite.rel.RelRoot) RelOptPlanner(org.apache.calcite.plan.RelOptPlanner) ValidationException(org.apache.calcite.tools.ValidationException) RelConversionException(org.apache.calcite.tools.RelConversionException) SqlParseException(org.apache.calcite.sql.parser.SqlParseException) SqlNode(org.apache.calcite.sql.SqlNode)

Example 17 with SqlNode

use of org.apache.calcite.sql.SqlNode in project drill by apache.

the class UnsupportedOperatorsVisitor method visit.

@Override
public SqlNode visit(SqlCall sqlCall) {
    // Inspect the window functions
    if (sqlCall instanceof SqlSelect) {
        SqlSelect sqlSelect = (SqlSelect) sqlCall;
        checkGrouping((sqlSelect));
        checkRollupCubeGrpSets(sqlSelect);
        for (SqlNode nodeInSelectList : sqlSelect.getSelectList()) {
            // enter the first operand of AS operator
            if (nodeInSelectList.getKind() == SqlKind.AS && (((SqlCall) nodeInSelectList).getOperandList().get(0).getKind() == SqlKind.OVER)) {
                nodeInSelectList = ((SqlCall) nodeInSelectList).getOperandList().get(0);
            }
            if (nodeInSelectList.getKind() == SqlKind.OVER) {
                // Throw exceptions if window functions are disabled
                if (!context.getOptions().getOption(ExecConstants.ENABLE_WINDOW_FUNCTIONS).bool_val) {
                    unsupportedOperatorCollector.setException(SqlUnsupportedException.ExceptionType.FUNCTION, "Window functions are disabled\n" + "See Apache Drill JIRA: DRILL-2559");
                    throw new UnsupportedOperationException();
                }
                // DRILL-3182, DRILL-3195
                SqlCall over = (SqlCall) nodeInSelectList;
                if (over.getOperandList().get(0) instanceof SqlCall) {
                    SqlCall function = (SqlCall) over.getOperandList().get(0);
                    // Window function with DISTINCT qualifier is temporarily disabled
                    if (function.getFunctionQuantifier() != null && function.getFunctionQuantifier().getValue() == SqlSelectKeyword.DISTINCT) {
                        unsupportedOperatorCollector.setException(SqlUnsupportedException.ExceptionType.FUNCTION, "DISTINCT for window aggregate functions is not currently supported\n" + "See Apache Drill JIRA: DRILL-3182");
                        throw new UnsupportedOperationException();
                    }
                    // DRILL-3596: we only allow (<column-name>) or (<column-name>, 1)
                    final String functionName = function.getOperator().getName().toUpperCase();
                    if ("LEAD".equals(functionName) || "LAG".equals(functionName)) {
                        boolean supported = true;
                        if (function.operandCount() > 2) {
                            // we don't support more than 2 arguments
                            supported = false;
                        } else if (function.operandCount() == 2) {
                            SqlNode operand = function.operand(1);
                            if (operand instanceof SqlNumericLiteral) {
                                SqlNumericLiteral offsetLiteral = (SqlNumericLiteral) operand;
                                try {
                                    if (offsetLiteral.intValue(true) != 1) {
                                        // we don't support offset != 1
                                        supported = false;
                                    }
                                } catch (AssertionError e) {
                                    // we only support offset as an integer
                                    supported = false;
                                }
                            } else {
                                // we only support offset as a numeric literal
                                supported = false;
                            }
                        }
                        if (!supported) {
                            unsupportedOperatorCollector.setException(SqlUnsupportedException.ExceptionType.FUNCTION, "Function " + functionName + " only supports (<value expression>) or (<value expression>, 1)\n" + "See Apache DRILL JIRA: DRILL-3596");
                            throw new UnsupportedOperationException();
                        }
                    }
                }
            }
        }
    }
    // (i.e., BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)
    if (sqlCall instanceof SqlWindow) {
        SqlWindow window = (SqlWindow) sqlCall;
        SqlNode lowerBound = window.getLowerBound();
        SqlNode upperBound = window.getUpperBound();
        // If no frame is specified
        // it is a default frame
        boolean isSupported = (lowerBound == null && upperBound == null);
        // RANGE BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING
        if (window.getOrderList().size() != 0 && !window.isRows() && SqlWindow.isUnboundedPreceding(lowerBound) && (upperBound == null || SqlWindow.isCurrentRow(upperBound) || SqlWindow.isUnboundedFollowing(upperBound))) {
            isSupported = true;
        }
        // is supported with and without the ORDER BY clause
        if (window.isRows() && SqlWindow.isUnboundedPreceding(lowerBound) && (upperBound == null || SqlWindow.isCurrentRow(upperBound))) {
            isSupported = true;
        }
        // is supported with and without an ORDER BY clause
        if (!window.isRows() && SqlWindow.isCurrentRow(lowerBound) && SqlWindow.isCurrentRow(upperBound)) {
            isSupported = true;
        }
        // ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING
        if (window.getOrderList().size() == 0 && SqlWindow.isUnboundedPreceding(lowerBound) && SqlWindow.isUnboundedFollowing(upperBound)) {
            isSupported = true;
        }
        if (!isSupported) {
            unsupportedOperatorCollector.setException(SqlUnsupportedException.ExceptionType.FUNCTION, "This type of window frame is currently not supported \n" + "See Apache Drill JIRA: DRILL-3188");
            throw new UnsupportedOperationException();
        }
        // DRILL-3189: Disable DISALLOW PARTIAL
        if (!window.isAllowPartial()) {
            unsupportedOperatorCollector.setException(SqlUnsupportedException.ExceptionType.FUNCTION, "Disallowing partial windows is currently not supported \n" + "See Apache Drill JIRA: DRILL-3189");
            throw new UnsupportedOperationException();
        }
    }
    // Disable unsupported Intersect, Except
    if (sqlCall.getKind() == SqlKind.INTERSECT || sqlCall.getKind() == SqlKind.EXCEPT) {
        unsupportedOperatorCollector.setException(SqlUnsupportedException.ExceptionType.RELATIONAL, sqlCall.getOperator().getName() + " is not supported\n" + "See Apache Drill JIRA: DRILL-1921");
        throw new UnsupportedOperationException();
    }
    // Disable unsupported JOINs
    if (sqlCall.getKind() == SqlKind.JOIN) {
        SqlJoin join = (SqlJoin) sqlCall;
        // Block Natural Join
        if (join.isNatural()) {
            unsupportedOperatorCollector.setException(SqlUnsupportedException.ExceptionType.RELATIONAL, "NATURAL JOIN is not supported\n" + "See Apache Drill JIRA: DRILL-1986");
            throw new UnsupportedOperationException();
        }
        // Block Cross Join
        if (join.getJoinType() == JoinType.CROSS) {
            unsupportedOperatorCollector.setException(SqlUnsupportedException.ExceptionType.RELATIONAL, "CROSS JOIN is not supported\n" + "See Apache Drill JIRA: DRILL-1921");
            throw new UnsupportedOperationException();
        }
    }
    // Disable Function
    for (String strOperator : disabledOperators) {
        if (sqlCall.getOperator().isName(strOperator)) {
            unsupportedOperatorCollector.setException(SqlUnsupportedException.ExceptionType.FUNCTION, sqlCall.getOperator().getName() + " is not supported\n" + "See Apache Drill JIRA: DRILL-2115");
            throw new UnsupportedOperationException();
        }
    }
    // Disable complex functions incorrect placement
    if (sqlCall instanceof SqlSelect) {
        SqlSelect sqlSelect = (SqlSelect) sqlCall;
        for (SqlNode nodeInSelectList : sqlSelect.getSelectList()) {
            if (checkDirExplorers(nodeInSelectList)) {
                unsupportedOperatorCollector.setException(SqlUnsupportedException.ExceptionType.FUNCTION, "Directory explorers " + dirExplorers + " functions are not supported in Select List\n" + "See Apache Drill JIRA: DRILL-3944");
                throw new UnsupportedOperationException();
            }
        }
        if (sqlSelect.hasWhere()) {
            if (checkDirExplorers(sqlSelect.getWhere()) && !context.getPlannerSettings().isConstantFoldingEnabled()) {
                unsupportedOperatorCollector.setException(SqlUnsupportedException.ExceptionType.FUNCTION, "Directory explorers " + dirExplorers + " functions can not be used " + "when " + PlannerSettings.CONSTANT_FOLDING.getOptionName() + " option is set to false\n" + "See Apache Drill JIRA: DRILL-3944");
                throw new UnsupportedOperationException();
            }
        }
        if (sqlSelect.hasOrderBy()) {
            for (SqlNode sqlNode : sqlSelect.getOrderList()) {
                if (containsFlatten(sqlNode)) {
                    unsupportedOperatorCollector.setException(SqlUnsupportedException.ExceptionType.FUNCTION, "Flatten function is not supported in Order By\n" + "See Apache Drill JIRA: DRILL-2181");
                    throw new UnsupportedOperationException();
                } else if (checkDirExplorers(sqlNode)) {
                    unsupportedOperatorCollector.setException(SqlUnsupportedException.ExceptionType.FUNCTION, "Directory explorers " + dirExplorers + " functions are not supported in Order By\n" + "See Apache Drill JIRA: DRILL-3944");
                    throw new UnsupportedOperationException();
                }
            }
        }
        if (sqlSelect.getGroup() != null) {
            for (SqlNode sqlNode : sqlSelect.getGroup()) {
                if (containsFlatten(sqlNode)) {
                    unsupportedOperatorCollector.setException(SqlUnsupportedException.ExceptionType.FUNCTION, "Flatten function is not supported in Group By\n" + "See Apache Drill JIRA: DRILL-2181");
                    throw new UnsupportedOperationException();
                } else if (checkDirExplorers(sqlNode)) {
                    unsupportedOperatorCollector.setException(SqlUnsupportedException.ExceptionType.FUNCTION, "Directory explorers " + dirExplorers + " functions are not supported in Group By\n" + "See Apache Drill JIRA: DRILL-3944");
                    throw new UnsupportedOperationException();
                }
            }
        }
        if (sqlSelect.isDistinct()) {
            for (SqlNode column : sqlSelect.getSelectList()) {
                if (column.getKind() == SqlKind.AS) {
                    if (containsFlatten(((SqlCall) column).getOperandList().get(0))) {
                        unsupportedOperatorCollector.setException(SqlUnsupportedException.ExceptionType.FUNCTION, "Flatten function is not supported in Distinct\n" + "See Apache Drill JIRA: DRILL-2181");
                        throw new UnsupportedOperationException();
                    }
                } else {
                    if (containsFlatten(column)) {
                        unsupportedOperatorCollector.setException(SqlUnsupportedException.ExceptionType.FUNCTION, "Flatten function is not supported in Distinct\n" + "See Apache Drill JIRA: DRILL-2181");
                        throw new UnsupportedOperationException();
                    }
                }
            }
        }
    }
    if (DrillCalciteWrapperUtility.extractSqlOperatorFromWrapper(sqlCall.getOperator()) instanceof SqlCountAggFunction) {
        for (SqlNode sqlNode : sqlCall.getOperandList()) {
            if (containsFlatten(sqlNode)) {
                unsupportedOperatorCollector.setException(SqlUnsupportedException.ExceptionType.FUNCTION, "Flatten function in aggregate functions is not supported\n" + "See Apache Drill JIRA: DRILL-2181");
                throw new UnsupportedOperationException();
            }
        }
    }
    return sqlCall.getOperator().acceptCall(this, sqlCall);
}
Also used : SqlSelect(org.apache.calcite.sql.SqlSelect) SqlCall(org.apache.calcite.sql.SqlCall) SqlJoin(org.apache.calcite.sql.SqlJoin) SqlWindow(org.apache.calcite.sql.SqlWindow) SqlNumericLiteral(org.apache.calcite.sql.SqlNumericLiteral) SqlCountAggFunction(org.apache.calcite.sql.fun.SqlCountAggFunction) SqlNode(org.apache.calcite.sql.SqlNode)

Example 18 with SqlNode

use of org.apache.calcite.sql.SqlNode in project drill by apache.

the class ShowSchemasHandler method rewrite.

/** Rewrite the parse tree as SELECT ... FROM INFORMATION_SCHEMA.SCHEMATA ... */
@Override
public SqlNode rewrite(SqlNode sqlNode) throws RelConversionException, ForemanSetupException {
    SqlShowSchemas node = unwrap(sqlNode, SqlShowSchemas.class);
    List<SqlNode> selectList = ImmutableList.of((SqlNode) new SqlIdentifier(SCHS_COL_SCHEMA_NAME, SqlParserPos.ZERO));
    SqlNode fromClause = new SqlIdentifier(ImmutableList.of(IS_SCHEMA_NAME, TAB_SCHEMATA), null, SqlParserPos.ZERO, null);
    SqlNode where = null;
    final SqlNode likePattern = node.getLikePattern();
    if (likePattern != null) {
        where = DrillParserUtil.createCondition(new SqlIdentifier(SCHS_COL_SCHEMA_NAME, SqlParserPos.ZERO), SqlStdOperatorTable.LIKE, likePattern);
    } else if (node.getWhereClause() != null) {
        where = node.getWhereClause();
    }
    return new SqlSelect(SqlParserPos.ZERO, null, new SqlNodeList(selectList, SqlParserPos.ZERO), fromClause, where, null, null, null, null, null, null);
}
Also used : SqlSelect(org.apache.calcite.sql.SqlSelect) SqlShowSchemas(org.apache.drill.exec.planner.sql.parser.SqlShowSchemas) SqlNodeList(org.apache.calcite.sql.SqlNodeList) SqlIdentifier(org.apache.calcite.sql.SqlIdentifier) SqlNode(org.apache.calcite.sql.SqlNode)

Example 19 with SqlNode

use of org.apache.calcite.sql.SqlNode in project drill by apache.

the class ShowTablesHandler method rewrite.

/** Rewrite the parse tree as SELECT ... FROM INFORMATION_SCHEMA.`TABLES` ... */
@Override
public SqlNode rewrite(SqlNode sqlNode) throws RelConversionException, ForemanSetupException {
    SqlShowTables node = unwrap(sqlNode, SqlShowTables.class);
    List<SqlNode> selectList = Lists.newArrayList();
    SqlNode fromClause;
    SqlNode where;
    // create select columns
    selectList.add(new SqlIdentifier(SHRD_COL_TABLE_SCHEMA, SqlParserPos.ZERO));
    selectList.add(new SqlIdentifier(SHRD_COL_TABLE_NAME, SqlParserPos.ZERO));
    fromClause = new SqlIdentifier(ImmutableList.of(IS_SCHEMA_NAME, TAB_TABLES), SqlParserPos.ZERO);
    final SqlIdentifier db = node.getDb();
    String tableSchema;
    if (db != null) {
        tableSchema = db.toString();
    } else {
        // If no schema is given in SHOW TABLES command, list tables from current schema
        SchemaPlus schema = config.getConverter().getDefaultSchema();
        if (SchemaUtilites.isRootSchema(schema)) {
            // If the default schema is a root schema, throw an error to select a default schema
            throw UserException.validationError().message("No default schema selected. Select a schema using 'USE schema' command").build(logger);
        }
        final AbstractSchema drillSchema = SchemaUtilites.unwrapAsDrillSchemaInstance(schema);
        tableSchema = drillSchema.getFullSchemaName();
    }
    final String charset = Util.getDefaultCharset().name();
    where = DrillParserUtil.createCondition(new SqlIdentifier(SHRD_COL_TABLE_SCHEMA, SqlParserPos.ZERO), SqlStdOperatorTable.EQUALS, SqlLiteral.createCharString(tableSchema, charset, SqlParserPos.ZERO));
    SqlNode filter = null;
    final SqlNode likePattern = node.getLikePattern();
    if (likePattern != null) {
        filter = DrillParserUtil.createCondition(new SqlIdentifier(SHRD_COL_TABLE_NAME, SqlParserPos.ZERO), SqlStdOperatorTable.LIKE, likePattern);
    } else if (node.getWhereClause() != null) {
        filter = node.getWhereClause();
    }
    where = DrillParserUtil.createCondition(where, SqlStdOperatorTable.AND, filter);
    return new SqlSelect(SqlParserPos.ZERO, null, new SqlNodeList(selectList, SqlParserPos.ZERO), fromClause, where, null, null, null, null, null, null);
}
Also used : SqlShowTables(org.apache.drill.exec.planner.sql.parser.SqlShowTables) SqlSelect(org.apache.calcite.sql.SqlSelect) AbstractSchema(org.apache.drill.exec.store.AbstractSchema) SchemaPlus(org.apache.calcite.schema.SchemaPlus) SqlNodeList(org.apache.calcite.sql.SqlNodeList) SqlIdentifier(org.apache.calcite.sql.SqlIdentifier) SqlNode(org.apache.calcite.sql.SqlNode)

Example 20 with SqlNode

use of org.apache.calcite.sql.SqlNode in project drill by apache.

the class DrillExtractConvertlet method convertCall.

/*
   * Custom convertlet to handle extract functions. Optiq rewrites
   * extract functions as divide and modulo functions, based on the
   * data type. We cannot do that in Drill since we don't know the data type
   * till we start scanning. So we don't rewrite extract and treat it as
   * a regular function.
   */
@Override
public RexNode convertCall(SqlRexContext cx, SqlCall call) {
    final RexBuilder rexBuilder = cx.getRexBuilder();
    final List<SqlNode> operands = call.getOperandList();
    final List<RexNode> exprs = new LinkedList<>();
    String timeUnit = ((SqlIntervalQualifier) operands.get(0)).timeUnitRange.toString();
    RelDataTypeFactory typeFactory = cx.getTypeFactory();
    for (SqlNode node : operands) {
        exprs.add(cx.convertExpression(node));
    }
    final RelDataType returnType;
    if (call.getOperator() == SqlStdOperatorTable.EXTRACT) {
        // Legacy code:
        // The return type is wrong!
        // Legacy code choose SqlTypeName.BIGINT simply to avoid conflicting against Calcite's inference mechanism
        // (, which chose BIGINT in validation phase already)
        // Determine NULL-able using 2nd argument's Null-able.
        returnType = typeFactory.createTypeWithNullability(typeFactory.createSqlType(SqlTypeName.BIGINT), exprs.get(1).getType().isNullable());
    } else {
        // Determine NULL-able using 2nd argument's Null-able.
        returnType = typeFactory.createTypeWithNullability(typeFactory.createSqlType(TypeInferenceUtils.getSqlTypeNameForTimeUnit(timeUnit)), exprs.get(1).getType().isNullable());
    }
    return rexBuilder.makeCall(returnType, call.getOperator(), exprs);
}
Also used : RelDataTypeFactory(org.apache.calcite.rel.type.RelDataTypeFactory) RexBuilder(org.apache.calcite.rex.RexBuilder) RelDataType(org.apache.calcite.rel.type.RelDataType) LinkedList(java.util.LinkedList) SqlNode(org.apache.calcite.sql.SqlNode) RexNode(org.apache.calcite.rex.RexNode)

Aggregations

SqlNode (org.apache.calcite.sql.SqlNode)23 RelNode (org.apache.calcite.rel.RelNode)6 SqlIdentifier (org.apache.calcite.sql.SqlIdentifier)5 FrameworkConfig (org.apache.calcite.tools.FrameworkConfig)5 Planner (org.apache.calcite.tools.Planner)5 SchemaPlus (org.apache.calcite.schema.SchemaPlus)4 SqlSelect (org.apache.calcite.sql.SqlSelect)4 HashMap (java.util.HashMap)3 SqlNodeList (org.apache.calcite.sql.SqlNodeList)3 RelConversionException (org.apache.calcite.tools.RelConversionException)3 SqlCreateFunction (org.apache.storm.sql.parser.SqlCreateFunction)3 SqlCreateTable (org.apache.storm.sql.parser.SqlCreateTable)3 StormParser (org.apache.storm.sql.parser.StormParser)3 QueryPlanner (org.apache.storm.sql.planner.trident.QueryPlanner)3 ISqlTridentDataSource (org.apache.storm.sql.runtime.ISqlTridentDataSource)3 ArrayList (java.util.ArrayList)2 JavaTypeFactory (org.apache.calcite.adapter.java.JavaTypeFactory)2 JavaTypeFactoryImpl (org.apache.calcite.jdbc.JavaTypeFactoryImpl)2 CalciteCatalogReader (org.apache.calcite.prepare.CalciteCatalogReader)2 StreamableTable (org.apache.calcite.schema.StreamableTable)2