Search in sources :

Example 6 with CalciteContextException

use of org.apache.calcite.runtime.CalciteContextException in project calcite by apache.

the class SqlAdvisor method getQualifiedName.

/**
 * Gets the fully qualified name for a {@link SqlIdentifier} at a given
 * position of a sql statement.
 *
 * @param sql    A syntactically correct sql statement for which to retrieve a
 *               fully qualified SQL identifier name
 * @param cursor to indicate the 0-based cursor position in the query that
 *               represents a SQL identifier for which its fully qualified
 *               name is to be returned.
 * @return a {@link SqlMoniker} that contains the fully qualified name of
 * the specified SQL identifier, returns null if none is found or the SQL
 * statement is invalid.
 */
public SqlMoniker getQualifiedName(String sql, int cursor) {
    SqlNode sqlNode;
    try {
        sqlNode = parseQuery(sql);
        validator.validate(sqlNode);
    } catch (Exception e) {
        return null;
    }
    SqlParserPos pos = new SqlParserPos(1, cursor + 1);
    try {
        return validator.lookupQualifiedName(sqlNode, pos);
    } catch (CalciteContextException e) {
        return null;
    } catch (java.lang.AssertionError e) {
        return null;
    }
}
Also used : CalciteContextException(org.apache.calcite.runtime.CalciteContextException) SqlParserPos(org.apache.calcite.sql.parser.SqlParserPos) CalciteContextException(org.apache.calcite.runtime.CalciteContextException) CalciteException(org.apache.calcite.runtime.CalciteException) SqlParseException(org.apache.calcite.sql.parser.SqlParseException) SqlNode(org.apache.calcite.sql.SqlNode)

Example 7 with CalciteContextException

use of org.apache.calcite.runtime.CalciteContextException in project calcite by apache.

the class SqlAdvisor method validate.

/**
 * Attempts to parse and validate a SQL statement. Throws the first
 * exception encountered. The error message of this exception is to be
 * displayed on the UI
 *
 * @param sql A user-input sql statement to be validated
 * @return a List of ValidateErrorInfo (null if sql is valid)
 */
public List<ValidateErrorInfo> validate(String sql) {
    SqlNode sqlNode;
    List<ValidateErrorInfo> errorList = new ArrayList<ValidateErrorInfo>();
    sqlNode = collectParserError(sql, errorList);
    if (!errorList.isEmpty()) {
        return errorList;
    }
    try {
        validator.validate(sqlNode);
    } catch (CalciteContextException e) {
        ValidateErrorInfo errInfo = new ValidateErrorInfo(e);
        // validator only returns 1 exception now
        errorList.add(errInfo);
        return errorList;
    } catch (Exception e) {
        ValidateErrorInfo errInfo = new ValidateErrorInfo(1, 1, 1, sql.length(), e.getMessage());
        // parser only returns 1 exception now
        errorList.add(errInfo);
        return errorList;
    }
    return null;
}
Also used : CalciteContextException(org.apache.calcite.runtime.CalciteContextException) ArrayList(java.util.ArrayList) CalciteContextException(org.apache.calcite.runtime.CalciteContextException) CalciteException(org.apache.calcite.runtime.CalciteException) SqlParseException(org.apache.calcite.sql.parser.SqlParseException) SqlNode(org.apache.calcite.sql.SqlNode)

Example 8 with CalciteContextException

use of org.apache.calcite.runtime.CalciteContextException in project calcite by apache.

the class SqlUtil method newContextException.

/**
 * Wraps an exception with context.
 */
public static CalciteContextException newContextException(int line, int col, int endLine, int endCol, Resources.ExInst<?> e) {
    CalciteContextException contextExcn = (line == endLine && col == endCol ? RESOURCE.validatorContextPoint(line, col) : RESOURCE.validatorContext(line, col, endLine, endCol)).ex(e.ex());
    contextExcn.setPosition(line, col, endLine, endCol);
    return contextExcn;
}
Also used : CalciteContextException(org.apache.calcite.runtime.CalciteContextException)

Example 9 with CalciteContextException

use of org.apache.calcite.runtime.CalciteContextException in project calcite by apache.

the class SqlUtil method newContextException.

/**
 * Wraps an exception with context.
 */
public static CalciteException newContextException(final SqlParserPos pos, Resources.ExInst<?> e, String inputText) {
    CalciteContextException ex = newContextException(pos, e);
    ex.setOriginalStatement(inputText);
    return ex;
}
Also used : CalciteContextException(org.apache.calcite.runtime.CalciteContextException)

