Search in sources :

Example 11 with ValidationException

use of org.apache.beam.vendor.calcite.v1_28_0.org.apache.calcite.tools.ValidationException in project druid by druid-io.

the class SqlLifecycle method plan.

/**
 * Plan the query to enable execution.
 *
 * If successful, the lifecycle will first transition from {@link State#AUTHORIZED} to {@link State#PLANNED}.
 */
public void plan() throws RelConversionException {
    transition(State.AUTHORIZED, State.PLANNED);
    Preconditions.checkNotNull(plannerContext, "Cannot plan, plannerContext is null");
    try (DruidPlanner planner = plannerFactory.createPlannerWithContext(plannerContext)) {
        this.plannerResult = planner.plan();
    }// we can't collapse catch clauses since SqlPlanningException has type-sensitive constructors.
     catch (SqlParseException e) {
        throw new SqlPlanningException(e);
    } catch (ValidationException e) {
        throw new SqlPlanningException(e);
    }
}
Also used : ValidationException(org.apache.calcite.tools.ValidationException) SqlParseException(org.apache.calcite.sql.parser.SqlParseException) DruidPlanner(org.apache.druid.sql.calcite.planner.DruidPlanner)

Example 12 with ValidationException

use of org.apache.beam.vendor.calcite.v1_28_0.org.apache.calcite.tools.ValidationException 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)

Example 13 with ValidationException

use of org.apache.beam.vendor.calcite.v1_28_0.org.apache.calcite.tools.ValidationException in project herddb by diennea.

the class ServerSideConnectionPeer method executeScan.

public ScanResultSet executeScan(String tableSpace, String query, boolean usePreparedStatement, List<Object> parameters, long txId, int maxRows, int fetchSize, boolean keepReadLocks) throws HDBException {
    if (query == null) {
        throw new HDBException("bad query null");
    }
    parameters = PduCodec.normalizeParametersList(parameters);
    try {
        TranslatedQuery translatedQuery = server.getManager().getPlanner().translate(tableSpace, query, parameters, true, true, false, maxRows);
        translatedQuery.context.setForceRetainReadLock(keepReadLocks);
        if (LOGGER.isLoggable(Level.FINEST)) {
            LOGGER.log(Level.FINEST, "{0} -> {1}", new Object[] { query, translatedQuery.plan.mainStatement });
        }
        TransactionContext transactionContext = new TransactionContext(txId);
        if (translatedQuery.plan.mainStatement instanceof SQLPlannedOperationStatement || translatedQuery.plan.mainStatement instanceof ScanStatement) {
            ScanResult scanResult = (ScanResult) server.getManager().executePlan(translatedQuery.plan, translatedQuery.context, transactionContext);
            DataScanner dataScanner = scanResult.dataScanner;
            return new LocalClientScanResultSetImpl(dataScanner);
        } else {
            throw new HDBException("unsupported query type for scan " + query + ": PLAN is " + translatedQuery.plan);
        }
    } catch (HerdDBInternalException err) {
        if (err.getCause() != null && err.getCause() instanceof ValidationException) {
            // no stacktraces for bad queries
            LOGGER.log(Level.FINE, "SQL error on scanner: " + err);
        } else {
            LOGGER.log(Level.SEVERE, "error on scanner: " + err, err);
        }
        throw new HDBException(err);
    }
}
Also used : ScanResult(herddb.model.ScanResult) TranslatedQuery(herddb.sql.TranslatedQuery) DataScanner(herddb.model.DataScanner) HerdDBInternalException(herddb.core.HerdDBInternalException) ValidationException(org.apache.calcite.tools.ValidationException) TransactionContext(herddb.model.TransactionContext) HDBException(herddb.client.HDBException) SQLPlannedOperationStatement(herddb.model.commands.SQLPlannedOperationStatement) ScanStatement(herddb.model.commands.ScanStatement)

Example 14 with ValidationException

use of org.apache.beam.vendor.calcite.v1_28_0.org.apache.calcite.tools.ValidationException in project herddb by diennea.

the class ServerSideConnectionPeer method handleOpenScanner.

