Search in sources :

Example 61 with StatementExecutionException

use of herddb.model.StatementExecutionException in project herddb by diennea.

the class ServerSideConnectionPeer method handlePushTransactionsBlock.

private void handlePushTransactionsBlock(Pdu message, Channel channel) {
    try {
        String tableSpace = PduCodec.PushTransactionsBlock.readTablespace(message);
        List<Transaction> entries = new ArrayList<>();
        PduCodec.PushTransactionsBlock.readTransactions(message, (value) -> entries.add(Transaction.deserialize(tableSpace, value)));
        LOGGER.log(Level.INFO, "Received " + entries.size() + " records for restore of transactions in tableSpace " + tableSpace);
        server.getManager().getTableSpaceManager(tableSpace).restoreRawDumpedTransactions(entries);
        ByteBuf res = PduCodec.AckResponse.write(message.messageId);
        channel.sendReplyMessage(message.messageId, res);
    } catch (StatementExecutionException err) {
        ByteBuf res = composeErrorResponse(message.messageId, err);
        channel.sendReplyMessage(message.messageId, res);
    }
}
Also used : Transaction(herddb.model.Transaction) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) ArrayList(java.util.ArrayList) RawString(herddb.utils.RawString) ByteBuf(io.netty.buffer.ByteBuf) StatementExecutionException(herddb.model.StatementExecutionException)

Example 62 with StatementExecutionException

use of herddb.model.StatementExecutionException in project herddb by diennea.

the class ServerSideConnectionPeer method handleTxCommand.

private void handleTxCommand(Pdu message, Channel channel) {
    long txId = PduCodec.TxCommand.readTx(message);
    int type = PduCodec.TxCommand.readCommand(message);
    String tableSpace = PduCodec.TxCommand.readTablespace(message);
    TransactionContext transactionContext = new TransactionContext(txId);
    Statement statement;
    switch(type) {
        case TX_COMMAND_COMMIT_TRANSACTION:
            statement = new CommitTransactionStatement(tableSpace, txId);
            break;
        case TX_COMMAND_ROLLBACK_TRANSACTION:
            statement = new RollbackTransactionStatement(tableSpace, txId);
            break;
        case TX_COMMAND_BEGIN_TRANSACTION:
            statement = new BeginTransactionStatement(tableSpace);
            break;
        default:
            statement = null;
    }
    if (statement == null) {
        ByteBuf error = PduCodec.ErrorResponse.write(message.messageId, "unknown txcommand type:" + type);
        channel.sendReplyMessage(message.messageId, error);
        message.close();
    } else {
        // LOGGER.log(Level.SEVERE, "statement " + statement);
        CompletableFuture<StatementExecutionResult> res = server.getManager().executeStatementAsync(statement, StatementEvaluationContext.DEFAULT_EVALUATION_CONTEXT(), transactionContext);
        // LOGGER.log(Level.SEVERE, "query " + query + ", " + parameters + ", result:" + result);
        res.whenComplete((result, err) -> {
            try {
                if (err != null) {
                    if (err instanceof NotLeaderException) {
                        ByteBuf error = composeErrorResponse(message.messageId, err);
                        channel.sendReplyMessage(message.messageId, error);
                    } else if (err instanceof StatementExecutionException) {
                        ByteBuf error = composeErrorResponse(message.messageId, err);
                        channel.sendReplyMessage(message.messageId, error);
                    } else {
                        LOGGER.log(Level.SEVERE, "unexpected error on tx command: ", err);
                        ByteBuf error = composeErrorResponse(message.messageId, err);
                        channel.sendReplyMessage(message.messageId, error);
                    }
                } else {
                    if (result instanceof TransactionResult) {
                        TransactionResult txresult = (TransactionResult) result;
                        ByteBuf response = PduCodec.TxCommandResult.write(message.messageId, txresult.transactionId);
                        channel.sendReplyMessage(message.messageId, response);
                    } else {
                        ByteBuf error = PduCodec.ErrorResponse.write(message.messageId, "unknown result type:" + result);
                        channel.sendReplyMessage(message.messageId, error);
                    }
                }
            } finally {
                message.close();
            }
        });
    }
}
Also used : NotLeaderException(herddb.model.NotLeaderException) TransactionResult(herddb.model.TransactionResult) CommitTransactionStatement(herddb.model.commands.CommitTransactionStatement) CommitTransactionStatement(herddb.model.commands.CommitTransactionStatement) RollbackTransactionStatement(herddb.model.commands.RollbackTransactionStatement) BeginTransactionStatement(herddb.model.commands.BeginTransactionStatement) TableAwareStatement(herddb.model.TableAwareStatement) ScanStatement(herddb.model.commands.ScanStatement) Statement(herddb.model.Statement) SQLPlannedOperationStatement(herddb.model.commands.SQLPlannedOperationStatement) RollbackTransactionStatement(herddb.model.commands.RollbackTransactionStatement) RawString(herddb.utils.RawString) ByteBuf(io.netty.buffer.ByteBuf) StatementExecutionException(herddb.model.StatementExecutionException) TransactionContext(herddb.model.TransactionContext) BeginTransactionStatement(herddb.model.commands.BeginTransactionStatement) DDLStatementExecutionResult(herddb.model.DDLStatementExecutionResult) DMLStatementExecutionResult(herddb.model.DMLStatementExecutionResult) StatementExecutionResult(herddb.model.StatementExecutionResult)

