Search in sources :

Example 1 with AbstractEnumerable

use of org.apache.calcite.linq4j.AbstractEnumerable in project calcite by apache.

the class CassandraTable method query.

/**
 * Executes a CQL query on the underlying table.
 *
 * @param session Cassandra session
 * @param fields List of fields to project
 * @param predicates A list of predicates which should be used in the query
 * @return Enumerator of results
 */
public Enumerable<Object> query(final Session session, List<Map.Entry<String, Class>> fields, final List<Map.Entry<String, String>> selectFields, List<String> predicates, List<String> order, final Integer offset, final Integer fetch) {
    // Build the type of the resulting row based on the provided fields
    final RelDataTypeFactory typeFactory = new SqlTypeFactoryImpl(RelDataTypeSystem.DEFAULT);
    final RelDataTypeFactory.Builder fieldInfo = typeFactory.builder();
    final RelDataType rowType = getRowType(typeFactory);
    Function1<String, Void> addField = new Function1<String, Void>() {

        public Void apply(String fieldName) {
            SqlTypeName typeName = rowType.getField(fieldName, true, false).getType().getSqlTypeName();
            fieldInfo.add(fieldName, typeFactory.createSqlType(typeName)).nullable(true);
            return null;
        }
    };
    if (selectFields.isEmpty()) {
        for (Map.Entry<String, Class> field : fields) {
            addField.apply(field.getKey());
        }
    } else {
        for (Map.Entry<String, String> field : selectFields) {
            addField.apply(field.getKey());
        }
    }
    final RelProtoDataType resultRowType = RelDataTypeImpl.proto(fieldInfo.build());
    // Construct the list of fields to project
    final String selectString;
    if (selectFields.isEmpty()) {
        selectString = "*";
    } else {
        selectString = Util.toString(new Iterable<String>() {

            public Iterator<String> iterator() {
                final Iterator<Map.Entry<String, String>> selectIterator = selectFields.iterator();
                return new Iterator<String>() {

                    @Override
                    public boolean hasNext() {
                        return selectIterator.hasNext();
                    }

                    @Override
                    public String next() {
                        Map.Entry<String, String> entry = selectIterator.next();
                        return entry.getKey() + " AS " + entry.getValue();
                    }

                    @Override
                    public void remove() {
                        throw new UnsupportedOperationException();
                    }
                };
            }
        }, "", ", ", "");
    }
    // Combine all predicates conjunctively
    String whereClause = "";
    if (!predicates.isEmpty()) {
        whereClause = " WHERE ";
        whereClause += Util.toString(predicates, "", " AND ", "");
    }
    // Build and issue the query and return an Enumerator over the results
    StringBuilder queryBuilder = new StringBuilder("SELECT ");
    queryBuilder.append(selectString);
    queryBuilder.append(" FROM \"" + columnFamily + "\"");
    queryBuilder.append(whereClause);
    if (!order.isEmpty()) {
        queryBuilder.append(Util.toString(order, " ORDER BY ", ", ", ""));
    }
    int limit = offset;
    if (fetch >= 0) {
        limit += fetch;
    }
    if (limit > 0) {
        queryBuilder.append(" LIMIT " + limit);
    }
    queryBuilder.append(" ALLOW FILTERING");
    final String query = queryBuilder.toString();
    return new AbstractEnumerable<Object>() {

        public Enumerator<Object> enumerator() {
            final ResultSet results = session.execute(query);
            // Skip results until we get to the right offset
            int skip = 0;
            Enumerator<Object> enumerator = new CassandraEnumerator(results, resultRowType);
            while (skip < offset && enumerator.moveNext()) {
                skip++;
            }
            return enumerator;
        }
    };
}
Also used : SqlTypeName(org.apache.calcite.sql.type.SqlTypeName) RelDataType(org.apache.calcite.rel.type.RelDataType) RelProtoDataType(org.apache.calcite.rel.type.RelProtoDataType) RelDataTypeFactory(org.apache.calcite.rel.type.RelDataTypeFactory) Iterator(java.util.Iterator) AbstractEnumerable(org.apache.calcite.linq4j.AbstractEnumerable) ResultSet(com.datastax.driver.core.ResultSet) Function1(org.apache.calcite.linq4j.function.Function1) SqlTypeFactoryImpl(org.apache.calcite.sql.type.SqlTypeFactoryImpl) Map(java.util.Map)

