Search in sources :

Example 21 with DataContext

use of org.apache.calcite.DataContext in project calcite by apache.

the class StdinTableFunction method eval.

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

        @Override
        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);

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

                        @Nullable
                        String line;

                        int i;

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

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

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

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

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

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

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

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

        @Override
        public boolean rolledUpColumnValidInsideAgg(String column, SqlCall call, @Nullable SqlNode parent, @Nullable 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) Nullable(org.checkerframework.checker.nullness.qual.Nullable) SqlNode(org.apache.calcite.sql.SqlNode)

Example 22 with DataContext

use of org.apache.calcite.DataContext 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() {

        @Override
        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);
        }

        @Override
        public Enumerable<@Nullable Object[]> scan(DataContext root) {
            JavaTypeFactory typeFactory = root.getTypeFactory();
            final RelDataType rowType = getRowType(typeFactory);
            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<@Nullable Object[]>() {

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

                        @Nullable
                        Object @Nullable [] current;

                        @Override
                        public Object[] current() {
                            return requireNonNull(current, "current");
                        }

                        @Override
                        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 (".".equals(path)) {
                                        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] = "/".equals(type) ? "d" : "".equals(type) || "*".equals(type) ? "f" : "@".equals(type) ? "l" : type;
                                    break;
                                default:
                                    break;
                            }
                            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;
                        }

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

                        @Override
                        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;
                            }
                        }
                    };
                }
            };
        }

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

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

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

        @Override
        public boolean rolledUpColumnValidInsideAgg(String column, SqlCall call, @Nullable SqlNode parent, @Nullable 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) JavaTypeFactory(org.apache.calcite.adapter.java.JavaTypeFactory) AbstractEnumerable(org.apache.calcite.linq4j.AbstractEnumerable) ScannableTable(org.apache.calcite.schema.ScannableTable) Nullable(org.checkerframework.checker.nullness.qual.Nullable) SqlNode(org.apache.calcite.sql.SqlNode)

Example 23 with DataContext

use of org.apache.calcite.DataContext in project druid by apache.

the class SystemSchemaTest method testServerSegmentsTable.

@Test
public void testServerSegmentsTable() {
    SystemSchema.ServerSegmentsTable serverSegmentsTable = EasyMock.createMockBuilder(SystemSchema.ServerSegmentsTable.class).withConstructor(serverView, authMapper).createMock();
    EasyMock.replay(serverSegmentsTable);
    EasyMock.expect(serverView.getDruidServers()).andReturn(immutableDruidServers).once();
    EasyMock.replay(serverView);
    DataContext dataContext = createDataContext(Users.SUPER);
    // server_segments table is the join of servers and segments table
    // it will have 5 rows as follows
    // localhost:0000 |  test1_2010-01-01T00:00:00.000Z_2011-01-01T00:00:00.000Z_version1(segment1)
    // localhost:0000 |  test2_2011-01-01T00:00:00.000Z_2012-01-01T00:00:00.000Z_version2(segment2)
    // server2:1234   |  test3_2012-01-01T00:00:00.000Z_2013-01-01T00:00:00.000Z_version3(segment3)
    // server2:1234   |  test4_2017-01-01T00:00:00.000Z_2018-01-01T00:00:00.000Z_version4(segment4)
    // server2:1234   |  test5_2017-01-01T00:00:00.000Z_2018-01-01T00:00:00.000Z_version5(segment5)
    final List<Object[]> rows = serverSegmentsTable.scan(dataContext).toList();
    Assert.assertEquals(5, rows.size());
    Object[] row0 = rows.get(0);
    Assert.assertEquals("localhost:0000", row0[0]);
    Assert.assertEquals("test1_2010-01-01T00:00:00.000Z_2011-01-01T00:00:00.000Z_version1", row0[1].toString());
    Object[] row1 = rows.get(1);
    Assert.assertEquals("localhost:0000", row1[0]);
    Assert.assertEquals("test2_2011-01-01T00:00:00.000Z_2012-01-01T00:00:00.000Z_version2", row1[1].toString());
    Object[] row2 = rows.get(2);
    Assert.assertEquals("server2:1234", row2[0]);
    Assert.assertEquals("test3_2012-01-01T00:00:00.000Z_2013-01-01T00:00:00.000Z_version3_2", row2[1].toString());
    Object[] row3 = rows.get(3);
    Assert.assertEquals("server2:1234", row3[0]);
    Assert.assertEquals("test4_2014-01-01T00:00:00.000Z_2015-01-01T00:00:00.000Z_version4", row3[1].toString());
    Object[] row4 = rows.get(4);
    Assert.assertEquals("server2:1234", row4[0]);
    Assert.assertEquals("test5_2015-01-01T00:00:00.000Z_2016-01-01T00:00:00.000Z_version5", row4[1].toString());
    // Verify value types.
    verifyTypes(rows, SystemSchema.SERVER_SEGMENTS_SIGNATURE);
}
Also used : DataContext(org.apache.calcite.DataContext) Test(org.junit.Test)

Example 24 with DataContext

