Search in sources :

Example 66 with RelRoot

use of org.apache.beam.vendor.calcite.v1_28_0.org.apache.calcite.rel.RelRoot in project calcite by apache.

the class ViewTable method expandView.

private RelRoot expandView(RelOptTable.ToRelContext context, RelDataType rowType, String queryString) {
    try {
        final RelRoot root = context.expandView(rowType, queryString, schemaPath, viewPath);
        final RelNode rel = RelOptUtil.createCastRel(root.rel, rowType, true);
        // Expand any views
        final RelNode rel2 = rel.accept(new RelShuttleImpl() {

            @Override
            public RelNode visit(TableScan scan) {
                final RelOptTable table = scan.getTable();
                final TranslatableTable translatableTable = table.unwrap(TranslatableTable.class);
                if (translatableTable != null) {
                    return translatableTable.toRel(context, table);
                }
                return super.visit(scan);
            }
        });
        return root.withRel(rel2);
    } catch (Exception e) {
        throw new RuntimeException("Error while parsing view definition: " + queryString, e);
    }
}
Also used : TableScan(org.apache.calcite.rel.core.TableScan) RelNode(org.apache.calcite.rel.RelNode) RelShuttleImpl(org.apache.calcite.rel.RelShuttleImpl) RelRoot(org.apache.calcite.rel.RelRoot) TranslatableTable(org.apache.calcite.schema.TranslatableTable) RelOptTable(org.apache.calcite.plan.RelOptTable)

Example 67 with RelRoot

use of org.apache.beam.vendor.calcite.v1_28_0.org.apache.calcite.rel.RelRoot in project calcite by apache.

the class SqlToRelConverter method convertMultisets.

private RelNode convertMultisets(final List<SqlNode> operands, Blackboard bb) {
    // NOTE: Wael 2/04/05: this implementation is not the most efficient in
    // terms of planning since it generates XOs that can be reduced.
    final List<Object> joinList = new ArrayList<>();
    List<SqlNode> lastList = new ArrayList<>();
    for (int i = 0; i < operands.size(); i++) {
        SqlNode operand = operands.get(i);
        if (!(operand instanceof SqlCall)) {
            lastList.add(operand);
            continue;
        }
        final SqlCall call = (SqlCall) operand;
        final RelNode input;
        switch(call.getKind()) {
            case MULTISET_VALUE_CONSTRUCTOR:
            case ARRAY_VALUE_CONSTRUCTOR:
                final SqlNodeList list = new SqlNodeList(call.getOperandList(), call.getParserPosition());
                CollectNamespace nss = getNamespaceOrNull(call);
                Blackboard usedBb;
                if (null != nss) {
                    usedBb = createBlackboard(nss.getScope(), null, false);
                } else {
                    usedBb = createBlackboard(new ListScope(bb.scope()) {

                        @Override
                        public SqlNode getNode() {
                            return call;
                        }
                    }, null, false);
                }
                RelDataType multisetType = validator().getValidatedNodeType(call);
                validator().setValidatedNodeType(list, requireNonNull(multisetType.getComponentType(), () -> "componentType for multisetType " + multisetType));
                input = convertQueryOrInList(usedBb, list, null);
                break;
            case MULTISET_QUERY_CONSTRUCTOR:
            case ARRAY_QUERY_CONSTRUCTOR:
            case MAP_QUERY_CONSTRUCTOR:
                final RelRoot root = convertQuery(call.operand(0), false, true);
                input = root.rel;
                break;
            default:
                lastList.add(operand);
                continue;
        }
        if (lastList.size() > 0) {
            joinList.add(lastList);
        }
        lastList = new ArrayList<>();
        final SqlTypeName typeName = requireNonNull(validator, "validator").getValidatedNodeType(call).getSqlTypeName();
        relBuilder.push(Collect.create(requireNonNull(input, "input"), typeName, castNonNull(validator().deriveAlias(call, i))));
        joinList.add(relBuilder.build());
    }
    if (joinList.size() == 0) {
        joinList.add(lastList);
    }
    for (int i = 0; i < joinList.size(); i++) {
        Object o = joinList.get(i);
        if (o instanceof List) {
            @SuppressWarnings("unchecked") List<SqlNode> projectList = (List<SqlNode>) o;
            final List<RexNode> selectList = new ArrayList<>();
            final List<String> fieldNameList = new ArrayList<>();
            for (int j = 0; j < projectList.size(); j++) {
                SqlNode operand = projectList.get(j);
                selectList.add(bb.convertExpression(operand));
                // REVIEW angel 5-June-2005: Use deriveAliasFromOrdinal
                // instead of deriveAlias to match field names from
                // SqlRowOperator. Otherwise, get error   Type
                // 'RecordType(INTEGER EMPNO)' has no field 'EXPR$0' when
                // doing   select * from unnest(     select multiset[empno]
                // from sales.emps);
                fieldNameList.add(SqlUtil.deriveAliasFromOrdinal(j));
            }
            relBuilder.push(LogicalValues.createOneRow(cluster)).projectNamed(selectList, fieldNameList, true);
            joinList.set(i, relBuilder.build());
        }
    }
    RelNode ret = (RelNode) joinList.get(0);
    for (int i = 1; i < joinList.size(); i++) {
        RelNode relNode = (RelNode) joinList.get(i);
        ret = RelFactories.DEFAULT_JOIN_FACTORY.createJoin(ret, relNode, ImmutableList.of(), rexBuilder.makeLiteral(true), ImmutableSet.of(), JoinRelType.INNER, false);
    }
    return ret;
}
Also used : SqlTypeName(org.apache.calcite.sql.type.SqlTypeName) SqlCall(org.apache.calcite.sql.SqlCall) ArrayList(java.util.ArrayList) RelDataType(org.apache.calcite.rel.type.RelDataType) RelRoot(org.apache.calcite.rel.RelRoot) NlsString(org.apache.calcite.util.NlsString) RelHint(org.apache.calcite.rel.hint.RelHint) RelNode(org.apache.calcite.rel.RelNode) SqlNodeList(org.apache.calcite.sql.SqlNodeList) ArrayList(java.util.ArrayList) AbstractList(java.util.AbstractList) ImmutableIntList(org.apache.calcite.util.ImmutableIntList) List(java.util.List) ImmutableList(com.google.common.collect.ImmutableList) SqlNodeList(org.apache.calcite.sql.SqlNodeList) CollectNamespace(org.apache.calcite.sql.validate.CollectNamespace) ListScope(org.apache.calcite.sql.validate.ListScope) SqlNode(org.apache.calcite.sql.SqlNode) RexNode(org.apache.calcite.rex.RexNode)