Example 2 with AbstractEnumerable

use of org.apache.calcite.linq4j.AbstractEnumerable in project calcite by apache.

the class FilesTableFunction method eval.

/**
 * Evaluates the function.
 *
 * @param path Directory in which to start the search. Typically '.'
 * @return Table that can be inspected, planned, and evaluated
 */
public static ScannableTable eval(final String path) {
    return new ScannableTable() {

        public RelDataType getRowType(RelDataTypeFactory typeFactory) {
            return typeFactory.builder().add("access_time", // %A@ sec since epoch
            SqlTypeName.TIMESTAMP).add("block_count", // %b in 512B blocks
            SqlTypeName.INTEGER).add("change_time", // %C@ sec since epoch
            SqlTypeName.TIMESTAMP).add("depth", // %d depth in directory tree
            SqlTypeName.INTEGER).add("device", // %D device number
            SqlTypeName.INTEGER).add("file_name", // %f file name, sans dirs
            SqlTypeName.VARCHAR).add("fstype", // %F file system type
            SqlTypeName.VARCHAR).add("gname", // %g group name
            SqlTypeName.VARCHAR).add("gid", // %G numeric group id
            SqlTypeName.INTEGER).add("dir_name", // %h leading dirs
            SqlTypeName.VARCHAR).add("inode", // %i inode number
            SqlTypeName.BIGINT).add("link", // %l object of sym link
            SqlTypeName.VARCHAR).add("perm", SqlTypeName.CHAR, // %#m permission octal
            4).add("hard", // %n number of hard links
            SqlTypeName.INTEGER).add("path", // %P file's name
            SqlTypeName.VARCHAR).add("size", // %s file's size in bytes
            SqlTypeName.BIGINT).add("mod_time", // %T@ seconds since epoch
            SqlTypeName.TIMESTAMP).add("user", // %u user name
            SqlTypeName.VARCHAR).add("uid", // %U numeric user id
            SqlTypeName.INTEGER).add("type", SqlTypeName.CHAR, // %Y file type
            1).build();
        // Fields in Linux find that are currently ignored:
        // %y file type (not following sym links)
        // %k block count in 1KB blocks
        // %p file name (including argument)
        }

        private Enumerable<String> sourceLinux() {
            final String[] args = { "find", path, "-printf", "" + // access_time
            "%A@\\0" + // block_count
            "%b\\0" + // change_time
            "%C@\\0" + // depth
            "%d\\0" + // device
            "%D\\0" + // file_name
            "%f\\0" + // fstype
            "%F\\0" + // gname
            "%g\\0" + // gid
            "%G\\0" + // dir_name
            "%h\\0" + // inode
            "%i\\0" + // link
            "%l\\0" + // perm
            "%#m\\0" + // hard
            "%n\\0" + // path
            "%P\\0" + // size
            "%s\\0" + // mod_time
            "%T@\\0" + // user
            "%u\\0" + // uid
            "%U\\0" + // type
            "%Y\\0" };
            return Processes.processLines('\0', args);
        }

        private Enumerable<String> sourceMacOs() {
            if (path.contains("'")) {
                // no injection monkey business
                throw new IllegalArgumentException();
            }
            final String[] args = { "/bin/sh", "-c", "find '" + path + "' | xargs stat -f " + // access_time
            "%a%n" + // block_count
            "%b%n" + // change_time
            "%c%n" + // depth: not supported by macOS stat
            "0%n" + // device: we only use the high part of "H,L" device
            "%Hd%n" + // filename: not supported by macOS stat
            "filename%n" + // fstype: not supported by macOS stat
            "fstype%n" + // gname
            "%Sg%n" + // gid
            "%g%n" + // dir_name: not supported by macOS stat
            "dir_name%n" + // inode
            "%i%n" + // link
            "%Y%n" + // perm
            "%Lp%n" + // hard
            "%l%n" + // path
            "%SN%n" + // size
            "%z%n" + // mod_time
            "%m%n" + // user
            "%Su%n" + // uid
            "%u%n" + // type
            "%LT%n" };
            return Processes.processLines('\n', args);
        }

        public Enumerable<Object[]> scan(DataContext root) {
            final RelDataType rowType = getRowType(root.getTypeFactory());
            final List<String> fieldNames = ImmutableList.copyOf(rowType.getFieldNames());
            final String osName = System.getProperty("os.name");
            final String osVersion = System.getProperty("os.version");
            Util.discard(osVersion);
            final Enumerable<String> enumerable;
            switch(osName) {
                case // tested on version 10.12.5
                "Mac OS X":
                    enumerable = sourceMacOs();
                    break;
                default:
                    enumerable = sourceLinux();
            }
            return new AbstractEnumerable<Object[]>() {

                public Enumerator<Object[]> enumerator() {
                    final Enumerator<String> e = enumerable.enumerator();
                    return new Enumerator<Object[]>() {

                        Object[] current;

                        public Object[] current() {
                            return current;
                        }

                        public boolean moveNext() {
                            current = new Object[fieldNames.size()];
                            for (int i = 0; i < current.length; i++) {
                                if (!e.moveNext()) {
                                    return false;
                                }
                                final String v = e.current();
                                try {
                                    current[i] = field(fieldNames.get(i), v);
                                } catch (RuntimeException e) {
                                    throw new RuntimeException("while parsing value [" + v + "] of field [" + fieldNames.get(i) + "] in line [" + Arrays.toString(current) + "]", e);
                                }
                            }
                            switch(osName) {
                                case "Mac OS X":
                                    // Strip leading "./"
                                    String path = (String) current[14];
                                    if (path.equals(".")) {
                                        current[14] = path = "";
                                        // depth
                                        current[3] = 0;
                                    } else if (path.startsWith("./")) {
                                        current[14] = path = path.substring(2);
                                        // depth
                                        current[3] = count(path, '/') + 1;
                                    } else {
                                        // depth
                                        current[3] = count(path, '/');
                                    }
                                    final int slash = path.lastIndexOf('/');
                                    if (slash >= 0) {
                                        // filename
                                        current[5] = path.substring(slash + 1);
                                        // dir_name
                                        current[9] = path.substring(0, slash);
                                    } else {
                                        // filename
                                        current[5] = path;
                                        // dir_name
                                        current[9] = "";
                                    }
                                    // Make type values more like those on Linux
                                    final String type = (String) current[19];
                                    current[19] = type.equals("/") ? "d" : type.equals("") || type.equals("*") ? "f" : type.equals("@") ? "l" : type;
                            }
                            return true;
                        }

                        private int count(String s, char c) {
                            int n = 0;
                            for (int i = 0, len = s.length(); i < len; i++) {
                                if (s.charAt(i) == c) {
                                    ++n;
                                }
                            }
                            return n;
                        }

                        public void reset() {
                            throw new UnsupportedOperationException();
                        }

                        public void close() {
                            e.close();
                        }

                        private Object field(String field, String value) {
                            switch(field) {
                                case "block_count":
                                case "depth":
                                case "device":
                                case "gid":
                                case "uid":
                                case "hard":
                                    return Integer.valueOf(value);
                                case "inode":
                                case "size":
                                    return Long.valueOf(value);
                                case "access_time":
                                case "change_time":
                                case "mod_time":
                                    return new BigDecimal(value).multiply(THOUSAND).longValue();
                                default:
                                    return value;
                            }
                        }
                    };
                }
            };
        }

        public Statistic getStatistic() {
            return Statistics.of(1000d, ImmutableList.of(ImmutableBitSet.of(1)));
        }

        public Schema.TableType getJdbcTableType() {
            return Schema.TableType.TABLE;
        }

        public boolean isRolledUp(String column) {
            return false;
        }

        public boolean rolledUpColumnValidInsideAgg(String column, SqlCall call, SqlNode parent, CalciteConnectionConfig config) {
            return true;
        }
    };
}
Also used : SqlCall(org.apache.calcite.sql.SqlCall) CalciteConnectionConfig(org.apache.calcite.config.CalciteConnectionConfig) Schema(org.apache.calcite.schema.Schema) RelDataType(org.apache.calcite.rel.type.RelDataType) BigDecimal(java.math.BigDecimal) DataContext(org.apache.calcite.DataContext) Enumerator(org.apache.calcite.linq4j.Enumerator) RelDataTypeFactory(org.apache.calcite.rel.type.RelDataTypeFactory) AbstractEnumerable(org.apache.calcite.linq4j.AbstractEnumerable) ScannableTable(org.apache.calcite.schema.ScannableTable) SqlNode(org.apache.calcite.sql.SqlNode)