Example 10 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 {
    ensureDefaultTableSpaceBootedLocally(defaultTableSpace);
    /* Strips out leading comments */
    int idx = SQLUtils.findQueryStart(query);
    if (idx != -1) {
        query = query.substring(idx);
    }
    if (parameters == null) {
        parameters = Collections.emptyList();
    }
    String cacheKey = "scan:" + scan + ",defaultTableSpace:" + defaultTableSpace + ",query:" + query + ",returnValues:" + returnValues + ",maxRows:" + maxRows;
    boolean forceAcquireWriteLock;
    if (// this looks very hacky
    query.endsWith(" FOR UPDATE") && query.substring(0, 6).toLowerCase().equals("select")) {
        forceAcquireWriteLock = true;
        query = query.substring(0, query.length() - " FOR UPDATE".length());
    } else {
        forceAcquireWriteLock = false;
    }
    if (allowCache) {
        ExecutionPlan cached = cache.get(cacheKey);
        if (cached != null) {
            return new TranslatedQuery(cached, new SQLStatementEvaluationContext(query, parameters, forceAcquireWriteLock, false));
        }
    }
    if (isDDL(query)) {
        query = JSQLParserPlanner.rewriteExecuteSyntax(query);
        return fallback.translate(defaultTableSpace, query, parameters, scan, allowCache, returnValues, maxRows);
    }
    if (query.startsWith(TABLE_CONSISTENCY_COMMAND)) {
        query = JSQLParserPlanner.rewriteExecuteSyntax(query);
        return fallback.translate(defaultTableSpace, query, parameters, scan, allowCache, returnValues, maxRows);
    }
    if (query.startsWith(TABLESPACE_CONSISTENCY_COMMAND)) {
        query = JSQLParserPlanner.rewriteExecuteSyntax(query);
        return fallback.translate(defaultTableSpace, query, parameters, scan, allowCache, returnValues, maxRows);
    }
    if (!isCachable(query)) {
        allowCache = false;
    }
    try {
        if (query.startsWith("EXPLAIN ")) {
            query = query.substring("EXPLAIN ".length());
            PlannerResult plan = runPlanner(defaultTableSpace, query);
            boolean upsert = detectUpsert(plan);
            PlannerOp finalPlan = convertRelNode(plan.topNode, plan.originalRowType, returnValues, upsert).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", ColumnTypes.NOTNULL_STRING), new ConstantExpression(query, ColumnTypes.NOTNULL_STRING)), java.util.Arrays.asList(new ConstantExpression("logicalplan", ColumnTypes.NOTNULL_STRING), new ConstantExpression(RelOptUtil.dumpPlan("", plan.logicalPlan, SqlExplainFormat.TEXT, SqlExplainLevel.ALL_ATTRIBUTES), ColumnTypes.NOTNULL_STRING)), java.util.Arrays.asList(new ConstantExpression("plan", ColumnTypes.NOTNULL_STRING), new ConstantExpression(RelOptUtil.dumpPlan("", plan.topNode, SqlExplainFormat.TEXT, SqlExplainLevel.ALL_ATTRIBUTES), ColumnTypes.NOTNULL_STRING)), java.util.Arrays.asList(new ConstantExpression("finalplan", ColumnTypes.NOTNULL_STRING), new ConstantExpression(finalPlan + "", ColumnTypes.NOTNULL_STRING))));
            ExecutionPlan executionPlan = ExecutionPlan.simple(new SQLPlannedOperationStatement(values), values);
            return new TranslatedQuery(executionPlan, new SQLStatementEvaluationContext(query, parameters, false, false));
        }
        if (query.startsWith("SHOW")) {
            return calculateShowCreateTable(query, defaultTableSpace, parameters, manager);
        }
        PlannerResult plan = runPlanner(defaultTableSpace, query);
        boolean upsert = detectUpsert(plan);
        SQLPlannedOperationStatement sqlPlannedOperationStatement = new SQLPlannedOperationStatement(convertRelNode(plan.topNode, plan.originalRowType, returnValues, upsert).optimize());
        if (LOG.isLoggable(DUMP_QUERY_LEVEL)) {
            LOG.log(DUMP_QUERY_LEVEL, "Query: {0} --HerdDB Plan\n{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 = IndexUtils.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, forceAcquireWriteLock, false));
            }
        }
        if (maxRows > 0) {
            PlannerOp op = new LimitOp(sqlPlannedOperationStatement.getRootOp(), new ConstantExpression(maxRows, ColumnTypes.NOTNULL_LONG), new ConstantExpression(0, ColumnTypes.NOTNULL_LONG)).optimize();
            sqlPlannedOperationStatement = new SQLPlannedOperationStatement(op);
        }
        PlannerOp rootOp = sqlPlannedOperationStatement.getRootOp();
        ExecutionPlan executionPlan;
        if (rootOp.isSimpleStatementWrapper()) {
            executionPlan = ExecutionPlan.simple(rootOp.unwrap(herddb.model.Statement.class), rootOp);
        } else {
            executionPlan = ExecutionPlan.simple(sqlPlannedOperationStatement, rootOp);
        }
        if (allowCache) {
            cache.put(cacheKey, executionPlan);
        }
        return new TranslatedQuery(executionPlan, new SQLStatementEvaluationContext(query, parameters, forceAcquireWriteLock, false));
    } 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: ", ""), ex);
    } catch (MetadataStorageManagerException ex) {
        LOG.log(Level.INFO, "Error while parsing '" + query + "'", ex);
        throw new StatementExecutionException(ex);
    }
}
Also used : ValidationException(org.apache.calcite.tools.ValidationException) ConstantExpression(herddb.sql.expressions.ConstantExpression) CompiledSQLExpression(herddb.sql.expressions.CompiledSQLExpression) ValuesOp(herddb.model.planner.ValuesOp) StatementExecutionException(herddb.model.StatementExecutionException) SQLPlannedOperationStatement(herddb.model.commands.SQLPlannedOperationStatement) MetadataStorageManagerException(herddb.metadata.MetadataStorageManagerException) CalciteContextException(org.apache.calcite.runtime.CalciteContextException) ExecutionPlan(herddb.model.ExecutionPlan) ScanStatement(herddb.model.commands.ScanStatement) PlannerOp(herddb.model.planner.PlannerOp) Table(herddb.model.Table) ShowCreateTableCalculator.calculateShowCreateTable(herddb.sql.functions.ShowCreateTableCalculator.calculateShowCreateTable) SqlStdOperatorTable(org.apache.calcite.sql.fun.SqlStdOperatorTable) 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) SqlParseException(org.apache.calcite.sql.parser.SqlParseException) LimitOp(herddb.model.planner.LimitOp) RelConversionException(org.apache.calcite.tools.RelConversionException) GetStatement(herddb.model.commands.GetStatement)

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