Example 68 with RelRoot

use of org.apache.beam.vendor.calcite.v1_28_0.org.apache.calcite.rel.RelRoot in project calcite by apache.

the class ServerDdlExecutor method populate.

/**
 * Populates the table called {@code name} by executing {@code query}.
 */
static void populate(SqlIdentifier name, SqlNode query, CalcitePrepare.Context context) {
    // Generate, prepare and execute an "INSERT INTO table query" statement.
    // (It's a bit inefficient that we convert from SqlNode to SQL and back
    // again.)
    final FrameworkConfig config = Frameworks.newConfigBuilder().defaultSchema(context.getRootSchema().plus()).build();
    final Planner planner = Frameworks.getPlanner(config);
    try {
        final StringBuilder buf = new StringBuilder();
        final SqlWriterConfig writerConfig = SqlPrettyWriter.config().withAlwaysUseParentheses(false);
        final SqlPrettyWriter w = new SqlPrettyWriter(writerConfig, buf);
        buf.append("INSERT INTO ");
        name.unparse(w, 0, 0);
        buf.append(' ');
        query.unparse(w, 0, 0);
        final String sql = buf.toString();
        final SqlNode query1 = planner.parse(sql);
        final SqlNode query2 = planner.validate(query1);
        final RelRoot r = planner.rel(query2);
        final PreparedStatement prepare = context.getRelRunner().prepareStatement(r.rel);
        int rowCount = prepare.executeUpdate();
        Util.discard(rowCount);
        prepare.close();
    } catch (SqlParseException | ValidationException | RelConversionException | SQLException e) {
        throw Util.throwAsRuntime(e);
    }
}
Also used : ValidationException(org.apache.calcite.tools.ValidationException) SqlParseException(org.apache.calcite.sql.parser.SqlParseException) SQLException(java.sql.SQLException) SqlWriterConfig(org.apache.calcite.sql.SqlWriterConfig) RelRoot(org.apache.calcite.rel.RelRoot) PreparedStatement(java.sql.PreparedStatement) NlsString(org.apache.calcite.util.NlsString) RelConversionException(org.apache.calcite.tools.RelConversionException) SqlPrettyWriter(org.apache.calcite.sql.pretty.SqlPrettyWriter) Planner(org.apache.calcite.tools.Planner) FrameworkConfig(org.apache.calcite.tools.FrameworkConfig) SqlNode(org.apache.calcite.sql.SqlNode)

Example 69 with RelRoot

use of org.apache.beam.vendor.calcite.v1_28_0.org.apache.calcite.rel.RelRoot in project druid by apache.

the class DruidPlanner method possiblyWrapRootWithOuterLimitFromContext.

/**
 * This method wraps the root with a {@link LogicalSort} that applies a limit (no ordering change). If the outer rel
 * is already a {@link Sort}, we can merge our outerLimit into it, similar to what is going on in
 * {@link org.apache.druid.sql.calcite.rule.SortCollapseRule}.
 *
 * The {@link PlannerContext#CTX_SQL_OUTER_LIMIT} flag that controls this wrapping is meant for internal use only by
 * the web console, allowing it to apply a limit to queries without rewriting the original SQL.
 *
 * @param root root node
 * @return root node wrapped with a limiting logical sort if a limit is specified in the query context.
 */