Example 3 with AbstractEnumerable

use of org.apache.calcite.linq4j.AbstractEnumerable in project calcite by apache.

the class StdinTableFunction method eval.

public static ScannableTable eval(boolean b) {
    return new ScannableTable() {

        public Enumerable<Object[]> scan(DataContext root) {
            final InputStream is = DataContext.Variable.STDIN.get(root);
            return new AbstractEnumerable<Object[]>() {

                final InputStreamReader in = new InputStreamReader(is, StandardCharsets.UTF_8);

                final BufferedReader br = new BufferedReader(in);

                public Enumerator<Object[]> enumerator() {
                    return new Enumerator<Object[]>() {

                        String line;

                        int i;

                        public Object[] current() {
                            if (line == null) {
                                throw new NoSuchElementException();
                            }
                            return new Object[] { i, line };
                        }

                        public boolean moveNext() {
                            try {
                                line = br.readLine();
                                ++i;
                                return line != null;
                            } catch (IOException e) {
                                throw new RuntimeException(e);
                            }
                        }

                        public void reset() {
                            throw new UnsupportedOperationException();
                        }

                        public void close() {
                            try {
                                br.close();
                            } catch (IOException e) {
                                throw new RuntimeException(e);
                            }
                        }
                    };
                }
            };
        }

        public RelDataType getRowType(RelDataTypeFactory typeFactory) {
            return typeFactory.builder().add("ordinal", SqlTypeName.INTEGER).add("line", SqlTypeName.VARCHAR).build();
        }

        public Statistic getStatistic() {
            return Statistics.of(1000d, ImmutableList.of(ImmutableBitSet.of(1)));
        }

        public Schema.TableType getJdbcTableType() {
            return Schema.TableType.TABLE;
        }

        public boolean isRolledUp(String column) {
            return false;
        }

        public boolean rolledUpColumnValidInsideAgg(String column, SqlCall call, SqlNode parent, CalciteConnectionConfig config) {
            return true;
        }
    };
}
Also used : InputStreamReader(java.io.InputStreamReader) InputStream(java.io.InputStream) SqlCall(org.apache.calcite.sql.SqlCall) CalciteConnectionConfig(org.apache.calcite.config.CalciteConnectionConfig) Schema(org.apache.calcite.schema.Schema) IOException(java.io.IOException) DataContext(org.apache.calcite.DataContext) Enumerator(org.apache.calcite.linq4j.Enumerator) AbstractEnumerable(org.apache.calcite.linq4j.AbstractEnumerable) BufferedReader(java.io.BufferedReader) RelDataTypeFactory(org.apache.calcite.rel.type.RelDataTypeFactory) ScannableTable(org.apache.calcite.schema.ScannableTable) NoSuchElementException(java.util.NoSuchElementException) SqlNode(org.apache.calcite.sql.SqlNode)