use of org.apache.calcite.DataContext in project druid by apache.

the class SystemSchemaTest method testTasksTable.

@Test
public void testTasksTable() throws Exception {
    SystemSchema.TasksTable tasksTable = EasyMock.createMockBuilder(SystemSchema.TasksTable.class).withConstructor(client, mapper, authMapper).createMock();
    EasyMock.replay(tasksTable);
    EasyMock.expect(client.makeRequest(HttpMethod.GET, "/druid/indexer/v1/tasks")).andReturn(request).anyTimes();
    HttpResponse httpResp = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
    InputStreamFullResponseHolder responseHolder = new InputStreamFullResponseHolder(httpResp);
    EasyMock.expect(client.go(EasyMock.eq(request), EasyMock.anyObject(InputStreamFullResponseHandler.class))).andReturn(responseHolder).once();
    EasyMock.expect(request.getUrl()).andReturn(new URL("http://test-host:1234/druid/indexer/v1/tasks")).anyTimes();
    String json = "[{\n" + "\t\"id\": \"index_wikipedia_2018-09-20T22:33:44.911Z\",\n" + "\t\"groupId\": \"group_index_wikipedia_2018-09-20T22:33:44.911Z\",\n" + "\t\"type\": \"index\",\n" + "\t\"createdTime\": \"2018-09-20T22:33:44.922Z\",\n" + "\t\"queueInsertionTime\": \"1970-01-01T00:00:00.000Z\",\n" + "\t\"statusCode\": \"FAILED\",\n" + "\t\"runnerStatusCode\": \"NONE\",\n" + "\t\"duration\": -1,\n" + "\t\"location\": {\n" + "\t\t\"host\": \"testHost\",\n" + "\t\t\"port\": 1234,\n" + "\t\t\"tlsPort\": -1\n" + "\t},\n" + "\t\"dataSource\": \"wikipedia\",\n" + "\t\"errorMsg\": null\n" + "}, {\n" + "\t\"id\": \"index_wikipedia_2018-09-21T18:38:47.773Z\",\n" + "\t\"groupId\": \"group_index_wikipedia_2018-09-21T18:38:47.773Z\",\n" + "\t\"type\": \"index\",\n" + "\t\"createdTime\": \"2018-09-21T18:38:47.873Z\",\n" + "\t\"queueInsertionTime\": \"2018-09-21T18:38:47.910Z\",\n" + "\t\"statusCode\": \"RUNNING\",\n" + "\t\"runnerStatusCode\": \"RUNNING\",\n" + "\t\"duration\": null,\n" + "\t\"location\": {\n" + "\t\t\"host\": \"192.168.1.6\",\n" + "\t\t\"port\": 8100,\n" + "\t\t\"tlsPort\": -1\n" + "\t},\n" + "\t\"dataSource\": \"wikipedia\",\n" + "\t\"errorMsg\": null\n" + "}]";
    byte[] bytesToWrite = json.getBytes(StandardCharsets.UTF_8);
    responseHolder.addChunk(bytesToWrite);
    responseHolder.done();
    EasyMock.replay(client, request, responseHandler);
    DataContext dataContext = createDataContext(Users.SUPER);
    final List<Object[]> rows = tasksTable.scan(dataContext).toList();
    Object[] row0 = rows.get(0);
    Assert.assertEquals("index_wikipedia_2018-09-20T22:33:44.911Z", row0[0].toString());
    Assert.assertEquals("group_index_wikipedia_2018-09-20T22:33:44.911Z", row0[1].toString());
    Assert.assertEquals("index", row0[2].toString());
    Assert.assertEquals("wikipedia", row0[3].toString());
    Assert.assertEquals("2018-09-20T22:33:44.922Z", row0[4].toString());
    Assert.assertEquals("1970-01-01T00:00:00.000Z", row0[5].toString());
    Assert.assertEquals("FAILED", row0[6].toString());
    Assert.assertEquals("NONE", row0[7].toString());
    Assert.assertEquals(-1L, row0[8]);
    Assert.assertEquals("testHost:1234", row0[9]);
    Assert.assertEquals("testHost", row0[10]);
    Assert.assertEquals(1234L, row0[11]);
    Assert.assertEquals(-1L, row0[12]);
    Assert.assertEquals(null, row0[13]);
    Object[] row1 = rows.get(1);
    Assert.assertEquals("index_wikipedia_2018-09-21T18:38:47.773Z", row1[0].toString());
    Assert.assertEquals("group_index_wikipedia_2018-09-21T18:38:47.773Z", row1[1].toString());
    Assert.assertEquals("index", row1[2].toString());
    Assert.assertEquals("wikipedia", row1[3].toString());
    Assert.assertEquals("2018-09-21T18:38:47.873Z", row1[4].toString());
    Assert.assertEquals("2018-09-21T18:38:47.910Z", row1[5].toString());
    Assert.assertEquals("RUNNING", row1[6].toString());
    Assert.assertEquals("RUNNING", row1[7].toString());
    Assert.assertEquals(0L, row1[8]);
    Assert.assertEquals("192.168.1.6:8100", row1[9]);
    Assert.assertEquals("192.168.1.6", row1[10]);
    Assert.assertEquals(8100L, row1[11]);
    Assert.assertEquals(-1L, row1[12]);
    Assert.assertEquals(null, row1[13]);
    // Verify value types.
    verifyTypes(rows, SystemSchema.TASKS_SIGNATURE);
}
Also used : DataContext(org.apache.calcite.DataContext) InputStreamFullResponseHolder(org.apache.druid.java.util.http.client.response.InputStreamFullResponseHolder) DefaultHttpResponse(org.jboss.netty.handler.codec.http.DefaultHttpResponse) DefaultHttpResponse(org.jboss.netty.handler.codec.http.DefaultHttpResponse) HttpResponse(org.jboss.netty.handler.codec.http.HttpResponse) URL(java.net.URL) Test(org.junit.Test)

