Java Code Examples for org.apache.calcite.util.Util#printWriter()

The following examples show how to use org.apache.calcite.util.Util#printWriter() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: MazeTable.java    From calcite with Apache License 2.0 6 votes vote down vote up
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),
          s -> new Object[] {s});
    }
  };
}
 
Example 2
Source File: CalciteRemoteDriverTest.java    From calcite with Apache License 2.0 6 votes vote down vote up
/** Check that the "get" conversion table looks like Table B-5 in JDBC 4.1
 * specification */
@Test void testTableB6() {
  SqlType[] columns = {
      SqlType.TINYINT, SqlType.SMALLINT, SqlType.INTEGER, SqlType.BIGINT,
      SqlType.REAL, SqlType.FLOAT, SqlType.DOUBLE, SqlType.DECIMAL,
      SqlType.NUMERIC, SqlType.BIT, SqlType.BOOLEAN, SqlType.CHAR,
      SqlType.VARCHAR, SqlType.LONGVARCHAR, SqlType.BINARY, SqlType.VARBINARY,
      SqlType.LONGVARBINARY, SqlType.DATE, SqlType.TIME, SqlType.TIMESTAMP,
      SqlType.CLOB, SqlType.BLOB, SqlType.ARRAY, SqlType.REF,
      SqlType.DATALINK, SqlType.STRUCT, SqlType.JAVA_OBJECT, SqlType.ROWID,
      SqlType.NCHAR, SqlType.NVARCHAR, SqlType.LONGNVARCHAR, SqlType.NCLOB,
      SqlType.SQLXML
  };
  final PrintWriter out =
      CalciteSystemProperty.DEBUG.value()
          ? Util.printWriter(System.out)
          : new PrintWriter(new StringWriter());
  for (SqlType.Method row : SqlType.Method.values()) {
    out.print(pad(row.methodName));
    for (SqlType column : columns) {
      out.print(SqlType.canGet(row, column) ? "x " : ". ");
    }
    out.println();
  }
}
 
Example 3
Source File: SqlLineTest.java    From calcite with Apache License 2.0 6 votes vote down vote up
/**
 * Attempts to execute a simple script file with the -f option to SqlLine.
 * Tests for presence of an expected pattern in the output (stdout or stderr).
 *
 * @param scriptText Script text
 * @param flag Command flag (--run or -f)
 * @param statusMatcher Checks whether status is as expected
 * @param outputMatcher Checks whether output is as expected
 * @throws Exception on command execution error
 */
private void checkScriptFile(String scriptText, boolean flag,
    Matcher<SqlLine.Status> statusMatcher,
    Matcher<String> outputMatcher) throws Throwable {
  // Put the script content in a temp file
  File scriptFile = File.createTempFile("foo", "temp");
  scriptFile.deleteOnExit();
  try (PrintWriter w = Util.printWriter(scriptFile)) {
    w.print(scriptText);
  }

  Pair<SqlLine.Status, String> pair = runScript(scriptFile, flag);

  // Check output before status. It gives a better clue what went wrong.
  assertThat(pair.right, outputMatcher);
  assertThat(pair.left, statusMatcher);
  final boolean delete = scriptFile.delete();
  assertThat(delete, is(true));
}
 
Example 4
Source File: DiffRepository.java    From flink with Apache License 2.0 5 votes vote down vote up
/**
 * Flushes the reference document to the file system.
 */
private void flushDoc() {
	try {
		boolean b = logFile.getParentFile().mkdirs();
		Util.discard(b);
		try (Writer w = Util.printWriter(logFile)) {
			write(doc, w, indent);
		}
	} catch (IOException e) {
		throw new RuntimeException("error while writing test reference log '"
			+ logFile + "'", e);
	}
}
 
Example 5
Source File: DiffRepository.java    From flink with Apache License 2.0 5 votes vote down vote up
/**
 * Flushes the reference document to the file system.
 */
private void flushDoc() {
	try {
		boolean b = logFile.getParentFile().mkdirs();
		Util.discard(b);
		try (Writer w = Util.printWriter(logFile)) {
			write(doc, w, indent);
		}
	} catch (IOException e) {
		throw new RuntimeException("error while writing test reference log '"
			+ logFile + "'", e);
	}
}
 
Example 6
Source File: DiffRepository.java    From calcite with Apache License 2.0 5 votes vote down vote up
/**
 * Flushes the reference document to the file system.
 */
private void flushDoc() {
  try {
    boolean b = logFile.getParentFile().mkdirs();
    Util.discard(b);
    try (Writer w = Util.printWriter(logFile)) {
      write(doc, w, indent);
    }
  } catch (IOException e) {
    throw new RuntimeException("error while writing test reference log '"
        + logFile + "'", e);
  }
}
 