Example 4 with AbstractEnumerable

use of org.apache.calcite.linq4j.AbstractEnumerable in project calcite by apache.

the class MazeTable method scan.

public Enumerable<Object[]> scan(DataContext root) {
    final Random random = seed >= 0 ? new Random(seed) : new Random();
    final Maze maze = new Maze(width, height);
    final PrintWriter pw = Util.printWriter(System.out);
    maze.layout(random, pw);
    if (Maze.DEBUG) {
        maze.print(pw, true);
    }
    return new AbstractEnumerable<Object[]>() {

        public Enumerator<Object[]> enumerator() {
            final Set<Integer> solutionSet;
            if (solution) {
                solutionSet = maze.solve(0, 0);
            } else {
                solutionSet = null;
            }
            return Linq4j.transform(maze.enumerator(solutionSet), new Function1<String, Object[]>() {

                public Object[] apply(String s) {
                    return new Object[] { s };
                }
            });
        }
    };
}
Also used : Random(java.util.Random) AbstractEnumerable(org.apache.calcite.linq4j.AbstractEnumerable) PrintWriter(java.io.PrintWriter)

Example 5 with AbstractEnumerable

use of org.apache.calcite.linq4j.AbstractEnumerable in project calcite by apache.

the class CsvFilterableTable method scan.