Example 63 with StatementExecutionException

use of herddb.model.StatementExecutionException in project herddb by diennea.

the class ServerSideConnectionPeer method handleFetchScannerData.

private void handleFetchScannerData(Pdu message, Channel channel) {
    long scannerId = PduCodec.FetchScannerData.readScannerId(message);
    int fetchSize = PduCodec.FetchScannerData.readFetchSize(message);
    if (fetchSize <= 0) {
        fetchSize = 10;
    }
    ServerSideScannerPeer scanner = scanners.get(scannerId);
    if (scanner != null) {
        try {
            DataScanner dataScanner = scanner.getScanner();
            List<DataAccessor> records = dataScanner.consume(fetchSize);
            String[] columns = dataScanner.getFieldNames();
            TuplesList tuplesList = new TuplesList(columns, records);
            boolean last = false;
            if (dataScanner.isFinished()) {
                LOGGER.log(Level.FINEST, "unregistering scanner {0}, resultset is finished", scannerId);
                scanners.remove(scannerId);
                last = true;
            }
            // LOGGER.log(Level.SEVERE, "sending " + converted.size() + " records to scanner " + scannerId);
            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
                scanners.remove(scannerId);
                scanner.close();
                throw err;
            }
            if (last) {
                dataScanner.close();
            }
        } catch (DataScannerException | StatementExecutionException err) {
            ByteBuf error = composeErrorResponse(message.messageId, err);
            channel.sendReplyMessage(message.messageId, error);
        }
    } else {
        ByteBuf error = PduCodec.ErrorResponse.write(message.messageId, "no such scanner " + scannerId);
        channel.sendReplyMessage(message.messageId, error);
    }
}
Also used : HerdDBInternalException(herddb.core.HerdDBInternalException) DataAccessor(herddb.utils.DataAccessor) RawString(herddb.utils.RawString) ByteBuf(io.netty.buffer.ByteBuf) StatementExecutionException(herddb.model.StatementExecutionException) DataScanner(herddb.model.DataScanner) TuplesList(herddb.utils.TuplesList) DataScannerException(herddb.model.DataScannerException)

Example 64 with StatementExecutionException

use of herddb.model.StatementExecutionException in project herddb by diennea.