private void handleOpenScanner(Pdu message, Channel channel) {
    long txId = PduCodec.OpenScanner.readTx(message);
    String tableSpace = PduCodec.OpenScanner.readTablespace(message);
    long statementId = PduCodec.OpenScanner.readStatementId(message);
    String query = statementId > 0 ? preparedStatements.resolveQuery(tableSpace, statementId) : PduCodec.OpenScanner.readQuery(message);
    if (query == null) {
        ByteBuf error = PduCodec.ErrorResponse.writeMissingPreparedStatementError(message.messageId, "bad statement id: " + statementId);
        channel.sendReplyMessage(message.messageId, error);
        return;
    }
    long scannerId = PduCodec.OpenScanner.readScannerId(message);
    int fetchSize = PduCodec.OpenScanner.readFetchSize(message);
    if (fetchSize <= 0) {
        fetchSize = 10;
    }
    // default 0
    int maxRows = PduCodec.OpenScanner.readMaxRows(message);
    PduCodec.ObjectListReader parametersReader = PduCodec.OpenScanner.startReadParameters(message);
    List<Object> parameters = new ArrayList<>(parametersReader.getNumParams());
    for (int i = 0; i < parametersReader.getNumParams(); i++) {
        parameters.add(parametersReader.nextObject());
    }
    // with clients older than 0.20.0 keepReadLocks will be always true
    byte trailer = parametersReader.readTrailer();
    boolean keepReadLocks = !isDontKeepReadLocks(trailer);
    if (LOGGER.isLoggable(Level.FINER)) {
        LOGGER.log(Level.FINER, "openScanner txId+" + txId + ", fetchSize " + fetchSize + ", maxRows " + maxRows + ", keepReadLocks " + keepReadLocks + ", " + query + " with " + parameters);
    }
    RunningStatementsStats runningStatements = server.getManager().getRunningStatements();
    RunningStatementInfo statementInfo = new RunningStatementInfo(query, System.currentTimeMillis(), tableSpace, "", 1);
    try {
        TranslatedQuery translatedQuery = server.getManager().getPlanner().translate(tableSpace, query, parameters, true, true, false, maxRows);
        translatedQuery.context.setForceRetainReadLock(keepReadLocks);
        if (LOGGER.isLoggable(Level.FINEST)) {
            LOGGER.log(Level.FINEST, "{0} -> {1}", new Object[] { query, translatedQuery.plan.mainStatement });
        }
        TransactionContext transactionContext = new TransactionContext(txId);
        if (translatedQuery.plan.mainStatement instanceof SQLPlannedOperationStatement || translatedQuery.plan.mainStatement instanceof ScanStatement) {
            runningStatements.registerRunningStatement(statementInfo);
            ScanResult scanResult = (ScanResult) server.getManager().executePlan(translatedQuery.plan, translatedQuery.context, transactionContext);
            DataScanner dataScanner = scanResult.dataScanner;
            ServerSideScannerPeer scanner = new ServerSideScannerPeer(dataScanner);
            String[] columns = dataScanner.getFieldNames();
            List<DataAccessor> records = dataScanner.consume(fetchSize);
            TuplesList tuplesList = new TuplesList(columns, records);
            boolean last = dataScanner.isFinished();
            if (LOGGER.isLoggable(Level.FINEST)) {
                LOGGER.log(Level.FINEST, "sending first {0} records to scanner {1} query {2}", new Object[] { records.size(), scannerId, query });
            }
            if (!last) {
                scanners.put(scannerId, scanner);
            }
            try {
                ByteBuf result = PduCodec.ResultSetChunk.write(message.messageId, tuplesList, last, dataScanner.getTransactionId());
                channel.sendReplyMessage(message.messageId, result);
            } catch (HerdDBInternalException err) {
                // do not leak an unserializable scanner
                scanner.close();
                throw err;
            }
            if (last) {
                // no need to hold the scanner anymore
                scanner.close();
            }
        } else {
            ByteBuf error = PduCodec.ErrorResponse.write(message.messageId, "unsupported query type for scan " + query + ": PLAN is " + translatedQuery.plan);
            channel.sendReplyMessage(message.messageId, error);
        }
    } catch (DataScannerException | HerdDBInternalException err) {
        if (err.getCause() != null && err.getCause() instanceof ValidationException) {
            // no stacktraces for bad queries
            LOGGER.log(Level.FINE, "SQL error on scanner " + scannerId + ": " + err);
        } else {
            LOGGER.log(Level.SEVERE, "error on scanner " + scannerId + ": " + err, err);
        }
        scanners.remove(scannerId);
        ByteBuf error = composeErrorResponse(message.messageId, err);
        channel.sendReplyMessage(message.messageId, error);
    } finally {
        runningStatements.unregisterRunningStatement(statementInfo);
    }
}
Also used : HerdDBInternalException(herddb.core.HerdDBInternalException) ValidationException(org.apache.calcite.tools.ValidationException) DataAccessor(herddb.utils.DataAccessor) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) ArrayList(java.util.ArrayList) RawString(herddb.utils.RawString) ByteBuf(io.netty.buffer.ByteBuf) RunningStatementInfo(herddb.core.RunningStatementInfo) SQLPlannedOperationStatement(herddb.model.commands.SQLPlannedOperationStatement) DataScanner(herddb.model.DataScanner) RunningStatementsStats(herddb.core.RunningStatementsStats) ScanStatement(herddb.model.commands.ScanStatement) TuplesList(herddb.utils.TuplesList) DataScannerException(herddb.model.DataScannerException) ScanResult(herddb.model.ScanResult) TranslatedQuery(herddb.sql.TranslatedQuery) PduCodec(herddb.proto.PduCodec) TransactionContext(herddb.model.TransactionContext)

Aggregations

ValidationException (org.apache.calcite.tools.ValidationException)13 SqlParseException (org.apache.calcite.sql.parser.SqlParseException)6 RelConversionException (org.apache.calcite.tools.RelConversionException)6 SqlNode (org.apache.calcite.sql.SqlNode)5 SQLPlannedOperationStatement (herddb.model.commands.SQLPlannedOperationStatement)3 ScanStatement (herddb.model.commands.ScanStatement)3 RelRoot (org.apache.calcite.rel.RelRoot)3 HerdDBInternalException (herddb.core.HerdDBInternalException)2 DataScanner (herddb.model.DataScanner)2 ScanResult (herddb.model.ScanResult)2 TransactionContext (herddb.model.TransactionContext)2 TranslatedQuery (herddb.sql.TranslatedQuery)2 IOException (java.io.IOException)2 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)1 HDBException (herddb.client.HDBException)1 RunningStatementInfo (herddb.core.RunningStatementInfo)1 RunningStatementsStats (herddb.core.RunningStatementsStats)1 MetadataStorageManagerException (herddb.metadata.MetadataStorageManagerException)1 DataScannerException (herddb.model.DataScannerException)1 ExecutionPlan (herddb.model.ExecutionPlan)1