org.apache.calcite.jdbc.CalciteSchema - java examples

Here are the examples of the java api org.apache.calcite.jdbc.CalciteSchema taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

75 Examples 7

19 View Complete Implementation : Lattice.java
Copyright Apache License 2.0
Author : apache
/**
 * Structure that allows materialized views based upon a star schema to be
 * recognized and recommended.
 */
@ParametersAreNonnullByDefault
public clreplaced Lattice {

    public final CalciteSchema rootSchema;

    public final LatticeRootNode rootNode;

    public final ImmutableList<Column> columns;

    public final boolean auto;

    public final boolean algorithm;

    public final long algorithmMaxMillis;

    public final double rowCountEstimate;

    public final ImmutableList<Measure> defaultMeasures;

    public final ImmutableList<Tile> tiles;

    public final ImmutableListMultimap<Integer, Boolean> columnUses;

    public final LatticeStatisticProvider statisticProvider;

    private Lattice(CalciteSchema rootSchema, LatticeRootNode rootNode, boolean auto, boolean algorithm, long algorithmMaxMillis, LatticeStatisticProvider.Factory statisticProviderFactory, @Nullable Double rowCountEstimate, ImmutableList<Column> columns, ImmutableSortedSet<Measure> defaultMeasures, ImmutableList<Tile> tiles, ImmutableListMultimap<Integer, Boolean> columnUses) {
        this.rootSchema = rootSchema;
        this.rootNode = Objects.requireNonNull(rootNode);
        this.columns = Objects.requireNonNull(columns);
        this.auto = auto;
        this.algorithm = algorithm;
        this.algorithmMaxMillis = algorithmMaxMillis;
        // unique and sorted
        this.defaultMeasures = defaultMeasures.asList();
        this.tiles = Objects.requireNonNull(tiles);
        this.columnUses = columnUses;
        replacedert isValid(Litmus.THROW);
        if (rowCountEstimate == null) {
            // We could improve this when we fix
            // [CALCITE-429] Add statistics SPI for lattice optimization algorithm
            rowCountEstimate = 1000d;
        }
        Preconditions.checkArgument(rowCountEstimate > 0d);
        this.rowCountEstimate = rowCountEstimate;
        this.statisticProvider = Objects.requireNonNull(statisticProviderFactory.apply(this));
    }

    /**
     * Creates a Lattice.
     */
    public static Lattice create(CalciteSchema schema, String sql, boolean auto) {
        return builder(schema, sql).auto(auto).build();
    }

    private boolean isValid(Litmus litmus) {
        if (!rootNode.isValid(litmus)) {
            return false;
        }
        for (Measure measure : defaultMeasures) {
            for (Column arg : measure.args) {
                if (columns.get(arg.ordinal) != arg) {
                    return litmus.fail("measure argument must be a column registered in" + " this lattice: {}", measure);
                }
            }
        }
        return litmus.succeed();
    }

    private static void populateAliases(SqlNode from, List<String> aliases, @Nullable String current) {
        if (from instanceof SqlJoin) {
            SqlJoin join = (SqlJoin) from;
            populateAliases(join.getLeft(), aliases, null);
            populateAliases(join.getRight(), aliases, null);
        } else if (from.getKind() == SqlKind.AS) {
            populateAliases(SqlUtil.stripAs(from), aliases, SqlValidatorUtil.getAlias(from, -1));
        } else {
            if (current == null) {
                current = SqlValidatorUtil.getAlias(from, -1);
            }
            aliases.add(current);
        }
    }

    private static boolean populate(List<RelNode> nodes, List<int[][]> tempLinks, RelNode rel) {
        if (nodes.isEmpty() && rel instanceof LogicalProject) {
            return populate(nodes, tempLinks, ((LogicalProject) rel).getInput());
        }
        if (rel instanceof TableScan) {
            nodes.add(rel);
            return true;
        }
        if (rel instanceof LogicalJoin) {
            LogicalJoin join = (LogicalJoin) rel;
            if (join.getJoinType().isOuterJoin()) {
                throw new RuntimeException("only non nulls-generating join allowed, but got " + join.getJoinType());
            }
            populate(nodes, tempLinks, join.getLeft());
            populate(nodes, tempLinks, join.getRight());
            for (RexNode rex : RelOptUtil.conjunctions(join.getCondition())) {
                tempLinks.add(grab(nodes, rex));
            }
            return true;
        }
        throw new RuntimeException("Invalid node type " + rel.getClreplaced().getSimpleName() + " in lattice query");
    }

    /**
     * Converts an "t1.c1 = t2.c2" expression into two (input, field) pairs.
     */
    private static int[][] grab(List<RelNode> leaves, RexNode rex) {
        switch(rex.getKind()) {
            case EQUALS:
                break;
            default:
                throw new replacedertionError("only equi-join allowed");
        }
        final List<RexNode> operands = ((RexCall) rex).getOperands();
        return new int[][] { inputField(leaves, operands.get(0)), inputField(leaves, operands.get(1)) };
    }

    /**
     * Converts an expression into an (input, field) pair.
     */
    private static int[] inputField(List<RelNode> leaves, RexNode rex) {
        if (!(rex instanceof RexInputRef)) {
            throw new RuntimeException("only equi-join of columns allowed: " + rex);
        }
        RexInputRef ref = (RexInputRef) rex;
        int start = 0;
        for (int i = 0; i < leaves.size(); i++) {
            final RelNode leaf = leaves.get(i);
            final int end = start + leaf.getRowType().getFieldCount();
            if (ref.getIndex() < end) {
                return new int[] { i, ref.getIndex() - start };
            }
            start = end;
        }
        throw new replacedertionError("input not found");
    }

    @Override
    public String toString() {
        return rootNode + ":" + defaultMeasures;
    }

    /**
     * Generates a SQL query to populate a tile of the lattice specified by a
     * given set of columns and measures.
     */
    public String sql(ImmutableBitSet groupSet, List<Measure> aggCallList) {
        return sql(groupSet, true, aggCallList);
    }

    /**
     * Generates a SQL query to populate a tile of the lattice specified by a
     * given set of columns and measures, optionally grouping.
     */
    public String sql(ImmutableBitSet groupSet, boolean group, List<Measure> aggCallList) {
        final List<LatticeNode> usedNodes = new ArrayList<>();
        if (group) {
            final ImmutableBitSet.Builder columnSetBuilder = groupSet.rebuild();
            for (Measure call : aggCallList) {
                for (Column arg : call.args) {
                    columnSetBuilder.set(arg.ordinal);
                }
            }
            final ImmutableBitSet columnSet = columnSetBuilder.build();
            // Figure out which nodes are needed. Use a node if its columns are used
            // or if has a child whose columns are used.
            for (LatticeNode node : rootNode.descendants) {
                if (ImmutableBitSet.range(node.startCol, node.endCol).intersects(columnSet)) {
                    node.use(usedNodes);
                }
                if (usedNodes.isEmpty()) {
                    usedNodes.add(rootNode);
                }
            }
        } else {
            usedNodes.addAll(rootNode.descendants);
        }
        final SqlDialect dialect = SqlDialect.DatabaseProduct.CALCITE.getDialect();
        final StringBuilder buf = new StringBuilder("SELECT ");
        final StringBuilder groupBuf = new StringBuilder("\nGROUP BY ");
        int k = 0;
        final Set<String> columnNames = new HashSet<>();
        final SqlWriter w = createSqlWriter(dialect, buf, f -> {
            throw new UnsupportedOperationException();
        });
        if (groupSet != null) {
            for (int i : groupSet) {
                if (k++ > 0) {
                    buf.append(", ");
                    groupBuf.append(", ");
                }
                final Column column = columns.get(i);
                column.toSql(w);
                column.toSql(w.with(groupBuf));
                if (column instanceof BaseColumn) {
                    columnNames.add(((BaseColumn) column).column);
                }
                if (!column.alias.equals(column.defaultAlias())) {
                    buf.append(" AS ");
                    dialect.quoteIdentifier(buf, column.alias);
                }
            }
            int m = 0;
            for (Measure measure : aggCallList) {
                if (k++ > 0) {
                    buf.append(", ");
                }
                buf.append(measure.agg.getName()).append("(");
                if (measure.args.isEmpty()) {
                    buf.append("*");
                } else {
                    int z = 0;
                    for (Column arg : measure.args) {
                        if (z++ > 0) {
                            buf.append(", ");
                        }
                        arg.toSql(w);
                    }
                }
                buf.append(") AS ");
                String measureName;
                while (!columnNames.add(measureName = "m" + m)) {
                    ++m;
                }
                dialect.quoteIdentifier(buf, measureName);
            }
        } else {
            buf.append("*");
        }
        buf.append("\nFROM ");
        for (LatticeNode node : usedNodes) {
            if (node instanceof LatticeChildNode) {
                buf.append("\nJOIN ");
            }
            dialect.quoteIdentifier(buf, node.table.t.getQualifiedName());
            buf.append(" AS ");
            dialect.quoteIdentifier(buf, node.alias);
            if (node instanceof LatticeChildNode) {
                final LatticeChildNode node1 = (LatticeChildNode) node;
                buf.append(" ON ");
                k = 0;
                for (IntPair pair : node1.link) {
                    if (k++ > 0) {
                        buf.append(" AND ");
                    }
                    final Column left = columns.get(node1.parent.startCol + pair.source);
                    left.toSql(w);
                    buf.append(" = ");
                    final Column right = columns.get(node.startCol + pair.target);
                    right.toSql(w);
                }
            }
        }
        if (CalciteSystemProperty.DEBUG.value()) {
            System.out.println("Lattice SQL:\n" + buf);
        }
        if (group) {
            if (groupSet.isEmpty()) {
                groupBuf.append("()");
            }
            buf.append(groupBuf);
        }
        return buf.toString();
    }

    /**
     * Creates a context to which SQL can be generated.
     */
    public SqlWriter createSqlWriter(SqlDialect dialect, StringBuilder buf, IntFunction<SqlNode> field) {
        return new SqlWriter(this, dialect, buf, new SqlImplementor.SimpleContext(dialect, field));
    }

    /**
     * Returns a SQL query that counts the number of distinct values of the
     * attributes given in {@code groupSet}.
     */
    public String countSql(ImmutableBitSet groupSet) {
        return "select count(*) as c from (" + sql(groupSet, ImmutableList.of()) + ")";
    }

    public StarTable createStarTable() {
        final List<Table> tables = new ArrayList<>();
        for (LatticeNode node : rootNode.descendants) {
            tables.add(node.table.t.unwrap(Table.clreplaced));
        }
        return StarTable.of(this, tables);
    }

    public static Builder builder(CalciteSchema calciteSchema, String sql) {
        return builder(new LatticeSpace(MapSqlStatisticProvider.INSTANCE), calciteSchema, sql);
    }

    static Builder builder(LatticeSpace space, CalciteSchema calciteSchema, String sql) {
        return new Builder(space, calciteSchema, sql);
    }

    public List<Measure> toMeasures(List<AggregateCall> aggCallList) {
        return Lists.transform(aggCallList, this::toMeasure);
    }

    private Measure toMeasure(AggregateCall aggCall) {
        return new Measure(aggCall.getAggregation(), aggCall.isDistinct(), aggCall.name, Lists.transform(aggCall.getArgList(), columns::get));
    }

    public Iterable<? extends Tile> computeTiles() {
        if (!algorithm) {
            return tiles;
        }
        return new TileSuggester(this).tiles();
    }

    /**
     * Returns an estimate of the number of rows in the un-aggregated star.
     */
    public double getFactRowCount() {
        return rowCountEstimate;
    }

    /**
     * Returns an estimate of the number of rows in the tile with the given
     * dimensions.
     */
    public double getRowCount(List<Column> columns) {
        return statisticProvider.cardinality(columns);
    }

    /**
     * Returns an estimate of the number of rows in the tile with the given
     * dimensions.
     */
    public static double getRowCount(double factCount, double... columnCounts) {
        return getRowCount(factCount, Primitive.asList(columnCounts));
    }

    /**
     * Returns an estimate of the number of rows in the tile with the given
     * dimensions.
     */
    public static double getRowCount(double factCount, List<Double> columnCounts) {
        // The expected number of distinct values when choosing p values
        // with replacement from n integers is n . (1 - ((n - 1) / n) ^ p).
        // 
        // If we have several uniformly distributed attributes A1 ... Am
        // with N1 ... Nm distinct values, they behave as one uniformly
        // distributed attribute with N1 * ... * Nm distinct values.
        double n = 1d;
        for (Double columnCount : columnCounts) {
            if (columnCount > 1d) {
                n *= columnCount;
            }
        }
        final double a = (n - 1d) / n;
        if (a == 1d) {
            // A under-flows if nn is large.
            return factCount;
        }
        final double v = n * (1d - Math.pow(a, factCount));
        // Cap at fact-row-count, because numerical artifacts can cause it
        // to go a few % over.
        return Math.min(v, factCount);
    }

    public List<String> uniqueColumnNames() {
        return Lists.transform(columns, column -> column.alias);
    }

    Pair<Path, Integer> columnToPathOffset(BaseColumn c) {
        for (Pair<LatticeNode, Path> p : Pair.zip(rootNode.descendants, rootNode.paths)) {
            if (p.left.alias.equals(c.table)) {
                return Pair.of(p.right, c.ordinal - p.left.startCol);
            }
        }
        throw new replacedertionError("lattice column not found: " + c);
    }

    /**
     * Returns the set of tables in this lattice.
     */
    public Set<LatticeTable> tables() {
        return rootNode.descendants.stream().map(n -> n.table).collect(Collectors.toCollection(LinkedHashSet::new));
    }

    /**
     * Returns the ordinal, within all of the columns in this Lattice, of the
     * first column in the table with a given alias.
     * Returns -1 if the table is not found.
     */
    public int firstColumn(String tableAlias) {
        for (Column column : columns) {
            if (column instanceof BaseColumn && ((BaseColumn) column).table.equals(tableAlias)) {
                return column.ordinal;
            }
        }
        return -1;
    }

    /**
     * Returns whether every use of a column is as an argument to a measure.
     *
     * <p>For example, in the query
     * {@code select sum(x + y), sum(a + b) from t group by x + y}
     * the expression "x + y" is used once as an argument to a measure,
     * and once as a dimension.
     *
     * <p>Therefore, in a lattice created from that one query,
     * {@code isAlwaysMeasure} for the derived column corresponding to "x + y"
     * returns false, and for "a + b" returns true.
     *
     * @param column Column or derived column
     * @return Whether all uses are as arguments to aggregate functions
     */
    public boolean isAlwaysMeasure(Column column) {
        return !columnUses.get(column.ordinal).contains(false);
    }

    /**
     * Edge in the temporary graph.
     */
    private static clreplaced Edge extends DefaultEdge {

        public static final DirectedGraph.EdgeFactory<Vertex, Edge> FACTORY = Edge::new;

        final List<IntPair> pairs = new ArrayList<>();

        Edge(Vertex source, Vertex target) {
            super(source, target);
        }

        Vertex getTarget() {
            return (Vertex) target;
        }

        Vertex getSource() {
            return (Vertex) source;
        }
    }

    /**
     * Vertex in the temporary graph.
     */
    private static clreplaced Vertex {

        final LatticeTable table;

        final String alias;

        private Vertex(LatticeTable table, String alias) {
            this.table = table;
            this.alias = alias;
        }
    }

    /**
     * A measure within a {@link Lattice}.
     *
     * <p>It is immutable.
     *
     * <p>Examples: SUM(products.weight), COUNT() (means "COUNT(*")),
     * COUNT(DISTINCT customer.id).
     */
    public static clreplaced Measure implements Comparable<Measure> {

        public final SqlAggFunction agg;

        public final boolean distinct;

        @Nullable
        public final String name;

        public final ImmutableList<Column> args;

        public final String digest;

        public Measure(SqlAggFunction agg, boolean distinct, @Nullable String name, Iterable<Column> args) {
            this.agg = Objects.requireNonNull(agg);
            this.distinct = distinct;
            this.name = name;
            this.args = ImmutableList.copyOf(args);
            final StringBuilder b = new StringBuilder().append(agg).append(distinct ? "(DISTINCT " : "(");
            for (Ord<Column> arg : Ord.zip(this.args)) {
                if (arg.i > 0) {
                    b.append(", ");
                }
                if (arg.e instanceof BaseColumn) {
                    b.append(((BaseColumn) arg.e).table);
                    b.append('.');
                    b.append(((BaseColumn) arg.e).column);
                } else {
                    b.append(arg.e.alias);
                }
            }
            b.append(')');
            this.digest = b.toString();
        }

        public int compareTo(@Nonnull Measure measure) {
            int c = compare(args, measure.args);
            if (c == 0) {
                c = agg.getName().compareTo(measure.agg.getName());
                if (c == 0) {
                    c = Boolean.compare(distinct, measure.distinct);
                }
            }
            return c;
        }

        @Override
        public String toString() {
            return digest;
        }

        @Override
        public int hashCode() {
            return Objects.hash(agg, args);
        }

        @Override
        public boolean equals(Object obj) {
            return obj == this || obj instanceof Measure && this.agg.equals(((Measure) obj).agg) && this.args.equals(((Measure) obj).args) && this.distinct == ((Measure) obj).distinct;
        }

        /**
         * Returns the set of distinct argument ordinals.
         */
        public ImmutableBitSet argBitSet() {
            final ImmutableBitSet.Builder bitSet = ImmutableBitSet.builder();
            for (Column arg : args) {
                bitSet.set(arg.ordinal);
            }
            return bitSet.build();
        }

        /**
         * Returns a list of argument ordinals.
         */
        public List<Integer> argOrdinals() {
            return Lists.transform(args, column -> column.ordinal);
        }

        private static int compare(List<Column> list0, List<Column> list1) {
            final int size = Math.min(list0.size(), list1.size());
            for (int i = 0; i < size; i++) {
                final int o0 = list0.get(i).ordinal;
                final int o1 = list1.get(i).ordinal;
                final int c = Utilities.compare(o0, o1);
                if (c != 0) {
                    return c;
                }
            }
            return Utilities.compare(list0.size(), list1.size());
        }

        /**
         * Copies this measure, mapping its arguments using a given function.
         */
        Measure copy(Function<Column, Column> mapper) {
            return new Measure(agg, distinct, name, Util.transform(args, mapper));
        }
    }

    /**
     * Column in a lattice. May be an a base column or an expression,
     * and may have an additional alias that is unique
     * within the entire lattice.
     */
    public abstract static clreplaced Column implements Comparable<Column> {

        /**
         * Ordinal of the column within the lattice.
         */
        public final int ordinal;

        /**
         * Alias of the column, unique within the lattice. Derived from the column
         * name, automatically disambiguated if necessary.
         */
        public final String alias;

        private Column(int ordinal, String alias) {
            this.ordinal = ordinal;
            this.alias = Objects.requireNonNull(alias);
        }

        /**
         * Converts a list of columns to a bit set of their ordinals.
         */
        static ImmutableBitSet toBitSet(List<Column> columns) {
            final ImmutableBitSet.Builder builder = ImmutableBitSet.builder();
            for (Column column : columns) {
                builder.set(column.ordinal);
            }
            return builder.build();
        }

        public int compareTo(Column column) {
            return Utilities.compare(ordinal, column.ordinal);
        }

        @Override
        public int hashCode() {
            return ordinal;
        }

        @Override
        public boolean equals(Object obj) {
            return obj == this || obj instanceof Column && this.ordinal == ((Column) obj).ordinal;
        }

        public abstract void toSql(SqlWriter writer);

        /**
         * The alias that SQL would give to this expression.
         */
        public abstract String defaultAlias();
    }

    /**
     * Column in a lattice. Columns are identified by table alias and
     * column name, and may have an additional alias that is unique
     * within the entire lattice.
     */
    public static clreplaced BaseColumn extends Column {

        /**
         * Alias of the table reference that the column belongs to.
         */
        public final String table;

        /**
         * Name of the column. Unique within the table reference, but not
         * necessarily within the lattice.
         */
        @Nonnull
        public final String column;

        private BaseColumn(int ordinal, String table, String column, String alias) {
            super(ordinal, alias);
            this.table = Objects.requireNonNull(table);
            this.column = Objects.requireNonNull(column);
        }

        @Override
        public String toString() {
            return identifiers().toString();
        }

        public List<String> identifiers() {
            return ImmutableList.of(table, column);
        }

        public void toSql(SqlWriter writer) {
            writer.dialect.quoteIdentifier(writer.buf, identifiers());
        }

        public String defaultAlias() {
            return column;
        }
    }

    /**
     * Column in a lattice that is based upon a SQL expression.
     */
    public static clreplaced DerivedColumn extends Column {

        @Nonnull
        public final RexNode e;

        @Nonnull
        final List<String> tables;

        private DerivedColumn(int ordinal, String alias, RexNode e, List<String> tables) {
            super(ordinal, alias);
            this.e = e;
            this.tables = ImmutableList.copyOf(tables);
        }

        @Override
        public String toString() {
            return Arrays.toString(new Object[] { e, alias });
        }

        public void toSql(SqlWriter writer) {
            writer.write(e);
        }

        public String defaultAlias() {
            // there is no default alias for an expression
            return null;
        }
    }

    /**
     * The information necessary to convert a column to SQL.
     */
    public static clreplaced SqlWriter {

        public final Lattice lattice;

        public final StringBuilder buf;

        public final SqlDialect dialect;

        private final SqlImplementor.SimpleContext context;

        SqlWriter(Lattice lattice, SqlDialect dialect, StringBuilder buf, SqlImplementor.SimpleContext context) {
            this.lattice = lattice;
            this.context = context;
            this.buf = buf;
            this.dialect = dialect;
        }

        /**
         * Re-binds this writer to a different {@link StringBuilder}.
         */
        public SqlWriter with(StringBuilder buf) {
            return new SqlWriter(lattice, dialect, buf, context);
        }

        /**
         * Writes an expression.
         */
        public SqlWriter write(RexNode e) {
            final SqlNode node = context.toSql(null, e);
            buf.append(node.toSqlString(dialect));
            return this;
        }
    }

    /**
     * Lattice builder.
     */
    public static clreplaced Builder {

        private final LatticeRootNode rootNode;

        private final ImmutableList<BaseColumn> baseColumns;

        private final ImmutableListMultimap<String, Column> columnsByAlias;

        private final SortedSet<Measure> defaultMeasureSet = new TreeSet<>();

        private final ImmutableList.Builder<Tile> tileListBuilder = ImmutableList.builder();

        private final Multimap<Integer, Boolean> columnUses = LinkedHashMultimap.create();

        private final CalciteSchema rootSchema;

        private boolean algorithm = false;

        private long algorithmMaxMillis = -1;

        private boolean auto = true;

        private Double rowCountEstimate;

        private String statisticProvider;

        private Map<String, DerivedColumn> derivedColumnsByName = new LinkedHashMap<>();

        public Builder(LatticeSpace space, CalciteSchema schema, String sql) {
            this.rootSchema = Objects.requireNonNull(schema.root());
            Preconditions.checkArgument(rootSchema.isRoot(), "must be root schema");
            CalcitePrepare.ConvertResult parsed = Schemas.convert(MaterializedViewTable.MATERIALIZATION_CONNECTION, schema, schema.path(null), sql);
            // Walk the join tree.
            List<RelNode> relNodes = new ArrayList<>();
            List<int[][]> tempLinks = new ArrayList<>();
            populate(relNodes, tempLinks, parsed.root.rel);
            // Get aliases.
            List<String> aliases = new ArrayList<>();
            populateAliases(((SqlSelect) parsed.sqlNode).getFrom(), aliases, null);
            // Build a graph.
            final DirectedGraph<Vertex, Edge> graph = DefaultDirectedGraph.create(Edge.FACTORY);
            final List<Vertex> vertices = new ArrayList<>();
            for (Pair<RelNode, String> p : Pair.zip(relNodes, aliases)) {
                final LatticeTable table = space.register(p.left.getTable());
                final Vertex vertex = new Vertex(table, p.right);
                graph.addVertex(vertex);
                vertices.add(vertex);
            }
            for (int[][] tempLink : tempLinks) {
                final Vertex source = vertices.get(tempLink[0][0]);
                final Vertex target = vertices.get(tempLink[1][0]);
                Edge edge = graph.getEdge(source, target);
                if (edge == null) {
                    edge = graph.addEdge(source, target);
                }
                edge.pairs.add(IntPair.of(tempLink[0][1], tempLink[1][1]));
            }
            // Convert the graph into a tree of nodes, each connected to a parent and
            // with a join condition to that parent.
            MutableNode root = null;
            final Map<LatticeTable, MutableNode> map = new IdenreplacedyHashMap<>();
            for (Vertex vertex : TopologicalOrderIterator.of(graph)) {
                final List<Edge> edges = graph.getInwardEdges(vertex);
                MutableNode node;
                if (root == null) {
                    if (!edges.isEmpty()) {
                        throw new RuntimeException("root node must not have relationships: " + vertex);
                    }
                    root = node = new MutableNode(vertex.table);
                    node.alias = vertex.alias;
                } else {
                    if (edges.size() != 1) {
                        throw new RuntimeException("child node must have precisely one parent: " + vertex);
                    }
                    final Edge edge = edges.get(0);
                    final MutableNode parent = map.get(edge.getSource().table);
                    final Step step = Step.create(edge.getSource().table, edge.getTarget().table, edge.pairs, space);
                    node = new MutableNode(vertex.table, parent, step);
                    node.alias = vertex.alias;
                }
                map.put(vertex.table, node);
            }
            replacedert root != null;
            final Fixer fixer = new Fixer();
            fixer.fixUp(root);
            baseColumns = fixer.columnList.build();
            columnsByAlias = fixer.columnAliasList.build();
            rootNode = new LatticeRootNode(space, root);
        }

        /**
         * Creates a Builder based upon a mutable node.
         */
        Builder(LatticeSpace space, CalciteSchema schema, MutableNode mutableNode) {
            this.rootSchema = schema;
            final Fixer fixer = new Fixer();
            fixer.fixUp(mutableNode);
            final LatticeRootNode node0 = new LatticeRootNode(space, mutableNode);
            final LatticeRootNode node1 = space.nodeMap.get(node0.digest);
            final LatticeRootNode node;
            if (node1 != null) {
                node = node1;
            } else {
                node = node0;
                space.nodeMap.put(node0.digest, node0);
            }
            this.rootNode = node;
            baseColumns = fixer.columnList.build();
            columnsByAlias = fixer.columnAliasList.build();
        }

        /**
         * Sets the "auto" attribute (default true).
         */
        public Builder auto(boolean auto) {
            this.auto = auto;
            return this;
        }

        /**
         * Sets the "algorithm" attribute (default false).
         */
        public Builder algorithm(boolean algorithm) {
            this.algorithm = algorithm;
            return this;
        }

        /**
         * Sets the "algorithmMaxMillis" attribute (default -1).
         */
        public Builder algorithmMaxMillis(long algorithmMaxMillis) {
            this.algorithmMaxMillis = algorithmMaxMillis;
            return this;
        }

        /**
         * Sets the "rowCountEstimate" attribute (default null).
         */
        public Builder rowCountEstimate(double rowCountEstimate) {
            this.rowCountEstimate = rowCountEstimate;
            return this;
        }

        /**
         * Sets the "statisticProvider" attribute.
         *
         * <p>If not set, the lattice will use {@link Lattices#CACHED_SQL}.
         */
        public Builder statisticProvider(String statisticProvider) {
            this.statisticProvider = statisticProvider;
            return this;
        }

        /**
         * Builds a lattice.
         */
        public Lattice build() {
            LatticeStatisticProvider.Factory statisticProvider = this.statisticProvider != null ? AvaticaUtils.instantiatePlugin(LatticeStatisticProvider.Factory.clreplaced, this.statisticProvider) : Lattices.CACHED_SQL;
            Preconditions.checkArgument(rootSchema.isRoot(), "must be root schema");
            final ImmutableList.Builder<Column> columnBuilder = ImmutableList.<Column>builder().addAll(baseColumns).addAll(derivedColumnsByName.values());
            return new Lattice(rootSchema, rootNode, auto, algorithm, algorithmMaxMillis, statisticProvider, rowCountEstimate, columnBuilder.build(), ImmutableSortedSet.copyOf(defaultMeasureSet), tileListBuilder.build(), ImmutableListMultimap.copyOf(columnUses));
        }

        /**
         * Resolves the arguments of a
         * {@link org.apache.calcite.model.JsonMeasure}. They must either be null,
         * a string, or a list of strings. Throws if the structure is invalid, or if
         * any of the columns do not exist in the lattice.
         */
        public ImmutableList<Column> resolveArgs(@Nullable Object args) {
            if (args == null) {
                return ImmutableList.of();
            } else if (args instanceof String) {
                return ImmutableList.of(resolveColumnByAlias((String) args));
            } else if (args instanceof List) {
                final ImmutableList.Builder<Column> builder = ImmutableList.builder();
                for (Object o : (List) args) {
                    if (o instanceof String) {
                        builder.add(resolveColumnByAlias((String) o));
                    } else {
                        throw new RuntimeException("Measure arguments must be a string or a list of strings; argument: " + o);
                    }
                }
                return builder.build();
            } else {
                throw new RuntimeException("Measure arguments must be a string or a list of strings");
            }
        }

        /**
         * Looks up a column in this lattice by alias. The alias must be unique
         * within the lattice.
         */
        private Column resolveColumnByAlias(String name) {
            final ImmutableList<Column> list = columnsByAlias.get(name);
            if (list == null || list.size() == 0) {
                throw new RuntimeException("Unknown lattice column '" + name + "'");
            } else if (list.size() == 1) {
                return list.get(0);
            } else {
                throw new RuntimeException("Lattice column alias '" + name + "' is not unique");
            }
        }

        public Column resolveColumn(Object name) {
            if (name instanceof String) {
                return resolveColumnByAlias((String) name);
            }
            if (name instanceof List) {
                List list = (List) name;
                switch(list.size()) {
                    case 1:
                        final Object alias = list.get(0);
                        if (alias instanceof String) {
                            return resolveColumnByAlias((String) alias);
                        }
                        break;
                    case 2:
                        final Object table = list.get(0);
                        final Object column = list.get(1);
                        if (table instanceof String && column instanceof String) {
                            return resolveQualifiedColumn((String) table, (String) column);
                        }
                        break;
                }
            }
            throw new RuntimeException("Lattice column reference must be a string or a list of 1 or 2 strings; column: " + name);
        }

        private Column resolveQualifiedColumn(String table, String column) {
            for (BaseColumn column1 : baseColumns) {
                if (column1.table.equals(table) && column1.column.equals(column)) {
                    return column1;
                }
            }
            throw new RuntimeException("Unknown lattice column [" + table + ", " + column + "]");
        }

        public Measure resolveMeasure(String aggName, boolean distinct, @Nullable Object args) {
            final SqlAggFunction agg = resolveAgg(aggName);
            final ImmutableList<Column> list = resolveArgs(args);
            return new Measure(agg, distinct, aggName, list);
        }

        private SqlAggFunction resolveAgg(String aggName) {
            if (aggName.equalsIgnoreCase("count")) {
                return SqlStdOperatorTable.COUNT;
            } else if (aggName.equalsIgnoreCase("sum")) {
                return SqlStdOperatorTable.SUM;
            } else {
                throw new RuntimeException("Unknown lattice aggregate function " + aggName);
            }
        }

        /**
         * Adds a measure, if it does not already exist.
         * Returns false if an identical measure already exists.
         */
        public boolean addMeasure(Measure measure) {
            return defaultMeasureSet.add(measure);
        }

        public void addTile(Tile tile) {
            tileListBuilder.add(tile);
        }

        public Column column(int table, int column) {
            int i = 0;
            for (LatticeNode descendant : rootNode.descendants) {
                if (table-- == 0) {
                    break;
                }
                i += descendant.table.t.getRowType().getFieldCount();
            }
            return baseColumns.get(i + column);
        }

        Column pathOffsetToColumn(Path path, int offset) {
            final int i = rootNode.paths.indexOf(path);
            final LatticeNode node = rootNode.descendants.get(i);
            final int c = node.startCol + offset;
            if (c >= node.endCol) {
                throw new replacedertionError();
            }
            return baseColumns.get(c);
        }

        /**
         * Adds a lattice column based on a SQL expression,
         * or returns a column based on the same expression seen previously.
         */
        public Column expression(RexNode e, String alias, List<String> tableAliases) {
            return derivedColumnsByName.computeIfAbsent(e.toString(), k -> {
                final int derivedOrdinal = derivedColumnsByName.size();
                final int ordinal = baseColumns.size() + derivedOrdinal;
                return new DerivedColumn(ordinal, Util.first(alias, "e$" + derivedOrdinal), e, tableAliases);
            });
        }

        /**
         * Records a use of a column.
         *
         * @param column Column
         * @param measure Whether this use is as an argument to a measure;
         *                e.g. "sum(x + y)" is a measure use of the expression
         *                "x + y"; "group by x + y" is not
         */
        public void use(Column column, boolean measure) {
            columnUses.put(column.ordinal, measure);
        }

        /**
         * Work space for fixing up a tree of mutable nodes.
         */
        private static clreplaced Fixer {

            final Set<String> aliases = new HashSet<>();

            final Set<String> columnAliases = new HashSet<>();

            final Set<MutableNode> seen = new HashSet<>();

            final ImmutableList.Builder<BaseColumn> columnList = ImmutableList.builder();

            final ImmutableListMultimap.Builder<String, Column> columnAliasList = ImmutableListMultimap.builder();

            int c;

            void fixUp(MutableNode node) {
                if (!seen.add(node)) {
                    throw new IllegalArgumentException("cyclic query graph");
                }
                if (node.alias == null) {
                    node.alias = Util.last(node.table.t.getQualifiedName());
                }
                node.alias = SqlValidatorUtil.uniquify(node.alias, aliases, SqlValidatorUtil.ATTEMPT_SUGGESTER);
                node.startCol = c;
                for (String name : node.table.t.getRowType().getFieldNames()) {
                    final String alias = SqlValidatorUtil.uniquify(name, columnAliases, SqlValidatorUtil.ATTEMPT_SUGGESTER);
                    final BaseColumn column = new BaseColumn(c++, node.alias, name, alias);
                    columnList.add(column);
                    // name before it is made unique
                    columnAliasList.put(name, column);
                }
                node.endCol = c;
                replacedert MutableNode.ORDERING.isStrictlyOrdered(node.children) : node.children;
                for (MutableNode child : node.children) {
                    fixUp(child);
                }
            }
        }
    }

    /**
     * Materialized aggregate within a lattice.
     */
    public static clreplaced Tile {

        public final ImmutableList<Measure> measures;

        public final ImmutableList<Column> dimensions;

        public final ImmutableBitSet bitSet;

        public Tile(ImmutableList<Measure> measures, ImmutableList<Column> dimensions) {
            this.measures = Objects.requireNonNull(measures);
            this.dimensions = Objects.requireNonNull(dimensions);
            replacedert Ordering.natural().isStrictlyOrdered(dimensions);
            replacedert Ordering.natural().isStrictlyOrdered(measures);
            bitSet = Column.toBitSet(dimensions);
        }

        public static TileBuilder builder() {
            return new TileBuilder();
        }

        public ImmutableBitSet bitSet() {
            return bitSet;
        }
    }

    /**
     * Tile builder.
     */
    public static clreplaced TileBuilder {

        private final List<Measure> measureBuilder = new ArrayList<>();

        private final List<Column> dimensionListBuilder = new ArrayList<>();

        public Tile build() {
            return new Tile(Ordering.natural().immutableSortedCopy(measureBuilder), Ordering.natural().immutableSortedCopy(dimensionListBuilder));
        }

        public void addMeasure(Measure measure) {
            measureBuilder.add(measure);
        }

        public void addDimension(Column column) {
            dimensionListBuilder.add(column);
        }
    }
}