Example 25 with DataContext

use of org.apache.calcite.DataContext in project plc4x by apache.

the class Plc4xBaseTable method scan.

/**
 * if tableCutoff is positive, then the row gets limited to that.
 */
public Enumerable<Object[]> scan(DataContext root) {
    return new AbstractEnumerable<Object[]>() {

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

                private final AtomicLong counter = new AtomicLong(0);

                @Override
                public Object[] current() {
                    List<Object> objects = new ArrayList<>(Arrays.asList(new Timestamp(current.timestamp.toEpochMilli()), current.source));
                    List<Object> objects2 = names.stream().map(name -> current.values.get(name)).collect(Collectors.toList());
                    objects.addAll(objects2);
                    return objects.toArray();
                }

                @Override
                public boolean moveNext() {
                    try {
                        current = queue.take();
                        // If stream, simply return
                        if (tableCutoff <= 0L) {
                            return true;
                        }
                        // If table, return if below cutoff
                        return counter.getAndIncrement() < tableCutoff;
                    } catch (InterruptedException e) {
                        Thread.currentThread().interrupt();
                    }
                    return false;
                }

                @Override
                public void reset() {
                    counter.set(0);
                }

                @Override
                public void close() {
                // Unimplemented
                }
            };
        }
    };
}
Also used : ImmutableBitSet(org.apache.calcite.util.ImmutableBitSet) RelDataType(org.apache.calcite.rel.type.RelDataType) RelDataTypeFactory(org.apache.calcite.rel.type.RelDataTypeFactory) Arrays(java.util.Arrays) Logger(org.slf4j.Logger) java.util.concurrent(java.util.concurrent) Timestamp(java.sql.Timestamp) LoggerFactory(org.slf4j.LoggerFactory) DataContext(org.apache.calcite.DataContext) Enumerable(org.apache.calcite.linq4j.Enumerable) Supplier(java.util.function.Supplier) Collectors(java.util.stream.Collectors) AbstractTable(org.apache.calcite.schema.impl.AbstractTable) ArrayList(java.util.ArrayList) AtomicLong(java.util.concurrent.atomic.AtomicLong) List(java.util.List) PlcRuntimeException(org.apache.plc4x.java.api.exceptions.PlcRuntimeException) Stream(java.util.stream.Stream) Enumerator(org.apache.calcite.linq4j.Enumerator) AbstractEnumerable(org.apache.calcite.linq4j.AbstractEnumerable) org.apache.calcite.rel(org.apache.calcite.rel) Collections(java.util.Collections) Statistic(org.apache.calcite.schema.Statistic) JobConfiguration(org.apache.plc4x.java.scraper.config.JobConfiguration) AtomicLong(java.util.concurrent.atomic.AtomicLong) Enumerator(org.apache.calcite.linq4j.Enumerator) AbstractEnumerable(org.apache.calcite.linq4j.AbstractEnumerable) ArrayList(java.util.ArrayList) Timestamp(java.sql.Timestamp)

Aggregations

DataContext (org.apache.calcite.DataContext)45 Test (org.junit.Test)13 ArrayList (java.util.ArrayList)10 RexNode (org.apache.calcite.rex.RexNode)8 Nullable (org.checkerframework.checker.nullness.qual.Nullable)8 HashMap (java.util.HashMap)7 RelDataType (org.apache.calcite.rel.type.RelDataType)7 RelDataTypeFactory (org.apache.calcite.rel.type.RelDataTypeFactory)7 Values (org.apache.storm.tuple.Values)7 Context (org.apache.calcite.interpreter.Context)6 StormContext (org.apache.calcite.interpreter.StormContext)6 Enumerable (org.apache.calcite.linq4j.Enumerable)5 ScannableTable (org.apache.calcite.schema.ScannableTable)5 URL (java.net.URL)4 JavaTypeFactory (org.apache.calcite.adapter.java.JavaTypeFactory)4 TypedValue (org.apache.calcite.avatica.remote.TypedValue)4 Enumerator (org.apache.calcite.linq4j.Enumerator)4 RexBuilder (org.apache.calcite.rex.RexBuilder)4 IOException (java.io.IOException)3 SQLException (java.sql.SQLException)3