Search in sources :

Example 1 with CalciteContextException

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);
}
Also used : SqlValidatorScope(org.apache.calcite.sql.validate.SqlValidatorScope) SqlSyntax(org.apache.calcite.sql.SqlSyntax) SqlCaseOperator(org.apache.calcite.sql.fun.SqlCaseOperator) CalciteContextException(org.apache.calcite.runtime.CalciteContextException) HazelcastReturnTypeInference.wrap(com.hazelcast.jet.sql.impl.validate.operators.typeinference.HazelcastReturnTypeInference.wrap) SqlOperandCountRanges(org.apache.calcite.sql.type.SqlOperandCountRanges) SqlValidatorScope(org.apache.calcite.sql.validate.SqlValidatorScope) HazelcastResources(com.hazelcast.jet.sql.impl.validate.HazelcastResources) Supplier(java.util.function.Supplier) RESOURCE(org.apache.calcite.util.Static.RESOURCE) ArrayList(java.util.ArrayList) SqlCall(org.apache.calcite.sql.SqlCall) SqlLiteral(org.apache.calcite.sql.SqlLiteral) SqlNode(org.apache.calcite.sql.SqlNode) Pair(org.apache.calcite.util.Pair) SqlValidator(org.apache.calcite.sql.validate.SqlValidator) SqlOperator(org.apache.calcite.sql.SqlOperator) SqlOperatorBinding(org.apache.calcite.sql.SqlOperatorBinding) RelDataType(org.apache.calcite.rel.type.RelDataType) SqlParserPos(org.apache.calcite.sql.parser.SqlParserPos) HazelcastSqlValidator(com.hazelcast.jet.sql.impl.validate.HazelcastSqlValidator) SqlKind(org.apache.calcite.sql.SqlKind) SqlWriter(org.apache.calcite.sql.SqlWriter) HazelcastTypeUtils(com.hazelcast.jet.sql.impl.validate.types.HazelcastTypeUtils) SqlTypeName(org.apache.calcite.sql.type.SqlTypeName) SqlCallBinding(org.apache.calcite.sql.SqlCallBinding) SqlTypeUtil(org.apache.calcite.sql.type.SqlTypeUtil) HazelcastSqlCase(com.hazelcast.jet.sql.impl.validate.operators.special.HazelcastSqlCase) Consumer(java.util.function.Consumer) SqlReturnTypeInference(org.apache.calcite.sql.type.SqlReturnTypeInference) List(java.util.List) SqlOperandCountRange(org.apache.calcite.sql.SqlOperandCountRange) SqlNodeList(org.apache.calcite.sql.SqlNodeList) CalciteContextException(org.apache.calcite.runtime.CalciteContextException) HazelcastSqlCase(com.hazelcast.jet.sql.impl.validate.operators.special.HazelcastSqlCase) ArrayList(java.util.ArrayList) SqlNodeList(org.apache.calcite.sql.SqlNodeList) HazelcastSqlValidator(com.hazelcast.jet.sql.impl.validate.HazelcastSqlValidator) RelDataType(org.apache.calcite.rel.type.RelDataType) SqlNode(org.apache.calcite.sql.SqlNode)

Example 2 with CalciteContextException

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);
    }
}
Also used : PlannerOp(herddb.model.planner.PlannerOp) Table(herddb.model.Table) RelOptTable(org.apache.calcite.plan.RelOptTable) ProjectableFilterableTable(org.apache.calcite.schema.ProjectableFilterableTable) ScannableTable(org.apache.calcite.schema.ScannableTable) AbstractTable(org.apache.calcite.schema.impl.AbstractTable) ModifiableTable(org.apache.calcite.schema.ModifiableTable) ValidationException(org.apache.calcite.tools.ValidationException) SqlParseException(org.apache.calcite.sql.parser.SqlParseException) ConstantExpression(herddb.sql.expressions.ConstantExpression) CompiledSQLExpression(herddb.sql.expressions.CompiledSQLExpression) LimitOp(herddb.model.planner.LimitOp) ValuesOp(herddb.model.planner.ValuesOp) StatementExecutionException(herddb.model.StatementExecutionException) RelConversionException(org.apache.calcite.tools.RelConversionException) SQLPlannedOperationStatement(herddb.model.commands.SQLPlannedOperationStatement) MetadataStorageManagerException(herddb.metadata.MetadataStorageManagerException) CalciteContextException(org.apache.calcite.runtime.CalciteContextException) ExecutionPlan(herddb.model.ExecutionPlan) GetStatement(herddb.model.commands.GetStatement) ScanStatement(herddb.model.commands.ScanStatement)

Example 3 with CalciteContextException

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);
}
Also used : CalciteContextException(org.apache.calcite.runtime.CalciteContextException) TimeString(org.apache.calcite.util.TimeString) HazelcastResources(com.hazelcast.jet.sql.impl.validate.HazelcastResources) Resources(org.apache.calcite.runtime.Resources) SqlValidatorException(org.apache.calcite.sql.validate.SqlValidatorException)

Example 4 with CalciteContextException

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;
}
Also used : CalciteContextException(org.apache.calcite.runtime.CalciteContextException) SqlCreateMapping(com.hazelcast.jet.sql.impl.parse.SqlCreateMapping) Mapping(com.hazelcast.sql.impl.schema.Mapping)

Example 5 with CalciteContextException

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);
}
Also used : CalciteContextException(org.apache.calcite.runtime.CalciteContextException) ArrayList(java.util.ArrayList) SqlTesterImpl(org.apache.calcite.sql.test.SqlTesterImpl) SqlIdentifier(org.apache.calcite.sql.SqlIdentifier) SqlNode(org.apache.calcite.sql.SqlNode) Test(org.junit.Test)

Aggregations

CalciteContextException (org.apache.calcite.runtime.CalciteContextException)10 SqlNode (org.apache.calcite.sql.SqlNode)4 SqlParseException (org.apache.calcite.sql.parser.SqlParseException)4 ArrayList (java.util.ArrayList)3 HazelcastResources (com.hazelcast.jet.sql.impl.validate.HazelcastResources)2 CalciteException (org.apache.calcite.runtime.CalciteException)2 SqlParserPos (org.apache.calcite.sql.parser.SqlParserPos)2 SqlCreateMapping (com.hazelcast.jet.sql.impl.parse.SqlCreateMapping)1 HazelcastSqlValidator (com.hazelcast.jet.sql.impl.validate.HazelcastSqlValidator)1 HazelcastSqlCase (com.hazelcast.jet.sql.impl.validate.operators.special.HazelcastSqlCase)1 HazelcastReturnTypeInference.wrap (com.hazelcast.jet.sql.impl.validate.operators.typeinference.HazelcastReturnTypeInference.wrap)1 HazelcastTypeUtils (com.hazelcast.jet.sql.impl.validate.types.HazelcastTypeUtils)1 Mapping (com.hazelcast.sql.impl.schema.Mapping)1 MetadataStorageManagerException (herddb.metadata.MetadataStorageManagerException)1 ExecutionPlan (herddb.model.ExecutionPlan)1 StatementExecutionException (herddb.model.StatementExecutionException)1 Table (herddb.model.Table)1 GetStatement (herddb.model.commands.GetStatement)1 SQLPlannedOperationStatement (herddb.model.commands.SQLPlannedOperationStatement)1 ScanStatement (herddb.model.commands.ScanStatement)1