org.apache.calcite.sql.advise.SqlAdvisor Java Examples

The following examples show how to use org.apache.calcite.sql.advise.SqlAdvisor. 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: SQLResource.java    From dremio-oss with Apache License 2.0 6 votes vote down vote up
@POST
@Path("/analyze/validate")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public ValidationResponse validateSQL(AnalyzeRequest analyzeRequest) {

  final String sql = analyzeRequest.getSql();
  final List<String> context = analyzeRequest.getContext();

  // Setup dependencies and execute validation
  SQLAnalyzer SQLAnalyzer =
    SQLAnalyzerFactory.createSQLAnalyzer(
      securityContext.getUserPrincipal().getName(), sabotContext, context, false, projectOptionManager);

  List<SqlAdvisor.ValidateErrorInfo> validationErrors = SQLAnalyzer.validate(sql);

  // Build response object and return
  return buildValidationResponse(validationErrors);
}
 
Example #2
Source File: SQLResource.java    From dremio-oss with Apache License 2.0 6 votes vote down vote up
/**
 * Builds the response object for query validation.
 *
 * @param errorList  The list of query errors returned from the SqlAdvisor.
 *
 * @return The built ValidationResponse object or null if there are no available validation errors.
 */
protected ValidationResponse buildValidationResponse(List<SqlAdvisor.ValidateErrorInfo> errorList) {

  // Return empty response in REST request
  if (errorList == null || errorList.isEmpty()) {
    return null;
  }

  // Create and populate error response list
  List<QueryError> sqlErrors = new ArrayList<>();
  for (SqlAdvisor.ValidateErrorInfo error : errorList) {
    sqlErrors.add(
      new QueryError(error.getMessage(),
      new QueryError.Range(error.getStartLineNum(),
        error.getStartColumnNum(),
        error.getEndLineNum() + 1,
        error.getEndColumnNum() + 1)));
  }

  ValidationResponse response = new ValidationResponse(sqlErrors);
  return response;
}
 
Example #3
Source File: SqlAdvisorTest.java    From calcite with Apache License 2.0 6 votes vote down vote up
/**
 * Tests that a given SQL which may be invalid or incomplete simplifies
 * itself and yields the salesTables set of completion hints. This is an
 * integration test of {@link #assertHint} and {@link #assertSimplify}.
 *
 * @param sql             SQL statement
 * @param expectedResults Expected list of hints
 * @param expectedWord    Word that we expect to be replaced, or null if we
 *                        don't care
 */
protected void assertComplete(
    String sql,
    String expectedResults,
    String expectedWord,
    Map<String, String> replacements) {
  SqlAdvisor advisor = tester.getFactory().createAdvisor();

  SqlParserUtil.StringAndPos sap = SqlParserUtil.findPos(sql);
  final String[] replaced = {null};
  List<SqlMoniker> results =
      advisor.getCompletionHints(sap.sql, sap.cursor, replaced);
  Assertions.assertEquals(expectedResults, convertCompletionHints(results),
      () -> "Completion hints for " + sql);
  if (expectedWord != null) {
    Assertions.assertEquals(expectedWord, replaced[0], "replaced[0] for " + sql);
  } else {
    assertNotNull(replaced[0]);
  }
  assertReplacements(sql, replacements, advisor, replaced[0], results);
}
 
Example #4
Source File: SqlAdvisorTest.java    From calcite with Apache License 2.0 6 votes vote down vote up
private void assertReplacements(String sql, Map<String, String> replacements, SqlAdvisor advisor,
    String word, List<SqlMoniker> results) {
  if (replacements == null) {
    return;
  }
  Set<String> missingReplacemenets = new HashSet<>(replacements.keySet());
  for (SqlMoniker result : results) {
    String id = result.id();
    String expectedReplacement = replacements.get(id);
    if (expectedReplacement == null) {
      continue;
    }
    missingReplacemenets.remove(id);
    String actualReplacement = advisor.getReplacement(result, word);
    Assertions.assertEquals(expectedReplacement, actualReplacement,
        () -> sql + ", replacement of " + word + " with " + id);
  }
  if (missingReplacemenets.isEmpty()) {
    return;
  }
  fail("Sql " + sql + " did not produce replacement hints " + missingReplacemenets);

}
 