@Nullable
private RelRoot possiblyWrapRootWithOuterLimitFromContext(RelRoot root) {
    Object outerLimitObj = plannerContext.getQueryContext().get(PlannerContext.CTX_SQL_OUTER_LIMIT);
    Long outerLimit = DimensionHandlerUtils.convertObjectToLong(outerLimitObj, true);
    if (outerLimit == null) {
        return root;
    }
    final LogicalSort newRootRel;
    if (root.rel instanceof Sort) {
        Sort sort = (Sort) root.rel;
        final OffsetLimit originalOffsetLimit = OffsetLimit.fromSort(sort);
        final OffsetLimit newOffsetLimit = originalOffsetLimit.andThen(new OffsetLimit(0, outerLimit));
        if (newOffsetLimit.equals(originalOffsetLimit)) {
            // nothing to do, don't bother to make a new sort
            return root;
        }
        newRootRel = LogicalSort.create(sort.getInput(), sort.collation, newOffsetLimit.getOffsetAsRexNode(rexBuilder), newOffsetLimit.getLimitAsRexNode(rexBuilder));
    } else {
        newRootRel = LogicalSort.create(root.rel, root.collation, null, new OffsetLimit(0, outerLimit).getLimitAsRexNode(rexBuilder));
    }
    return new RelRoot(newRootRel, root.validatedRowType, root.kind, root.fields, root.collation);
}
Also used : LogicalSort(org.apache.calcite.rel.logical.LogicalSort) Sort(org.apache.calcite.rel.core.Sort) RelRoot(org.apache.calcite.rel.RelRoot) LogicalSort(org.apache.calcite.rel.logical.LogicalSort) Nullable(javax.annotation.Nullable)

Example 70 with RelRoot

use of org.apache.beam.vendor.calcite.v1_28_0.org.apache.calcite.rel.RelRoot in project druid by apache.

the class DruidPlanner method prepare.

/**
 * Prepare an SQL query for execution, including some initial parsing and validation and any dynamic parameter type
 * resolution, to support prepared statements via JDBC.
 *
 * In some future this could perhaps re-use some of the work done by {@link #validate()}
 * instead of repeating it, but that day is not today.
 */
public PrepareResult prepare() throws SqlParseException, ValidationException, RelConversionException {
    resetPlanner();
    final ParsedNodes parsed = ParsedNodes.create(planner.parse(plannerContext.getSql()));
    final SqlNode validatedQueryNode = planner.validate(parsed.getQueryNode());
    final RelRoot rootQueryRel = planner.rel(validatedQueryNode);
    final SqlValidator validator = getValidator();
    final RelDataTypeFactory typeFactory = rootQueryRel.rel.getCluster().getTypeFactory();
    final RelDataType parameterTypes = validator.getParameterRowType(validator.validate(validatedQueryNode));
    final RelDataType returnedRowType;
    if (parsed.getExplainNode() != null) {
        returnedRowType = getExplainStructType(typeFactory);
    } else {
        returnedRowType = buildQueryMaker(rootQueryRel, parsed.getInsertNode()).getResultType();
    }
    return new PrepareResult(returnedRowType, parameterTypes);
}
Also used : SqlValidator(org.apache.calcite.sql.validate.SqlValidator) RelDataTypeFactory(org.apache.calcite.rel.type.RelDataTypeFactory) RelRoot(org.apache.calcite.rel.RelRoot) RelDataType(org.apache.calcite.rel.type.RelDataType) SqlNode(org.apache.calcite.sql.SqlNode)

Aggregations

RelRoot (org.apache.calcite.rel.RelRoot)77 SqlNode (org.apache.calcite.sql.SqlNode)30 RelNode (org.apache.calcite.rel.RelNode)22 Test (org.junit.jupiter.api.Test)18 NlsString (org.apache.calcite.util.NlsString)17 DingoTableScan (io.dingodb.calcite.rel.DingoTableScan)13 SqlParseException (org.apache.calcite.sql.parser.SqlParseException)11 SqlToRelConverter (org.apache.calcite.sql2rel.SqlToRelConverter)11 LogicalProject (org.apache.calcite.rel.logical.LogicalProject)9 SamzaSqlDslConverterFactory (org.apache.samza.sql.dsl.SamzaSqlDslConverterFactory)8 RelOptPlanner (org.apache.calcite.plan.RelOptPlanner)7 RelDataType (org.apache.calcite.rel.type.RelDataType)7 RexBuilder (org.apache.calcite.rex.RexBuilder)7 SqlValidator (org.apache.calcite.sql.validate.SqlValidator)7 DslConverter (org.apache.samza.sql.interfaces.DslConverter)7 Test (org.junit.Test)7 RelOptCluster (org.apache.calcite.plan.RelOptCluster)6 SqlParser (org.apache.calcite.sql.parser.SqlParser)6 Planner (org.apache.calcite.tools.Planner)6 LogicalFilter (org.apache.calcite.rel.logical.LogicalFilter)5