19 View Complete Implementation : Schemas.java
Copyright Apache License 2.0
Author : apache
/**
 * Returns a sub-schema of a given schema obtained by following a sequence
 * of names.
 *
 * <p>The result is null if the initial schema is null or any sub-schema does
 * not exist.
 */
public static CalciteSchema subSchema(CalciteSchema schema, Iterable<String> names) {
    for (String string : names) {
        if (schema == null) {
            return null;
        }
        schema = schema.getSubSchema(string, false);
    }
    return schema;
}

19 View Complete Implementation : Lattice.java
Copyright Apache License 2.0
Author : apache
/**
 * Creates a Lattice.
 */
public static Lattice create(CalciteSchema schema, String sql, boolean auto) {
    return builder(schema, sql).auto(auto).build();
}

19 View Complete Implementation : Lattice.java
Copyright Apache License 2.0
Author : apache
static Builder builder(LatticeSpace space, CalciteSchema calciteSchema, String sql) {
    return new Builder(space, calciteSchema, sql);
}

19 View Complete Implementation : SqlValidatorUtil.java
Copyright Apache License 2.0
Author : apache
/**
 * Finds a {@link org.apache.calcite.jdbc.CalciteSchema.TypeEntry} in a
 * given schema whose type has the given name, possibly qualified.
 *
 * @param rootSchema root schema
 * @param typeName name of the type, may be qualified or fully-qualified
 *
 * @return TypeEntry with a table with the given name, or null
 */