Example 7
Source File: ConcurrentTestCommandScript.java    From calcite with Apache License 2.0 5 votes vote down vote up
public int run(String[] args) {
  try (PrintWriter w = Util.printWriter(System.out)) {
    if (!parseCommand(args)) {
      usage();
      return 2;
    }

    Class z = Class.forName(driver); // load driver
    Properties jdbcProps = new Properties();
    if (user != null) {
      jdbcProps.setProperty("user", user);
    }
    if (password != null) {
      jdbcProps.setProperty("password", password);
    }

    for (String file : files) {
      ConcurrentTestCommandScript script =
          new ConcurrentTestCommandScript();
      try {
        script.setQuiet(quiet);
        script.setVerbose(verbose);
        script.setDebug(debug);
        script.prepare(file, bindings);
        script.setDataSource(server, jdbcProps);
        script.execute();
      } finally {
        if (!quiet) {
          script.printResults(w);
        }
      }
    }
  } catch (Exception e) {
    System.err.println(e.getMessage());
    return 1;
  }
  return 0;
}
 
Example 8
Source File: CsvTest.java    From calcite with Apache License 2.0 4 votes vote down vote up
@Disabled("CALCITE-1894: there's a bug in the test code, so it does not test what it should")
@Test @Timeout(10) public void testCsvStream() throws Exception {
  final File file = File.createTempFile("stream", "csv");
  final String model = "{\n"
      + "  version: '1.0',\n"
      + "  defaultSchema: 'STREAM',\n"
      + "  schemas: [\n"
      + "    {\n"
      + "      name: 'SS',\n"
      + "      tables: [\n"
      + "        {\n"
      + "          name: 'DEPTS',\n"
      + "          type: 'custom',\n"
      + "          factory: '" + CsvStreamTableFactory.class.getName()
      + "',\n"
      + "          stream: {\n"
      + "            stream: true\n"
      + "          },\n"
      + "          operand: {\n"
      + "            file: " + escapeString(file.getAbsolutePath()) + ",\n"
      + "            flavor: \"scannable\"\n"
      + "          }\n"
      + "        }\n"
      + "      ]\n"
      + "    }\n"
      + "  ]\n"
      + "}\n";
  final String[] strings = {
      "DEPTNO:int,NAME:string",
      "10,\"Sales\"",
      "20,\"Marketing\"",
      "30,\"Engineering\""
  };

  try (Connection connection =
           DriverManager.getConnection("jdbc:calcite:model=inline:" + model);
       PrintWriter pw = Util.printWriter(file);
       Worker<Void> worker = new Worker<>()) {
    final Thread thread = new Thread(worker);
    thread.start();

    // Add some rows so that the table can deduce its row type.
    final Iterator<String> lines = Arrays.asList(strings).iterator();
    pw.println(lines.next()); // header
    pw.flush();
    worker.queue.put(writeLine(pw, lines.next())); // first row
    worker.queue.put(writeLine(pw, lines.next())); // second row
    final CalciteConnection calciteConnection =
        connection.unwrap(CalciteConnection.class);
    final String sql = "select stream * from \"SS\".\"DEPTS\"";
    final PreparedStatement statement =
        calciteConnection.prepareStatement(sql);
    final ResultSet resultSet = statement.executeQuery();
    int count = 0;
    try {
      while (resultSet.next()) {
        ++count;
        if (lines.hasNext()) {
          worker.queue.put(sleep(10));
          worker.queue.put(writeLine(pw, lines.next()));
        } else {
          worker.queue.put(cancel(statement));
        }
      }
      fail("expected exception, got end of data");
    } catch (SQLException e) {
      assertThat(e.getMessage(), is("Statement canceled"));
    }
    assertThat(count, anyOf(is(strings.length - 2), is(strings.length - 1)));
    assertThat(worker.e, nullValue());
    assertThat(worker.v, nullValue());
  } finally {
    Util.discard(file.delete());
  }
}
 
Example 9
Source File: DocumentationTest.java    From calcite with Apache License 2.0 4 votes vote down vote up
/** Generates a copy of {@code reference.md} with the current set of key
 * words. Fails if the copy is different from the original. */
@Test void testGenerateKeyWords() throws IOException {
  final FileFixture f = new FileFixture();
  f.outFile.getParentFile().mkdirs();
  try (BufferedReader r = Util.reader(f.inFile);
       FileOutputStream fos = new FileOutputStream(f.outFile);
       PrintWriter w = Util.printWriter(f.outFile)) {
    String line;
    int stage = 0;
    while ((line = r.readLine()) != null) {
      if (line.equals("{% comment %} end {% endcomment %}")) {
        ++stage;
      }
      if (stage != 1) {
        w.println(line);
      }
      if (line.equals("{% comment %} start {% endcomment %}")) {
        ++stage;
        SqlAbstractParserImpl.Metadata metadata =
            new SqlParserTest().getSqlParser("").getMetadata();
        int z = 0;
        for (String s : metadata.getTokens()) {
          if (z++ > 0) {
            w.println(",");
          }
          if (metadata.isKeyword(s)) {
            w.print(metadata.isReservedWord(s) ? ("**" + s + "**") : s);
          }
        }
        w.println(".");
      }
    }
    w.flush();
    fos.flush();
    fos.getFD().sync();
  }
  String diff = DiffTestCase.diff(f.outFile, f.inFile);
  if (!diff.isEmpty()) {
    throw new AssertionError("Mismatch between " + f.outFile
        + " and " + f.inFile + ":\n"
        + diff);
  }
}