the class JSQLParserPlanner 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);
    if (parameters == null) {
        parameters = Collections.emptyList();
    }
    /*
         * Strips out leading comments
         */
    int idx = SQLUtils.findQueryStart(query);
    if (idx != -1) {
        query = query.substring(idx);
    }
    query = rewriteExecuteSyntax(query);
    if (query.startsWith("ALTER TABLE") && query.contains("ADD FOREIGN KEY")) {
        // jsqlparser does not support unnamed foreign keys in "ALTER TABLE"
        query = query.replace("ADD FOREIGN KEY", "ADD CONSTRAINT generate_unnamed FOREIGN KEY");
    }
    if (query.startsWith("EXPLAIN ")) {
        query = query.substring("EXPLAIN ".length());
        net.sf.jsqlparser.statement.Statement stmt = parseStatement(query);
        if (!isCachable(stmt)) {
            allowCache = false;
        }
        ExecutionPlan queryExecutionPlan = plan(defaultTableSpace, stmt, scan, returnValues, maxRows);
        PlannerOp finalPlan = queryExecutionPlan.originalRoot;
        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(stmt + "", ColumnTypes.NOTNULL_STRING)), java.util.Arrays.asList(new ConstantExpression("plan", ColumnTypes.NOTNULL_STRING), new ConstantExpression(finalPlan + "", ColumnTypes.NOTNULL_STRING)), java.util.Arrays.asList(new ConstantExpression("finalplan", ColumnTypes.NOTNULL_STRING), // same as "plan"
        new ConstantExpression(finalPlan.optimize(), 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);
    }
    String cacheKey = "scan:" + scan + ",defaultTableSpace:" + defaultTableSpace + ",query:" + query + ",returnValues:" + returnValues + ",maxRows:" + maxRows;
    try {
        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 (query.startsWith(TABLE_CONSISTENCY_COMMAND)) {
            ExecutionPlan executionPlan = ExecutionPlan.simple(JSQLParserPlanner.this.queryConsistencyCheckStatement(defaultTableSpace, query, parameters));
            return new TranslatedQuery(executionPlan, new SQLStatementEvaluationContext(query, parameters, false, false));
        }
        if (query.startsWith(TABLESPACE_CONSISTENCY_COMMAND)) {
            ExecutionPlan executionPlan = ExecutionPlan.simple(JSQLParserPlanner.this.queryConsistencyCheckStatement(query));
            return new TranslatedQuery(executionPlan, new SQLStatementEvaluationContext(query, parameters, false, false));
        }
        net.sf.jsqlparser.statement.Statement stmt = parseStatement(query);
        if (!isCachable(stmt)) {
            allowCache = false;
        }
        ExecutionPlan executionPlan = plan(defaultTableSpace, stmt, scan, returnValues, maxRows);
        if (LOG.isLoggable(DUMP_QUERY_LEVEL)) {
            LOG.log(DUMP_QUERY_LEVEL, "Query: {0} --HerdDB Plan\n{1}", new Object[] { query, executionPlan.mainStatement });
        }
        if (allowCache) {
            cache.put(cacheKey, executionPlan);
        }
        return new TranslatedQuery(executionPlan, new SQLStatementEvaluationContext(query, parameters, forceAcquireWriteLock, false));
    } catch (StatementNotSupportedException err) {
        if (fallback == null) {
            throw new StatementExecutionException("I am sorry, I cannot plan SQL \"" + query + "\" with simple jSQLParser planner," + " consider setting " + ServerConfiguration.PROPERTY_PLANNER_TYPE + "=" + ServerConfiguration.PLANNER_TYPE_AUTO, err);
        }
        TranslatedQuery res = fallback.translate(defaultTableSpace, query, parameters, scan, allowCache, returnValues, maxRows);
        if (allowCache) {
            // cache plan from Calcite, not need to try jSQLParser again
            cache.put(cacheKey, res.plan);
        }
        return res;
    }
}
Also used : PlannerOp(herddb.model.planner.PlannerOp) ConstantExpression(herddb.sql.expressions.ConstantExpression) ValuesOp(herddb.model.planner.ValuesOp) StatementExecutionException(herddb.model.StatementExecutionException) SQLPlannedOperationStatement(herddb.model.commands.SQLPlannedOperationStatement) ExecutionPlan(herddb.model.ExecutionPlan)

Example 65 with StatementExecutionException

use of herddb.model.StatementExecutionException in project herddb by diennea.

the class JSQLParserPlanner method getTable.

private Table getTable(String defaultTableSpace, net.sf.jsqlparser.schema.Table table) {
    String tableSpace = table.getSchemaName();
    if (tableSpace == null) {
        tableSpace = defaultTableSpace;
    }
    tableSpace = fixMySqlBackTicks(tableSpace);
    TableSpaceManager tableSpaceManager = getTableSpaceManager(tableSpace);
    if (tableSpaceManager == null) {
        clearCache();
        throw new StatementExecutionException("tablespace " + defaultTableSpace + " is not available");
    }
    String tableName = fixMySqlBackTicks(table.getName().toLowerCase());
    AbstractTableManager tableManager = tableSpaceManager.getTableManager(tableName);
    if (tableManager == null) {
        throw new TableDoesNotExistException("no table " + tableName + " here for " + tableSpace);
    }
    return tableManager.getTable();
}
Also used : TableDoesNotExistException(herddb.model.TableDoesNotExistException) AbstractTableManager(herddb.core.AbstractTableManager) TableSpaceManager(herddb.core.TableSpaceManager) StatementExecutionException(herddb.model.StatementExecutionException)

Aggregations

StatementExecutionException (herddb.model.StatementExecutionException)163 Table (herddb.model.Table)69 ArrayList (java.util.ArrayList)57 DataScanner (herddb.model.DataScanner)49 TransactionContext (herddb.model.TransactionContext)47 DataStorageManagerException (herddb.storage.DataStorageManagerException)40 List (java.util.List)40 DataScannerException (herddb.model.DataScannerException)39 StatementExecutionResult (herddb.model.StatementExecutionResult)39 Column (herddb.model.Column)37 DataAccessor (herddb.utils.DataAccessor)36 LogNotAvailableException (herddb.log.LogNotAvailableException)35 LogEntry (herddb.log.LogEntry)34 Test (org.junit.Test)34 InsertStatement (herddb.model.commands.InsertStatement)32 Bytes (herddb.utils.Bytes)32 CommitLogResult (herddb.log.CommitLogResult)31 Record (herddb.model.Record)31 DMLStatementExecutionResult (herddb.model.DMLStatementExecutionResult)30 Map (java.util.Map)30