public Enumerable<Object[]> scan(DataContext root, List<RexNode> filters) {
    final String[] filterValues = new String[fieldTypes.size()];
    for (final Iterator<RexNode> i = filters.iterator(); i.hasNext(); ) {
        final RexNode filter = i.next();
        if (addFilter(filter, filterValues)) {
            i.remove();
        }
    }
    final int[] fields = CsvEnumerator.identityList(fieldTypes.size());
    final AtomicBoolean cancelFlag = DataContext.Variable.CANCEL_FLAG.get(root);
    return new AbstractEnumerable<Object[]>() {

        public Enumerator<Object[]> enumerator() {
            return new CsvEnumerator<>(source, cancelFlag, false, filterValues, new CsvEnumerator.ArrayRowConverter(fieldTypes, fields));
        }
    };
}
Also used : AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) AbstractEnumerable(org.apache.calcite.linq4j.AbstractEnumerable) RexNode(org.apache.calcite.rex.RexNode)

Aggregations

AbstractEnumerable (org.apache.calcite.linq4j.AbstractEnumerable)12 RelDataTypeFactory (org.apache.calcite.rel.type.RelDataTypeFactory)4 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)3 DataContext (org.apache.calcite.DataContext)3 Enumerator (org.apache.calcite.linq4j.Enumerator)3 ScannableTable (org.apache.calcite.schema.ScannableTable)3 Schema (org.apache.calcite.schema.Schema)3 IOException (java.io.IOException)2 Map (java.util.Map)2 CalciteConnectionConfig (org.apache.calcite.config.CalciteConnectionConfig)2 Enumerable (org.apache.calcite.linq4j.Enumerable)2 RelDataType (org.apache.calcite.rel.type.RelDataType)2 RelProtoDataType (org.apache.calcite.rel.type.RelProtoDataType)2 SqlCall (org.apache.calcite.sql.SqlCall)2 SqlNode (org.apache.calcite.sql.SqlNode)2 SqlTypeName (org.apache.calcite.sql.type.SqlTypeName)2 ResultSet (com.datastax.driver.core.ResultSet)1 ImmutableMap (com.google.common.collect.ImmutableMap)1 MongoCollection (com.mongodb.client.MongoCollection)1 BufferedReader (java.io.BufferedReader)1