public static CalciteSchema.TypeEntry getTypeEntry(CalciteSchema rootSchema, SqlIdentifier typeName) {
    final String name;
    final List<String> path;
    if (typeName.isSimple()) {
        path = ImmutableList.of();
        name = typeName.getSimple();
    } else {
        path = Util.skipLast(typeName.names);
        name = Util.last(typeName.names);
    }
    CalciteSchema schema = rootSchema;
    for (String p : path) {
        if (schema == rootSchema && SqlNameMatchers.withCaseSensitive(true).matches(p, schema.getName())) {
            continue;
        }
        schema = schema.getSubSchema(p, true);
    }
    return schema == null ? null : schema.getType(name, false);
}

19 View Complete Implementation : PigTableScan.java
Copyright Apache License 2.0
Author : apache
private PigTable getPigTable(String name) {
    final CalciteSchema schema = getTable().unwrap(org.apache.calcite.jdbc.CalciteSchema.clreplaced);
    return (PigTable) schema.getTable(name, false).getTable();
}

19 View Complete Implementation : Schemas.java
Copyright Apache License 2.0
Author : apache
/**
 * Returns the lattices defined in a schema.
 *
 * @param schema Schema
 */
public static List<CalciteSchema.LatticeEntry> getLatticeEntries(CalciteSchema schema) {
    final List<LatticeEntry> list = new ArrayList<>();
    gatherLattices(schema, list);
    return list;
}

19 View Complete Implementation : MaterializedViewTable.java
Copyright Apache License 2.0
Author : apache
/**
 * Table macro that returns a materialized view.
 */
public static MaterializedViewTableMacro create(final CalciteSchema schema, final String viewSql, final List<String> viewSchemaPath, List<String> viewPath, final String suggestedTableName, boolean existing) {
    return new MaterializedViewTableMacro(schema, viewSql, viewSchemaPath, viewPath, suggestedTableName, existing);
}

19 View Complete Implementation : SqlValidatorUtil.java
Copyright Apache License 2.0
Author : apache
/**
 * Finds and returns {@link CalciteSchema} nested to the given rootSchema
 * with specified schemaPath.
 *
 * <p>Uses the case-sensitivity policy of specified nameMatcher.
 *
 * <p>If not found, returns null.
 *
 * @param rootSchema root schema
 * @param schemaPath full schema path of required schema
 * @param nameMatcher name matcher
 *
 * @return CalciteSchema that corresponds specified schemaPath
 */
public static CalciteSchema getSchema(CalciteSchema rootSchema, Iterable<String> schemaPath, SqlNameMatcher nameMatcher) {
    CalciteSchema schema = rootSchema;
    for (String schemaName : schemaPath) {
        if (schema == rootSchema && nameMatcher.matches(schemaName, schema.getName())) {
            continue;
        }
        schema = schema.getSubSchema(schemaName, nameMatcher.isCaseSensitive());
        if (schema == null) {
            return null;
        }
    }
    return schema;
}

19 View Complete Implementation : CalcitePrepareImpl.java
Copyright Apache License 2.0
Author : apache
/**
 * Executes a prepare action.
 */
public <R> R perform(CalciteServerStatement statement, FrameworkConfig config, Frameworks.BasePrepareAction<R> action) {
    final CalcitePrepare.Context prepareContext = statement.createPrepareContext();
    final JavaTypeFactory typeFactory = prepareContext.getTypeFactory();
    final CalciteSchema schema = config.getDefaultSchema() != null ? CalciteSchema.from(config.getDefaultSchema()) : prepareContext.getRootSchema();
    CalciteCatalogReader catalogReader = new CalciteCatalogReader(schema.root(), schema.path(null), typeFactory, prepareContext.config());
    final RexBuilder rexBuilder = new RexBuilder(typeFactory);
    final RelOptPlanner planner = createPlanner(prepareContext, config.getContext(), config.getCostFactory());
    final RelOptCluster cluster = createCluster(planner, rexBuilder);
    return action.apply(cluster, catalogReader, prepareContext.getRootSchema().plus(), statement);
}

19 View Complete Implementation : MaterializationService.java
Copyright Apache License 2.0
Author : apache
/**
 * Defines a new materialization. Returns its key.
 */
public MaterializationKey defineMaterialization(final CalciteSchema schema, TileKey tileKey, String viewSql, List<String> viewSchemaPath, final String suggestedTableName, boolean create, boolean existing) {
    return defineMaterialization(schema, tileKey, viewSql, viewSchemaPath, suggestedTableName, tableFactory, create, existing);
}

19 View Complete Implementation : SqlValidatorUtil.java
Copyright Apache License 2.0
Author : apache
private static CalciteSchema.TableEntry getTableEntryFrom(CalciteSchema schema, String name, boolean caseSensitive) {
    CalciteSchema.TableEntry entry = schema.getTable(name, caseSensitive);
    if (entry == null) {
        entry = schema.getTableBasedOnNullaryFunction(name, caseSensitive);
    }
    return entry;
}

19 View Complete Implementation : CalcitePrepareImpl.java
Copyright Apache License 2.0
Author : apache
protected void populateMaterializations(Context context, RelOptCluster cluster, Prepare.Materialization materialization) {
    // REVIEW: initialize queryRel and tableRel inside MaterializationService,
    // not here?
    try {
        final CalciteSchema schema = materialization.materializedTable.schema;
        CalciteCatalogReader catalogReader = new CalciteCatalogReader(schema.root(), materialization.viewSchemaPath, context.getTypeFactory(), context.config());
        final CalciteMaterializer materializer = new CalciteMaterializer(this, context, catalogReader, schema, cluster, createConvertletTable());
        materializer.populate(materialization);
    } catch (Exception e) {
        throw new RuntimeException("While populating materialization " + materialization.materializedTable.path(), e);
    }
}

19 View Complete Implementation : CalciteConnectionImpl.java
Copyright Apache License 2.0
Author : bitnine-oss
public void setRootSchema(CalciteSchema rootSchema) {
    this.rootSchema = rootSchema;
}

19 View Complete Implementation : CalciteCatalogReader.java
Copyright Apache License 2.0
Author : apache
private SqlMonikerImpl moniker(CalciteSchema schema, String name, SqlMonikerType type) {
    final List<String> path = schema.path(name);
    if (path.size() == 1 && !schema.root().name.equals("") && type == SqlMonikerType.SCHEMA) {
        type = SqlMonikerType.CATALOG;
    }
    return new SqlMonikerImpl(path, type);
}

19 View Complete Implementation : Lattice.java
Copyright Apache License 2.0
Author : apache
public static Builder builder(CalciteSchema calciteSchema, String sql) {
    return builder(new LatticeSpace(MapSqlStatisticProvider.INSTANCE), calciteSchema, sql);
}

19 View Complete Implementation : Frameworks.java
Copyright Apache License 2.0
Author : apache
/**
 * Initializes a container then calls user-specified code with a planner.
 *
 * @param action Callback containing user-specified code
 * @param config FrameworkConfig to use for planner action.
 * @return Return value from action
 */
public static <R> R withPlanner(final PlannerAction<R> action, final FrameworkConfig config) {
    return withPrepare(config, (cluster, relOptSchema, rootSchema, statement) -> {
        final CalciteSchema schema = CalciteSchema.from(Util.first(config.getDefaultSchema(), rootSchema));
        return action.apply(cluster, relOptSchema, schema.root().plus());
    });
}