Example #5
Source File: TestSQLAnalyzer.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
@Test
public void testValidation() {
  List<SqlAdvisor.ValidateErrorInfo> validationErrors = sqlAnalyzer.validate("select * from");
  assertEquals(1, validationErrors.size());
  assertEquals(10, validationErrors.get(0).getStartColumnNum());
  assertEquals(13, validationErrors.get(0).getEndColumnNum());
}
 
Example #6
Source File: SqlTestFactory.java    From calcite with Apache License 2.0 5 votes vote down vote up
public SqlAdvisor createAdvisor() {
  SqlValidator validator = getValidator();
  if (validator instanceof SqlValidatorWithHints) {
    return new SqlAdvisor((SqlValidatorWithHints) validator, parserConfig.get());
  }
  throw new UnsupportedOperationException(
      "Validator should implement SqlValidatorWithHints, actual validator is " + validator);
}
 
Example #7
Source File: SqlAdvisorTest.java    From calcite with Apache License 2.0 5 votes vote down vote up
/**
 * Checks that a given SQL statement yields the expected set of completion
 * hints.
 *
 * @param sql             SQL statement
 * @param expectedResults Expected list of hints
 * @throws Exception on error
 */
protected void assertHint(
    String sql,
    String expectedResults) throws Exception {
  SqlAdvisor advisor = tester.getFactory().createAdvisor();

  SqlParserUtil.StringAndPos sap = SqlParserUtil.findPos(sql);

  List<SqlMoniker> results =
      advisor.getCompletionHints(
          sap.sql,
          sap.pos);
  Assertions.assertEquals(
      expectedResults, convertCompletionHints(results));
}
 
Example #8
Source File: SqlAdvisorTest.java    From calcite with Apache License 2.0 3 votes vote down vote up
/**
 * Tests that a given SQL statement simplifies to the salesTables result.
 *
 * @param sql      SQL statement to simplify. The SQL statement must contain
 *                 precisely one caret '^', which marks the location where
 *                 completion is to occur.
 * @param expected Expected result after simplification.
 */
protected void assertSimplify(String sql, String expected) {
  SqlAdvisor advisor = tester.getFactory().createAdvisor();

  SqlParserUtil.StringAndPos sap = SqlParserUtil.findPos(sql);
  String actual = advisor.simplifySql(sap.sql, sap.cursor);
  Assertions.assertEquals(expected, actual);
}
 
Example #9
Source File: SQLAnalyzer.java    From dremio-oss with Apache License 2.0 2 votes vote down vote up
/**
 * Pass the SqlValidatorWithHints implementation to Calcite's SqlAdvisor
 * for query completion hints.
 *
 * @param sql             The SQL being evaluated.
 * @param cursorPosition  The current cursor position in the editor.
 * @return List<SqlMoniker> that represents the query completion options for the SQL editor.
 */
public List<SqlMoniker> suggest(String sql, int cursorPosition) {
  SqlAdvisor sqlAdvisor = new SqlAdvisor(validator);
  String[] replaced = {null};
  return sqlAdvisor.getCompletionHints(sql, cursorPosition , replaced);
}
 
Example #10
Source File: SQLAnalyzer.java    From dremio-oss with Apache License 2.0 2 votes vote down vote up
/**
 * Pass the SqlValidatorWithHints implementation to Calcite's SqlAdvisor
 * for query validation.
 *
 * @param sql             The SQL being evaluated.
 * @return List<SqlAdvisor.ValidateErrorInfo> that represents parser or validation errors.
 */
public List<SqlAdvisor.ValidateErrorInfo> validate(String sql) {
  SqlAdvisor sqlAdvisor = new SqlAdvisor(validator);
  return sqlAdvisor.validate(sql);
}