use of org.apache.calcite.runtime.CalciteContextException in project hazelcast by hazelcast.
the class HazelcastCaseOperator method checkOperandTypes.
@Override
@SuppressWarnings("checkstyle:MethodLength")
public boolean checkOperandTypes(SqlCallBinding callBinding, boolean throwOnFailure) {
HazelcastSqlValidator validator = (HazelcastSqlValidator) callBinding.getValidator();
HazelcastSqlCase sqlCall = (HazelcastSqlCase) callBinding.getCall();
// at this point `CASE x WHEN y ...` is already converted to `CASE WHEN x=y ...`
assert sqlCall.getValueOperand() == null;
SqlNodeList whenList = sqlCall.getWhenOperands();
SqlNodeList thenList = sqlCall.getThenOperands();
SqlNode elseOperand = sqlCall.getElseOperand();
assert whenList.size() > 0 : "no WHEN clause";
assert whenList.size() == thenList.size();
SqlValidatorScope scope = callBinding.getScope();
if (!typeCheckWhen(scope, validator, whenList)) {
if (throwOnFailure) {
throw callBinding.newError(RESOURCE.expectedBoolean());
}
return false;
}
List<RelDataType> argTypes = new ArrayList<>(thenList.size() + 1);
for (SqlNode node : thenList) {
argTypes.add(validator.deriveType(scope, node));
}
argTypes.add(validator.deriveType(scope, elseOperand));
// noinspection OptionalGetWithoutIsPresent
RelDataType caseReturnType = argTypes.stream().reduce(HazelcastTypeUtils::withHigherPrecedence).get();
Supplier<CalciteContextException> exceptionSupplier = () -> validator.newValidationError(sqlCall, HazelcastResources.RESOURCES.cannotInferCaseResult(argTypes.toString(), "CASE"));
for (int i = 0; i < thenList.size(); i++) {
int finalI = i;
if (!coerceItem(validator, scope, thenList.get(i), caseReturnType, sqlNode -> thenList.getList().set(finalI, sqlNode), throwOnFailure, exceptionSupplier)) {
return false;
}
}
return coerceItem(validator, scope, elseOperand, caseReturnType, sqlNode -> sqlCall.setOperand(ELSE_BRANCH_OPERAND_INDEX, sqlNode), throwOnFailure, exceptionSupplier);
}
use of org.apache.calcite.runtime.CalciteContextException in project herddb by diennea.
the class CalcitePlanner method translate.
@Override
public TranslatedQuery translate(String defaultTableSpace, String query, List<Object> parameters, boolean scan, boolean allowCache, boolean returnValues, int maxRows) throws StatementExecutionException {
query = SQLPlanner.rewriteExecuteSyntax(query);
if (query.startsWith("EXECUTE") || query.startsWith("CREATE") || query.startsWith("DROP") || query.startsWith("ALTER") || query.startsWith("TRUNCATE")) {
return fallback.translate(defaultTableSpace, query, parameters, scan, allowCache, returnValues, maxRows);
}
if (parameters == null) {
parameters = Collections.emptyList();
}
String cacheKey = "scan:" + scan + ",defaultTableSpace:" + defaultTableSpace + ",query:" + query + ",returnValues:" + returnValues + ",maxRows:" + maxRows;
if (allowCache) {
ExecutionPlan cached = cache.get(cacheKey);
if (cached != null) {
return new TranslatedQuery(cached, new SQLStatementEvaluationContext(query, parameters));
}
}
if (!isCachable(query)) {
allowCache = false;
}
try {
if (query.startsWith("EXPLAIN ")) {
query = query.substring("EXPLAIN ".length());
PlannerResult plan = runPlanner(defaultTableSpace, query);
PlannerOp finalPlan = convertRelNode(plan.topNode, plan.originalRowType, returnValues).optimize();
ValuesOp values = new ValuesOp(manager.getNodeId(), new String[] { "name", "value" }, new Column[] { column("name", ColumnTypes.STRING), column("value", ColumnTypes.STRING) }, java.util.Arrays.asList(java.util.Arrays.asList(new ConstantExpression("query"), new ConstantExpression(query)), java.util.Arrays.asList(new ConstantExpression("logicalplan"), new ConstantExpression(RelOptUtil.dumpPlan("", plan.logicalPlan, SqlExplainFormat.TEXT, SqlExplainLevel.ALL_ATTRIBUTES))), java.util.Arrays.asList(new ConstantExpression("plan"), new ConstantExpression(RelOptUtil.dumpPlan("", plan.topNode, SqlExplainFormat.TEXT, SqlExplainLevel.ALL_ATTRIBUTES))), java.util.Arrays.asList(new ConstantExpression("finalplan"), new ConstantExpression(finalPlan + ""))));
ExecutionPlan executionPlan = ExecutionPlan.simple(new SQLPlannedOperationStatement(values));
return new TranslatedQuery(executionPlan, new SQLStatementEvaluationContext(query, parameters));
}
PlannerResult plan = runPlanner(defaultTableSpace, query);
SQLPlannedOperationStatement sqlPlannedOperationStatement = new SQLPlannedOperationStatement(convertRelNode(plan.topNode, plan.originalRowType, returnValues).optimize());
if (LOG.isLoggable(Level.FINE)) {
LOG.log(Level.FINE, "Query: {0} --HerdDB Plan {1}", new Object[] { query, sqlPlannedOperationStatement.getRootOp() });
}
if (!scan) {
ScanStatement scanStatement = sqlPlannedOperationStatement.unwrap(ScanStatement.class);
if (scanStatement != null) {
Table tableDef = scanStatement.getTableDef();
CompiledSQLExpression where = scanStatement.getPredicate().unwrap(CompiledSQLExpression.class);
SQLRecordKeyFunction keyFunction = findIndexAccess(where, tableDef.getPrimaryKey(), tableDef, "=", tableDef);
if (keyFunction == null || !keyFunction.isFullPrimaryKey()) {
throw new StatementExecutionException("unsupported GET not on PK, bad where clause: " + query);
}
GetStatement get = new GetStatement(scanStatement.getTableSpace(), scanStatement.getTable(), keyFunction, scanStatement.getPredicate(), true);
ExecutionPlan executionPlan = ExecutionPlan.simple(get);
if (allowCache) {
cache.put(cacheKey, executionPlan);
}
return new TranslatedQuery(executionPlan, new SQLStatementEvaluationContext(query, parameters));
}
}
if (maxRows > 0) {
PlannerOp op = new LimitOp(sqlPlannedOperationStatement.getRootOp(), new ConstantExpression(maxRows), new ConstantExpression(0)).optimize();
sqlPlannedOperationStatement = new SQLPlannedOperationStatement(op);
}
ExecutionPlan executionPlan = ExecutionPlan.simple(sqlPlannedOperationStatement);
if (allowCache) {
cache.put(cacheKey, executionPlan);
}
return new TranslatedQuery(executionPlan, new SQLStatementEvaluationContext(query, parameters));
} catch (CalciteContextException ex) {
LOG.log(Level.INFO, "Error while parsing '" + ex.getOriginalStatement() + "'", ex);
// TODO can this be done better ?
throw new StatementExecutionException(ex.getMessage());
} catch (RelConversionException | ValidationException | SqlParseException ex) {
LOG.log(Level.INFO, "Error while parsing '" + query + "'", ex);
// TODO can this be done better ?
throw new StatementExecutionException(ex.getMessage().replace("org.apache.calcite.runtime.CalciteContextException: ", ""));
} catch (MetadataStorageManagerException ex) {
LOG.log(Level.INFO, "Error while parsing '" + query + "'", ex);
throw new StatementExecutionException(ex);
}
}
use of org.apache.calcite.runtime.CalciteContextException in project hazelcast by hazelcast.
the class HazelcastSqlToRelConverter method literalConversionException.
private static QueryException literalConversionException(SqlValidator validator, SqlCall call, Literal literal, QueryDataType toType, Exception e) {
String literalValue = literal.getStringValue();
if (SqlTypeName.CHAR_TYPES.contains(literal.getTypeName())) {
literalValue = "'" + literalValue + "'";
}
Resources.ExInst<SqlValidatorException> contextError = HazelcastResources.RESOURCES.cannotCastLiteralValue(literalValue, toType.getTypeFamily().getPublicType().toString(), e.getMessage());
CalciteContextException calciteContextError = validator.newValidationError(call, contextError);
throw QueryException.error(SqlErrorCode.PARSING, calciteContextError.getMessage(), e);
}
use of org.apache.calcite.runtime.CalciteContextException in project hazelcast by hazelcast.
the class HazelcastSqlValidator method newValidationError.
@Override
public CalciteContextException newValidationError(SqlNode node, Resources.ExInst<SqlValidatorException> e) {
assert node != null;
CalciteContextException exception = SqlUtil.newContextException(node.getParserPosition(), e);
if (OBJECT_NOT_FOUND.equals(ResourceUtil.key(e)) || OBJECT_NOT_FOUND_WITHIN.equals(ResourceUtil.key(e))) {
Object[] arguments = ResourceUtil.args(e);
String identifier = (arguments != null && arguments.length > 0) ? String.valueOf(arguments[0]) : null;
Mapping mapping = identifier != null ? iMapResolver.resolve(identifier) : null;
String sql = mapping != null ? SqlCreateMapping.unparse(mapping) : null;
String message = sql != null ? ValidatorResource.imapNotMapped(e.str(), identifier, sql) : e.str();
throw QueryException.error(SqlErrorCode.OBJECT_NOT_FOUND, message, exception, sql);
}
return exception;
}
use of org.apache.calcite.runtime.CalciteContextException in project calcite by apache.
the class SqlValidatorUtilTest method testCheckingDuplicatesWithCompoundIdentifiers.
@SuppressWarnings("resource")
@Test
public void testCheckingDuplicatesWithCompoundIdentifiers() {
final List<SqlNode> newList = new ArrayList<>(2);
newList.add(new SqlIdentifier(Arrays.asList("f0", "c0"), SqlParserPos.ZERO));
newList.add(new SqlIdentifier(Arrays.asList("f0", "c0"), SqlParserPos.ZERO));
final SqlTesterImpl tester = new SqlTesterImpl(DefaultSqlTestFactory.INSTANCE);
final SqlValidatorImpl validator = (SqlValidatorImpl) tester.getValidator();
try {
SqlValidatorUtil.checkIdentifierListForDuplicates(newList, validator.getValidationErrorFunction());
fail("expected exception");
} catch (CalciteContextException e) {
// ok
}
// should not throw
newList.set(1, new SqlIdentifier(Arrays.asList("f0", "c1"), SqlParserPos.ZERO));
SqlValidatorUtil.checkIdentifierListForDuplicates(newList, null);
}
Aggregations