18 View Complete Implementation : CalciteConnectionImpl.java
Copyright Apache License 2.0
Author : bitnine-oss
/**
 * Implementation of JDBC connection
 * in the Calcite engine.
 * <p/>
 * <p>Abstract to allow newer versions of JDBC to add methods.</p>
 */
abstract clreplaced CalciteConnectionImpl extends AvaticaConnection implements CalciteConnection, QueryProvider {

    private final JavaTypeFactory typeFactory;

    private CalciteSchema rootSchema;

    private final Function0<CalcitePrepare> prepareFactory;

    private final CalciteServer server = new CalciteServerImpl();

    // must be package-protected
    static final Trojan TROJAN = createTrojan();

    /**
     * Creates a CalciteConnectionImpl.
     * <p/>
     * <p>Not public; method is called only from the driver.</p>
     *
     * @param driver      Driver
     * @param factory     Factory for JDBC objects
     * @param url         Server URL
     * @param info        Other connection properties
     * @param rootSchema  Root schema, or null
     * @param typeFactory Type factory, or null
     */
    protected CalciteConnectionImpl(Driver driver, AvaticaFactory factory, String url, Properties info, CalciteSchema rootSchema, JavaTypeFactory typeFactory) {
        super(driver, factory, url, info);
        CalciteConnectionConfig cfg = new CalciteConnectionConfigImpl(info);
        this.prepareFactory = driver.getPrepareFactory();
        if (typeFactory != null) {
            this.typeFactory = typeFactory;
        } else {
            final RelDataTypeSystem typeSystem = cfg.typeSystem(RelDataTypeSystem.clreplaced, RelDataTypeSystem.DEFAULT);
            this.typeFactory = new JavaTypeFactoryImpl(typeSystem);
        }
        this.rootSchema = Preconditions.checkNotNull(rootSchema != null ? rootSchema : CalciteSchema.createRootSchema(true));
        Preconditions.checkArgument(this.rootSchema.isRoot(), "must be root schema");
        this.properties.put(InternalProperty.CASE_SENSITIVE, cfg.caseSensitive());
        this.properties.put(InternalProperty.UNQUOTED_CASING, cfg.unquotedCasing());
        this.properties.put(InternalProperty.QUOTED_CASING, cfg.quotedCasing());
        this.properties.put(InternalProperty.QUOTING, cfg.quoting());
    }

    public Function0<CalcitePrepare> getPrepareFactory() {
        return prepareFactory;
    }

    public CalciteServer getServer() {
        return server;
    }

    CalciteMetaImpl meta() {
        return (CalciteMetaImpl) meta;
    }

    public CalciteConnectionConfig config() {
        return new CalciteConnectionConfigImpl(info);
    }

    /**
     * Called after the constructor has completed and the model has been
     * loaded.
     */
    void init() {
        final MaterializationService service = MaterializationService.instance();
        for (CalciteSchema.LatticeEntry e : Schemas.getLatticeEntries(rootSchema)) {
            final Lattice lattice = e.getLattice();
            for (Lattice.Tile tile : lattice.computeTiles()) {
                service.defineTile(lattice, tile.bitSet(), tile.measures, e.schema, true, true);
            }
        }
    }

    @Override
    public <T> T unwrap(Clreplaced<T> iface) throws SQLException {
        if (iface == RelRunner.clreplaced) {
            return iface.cast(new RelRunner() {

                public PreparedStatement prepare(RelNode rel) {
                    try {
                        return prepareStatementInternal(CalcitePrepare.Query.of(rel), ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY, getHoldability());
                    } catch (SQLException e) {
                        throw Throwables.propagate(e);
                    }
                }
            });
        }
        return super.unwrap(iface);
    }

    @Override
    public CalciteStatement createStatement(int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException {
        return (CalciteStatement) super.createStatement(resultSetType, resultSetConcurrency, resultSetHoldability);
    }

    @Override
    public CalcitePreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException {
        final CalcitePrepare.Query<Object> query = CalcitePrepare.Query.of(sql);
        return prepareStatementInternal(query, resultSetType, resultSetConcurrency, resultSetHoldability);
    }

    private CalcitePreparedStatement prepareStatementInternal(CalcitePrepare.Query<?> query, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException {
        try {
            final Meta.Signature signature = parseQuery(query, new ContextImpl(this), -1);
            final CalcitePreparedStatement calcitePreparedStatement = (CalcitePreparedStatement) factory.newPreparedStatement(this, null, signature, resultSetType, resultSetConcurrency, resultSetHoldability);
            server.addStatement(this, calcitePreparedStatement.handle);
            server.getStatement(calcitePreparedStatement.handle).setSignature(signature);
            return calcitePreparedStatement;
        } catch (Exception e) {
            throw Helper.INSTANCE.createException("Error while preparing statement [" + query.sql + "]", e);
        }
    }

    <T> CalcitePrepare.CalciteSignature<T> parseQuery(CalcitePrepare.Query<T> query, CalcitePrepare.Context prepareContext, long maxRowCount) {
        CalcitePrepare.Dummy.push(prepareContext);
        try {
            final CalcitePrepare prepare = prepareFactory.apply();
            return prepare.prepareSql(prepareContext, query, Object[].clreplaced, maxRowCount);
        } finally {
            CalcitePrepare.Dummy.pop(prepareContext);
        }
    }

    // CalciteConnection methods
    public CalciteSchema getCalciteRootSchema() {
        return rootSchema;
    }

    public SchemaPlus getRootSchema() {
        return rootSchema.plus();
    }

    public JavaTypeFactory getTypeFactory() {
        return typeFactory;
    }

    public Properties getProperties() {
        return info;
    }

    // QueryProvider methods
    public <T> Queryable<T> createQuery(Expression expression, Clreplaced<T> rowType) {
        return new CalciteQueryable<>(this, rowType, expression);
    }

    public <T> Queryable<T> createQuery(Expression expression, Type rowType) {
        return new CalciteQueryable<>(this, rowType, expression);
    }

    public <T> T execute(Expression expression, Type type) {
        // TODO:
        return null;
    }

    public <T> T execute(Expression expression, Clreplaced<T> type) {
        // TODO:
        return null;
    }

    public <T> Enumerator<T> executeQuery(Queryable<T> queryable) {
        try {
            CalciteStatement statement = (CalciteStatement) createStatement();
            CalcitePrepare.CalciteSignature<T> signature = statement.prepare(queryable);
            return enumerable(statement.handle, signature).enumerator();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    public <T> Enumerable<T> enumerable(Meta.StatementHandle handle, CalcitePrepare.CalciteSignature<T> signature) throws SQLException {
        Map<String, Object> map = Maps.newLinkedHashMap();
        AvaticaStatement statement = lookupStatement(handle);
        final List<TypedValue> parameterValues = TROJAN.getParameterValues(statement);
        if (MetaImpl.checkParameterValueHasNull(parameterValues)) {
            throw new SQLException("exception while executing query: unbound parameter");
        }
        for (Ord<TypedValue> o : Ord.zip(parameterValues)) {
            map.put("?" + o.i, o.e.toLocal());
        }
        map.putAll(signature.internalParameters);
        final DataContext dataContext = createDataContext(map);
        return signature.enumerable(dataContext);
    }

    public DataContext createDataContext(Map<String, Object> parameterValues) {
        if (config().spark()) {
            return new SlimDataContext();
        }
        return new DataContextImpl(this, parameterValues);
    }

    // do not make public
    UnregisteredDriver getDriver() {
        return driver;
    }

    // do not make public
    AvaticaFactory getFactory() {
        return factory;
    }

    public void setRootSchema(CalciteSchema rootSchema) {
        this.rootSchema = rootSchema;
    }

    /**
     * Implementation of Queryable.
     */
    static clreplaced CalciteQueryable<T> extends BaseQueryable<T> {

        CalciteQueryable(CalciteConnection connection, Type elementType, Expression expression) {
            super(connection, elementType, expression);
        }

        public CalciteConnection getConnection() {
            return (CalciteConnection) provider;
        }
    }

    /**
     * Implementation of Server.
     */
    private static clreplaced CalciteServerImpl implements CalciteServer {

        private final Map<Integer, CalciteServerStatement> statementMap = Maps.newHashMap();

        public void removeStatement(Meta.StatementHandle h) {
            statementMap.remove(h.id);
        }

        public void addStatement(CalciteConnection connection, Meta.StatementHandle h) {
            final CalciteConnectionImpl c = (CalciteConnectionImpl) connection;
            statementMap.put(h.id, new CalciteServerStatementImpl(c));
        }

        public CalciteServerStatement getStatement(Meta.StatementHandle h) {
            return statementMap.get(h.id);
        }
    }

    /**
     * Schema that has no parents.
     */
    static clreplaced RootSchema extends AbstractSchema {

        RootSchema() {
            super();
        }

        @Override
        public Expression getExpression(SchemaPlus parentSchema, String name) {
            return Expressions.call(DataContext.ROOT, BuiltInMethod.DATA_CONTEXT_GET_ROOT_SCHEMA.method);
        }
    }

    /**
     * Implementation of DataContext.
     */
    static clreplaced DataContextImpl implements DataContext {

        private final ImmutableMap<Object, Object> map;

        private final CalciteSchema rootSchema;

        private final QueryProvider queryProvider;

        private final JavaTypeFactory typeFactory;

        DataContextImpl(CalciteConnectionImpl connection, Map<String, Object> parameters) {
            this.queryProvider = connection;
            this.typeFactory = connection.getTypeFactory();
            this.rootSchema = connection.rootSchema;
            // Store the time at which the query started executing. The SQL
            // standard says that functions such as CURRENT_TIMESTAMP return the
            // same value throughout the query.
            final Holder<Long> timeHolder = Holder.of(System.currentTimeMillis());
            // Give a hook chance to alter the clock.
            Hook.CURRENT_TIME.run(timeHolder);
            final long time = timeHolder.get();
            final TimeZone timeZone = connection.getTimeZone();
            final long localOffset = timeZone.getOffset(time);
            final long currentOffset = localOffset;
            ImmutableMap.Builder<Object, Object> builder = ImmutableMap.builder();
            builder.put(Variable.UTC_TIMESTAMP.camelName, time).put(Variable.CURRENT_TIMESTAMP.camelName, time + currentOffset).put(Variable.LOCAL_TIMESTAMP.camelName, time + localOffset).put(Variable.TIME_ZONE.camelName, timeZone);
            for (Map.Entry<String, Object> entry : parameters.entrySet()) {
                Object e = entry.getValue();
                if (e == null) {
                    e = AvaticaSite.DUMMY_VALUE;
                }
                builder.put(entry.getKey(), e);
            }
            map = builder.build();
        }

        public synchronized Object get(String name) {
            Object o = map.get(name);
            if (o == AvaticaSite.DUMMY_VALUE) {
                return null;
            }
            if (o == null && Variable.SQL_ADVISOR.camelName.equals(name)) {
                return getSqlAdvisor();
            }
            return o;
        }

        private SqlAdvisor getSqlAdvisor() {
            final CalciteConnectionImpl con = (CalciteConnectionImpl) queryProvider;
            final String schemaName = con.getSchema();
            final List<String> schemaPath = schemaName == null ? ImmutableList.<String>of() : ImmutableList.of(schemaName);
            final SqlValidatorWithHints validator = new SqlAdvisorValidator(SqlStdOperatorTable.instance(), new CalciteCatalogReader(rootSchema, con.config().caseSensitive(), schemaPath, typeFactory), typeFactory, SqlConformance.DEFAULT);
            return new SqlAdvisor(validator);
        }

        public SchemaPlus getRootSchema() {
            return rootSchema.plus();
        }

        public JavaTypeFactory getTypeFactory() {
            return typeFactory;
        }

        public QueryProvider getQueryProvider() {
            return queryProvider;
        }
    }

    /**
     * Implementation of Context.
     */
    static clreplaced ContextImpl implements CalcitePrepare.Context {

        private final CalciteConnectionImpl connection;

        ContextImpl(CalciteConnectionImpl connection) {
            this.connection = Preconditions.checkNotNull(connection);
        }

        public JavaTypeFactory getTypeFactory() {
            return connection.typeFactory;
        }

        public CalciteSchema getRootSchema() {
            return connection.rootSchema;
        }

        public List<String> getDefaultSchemaPath() {
            final String schemaName = connection.getSchema();
            return schemaName == null ? ImmutableList.<String>of() : ImmutableList.of(schemaName);
        }

        public CalciteConnectionConfig config() {
            return connection.config();
        }

        public DataContext getDataContext() {
            return connection.createDataContext(ImmutableMap.<String, Object>of());
        }

        public CalcitePrepare.SparkHandler spark() {
            final boolean enable = config().spark();
            return CalcitePrepare.Dummy.getSparkHandler(enable);
        }
    }

    /**
     * Implementation of {@link DataContext} that has few variables and is
     * {@link Serializable}. For Spark.
     */
    private static clreplaced SlimDataContext implements DataContext, Serializable {

        public SchemaPlus getRootSchema() {
            return null;
        }

        public JavaTypeFactory getTypeFactory() {
            return null;
        }

        public QueryProvider getQueryProvider() {
            return null;
        }

        public Object get(String name) {
            return null;
        }
    }

    /**
     * Implementation of {@link CalciteServerStatement}.
     */
    static clreplaced CalciteServerStatementImpl implements CalciteServerStatement {

        private final CalciteConnectionImpl connection;

        private Iterator<Object> iterator;

        private Meta.Signature signature;

        CalciteServerStatementImpl(CalciteConnectionImpl connection) {
            this.connection = Preconditions.checkNotNull(connection);
        }

        public ContextImpl createPrepareContext() {
            return new ContextImpl(connection);
        }

        public CalciteConnection getConnection() {
            return connection;
        }

        public void setSignature(Meta.Signature signature) {
            this.signature = signature;
        }

        public Meta.Signature getSignature() {
            return signature;
        }

        public Iterator<Object> getResultSet() {
            return iterator;
        }

        public void setResultSet(Iterator<Object> iter) {
            this.iterator = iter;
        }
    }
}

18 View Complete Implementation : CalciteMetaImpl.java
Copyright Apache License 2.0
Author : bitnine-oss
/**
 * A trojan-horse method, subject to change without notice.
 */
@VisibleForTesting
public static CalciteConnection connect(CalciteSchema schema, JavaTypeFactory typeFactory) {
    return DRIVER.connect(schema, typeFactory);
}

18 View Complete Implementation : Driver.java
Copyright Apache License 2.0
Author : bitnine-oss
/**
 * Creates an internal connection.
 */
CalciteConnection connect(CalciteSchema rootSchema, JavaTypeFactory typeFactory) {
    /*
        return (CalciteConnection) ((CalciteFactory) factory)
                .newConnection(this, factory, CONNECT_STRING_PREFIX, new Properties(),
                        rootSchema, typeFactory);
                        */
    System.out.println("********************************************************************");
    System.out.println("********************************************************************");
    System.out.println("********************************************************************");
    System.out.println("********************************************************************");
    System.out.println("********************************************************************");
    return (CalciteConnection) ((CalciteFactory) factory).newConnection(this, factory, CONNECT_STRING_PREFIX, new Properties(), (CalciteSchema) SchemaManager.getSingletonInstance(null).getCurrentSchema(), typeFactory);
}

18 View Complete Implementation : TableEnv.java
Copyright Apache License 2.0
Author : 51nb
/**
 * A TableEnv can be used to:
 * 1.register a Table in [TableEnv]'s catalog
 * 2.add subSchema and Function in [TableEnv]'s catalog
 * 3.convert a JDBC ResultSet to a Table
 * 5.convert a simple java pojo list to a Table
 * 6.execute a sql query to get a Table
 * <p> a TableEnv supports the calcite-sql query by default,
 * but developers can extend a TableEnv to implement
 * a HiveTableEnv or MysqlTableEnv etc...,to support other sql dialects.
 */
public clreplaced TableEnv {

    private static int maxSqlPlanCacheSize;

    private static Cache<String, TableExecutionPlan> sql2ExecutionPlanCache;

    /**
     * for user to conveniently inspect the generated code
     */
    private static final Cache<String, String> SQL_2_EXECUTION_PLAN_CODE_CACHE = CacheBuilder.newBuilder().maximumSize(200).build();

    private static final Map<String, Clreplaced> SQL_2_BINDABLE_CLreplaced_MAP = new ConcurrentHashMap<>();

    private String cacheKeyPrefix = "";

    public String getCacheKeyPrefix() {
        return cacheKeyPrefix;
    }

    public void setCacheKeyPrefix(String cacheKeyPrefix) {
        this.cacheKeyPrefix = cacheKeyPrefix;
    }

    public static void clearExecutionPlan() {
        if (sql2ExecutionPlanCache != null) {
            sql2ExecutionPlanCache.invalidateAll();
        }
    }

    public void registerSqlBindableClreplaced(String sql, Clreplaced clazz) {
        SQL_2_BINDABLE_CLreplaced_MAP.put(cacheKeyPrefix + sql, clazz);
    }

    public static int getMaxSqlPlanCacheSize() {
        return maxSqlPlanCacheSize;
    }

    public static synchronized void enableSqlPlanCacheSize(int maxSqlPlanCacheSize) {
        if (sql2ExecutionPlanCache == null) {
            TableEnv.maxSqlPlanCacheSize = maxSqlPlanCacheSize;
            sql2ExecutionPlanCache = CacheBuilder.newBuilder().maximumSize(maxSqlPlanCacheSize).build();
        } else {
            throw new RuntimeException("sql2ExecutionPlanCache has already been enabled,maxSqlPlanCacheSize=" + maxSqlPlanCacheSize);
        }
    }

    public static TableEnv getTableEnv() {
        return new TableEnv(new TableConfig());
    }

    public static TableEnv getTableEnv(TableConfig tableConfig) {
        return new TableEnv(tableConfig);
    }

    protected TableConfig tableConfig;

    private CalciteSchema internalSchema = CalciteSchema.createRootSchema(false, false);

    protected SchemaPlus rootSchema = internalSchema.plus();

    protected FrameworkConfig frameworkConfig;

    protected CalciteCatalogReader calciteCatalogReader;

    public TableEnv(TableConfig tableConfig) {
        try {
            this.tableConfig = tableConfig;
            SqlParser.Config sqlParserConfig = tableConfig.getSqlParserConfig() != null ? tableConfig.getSqlParserConfig() : SqlParser.configBuilder().setCaseSensitive(false).build();
            SqlOperatorTable sqlStdOperatorTable = tableConfig.getSqlOperatorTable() != null ? tableConfig.getSqlOperatorTable() : ChainedSqlOperatorTable.of(SqlStdOperatorTable.instance());
            CalciteConnectionConfig calciteConnectionConfig = tableConfig.getCalciteConnectionConfig() != null ? tableConfig.getCalciteConnectionConfig() : createDefaultConnectionConfig(sqlParserConfig);
            RelDataTypeSystem typeSystem = tableConfig.getRelDataTypeSystem() != null ? tableConfig.getRelDataTypeSystem() : calciteConnectionConfig.typeSystem(RelDataTypeSystem.clreplaced, RelDataTypeSystem.DEFAULT);
            SqlRexConvertletTable convertletTable = tableConfig.getConvertletTable() != null ? tableConfig.getConvertletTable() : StandardConvertletTable.INSTANCE;
            RexExecutor rexExecutor = tableConfig.getRexExecutor() != null ? tableConfig.getRexExecutor() : RexUtil.EXECUTOR;
            this.calciteCatalogReader = new CalciteCatalogReader(CalciteSchema.from(rootSchema), CalciteSchema.from(rootSchema).path(null), new JavaTypeFactoryImpl(typeSystem), calciteConnectionConfig);
            this.frameworkConfig = createFrameworkConfig(sqlParserConfig, ChainedSqlOperatorTable.of(sqlStdOperatorTable, calciteCatalogReader), convertletTable, calciteConnectionConfig, typeSystem, rexExecutor);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public TableConfig getTableConfig() {
        return tableConfig;
    }

    protected Program createProgram() {
        final Program program1 = (planner, rel, requiredOutputTraits, materializations, lattices) -> {
            // override the default ruleSet of planner here
            planner.setRoot(rel);
            for (RelOptMaterialization materialization : materializations) {
                planner.addMaterialization(materialization);
            }
            for (RelOptLattice lattice : lattices) {
                planner.addLattice(lattice);
            }
            final RelNode rootRel2 = rel.getTraitSet().equals(requiredOutputTraits) ? rel : planner.changeTraits(rel, requiredOutputTraits);
            replacedert rootRel2 != null;
            planner.setRoot(rootRel2);
            final RelOptPlanner planner2 = planner.chooseDelegate();
            final RelNode rootRel3 = planner2.findBestExp();
            replacedert rootRel3 != null : "could not implement exp";
            return rootRel3;
        };
        DefaultRelMetadataProvider metadataProvider = DefaultRelMetadataProvider.INSTANCE;
        return Programs.sequence(Programs.subQuery(metadataProvider), new Programs.DecorrelateProgram(), new Programs.TrimFieldsProgram(), program1, // Second planner preplaced to do physical "tweaks". This the first time
        // that EnumerableCalcRel is introduced.
        Programs.calc(metadataProvider));
    }

    private FrameworkConfig createFrameworkConfig(SqlParser.Config sqlParserConfig, SqlOperatorTable sqlOperatorTable, SqlRexConvertletTable convertletTable, CalciteConnectionConfig calciteConnectionConfig, RelDataTypeSystem relDataTypeSystem, RexExecutor rexExecutor) {
        return Frameworks.newConfigBuilder().defaultSchema(rootSchema).parserConfig(sqlParserConfig).operatorTable(sqlOperatorTable).convertletTable(convertletTable).typeSystem(relDataTypeSystem).executor(rexExecutor).context(Contexts.of(calciteConnectionConfig)).build();
    }

    private CalciteConnectionConfig createDefaultConnectionConfig(SqlParser.Config sqlParserConfig) {
        Properties prop = new Properties();
        prop.setProperty(CalciteConnectionProperty.CASE_SENSITIVE.camelName(), String.valueOf(sqlParserConfig.caseSensitive()));
        return new CalciteConnectionConfigImpl(prop);
    }

    public DataTable getTable(String tableName) {
        return (DataTable) rootSchema.getTable(tableName.toUpperCase());
    }

    public DataTable getTable(String subSchemaName, String tableName) {
        return (DataTable) rootSchema.getSubSchema(subSchemaName.toUpperCase()).getTable(tableName.toUpperCase());
    }

    public void registerTable(String tableName, DataTable dataTable) {
        rootSchema.add(tableName.toUpperCase(), dataTable);
    }

    public void registerTable(String subSchemaName, String tableName, DataTable dataTable) {
        rootSchema.getSubSchema(subSchemaName.toUpperCase()).add(tableName.toUpperCase(), dataTable);
    }

    public SchemaPlus addSubSchema(String subSchemaName) {
        return rootSchema.add(subSchemaName.toUpperCase(), new AbstractSchema());
    }

    public void addFunction(String schemaName, String functionName, String clreplacedName, String methodName) {
        boolean upCase = true;
        SchemaPlus schema;
        schemaName = schemaName.toUpperCase();
        functionName = functionName.toUpperCase();
        if (StringUtils.isBlank(schemaName)) {
            schema = rootSchema;
        } else {
            schema = rootSchema.getSubSchema(schemaName);
            if (schema == null) {
                schema = addSubSchema(schemaName);
            }
        }
        final Clreplaced<?> clazz;
        try {
            clazz = Clreplaced.forName(clreplacedName);
        } catch (ClreplacedNotFoundException e) {
            throw new RuntimeException("UDF clreplaced '" + clreplacedName + "' not found");
        }
        final TableFunction tableFunction = TableFunctionImpl.create(clazz, Util.first(methodName, "eval"));
        if (tableFunction != null) {
            schema.add(functionName, tableFunction);
            return;
        }
        // Must look for TableMacro before ScalarFunction. Both have an "eval"
        // method.
        final TableMacro macro = TableMacroImpl.create(clazz);
        if (macro != null) {
            schema.add(functionName, macro);
            return;
        }
        if (methodName != null && methodName.equals("*")) {
            for (Map.Entry<String, ScalarFunction> entry : ScalarFunctionImpl.createAll(clazz).entries()) {
                String name = entry.getKey();
                if (upCase) {
                    name = name.toUpperCase(Locale.ROOT);
                }
                schema.add(name, entry.getValue());
            }
            return;
        } else {
            final ScalarFunction function = ScalarFunctionImpl.create(clazz, Util.first(methodName, "eval"));
            if (function != null) {
                final String name;
                if (functionName != null) {
                    name = functionName;
                } else if (upCase) {
                    name = methodName.toUpperCase(Locale.ROOT);
                } else {
                    name = methodName;
                }
                schema.add(name, function);
                return;
            }
        }
        if (methodName == null) {
            final AggregateFunction aggFunction = AggregateFunctionImpl.create(clazz);
            if (aggFunction != null) {
                schema.add(functionName, aggFunction);
                return;
            }
        }
        throw new RuntimeException("Not a valid function clreplaced: " + clazz + ". Scalar functions and table macros have an 'eval' method; " + "aggregate functions have 'init' and 'add' methods, and optionally " + "'initAdd', 'merge' and 'result' methods.");
    }

    protected void executeBeforeSqlQuery(String sql) {
    // 
    }

    protected void executeAfterSqlQuery(String sql) {
    // 
    }

    public TableExecutionPlan getExecutionPlan(String sql) {
        return sql2ExecutionPlanCache == null ? null : sql2ExecutionPlanCache.getIfPresent(sql);
    }

    public String getExecutionCode(String sql) {
        return SQL_2_EXECUTION_PLAN_CODE_CACHE.getIfPresent(cacheKeyPrefix + sql);
    }

    public DataTable sqlQuery(String sql) {
        try {
            executeBeforeSqlQuery(sql);
            if (sql2ExecutionPlanCache != null) {
                TableExecutionPlan executionPlan = sql2ExecutionPlanCache.getIfPresent(cacheKeyPrefix + sql);
                if (executionPlan != null) {
                    return implement(executionPlan.getBindable(), executionPlan.getRowType(), calciteCatalogReader.getTypeFactory());
                }
            }
            TableExecutionPlan executionPlan = toExecutionPlan(sql);
            DataTable dt = implement(executionPlan.getBindable(), executionPlan.rowType, calciteCatalogReader.getTypeFactory());
            if (sql2ExecutionPlanCache != null) {
                sql2ExecutionPlanCache.put(cacheKeyPrefix + sql, executionPlan);
            }
            executeAfterSqlQuery(sql);
            return dt;
        } catch (Throwable t) {
            throw new RuntimeException("current rootSchema:" + rootSchema.getTableNames(), t);
        }
    }

    public TableExecutionPlan toExecutionPlan(String sql) throws Throwable {
        RelRoot root = getSqlPlanRel(sql);
        return toExecutionPlan(root, sql);
    }

    protected RelRoot getSqlPlanRel(String sql) throws Throwable {
        try (Planner planner = Frameworks.getPlanner(frameworkConfig)) {
            RelRoot root;
            final SqlNode parsedSqlNode = planner.parse(sql);
            final Pair<SqlNode, RelDataType> validatedSqlNodeAndType = planner.validateAndGetType(parsedSqlNode);
            root = planner.rel(validatedSqlNodeAndType.getKey());
            final Program program = createProgram();
            // getDesiredTraits
            final RelTraitSet desiredTraits = root.rel.getTraitSet().replace(EnumerableConvention.INSTANCE).replace(root.collation).simplify();
            RelNode logicalRelNode = root.rel;
            final RelNode optimizedRelNode = program.run(root.rel.getCluster().getPlanner(), logicalRelNode, desiredTraits, Collections.emptyList(), Collections.emptyList());
            root = root.withRel(optimizedRelNode);
            return root;
        }
    }

    private TableExecutionPlan toExecutionPlan(RelRoot root, String sql) {
        EnumerableRel enumerable = (EnumerableRel) root.rel;
        if (!root.isRefTrivial()) {
            final List<RexNode> projects = new ArrayList<>();
            final RexBuilder rexBuilder = enumerable.getCluster().getRexBuilder();
            for (int field : Pair.left(root.fields)) {
                projects.add(rexBuilder.makeInputRef(enumerable, field));
            }
            RexProgram program = RexProgram.create(enumerable.getRowType(), projects, null, root.validatedRowType, rexBuilder);
            enumerable = EnumerableCalc.create(enumerable, program);
        }
        Bindable bindable = null;
        final TableExecutionPlan tableExecutionPlan = new TableExecutionPlan();
        Hook.Closeable planHookHandle = Hook.JAVA_PLAN.addThread((code) -> {
            SQL_2_EXECUTION_PLAN_CODE_CACHE.put(cacheKeyPrefix + sql, (String) code);
            tableExecutionPlan.setCode((String) code);
        });
        try {
            Prepare.CatalogReader.THREAD_LOCAL.set(calciteCatalogReader);
            try {
                Clreplaced clazz = SQL_2_BINDABLE_CLreplaced_MAP.get(cacheKeyPrefix + sql);
                if (clazz != null) {
                    bindable = (Bindable) clazz.newInstance();
                }
            } catch (Exception ex) {
                throw new RuntimeException(ex);
            }
            if (bindable == null) {
                bindable = toBindable(enumerable);
            }
            tableExecutionPlan.setBindable(bindable);
            tableExecutionPlan.setRowType(root.validatedRowType);
        } finally {
            Prepare.CatalogReader.THREAD_LOCAL.remove();
            planHookHandle.close();
        }
        return tableExecutionPlan;
    }

    protected Bindable toBindable(EnumerableRel rel) {
        return EnumerableInterpretable.toBindable(Maps.newHashMap(), null, rel, EnumerableRel.Prefer.ARRAY);
    }

    private DataTable implement(Bindable bindable, RelDataType rowType, RelDataTypeFactory typeFactory) {
        final DataContext dataContext = new TableDataContexImpl(null, rootSchema, (JavaTypeFactory) typeFactory, tableConfig);
        Enumerable<Object[]> enumerableResult = bindable.bind(dataContext);
        List rows = EnumerableDefaults.toList(enumerableResult);
        return new DataTable(rowType, rows);
    }

    protected SqlTypeName getSqlTypeNameForJdbcType(int jdbcType) {
        // FIX Calcite jdbc type converting bug
        SqlTypeName typeName = SqlTypeName.getNameForJdbcType(jdbcType);
        if (jdbcType == Types.LONGVARCHAR) {
            typeName = SqlTypeName.VARCHAR;
        }
        if (jdbcType == Types.SMALLINT || jdbcType == Types.TINYINT) {
            // the type of jdbc value is INTEGER when jdbcType is SMALLINT or TINYINT
            typeName = SqlTypeName.INTEGER;
        }
        return typeName;
    }

    public DataTable fromJdbcResultSet(ResultSet resultSet) {
        try {
            final RelDataTypeFactory.Builder builder = calciteCatalogReader.getTypeFactory().builder();
            ResultSetMetaData metaData = resultSet.getMetaData();
            int columnCount = metaData.getColumnCount();
            for (int i = 1; i <= columnCount; i++) {
                String columnName = metaData.getColumnLabel(i);
                int jdbcType = metaData.getColumnType(i);
                builder.add(columnName.toUpperCase(), getSqlTypeNameForJdbcType(jdbcType)).nullable(true);
            }
            RelDataType rowType = builder.build();
            List<Object[]> convertRows = new ArrayList<>();
            Calendar calendar = Calendar.getInstance(tableConfig.getTimeZone(), Locale.ROOT);
            while (resultSet.next()) {
                Object[] row = new Object[columnCount];
                for (int i = 1; i <= columnCount; i++) {
                    Object jdbcObject = resultSet.getObject(i);
                    Object convertedCalciteObject = TypedValue.ofJdbc(jdbcObject, calendar).value;
                    row[i - 1] = convertedCalciteObject;
                }
                convertRows.add(row);
            }
            return new DataTable(rowType, convertRows);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public DataTable fromJavaPojoList(List pojoList) {
        return fromJavaPojoList(pojoList, null, false);
    }

    public DataTable fromJavaPojoList(List pojoList, Map<String, String> fieldName2SqlColumnNameMap, boolean upperUnderscore) {
        try {
            PojoTypeConverter pojoTypeConverter = new PojoTypeConverter(calciteCatalogReader.getTypeFactory(), fieldName2SqlColumnNameMap, upperUnderscore, tableConfig.getTimeZone());
            Clreplaced pojoClreplaced = null;
            List<Field> fieldList = null;
            RelDataType relDataType = null;
            List rows = new DataTable.DataTableStoreList();
            for (Object pojo : pojoList) {
                if (pojoClreplaced == null) {
                    pojoClreplaced = pojo.getClreplaced();
                } else {
                    if (!pojoClreplaced.equals(pojo.getClreplaced())) {
                        throw new RuntimeException("the clreplacedes of elements in pojoList must be same !");
                    }
                }
                if (fieldList == null) {
                    fieldList = PojoTypeConverter.getAllDeclaredFields(pojoClreplaced);
                }
                PojoRelDataTypeValue relDataTypeValue = pojoTypeConverter.getPojoRelDataTypeValue(pojoClreplaced, fieldList, pojo);
                rows.add(relDataTypeValue.getValue());
                if (relDataType == null && relDataTypeValue != null) {
                    relDataType = relDataTypeValue.getRelDataType();
                }
            }
            return new DataTable(relDataType, rows);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public DataTable fromRowListWithSqlTypeMap(List<Map<String, Object>> rowList, Map<String, SqlTypeName> sqlTypeMap) {
        try {
            final RelDataTypeFactory.Builder builder = calciteCatalogReader.getTypeFactory().builder();
            PojoTypeConverter pojoTypeConverter = new PojoTypeConverter(calciteCatalogReader.getTypeFactory(), null, true, tableConfig.getTimeZone());
            RelDataType rowType;
            List convertRows = new DataTable.DataTableStoreList();
            List<String> schemaKeys = new ArrayList<>(sqlTypeMap.keySet());
            schemaKeys.forEach(key -> {
                builder.add(key.toLowerCase(), sqlTypeMap.get(key)).nullable(true);
            });
            rowType = builder.build();
            for (Map<String, Object> map : rowList) {
                int i = 0;
                Object[] row = new Object[sqlTypeMap.size()];
                for (String key : schemaKeys) {
                    Object o = map.get(key);
                    PojoRelDataTypeValue calciteValue = pojoTypeConverter.javaObjectToCalciteObject(sqlTypeMap.get(key), o, tableConfig.getTimeZone(), null);
                    row[i] = calciteValue.getValue();
                    i++;
                }
                convertRows.add(row);
            }
            return new DataTable(rowType, convertRows);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * the execution plan for a sql query
     */
    public static clreplaced TableExecutionPlan {

        private String code;

        private Bindable bindable;

        private RelDataType rowType;

        public TableExecutionPlan() {
        }

        public TableExecutionPlan(String code, Bindable bindable, RelDataType rowType) {
            this.code = code;
            this.bindable = bindable;
            this.rowType = rowType;
        }

        public Bindable getBindable() {
            return bindable;
        }

        public RelDataType getRowType() {
            return rowType;
        }

        public String getCode() {
            return code;
        }

        public void setCode(String code) {
            this.code = code;
        }

        public void setBindable(Bindable bindable) {
            this.bindable = bindable;
        }

        public void setRowType(RelDataType rowType) {
            this.rowType = rowType;
        }
    }
}

18 View Complete Implementation : Driver.java
Copyright Apache License 2.0
Author : rayokota
/**
 * Creates an internal connection.
 */
CalciteConnection connect(CalciteSchema rootSchema, JavaTypeFactory typeFactory) {
    return (CalciteConnection) ((CalciteFactory) factory).newConnection(this, factory, CONNECT_STRING_PREFIX, new Properties(), rootSchema, typeFactory);
}

18 View Complete Implementation : LatticeSuggester.java
Copyright Apache License 2.0
Author : apache
/**
 * Returns the best match for a lattice. If no match, registers the lattice
 * and returns it. Never returns null.
 */
private Lattice findMatch(final Lattice lattice, MutableNode mutableNode) {
    final Lattice lattice1 = latticeMap.get(lattice.toString());
    if (lattice1 != null) {
        // Exact match for an existing lattice
        return lattice1;
    }
    if (evolve) {
        // No exact match. Scan existing lattices for a sub-set.
        int bestMatchQuality = 0;
        Lattice bestMatch = null;
        for (Lattice lattice2 : latticeMap.values()) {
            int q = matchQuality(lattice2, lattice);
            if (q > bestMatchQuality) {
                bestMatch = lattice2;
                bestMatchQuality = q;
            } else if (q == bestMatchQuality && bestMatch != null && !lattice2.rootNode.paths.equals(bestMatch.rootNode.paths) && lattice2.rootNode.paths.containsAll(bestMatch.rootNode.paths)) {
                bestMatch = lattice2;
            }
        }
        if (bestMatch != null) {
            // Fix up the best batch
            for (Path path : minus(bestMatch.rootNode.paths, lattice.rootNode.paths)) {
                // TODO: replacedign alias based on node in bestMatch
                mutableNode.addPath(path, null);
            }
            final CalciteSchema rootSchema = CalciteSchema.createRootSchema(false);
            final Lattice.Builder builder = new Lattice.Builder(space, rootSchema, mutableNode);
            copyMeasures(builder, bestMatch);
            copyMeasures(builder, lattice);
            final Lattice lattice2 = builder.build();
            latticeMap.remove(bestMatch.toString());
            obsoleteLatticeMap.put(bestMatch, lattice2);
            latticeMap.put(lattice2.toString(), lattice2);
            return lattice2;
        }
    }
    // No suitable existing lattice. Register this one.
    latticeMap.put(lattice.toString(), lattice);
    return lattice;
}

18 View Complete Implementation : MaterializationService.java
Copyright Apache License 2.0
Author : apache
/**
 * Defines a tile.
 *
 * <p>Setting the {@code create} flag to false prevents a materialization
 * from being created if one does not exist. Critically, it is set to false
 * during the recursive SQL that populates a materialization. Otherwise a
 * materialization would try to create itself to populate itself!
 */
public Pair<CalciteSchema.TableEntry, TileKey> defineTile(Lattice lattice, ImmutableBitSet groupSet, List<Lattice.Measure> measureList, CalciteSchema schema, boolean create, boolean exact) {
    return defineTile(lattice, groupSet, measureList, schema, create, exact, "m" + groupSet, tableFactory);
}

18 View Complete Implementation : ModelHandler.java
Copyright Apache License 2.0
Author : apache
public void visit(JsonMaterialization jsonMaterialization) {
    try {
        checkRequiredAttributes(jsonMaterialization, "sql");
        final SchemaPlus schema = currentSchema();
        if (!schema.isMutable()) {
            throw new RuntimeException("Cannot define materialization; parent schema '" + currentSchemaName() + "' is not a SemiMutableSchema");
        }
        CalciteSchema calciteSchema = CalciteSchema.from(schema);
        final String viewName;
        final boolean existing;
        if (jsonMaterialization.view == null) {
            // If the user did not supply a view name, that means the materialized
            // view is pre-populated. Generate a synthetic view name.
            viewName = "$" + schema.getTableNames().size();
            existing = true;
        } else {
            viewName = jsonMaterialization.view;
            existing = false;
        }
        List<String> viewPath = calciteSchema.path(viewName);
        schema.add(viewName, MaterializedViewTable.create(calciteSchema, jsonMaterialization.getSql(), jsonMaterialization.viewSchemaPath, viewPath, jsonMaterialization.table, existing));
    } catch (Exception e) {
        throw new RuntimeException("Error instantiating " + jsonMaterialization, e);
    }
}

18 View Complete Implementation : ViewTableMacro.java
Copyright Apache License 2.0
Author : apache
/**
 * Allows a sub-clreplaced to return an extension of {@link ModifiableViewTable}
 * by overriding this method.
 */
protected ModifiableViewTable modifiableViewTable(CalcitePrepare.replacedyzeViewResult parsed, String viewSql, List<String> schemaPath, List<String> viewPath, CalciteSchema schema) {
    final JavaTypeFactory typeFactory = (JavaTypeFactory) parsed.typeFactory;
    final Type elementType = typeFactory.getJavaClreplaced(parsed.rowType);
    return new ModifiableViewTable(elementType, RelDataTypeImpl.proto(parsed.rowType), viewSql, schemaPath, viewPath, parsed.table, Schemas.path(schema.root(), parsed.tablePath), parsed.constraint, parsed.columnMapping);
}

18 View Complete Implementation : ViewTableMacro.java
Copyright Apache License 2.0
Author : apache
/**
 * Table function that implements a view. It returns the operator
 * tree of the view's SQL query.
 */
public clreplaced ViewTableMacro implements TableMacro {

    protected final String viewSql;

    protected final CalciteSchema schema;

    private final Boolean modifiable;

    /**
     * Typically null. If specified, overrides the path of the schema as the
     * context for validating {@code viewSql}.
     */
    protected final List<String> schemaPath;

    protected final List<String> viewPath;

    /**
     * Creates a ViewTableMacro.
     *
     * @param schema     Root schema
     * @param viewSql    SQL defining the view
     * @param schemaPath Schema path relative to the root schema
     * @param viewPath   View path relative to the schema path
     * @param modifiable Request that a view is modifiable (dependent on replacedysis
     *                   of {@code viewSql})
     */
    public ViewTableMacro(CalciteSchema schema, String viewSql, List<String> schemaPath, List<String> viewPath, Boolean modifiable) {
        this.viewSql = viewSql;
        this.schema = schema;
        this.viewPath = viewPath == null ? null : ImmutableList.copyOf(viewPath);
        this.modifiable = modifiable;
        this.schemaPath = schemaPath == null ? null : ImmutableList.copyOf(schemaPath);
    }

    public List<FunctionParameter> getParameters() {
        return Collections.emptyList();
    }

    public TranslatableTable apply(List<Object> arguments) {
        final CalciteConnection connection = MaterializedViewTable.MATERIALIZATION_CONNECTION;
        CalcitePrepare.replacedyzeViewResult parsed = Schemas.replacedyzeView(connection, schema, schemaPath, viewSql, viewPath, modifiable != null && modifiable);
        final List<String> schemaPath1 = schemaPath != null ? schemaPath : schema.path(null);
        if ((modifiable == null || modifiable) && parsed.modifiable && parsed.table != null) {
            return modifiableViewTable(parsed, viewSql, schemaPath1, viewPath, schema);
        } else {
            return viewTable(parsed, viewSql, schemaPath1, viewPath);
        }
    }

    /**
     * Allows a sub-clreplaced to return an extension of {@link ModifiableViewTable}
     * by overriding this method.
     */
    protected ModifiableViewTable modifiableViewTable(CalcitePrepare.replacedyzeViewResult parsed, String viewSql, List<String> schemaPath, List<String> viewPath, CalciteSchema schema) {
        final JavaTypeFactory typeFactory = (JavaTypeFactory) parsed.typeFactory;
        final Type elementType = typeFactory.getJavaClreplaced(parsed.rowType);
        return new ModifiableViewTable(elementType, RelDataTypeImpl.proto(parsed.rowType), viewSql, schemaPath, viewPath, parsed.table, Schemas.path(schema.root(), parsed.tablePath), parsed.constraint, parsed.columnMapping);
    }

    /**
     * Allows a sub-clreplaced to return an extension of {@link ViewTable} by
     * overriding this method.
     */
    protected ViewTable viewTable(CalcitePrepare.replacedyzeViewResult parsed, String viewSql, List<String> schemaPath, List<String> viewPath) {
        final JavaTypeFactory typeFactory = (JavaTypeFactory) parsed.typeFactory;
        final Type elementType = typeFactory.getJavaClreplaced(parsed.rowType);
        return new ViewTable(elementType, RelDataTypeImpl.proto(parsed.rowType), viewSql, schemaPath, viewPath);
    }
}

18 View Complete Implementation : SqlDropSchema.java
Copyright Apache License 2.0
Author : apache
public void execute(CalcitePrepare.Context context) {
    final List<String> path = context.getDefaultSchemaPath();
    CalciteSchema schema = context.getRootSchema();
    for (String p : path) {
        schema = schema.getSubSchema(p, true);
    }
    final boolean existed = schema.removeSubSchema(name.getSimple());
    if (!existed && !ifExists) {
        throw SqlUtil.newContextException(name.getParserPosition(), RESOURCE.schemaNotFound(name.getSimple()));
    }
}

18 View Complete Implementation : Schemas.java
Copyright Apache License 2.0
Author : apache
/**
 * Generates a table name that is unique within the given schema.
 */
public static String uniqueTableName(CalciteSchema schema, String base) {
    String t = Objects.requireNonNull(base);
    for (int x = 0; schema.getTable(t, true) != null; x++) {
        t = base + x;
    }
    return t;
}

18 View Complete Implementation : Schemas.java
Copyright Apache License 2.0
Author : apache
/**
 * Parses and validates a SQL query and converts to relational algebra. For
 * use within Calcite only.
 */
public static CalcitePrepare.ConvertResult convert(final CalciteConnection connection, final CalciteSchema schema, final List<String> schemaPath, final String sql) {
    final CalcitePrepare prepare = CalcitePrepare.DEFAULT_FACTORY.apply();
    final ImmutableMap<CalciteConnectionProperty, String> propValues = ImmutableMap.of();
    final CalcitePrepare.Context context = makeContext(connection, schema, schemaPath, null, propValues);
    CalcitePrepare.Dummy.push(context);
    try {
        return prepare.convert(context, sql);
    } finally {
        CalcitePrepare.Dummy.pop(context);
    }
}

18 View Complete Implementation : Schemas.java
Copyright Apache License 2.0
Author : apache
/**
 * Parses and validates a SQL query. For use within Calcite only.
 */
public static CalcitePrepare.ParseResult parse(final CalciteConnection connection, final CalciteSchema schema, final List<String> schemaPath, final String sql) {
    final CalcitePrepare prepare = CalcitePrepare.DEFAULT_FACTORY.apply();
    final ImmutableMap<CalciteConnectionProperty, String> propValues = ImmutableMap.of();
    final CalcitePrepare.Context context = makeContext(connection, schema, schemaPath, null, propValues);
    CalcitePrepare.Dummy.push(context);
    try {
        return prepare.parse(context, sql);
    } finally {
        CalcitePrepare.Dummy.pop(context);
    }
}

18 View Complete Implementation : Schemas.java
Copyright Apache License 2.0
Author : apache
/**
 * Returns the lattices defined in a schema.
 *
 * @param schema Schema
 */
public static List<Lattice> getLattices(CalciteSchema schema) {
    final List<CalciteSchema.LatticeEntry> list = getLatticeEntries(schema);
    return Lists.transform(list, CalciteSchema.LatticeEntry::getLattice);
}

18 View Complete Implementation : QuarkViewTable.java
Copyright Apache License 2.0
Author : qubole
/**
 * Table that is a materialized view.
 * <p></p>
 * <p>It can exist in two states: materialized and not materialized. Over time,
 * a given materialized view may switch states. How it is expanded depends upon
 * its current state. State is managed by
 * {@link org.apache.calcite.materialize.MaterializationService}.</p>
 */
public clreplaced QuarkViewTable extends QuarkTable {

    // This is of the backup table
    private final RelOptTableImpl backUpRelOptTable;

    private final QuarkTable backupTable;

    private final CalciteSchema backupTableSchema;

    public QuarkViewTable(QuarkSchema schema, String name, RelOptTableImpl relOptTable, QuarkTable backupTable, CalciteSchema tableSchema) {
        super(schema, name, backupTable.getColumns());
        this.backUpRelOptTable = relOptTable;
        this.backupTable = backupTable;
        this.backupTableSchema = tableSchema;
    }

    public RelDataType getRowType(RelDataTypeFactory typeFactory) {
        return backupTable.getRowType(typeFactory);
    }

    public <T> Queryable<T> asQueryable(final QueryProvider queryProvider, SchemaPlus schema, String tableName) {
        return new AbstractTableQueryable<T>(queryProvider, schema, this, tableName) {

            @SuppressWarnings("unchecked")
            public Enumerator<T> enumerator() {
                return null;
            }
        };
    }

    public Enumerable<Object[]> scan(DataContext root) {
        return new AbstractEnumerable<Object[]>() {

            public Enumerator<Object[]> enumerator() {
                return null;
            }
        };
    }

    public Statistic getStatistic() {
        return Statistics.of(0d, ImmutableList.<ImmutableBitSet>of());
    }

    public RelNode toRel(RelOptTable.ToRelContext context, RelOptTable relOptTable) {
        return new QuarkViewScan(context.getCluster(), this.backUpRelOptTable, this);
    }

    public CalciteSchema getBackupTableSchema() {
        return this.backupTableSchema;
    }
}

18 View Complete Implementation : Schemas.java
Copyright Apache License 2.0
Author : apache
private static void gatherLattices(CalciteSchema schema, List<CalciteSchema.LatticeEntry> list) {
    list.addAll(schema.getLatticeMap().values());
    for (CalciteSchema subSchema : schema.getSubSchemaMap().values()) {
        gatherLattices(subSchema, list);
    }
}

18 View Complete Implementation : Schemas.java
Copyright Apache License 2.0
Author : apache
private static CalcitePrepare.Context makeContext(final CalciteConnectionConfig connectionConfig, final JavaTypeFactory typeFactory, final DataContext dataContext, final CalciteSchema schema, final List<String> schemaPath, final List<String> objectPath_) {
    final ImmutableList<String> objectPath = objectPath_ == null ? null : ImmutableList.copyOf(objectPath_);
    return new CalcitePrepare.Context() {

        public JavaTypeFactory getTypeFactory() {
            return typeFactory;
        }

        public CalciteSchema getRootSchema() {
            return schema.root();
        }

        public CalciteSchema getMutableRootSchema() {
            return getRootSchema();
        }

        public List<String> getDefaultSchemaPath() {
            // schemaPath is usually null. If specified, it overrides schema
            // as the context within which the SQL is validated.
            if (schemaPath == null) {
                return schema.path(null);
            }
            return schemaPath;
        }

        public List<String> getObjectPath() {
            return objectPath;
        }

        public CalciteConnectionConfig config() {
            return connectionConfig;
        }

        public DataContext getDataContext() {
            return dataContext;
        }

        public RelRunner getRelRunner() {
            throw new UnsupportedOperationException();
        }

        public CalcitePrepare.SparkHandler spark() {
            final boolean enable = config().spark();
            return CalcitePrepare.Dummy.getSparkHandler(enable);
        }
    };
}

18 View Complete Implementation : SqlValidatorUtil.java
Copyright Apache License 2.0
Author : apache
/**
 * Finds a {@link org.apache.calcite.jdbc.CalciteSchema.TableEntry} in a
 * given catalog reader whose table has the given name, possibly qualified.
 *
 * <p>Uses the case-sensitivity policy of the specified catalog reader.
 *
 * <p>If not found, returns null.
 *
 * @param catalogReader accessor to the table metadata
 * @param names Name of table, may be qualified or fully-qualified
 *
 * @return TableEntry with a table with the given name, or null
 */
public static CalciteSchema.TableEntry getTableEntry(SqlValidatorCatalogReader catalogReader, List<String> names) {
    // First look in the default schema, if any.
    // If not found, look in the root schema.
    for (List<String> schemaPath : catalogReader.getSchemaPaths()) {
        CalciteSchema schema = getSchema(catalogReader.getRootSchema(), Iterables.concat(schemaPath, Util.skipLast(names)), catalogReader.nameMatcher());
        if (schema == null) {
            continue;
        }
        CalciteSchema.TableEntry entry = getTableEntryFrom(schema, Util.last(names), catalogReader.nameMatcher().isCaseSensitive());
        if (entry != null) {
            return entry;
        }
    }
    return null;
}

18 View Complete Implementation : SqlDdlNodes.java
Copyright Apache License 2.0
Author : apache
/**
 * Returns the schema in which to create an object.
 */
static Pair<CalciteSchema, String> schema(CalcitePrepare.Context context, boolean mutable, SqlIdentifier id) {
    final String name;
    final List<String> path;
    if (id.isSimple()) {
        path = context.getDefaultSchemaPath();
        name = id.getSimple();
    } else {
        path = Util.skipLast(id.names);
        name = Util.last(id.names);
    }
    CalciteSchema schema = mutable ? context.getMutableRootSchema() : context.getRootSchema();
    for (String p : path) {
        schema = schema.getSubSchema(p, true);
    }
    return Pair.of(schema, name);
}

17 View Complete Implementation : MaterializationService.java
Copyright Apache License 2.0
Author : apache
/**
 * Gathers a list of all materialized tables known within a given root
 * schema. (Each root schema defines a disconnected namespace, with no overlap
 * with the current schema. Especially in a test run, the contents of two
 * root schemas may look similar.)
 */
public List<Prepare.Materialization> query(CalciteSchema rootSchema) {
    final List<Prepare.Materialization> list = new ArrayList<>();
    for (MaterializationActor.Materialization materialization : actor.keyMap.values()) {
        if (materialization.rootSchema.schema == rootSchema.schema && materialization.materializedTable != null) {
            list.add(new Prepare.Materialization(materialization.materializedTable, materialization.sql, materialization.viewSchemaPath));
        }
    }
    return list;
}

17 View Complete Implementation : RelOptLattice.java
Copyright Apache License 2.0
Author : apache
/**
 * Retrieves a materialized table that will satisfy an aggregate query on
 * the star table.
 *
 * <p>The current implementation creates a materialization and populates it,
 * provided that {@link Lattice#auto} is true.
 *
 * <p>Future implementations might return materializations at a different
 * level of aggregation, from which the desired result can be obtained by
 * rolling up.
 *
 * @param planner Current planner
 * @param groupSet Grouping key
 * @param measureList Calls to aggregate functions
 * @return Materialized table
 */
public Pair<CalciteSchema.TableEntry, TileKey> getAggregate(RelOptPlanner planner, ImmutableBitSet groupSet, List<Lattice.Measure> measureList) {
    final CalciteConnectionConfig config = planner.getContext().unwrap(CalciteConnectionConfig.clreplaced);
    if (config == null) {
        return null;
    }
    final MaterializationService service = MaterializationService.instance();
    boolean create = lattice.auto && config.createMaterializations();
    final CalciteSchema schema = starRelOptTable.unwrap(CalciteSchema.clreplaced);
    return service.defineTile(lattice, groupSet, measureList, schema, create, false);
}

17 View Complete Implementation : Schemas.java
Copyright Apache License 2.0
Author : apache
/**
 * replacedyzes a view. For use within Calcite only.
 */
public static CalcitePrepare.replacedyzeViewResult replacedyzeView(final CalciteConnection connection, final CalciteSchema schema, final List<String> schemaPath, final String viewSql, List<String> viewPath, boolean fail) {
    final CalcitePrepare prepare = CalcitePrepare.DEFAULT_FACTORY.apply();
    final ImmutableMap<CalciteConnectionProperty, String> propValues = ImmutableMap.of();
    final CalcitePrepare.Context context = makeContext(connection, schema, schemaPath, viewPath, propValues);
    CalcitePrepare.Dummy.push(context);
    try {
        return prepare.replacedyzeView(context, viewSql, fail);
    } finally {
        CalcitePrepare.Dummy.pop(context);
    }
}

17 View Complete Implementation : Schemas.java
Copyright Apache License 2.0
Author : apache
/**
 * Prepares a SQL query for execution. For use within Calcite only.
 */
public static CalcitePrepare.CalciteSignature<Object> prepare(final CalciteConnection connection, final CalciteSchema schema, final List<String> schemaPath, final String sql, final ImmutableMap<CalciteConnectionProperty, String> map) {
    final CalcitePrepare prepare = CalcitePrepare.DEFAULT_FACTORY.apply();
    final CalcitePrepare.Context context = makeContext(connection, schema, schemaPath, null, map);
    CalcitePrepare.Dummy.push(context);
    try {
        return prepare.prepareSql(context, CalcitePrepare.Query.of(sql), Object[].clreplaced, -1);
    } finally {
        CalcitePrepare.Dummy.pop(context);
    }
}

17 View Complete Implementation : Schemas.java
Copyright Apache License 2.0
Author : apache
/**
 * Returns the star tables defined in a schema.
 *
 * @param schema Schema
 */
public static List<CalciteSchema.TableEntry> getStarTables(CalciteSchema schema) {
    final List<CalciteSchema.LatticeEntry> list = getLatticeEntries(schema);
    return Lists.transform(list, entry -> {
        final CalciteSchema.TableEntry starTable = Objects.requireNonNull(entry).getStarTable();
        replacedert starTable.getTable().getJdbcTableType() == Schema.TableType.STAR;
        return entry.getStarTable();
    });
}

17 View Complete Implementation : Schemas.java
Copyright Apache License 2.0
Author : apache
/**
 * Creates a path with a given list of names starting from a given root
 * schema.
 */
public static Path path(CalciteSchema rootSchema, Iterable<String> names) {
    final ImmutableList.Builder<Pair<String, Schema>> builder = ImmutableList.builder();
    Schema schema = rootSchema.plus();
    final Iterator<String> iterator = names.iterator();
    if (!iterator.hasNext()) {
        return PathImpl.EMPTY;
    }
    if (!rootSchema.name.isEmpty()) {
        Preconditions.checkState(rootSchema.name.equals(iterator.next()));
    }
    for (; ; ) {
        final String name = iterator.next();
        builder.add(Pair.of(name, schema));
        if (!iterator.hasNext()) {
            return path(builder.build());
        }
        schema = schema.getSubSchema(name);
    }
}

17 View Complete Implementation : EmptyScope.java
Copyright Apache License 2.0
Author : apache
private void resolve_(final CalciteSchema rootSchema, List<String> names, List<String> schemaNames, SqlNameMatcher nameMatcher, Path path, Resolved resolved) {
    final List<String> concat = ImmutableList.<String>builder().addAll(schemaNames).addAll(names).build();
    CalciteSchema schema = rootSchema;
    SqlValidatorNamespace namespace = null;
    List<String> remainingNames = concat;
    for (String schemaName : concat) {
        if (schema == rootSchema && nameMatcher.matches(schemaName, schema.name)) {
            remainingNames = Util.skip(remainingNames);
            continue;
        }
        final CalciteSchema subSchema = schema.getSubSchema(schemaName, nameMatcher.isCaseSensitive());
        if (subSchema != null) {
            path = path.plus(null, -1, subSchema.name, StructKind.NONE);
            remainingNames = Util.skip(remainingNames);
            schema = subSchema;
            namespace = new SchemaNamespace(validator, ImmutableList.copyOf(path.stepNames()));
            continue;
        }
        CalciteSchema.TableEntry entry = schema.getTable(schemaName, nameMatcher.isCaseSensitive());
        if (entry == null) {
            entry = schema.getTableBasedOnNullaryFunction(schemaName, nameMatcher.isCaseSensitive());
        }
        if (entry != null) {
            path = path.plus(null, -1, entry.name, StructKind.NONE);
            remainingNames = Util.skip(remainingNames);
            final Table table = entry.getTable();
            SqlValidatorTable table2 = null;
            if (table instanceof Wrapper) {
                table2 = ((Wrapper) table).unwrap(Prepare.PreparingTable.clreplaced);
            }
            if (table2 == null) {
                final RelOptSchema relOptSchema = validator.catalogReader.unwrap(RelOptSchema.clreplaced);
                final RelDataType rowType = table.getRowType(validator.typeFactory);
                table2 = RelOptTableImpl.create(relOptSchema, rowType, entry, null);
            }
            namespace = new TableNamespace(validator, table2);
            resolved.found(namespace, false, null, path, remainingNames);
            return;
        }
        // neither sub-schema nor table
        if (namespace != null && !remainingNames.equals(names)) {
            resolved.found(namespace, false, null, path, remainingNames);
        }
        return;
    }
}

17 View Complete Implementation : MockCatalogReader.java
Copyright Apache License 2.0
Author : apache
// ~ Methods ----------------------------------------------------------------
protected void registerType(final List<String> names, final RelProtoDataType relProtoDataType) {
    replacedert names.get(0).equals(DEFAULT_CATALOG);
    final List<String> schemaPath = Util.skipLast(names);
    final CalciteSchema schema = SqlValidatorUtil.getSchema(rootSchema, schemaPath, SqlNameMatchers.withCaseSensitive(true));
    schema.add(Util.last(names), relProtoDataType);
}

17 View Complete Implementation : MockCatalogReader.java
Copyright Apache License 2.0
Author : apache
private void registerTable(final List<String> names, final Table table) {
    replacedert names.get(0).equals(DEFAULT_CATALOG);
    final List<String> schemaPath = Util.skipLast(names);
    final String tableName = Util.last(names);
    final CalciteSchema schema = SqlValidatorUtil.getSchema(rootSchema, schemaPath, SqlNameMatchers.withCaseSensitive(true));
    schema.add(tableName, table);
}

17 View Complete Implementation : Driver.java
Copyright Apache License 2.0
Author : rayokota
/**
 * Creates an internal connection.
 */
CalciteConnection connect(CalciteSchema rootSchema, JavaTypeFactory typeFactory, Properties properties) {
    return (CalciteConnection) ((CalciteFactory) factory).newConnection(this, factory, CONNECT_STRING_PREFIX, properties, rootSchema, typeFactory);
}

16 View Complete Implementation : ModelHandler.java
Copyright Apache License 2.0
Author : apache
public void visit(JsonLattice jsonLattice) {
    try {
        checkRequiredAttributes(jsonLattice, "name", "sql");
        final SchemaPlus schema = currentSchema();
        if (!schema.isMutable()) {
            throw new RuntimeException("Cannot define lattice; parent schema '" + currentSchemaName() + "' is not a SemiMutableSchema");
        }
        CalciteSchema calciteSchema = CalciteSchema.from(schema);
        Lattice.Builder latticeBuilder = Lattice.builder(calciteSchema, jsonLattice.getSql()).auto(jsonLattice.auto).algorithm(jsonLattice.algorithm);
        if (jsonLattice.rowCountEstimate != null) {
            latticeBuilder.rowCountEstimate(jsonLattice.rowCountEstimate);
        }
        if (jsonLattice.statisticProvider != null) {
            latticeBuilder.statisticProvider(jsonLattice.statisticProvider);
        }
        populateLattice(jsonLattice, latticeBuilder);
        schema.add(jsonLattice.name, latticeBuilder.build());
    } catch (Exception e) {
        throw new RuntimeException("Error instantiating " + jsonLattice, e);
    }
}

16 View Complete Implementation : CalciteCatalogReader.java
Copyright Apache License 2.0
Author : apache
/**
 * Creates an operator table that contains functions in the given clreplaced.
 *
 * @see ModelHandler#addFunctions
 */
public static SqlOperatorTable operatorTable(String clreplacedName) {
    // Dummy schema to collect the functions
    final CalciteSchema schema = CalciteSchema.createRootSchema(false, false);
    ModelHandler.addFunctions(schema.plus(), null, ImmutableList.of(), clreplacedName, "*", true);
    // The following is technical debt; see [CALCITE-2082] Remove
    // RelDataTypeFactory argument from SqlUserDefinedAggFunction constructor
    final SqlTypeFactoryImpl typeFactory = new SqlTypeFactoryImpl(RelDataTypeSystem.DEFAULT);
    final ListSqlOperatorTable table = new ListSqlOperatorTable();
    for (String name : schema.getFunctionNames()) {
        for (Function function : schema.getFunctions(name, true)) {
            final SqlIdentifier id = new SqlIdentifier(name, SqlParserPos.ZERO);
            table.add(toOp(typeFactory, id, function));
        }
    }
    return table;
}

16 View Complete Implementation : CalciteCatalogReader.java
Copyright Apache License 2.0
Author : apache
/**
 * Implementation of {@link org.apache.calcite.prepare.Prepare.CatalogReader}
 * and also {@link org.apache.calcite.sql.SqlOperatorTable} based on tables and
 * functions defined schemas.
 */
public clreplaced CalciteCatalogReader implements Prepare.CatalogReader {

    protected final CalciteSchema rootSchema;

    protected final RelDataTypeFactory typeFactory;

    private final List<List<String>> schemaPaths;

    protected final SqlNameMatcher nameMatcher;

    protected final CalciteConnectionConfig config;

    public CalciteCatalogReader(CalciteSchema rootSchema, List<String> defaultSchema, RelDataTypeFactory typeFactory, CalciteConnectionConfig config) {
        this(rootSchema, SqlNameMatchers.withCaseSensitive(config != null && config.caseSensitive()), ImmutableList.of(Objects.requireNonNull(defaultSchema), ImmutableList.of()), typeFactory, config);
    }

    protected CalciteCatalogReader(CalciteSchema rootSchema, SqlNameMatcher nameMatcher, List<List<String>> schemaPaths, RelDataTypeFactory typeFactory, CalciteConnectionConfig config) {
        this.rootSchema = Objects.requireNonNull(rootSchema);
        this.nameMatcher = nameMatcher;
        this.schemaPaths = Util.immutableCopy(Util.isDistinct(schemaPaths) ? schemaPaths : new LinkedHashSet<>(schemaPaths));
        this.typeFactory = typeFactory;
        this.config = config;
    }

    public CalciteCatalogReader withSchemaPath(List<String> schemaPath) {
        return new CalciteCatalogReader(rootSchema, nameMatcher, ImmutableList.of(schemaPath, ImmutableList.of()), typeFactory, config);
    }

    public Prepare.PreparingTable getTable(final List<String> names) {
        // First look in the default schema, if any.
        // If not found, look in the root schema.
        CalciteSchema.TableEntry entry = SqlValidatorUtil.getTableEntry(this, names);
        if (entry != null) {
            final Table table = entry.getTable();
            if (table instanceof Wrapper) {
                final Prepare.PreparingTable relOptTable = ((Wrapper) table).unwrap(Prepare.PreparingTable.clreplaced);
                if (relOptTable != null) {
                    return relOptTable;
                }
            }
            return RelOptTableImpl.create(this, table.getRowType(typeFactory), entry, null);
        }
        return null;
    }

    @Override
    public CalciteConnectionConfig getConfig() {
        return config;
    }

    private Collection<Function> getFunctionsFrom(List<String> names) {
        final List<Function> functions2 = new ArrayList<>();
        final List<List<String>> schemaNameList = new ArrayList<>();
        if (names.size() > 1) {
            // Name qualified: ignore path. But we do look in "/catalog" and "/",
            // the last 2 items in the path.
            if (schemaPaths.size() > 1) {
                schemaNameList.addAll(Util.skip(schemaPaths));
            } else {
                schemaNameList.addAll(schemaPaths);
            }
        } else {
            for (List<String> schemaPath : schemaPaths) {
                CalciteSchema schema = SqlValidatorUtil.getSchema(rootSchema, schemaPath, nameMatcher);
                if (schema != null) {
                    schemaNameList.addAll(schema.getPath());
                }
            }
        }
        for (List<String> schemaNames : schemaNameList) {
            CalciteSchema schema = SqlValidatorUtil.getSchema(rootSchema, Iterables.concat(schemaNames, Util.skipLast(names)), nameMatcher);
            if (schema != null) {
                final String name = Util.last(names);
                boolean caseSensitive = nameMatcher.isCaseSensitive();
                functions2.addAll(schema.getFunctions(name, caseSensitive));
            }
        }
        return functions2;
    }

    public RelDataType getNamedType(SqlIdentifier typeName) {
        CalciteSchema.TypeEntry typeEntry = SqlValidatorUtil.getTypeEntry(getRootSchema(), typeName);
        if (typeEntry != null) {
            return typeEntry.getType().apply(typeFactory);
        } else {
            return null;
        }
    }

    public List<SqlMoniker> getAllSchemaObjectNames(List<String> names) {
        final CalciteSchema schema = SqlValidatorUtil.getSchema(rootSchema, names, nameMatcher);
        if (schema == null) {
            return ImmutableList.of();
        }
        final List<SqlMoniker> result = new ArrayList<>();
        // Add root schema if not anonymous
        if (!schema.name.equals("")) {
            result.add(moniker(schema, null, SqlMonikerType.SCHEMA));
        }
        final Map<String, CalciteSchema> schemaMap = schema.getSubSchemaMap();
        for (String subSchema : schemaMap.keySet()) {
            result.add(moniker(schema, subSchema, SqlMonikerType.SCHEMA));
        }
        for (String table : schema.getTableNames()) {
            result.add(moniker(schema, table, SqlMonikerType.TABLE));
        }
        final NavigableSet<String> functions = schema.getFunctionNames();
        for (String function : functions) {
            // views are here as well
            result.add(moniker(schema, function, SqlMonikerType.FUNCTION));
        }
        return result;
    }

    private SqlMonikerImpl moniker(CalciteSchema schema, String name, SqlMonikerType type) {
        final List<String> path = schema.path(name);
        if (path.size() == 1 && !schema.root().name.equals("") && type == SqlMonikerType.SCHEMA) {
            type = SqlMonikerType.CATALOG;
        }
        return new SqlMonikerImpl(path, type);
    }

    public List<List<String>> getSchemaPaths() {
        return schemaPaths;
    }

    public Prepare.PreparingTable getTableForMember(List<String> names) {
        return getTable(names);
    }

    @SuppressWarnings("deprecation")
    public RelDataTypeField field(RelDataType rowType, String alias) {
        return nameMatcher.field(rowType, alias);
    }

    @SuppressWarnings("deprecation")
    public boolean matches(String string, String name) {
        return nameMatcher.matches(string, name);
    }

    public RelDataType createTypeFromProjection(final RelDataType type, final List<String> columnNameList) {
        return SqlValidatorUtil.createTypeFromProjection(type, columnNameList, typeFactory, nameMatcher.isCaseSensitive());
    }

    public void lookupOperatorOverloads(final SqlIdentifier opName, SqlFunctionCategory category, SqlSyntax syntax, List<SqlOperator> operatorList, SqlNameMatcher nameMatcher) {
        if (syntax != SqlSyntax.FUNCTION) {
            return;
        }
        final Predicate<Function> predicate;
        if (category == null) {
            predicate = function -> true;
        } else if (category.isTableFunction()) {
            predicate = function -> function instanceof TableMacro || function instanceof TableFunction;
        } else {
            predicate = function -> !(function instanceof TableMacro || function instanceof TableFunction);
        }
        getFunctionsFrom(opName.names).stream().filter(predicate).map(function -> toOp(opName, function)).forEachOrdered(operatorList::add);
    }

    /**
     * Creates an operator table that contains functions in the given clreplaced.
     *
     * @see ModelHandler#addFunctions
     */
    public static SqlOperatorTable operatorTable(String clreplacedName) {
        // Dummy schema to collect the functions
        final CalciteSchema schema = CalciteSchema.createRootSchema(false, false);
        ModelHandler.addFunctions(schema.plus(), null, ImmutableList.of(), clreplacedName, "*", true);
        // The following is technical debt; see [CALCITE-2082] Remove
        // RelDataTypeFactory argument from SqlUserDefinedAggFunction constructor
        final SqlTypeFactoryImpl typeFactory = new SqlTypeFactoryImpl(RelDataTypeSystem.DEFAULT);
        final ListSqlOperatorTable table = new ListSqlOperatorTable();
        for (String name : schema.getFunctionNames()) {
            for (Function function : schema.getFunctions(name, true)) {
                final SqlIdentifier id = new SqlIdentifier(name, SqlParserPos.ZERO);
                table.add(toOp(typeFactory, id, function));
            }
        }
        return table;
    }

    private SqlOperator toOp(SqlIdentifier name, final Function function) {
        return toOp(typeFactory, name, function);
    }

    /**
     * Converts a function to a {@link org.apache.calcite.sql.SqlOperator}.
     *
     * <p>The {@code typeFactory} argument is technical debt; see [CALCITE-2082]
     * Remove RelDataTypeFactory argument from SqlUserDefinedAggFunction
     * constructor.
     */
    private static SqlOperator toOp(RelDataTypeFactory typeFactory, 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 FamilyOperandTypeChecker typeChecker = OperandTypes.family(typeFamilies, i -> function.getParameters().get(i).isOptional());
        final List<RelDataType> paramTypes = toSql(typeFactory, 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, Optionality.FORBIDDEN, 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 replacedertionError("unknown function type " + function);
        }
    }

    private static SqlReturnTypeInference infer(final ScalarFunction function) {
        return opBinding -> {
            final RelDataTypeFactory typeFactory = opBinding.getTypeFactory();
            final RelDataType type;
            if (function instanceof ScalarFunctionImpl) {
                type = ((ScalarFunctionImpl) function).getReturnType(typeFactory, opBinding);
            } else {
                type = function.getReturnType(typeFactory);
            }
            return toSql(typeFactory, type);
        };
    }

    private static SqlReturnTypeInference infer(final AggregateFunction function) {
        return opBinding -> {
            final RelDataTypeFactory typeFactory = opBinding.getTypeFactory();
            final RelDataType type = function.getReturnType(typeFactory);
            return toSql(typeFactory, type);
        };
    }

    private static List<RelDataType> toSql(final RelDataTypeFactory typeFactory, List<RelDataType> types) {
        return Lists.transform(types, type -> toSql(typeFactory, type));
    }

    private static RelDataType toSql(RelDataTypeFactory typeFactory, RelDataType type) {
        if (type instanceof RelDataTypeFactoryImpl.JavaType && ((RelDataTypeFactoryImpl.JavaType) type).getJavaClreplaced() == Object.clreplaced) {
            return typeFactory.createTypeWithNullability(typeFactory.createSqlType(SqlTypeName.ANY), true);
        }
        return JavaTypeFactoryImpl.toSql(typeFactory, type);
    }

    public List<SqlOperator> getOperatorList() {
        return null;
    }

    public CalciteSchema getRootSchema() {
        return rootSchema;
    }

    public RelDataTypeFactory getTypeFactory() {
        return typeFactory;
    }

    public void registerRules(RelOptPlanner planner) throws Exception {
    }

    @SuppressWarnings("deprecation")
    @Override
    public boolean isCaseSensitive() {
        return nameMatcher.isCaseSensitive();
    }

    public SqlNameMatcher nameMatcher() {
        return nameMatcher;
    }

    @Override
    public <C> C unwrap(Clreplaced<C> aClreplaced) {
        if (aClreplaced.isInstance(this)) {
            return aClreplaced.cast(this);
        }
        return null;
    }
}