Search in sources :

Example 6 with HerdDBInternalException

use of herddb.core.HerdDBInternalException in project herddb by diennea.

the class ServerSideConnectionPeer method commitTransaction.

public void commitTransaction(String tableSpace, long txId) throws HDBException {
    try {
        CommitTransactionStatement statement = new CommitTransactionStatement(tableSpace, txId);
        TransactionContext transactionContext = new TransactionContext(txId);
        server.getManager().executeStatement(statement, StatementEvaluationContext.DEFAULT_EVALUATION_CONTEXT(), transactionContext);
    } catch (HerdDBInternalException t) {
        throw new HDBException(t);
    }
}
Also used : HerdDBInternalException(herddb.core.HerdDBInternalException) CommitTransactionStatement(herddb.model.commands.CommitTransactionStatement) TransactionContext(herddb.model.TransactionContext) HDBException(herddb.client.HDBException)

Example 7 with HerdDBInternalException

use of herddb.core.HerdDBInternalException 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 8 with HerdDBInternalException

use of herddb.core.HerdDBInternalException in project herddb by diennea.

the class ServerSideConnectionPeer method handleExecuteStatements.

private void handleExecuteStatements(Pdu message, Channel channel) {
    long transactionId = PduCodec.ExecuteStatements.readTx(message);
    String tableSpace = PduCodec.ExecuteStatements.readTablespace(message);
    long statementId = PduCodec.ExecuteStatements.readStatementId(message);
    String query = statementId > 0 ? preparedStatements.resolveQuery(tableSpace, statementId) : PduCodec.ExecuteStatements.readQuery(message);
    if (query == null) {
        ByteBuf error = PduCodec.ErrorResponse.writeMissingPreparedStatementError(message.messageId, "bad statement id: " + statementId);
        channel.sendReplyMessage(message.messageId, error);
        message.close();
        return;
    }
    boolean returnValues = PduCodec.ExecuteStatements.readReturnValues(message);
    PduCodec.ListOfListsReader statementParameters = PduCodec.ExecuteStatements.startReadStatementsParameters(message);
    int numStatements = statementParameters.getNumLists();
    List<List<Object>> batch = new ArrayList<>(numStatements);
    for (int i = 0; i < numStatements; i++) {
        PduCodec.ObjectListReader parametersReader = statementParameters.nextList();
        List<Object> batchParams = new ArrayList<>(parametersReader.getNumParams());
        for (int j = 0; j < parametersReader.getNumParams(); j++) {
            batchParams.add(parametersReader.nextObject());
        }
        batch.add(batchParams);
    }
    RunningStatementsStats runningStatements = server.getManager().getRunningStatements();
    RunningStatementInfo statementInfo = new RunningStatementInfo(query, System.currentTimeMillis(), tableSpace, "", numStatements);
    try {
        List<TranslatedQuery> queries = new ArrayList<>();
        for (int i = 0; i < numStatements; i++) {
            List<Object> parameters = batch.get(i);
            TranslatedQuery translatedQuery = server.getManager().getPlanner().translate(tableSpace, query, parameters, false, true, returnValues, -1);
            queries.add(translatedQuery);
        }
        List<Long> updateCounts = new CopyOnWriteArrayList<>();
        List<Map<String, Object>> otherDatas = new CopyOnWriteArrayList<>();
        class ComputeNext implements BiConsumer<StatementExecutionResult, Throwable> {

            int current;

            public ComputeNext(int current) {
                this.current = current;
            }

            @Override
            public void accept(StatementExecutionResult result, Throwable error) {
                if (error != null) {
                    ByteBuf errorMsg = composeErrorResponse(message.messageId, error);
                    channel.sendReplyMessage(message.messageId, errorMsg);
                    message.close();
                    runningStatements.unregisterRunningStatement(statementInfo);
                    return;
                }
                if (result instanceof DMLStatementExecutionResult) {
                    DMLStatementExecutionResult dml = (DMLStatementExecutionResult) result;
                    Map<String, Object> otherData = Collections.emptyMap();
                    if (returnValues && dml.getKey() != null) {
                        TranslatedQuery translatedQuery = queries.get(current - 1);
                        Statement statement = translatedQuery.plan.mainStatement;
                        TableAwareStatement tableStatement = (TableAwareStatement) statement;
                        Table table = server.getManager().getTableSpaceManager(statement.getTableSpace()).getTableManager(tableStatement.getTable()).getTable();
                        Object key = RecordSerializer.deserializePrimaryKey(dml.getKey(), table);
                        otherData = new HashMap<>();
                        otherData.put("_key", key);
                        if (dml.getNewvalue() != null) {
                            Map<String, Object> newvalue = RecordSerializer.toBean(new Record(dml.getKey(), dml.getNewvalue()), table);
                            otherData.putAll(newvalue);
                        }
                    }
                    updateCounts.add((long) dml.getUpdateCount());
                    otherDatas.add(otherData);
                } else if (result instanceof DDLStatementExecutionResult) {
                    Map<String, Object> otherData = Collections.emptyMap();
                    updateCounts.add(1L);
                    otherDatas.add(otherData);
                } else {
                    ByteBuf response = PduCodec.ErrorResponse.write(message.messageId, "bad result type " + result.getClass() + " (" + result + ")");
                    channel.sendReplyMessage(message.messageId, response);
                    message.close();
                    runningStatements.unregisterRunningStatement(statementInfo);
                    return;
                }
                long newTransactionId = result.transactionId;
                if (current == queries.size()) {
                    try {
                        ByteBuf response = PduCodec.ExecuteStatementsResult.write(message.messageId, updateCounts, otherDatas, newTransactionId);
                        channel.sendReplyMessage(message.messageId, response);
                        message.close();
                        runningStatements.unregisterRunningStatement(statementInfo);
                    } catch (Throwable t) {
                        LOGGER.log(Level.SEVERE, "Internal error", t);
                    }
                    return;
                }
                TranslatedQuery nextPlannedQuery = queries.get(current);
                TransactionContext transactionContext = new TransactionContext(newTransactionId);
                CompletableFuture<StatementExecutionResult> nextPromise = server.getManager().executePlanAsync(nextPlannedQuery.plan, nextPlannedQuery.context, transactionContext);
                nextPromise.whenComplete(new ComputeNext(current + 1));
            }
        }
        TransactionContext transactionContext = new TransactionContext(transactionId);
        TranslatedQuery firstTranslatedQuery = queries.get(0);
        server.getManager().executePlanAsync(firstTranslatedQuery.plan, firstTranslatedQuery.context, transactionContext).whenComplete(new ComputeNext(1));
    } catch (HerdDBInternalException err) {
        ByteBuf response = composeErrorResponse(message.messageId, err);
        channel.sendReplyMessage(message.messageId, response);
        message.close();
        runningStatements.unregisterRunningStatement(statementInfo);
    }
}
Also used : HerdDBInternalException(herddb.core.HerdDBInternalException) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) ArrayList(java.util.ArrayList) RawString(herddb.utils.RawString) ByteBuf(io.netty.buffer.ByteBuf) RunningStatementInfo(herddb.core.RunningStatementInfo) DDLStatementExecutionResult(herddb.model.DDLStatementExecutionResult) DMLStatementExecutionResult(herddb.model.DMLStatementExecutionResult) StatementExecutionResult(herddb.model.StatementExecutionResult) List(java.util.List) TuplesList(herddb.utils.TuplesList) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) ArrayList(java.util.ArrayList) Record(herddb.model.Record) RunningStatementsStats(herddb.core.RunningStatementsStats) TranslatedQuery(herddb.sql.TranslatedQuery) Table(herddb.model.Table) 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) DDLStatementExecutionResult(herddb.model.DDLStatementExecutionResult) PduCodec(herddb.proto.PduCodec) TableAwareStatement(herddb.model.TableAwareStatement) DMLStatementExecutionResult(herddb.model.DMLStatementExecutionResult) TransactionContext(herddb.model.TransactionContext) AtomicLong(java.util.concurrent.atomic.AtomicLong) Map(java.util.Map) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) ConcurrentMap(java.util.concurrent.ConcurrentMap) BiConsumer(java.util.function.BiConsumer) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList)

Example 9 with HerdDBInternalException

use of herddb.core.HerdDBInternalException in project herddb by diennea.

the class ServerSideConnectionPeer method handleExecuteStatements.

private void handleExecuteStatements(Message message, Channel _channel) {
    Long tx = (Long) message.parameters.get("tx");
    long txId = tx != null ? tx : TransactionContext.NOTRANSACTION_ID;
    long transactionId = txId;
    String query = (String) message.parameters.get("query");
    String tableSpace = (String) message.parameters.get("tableSpace");
    Boolean returnValues = (Boolean) message.parameters.get("returnValues");
    if (returnValues == null) {
        returnValues = Boolean.FALSE;
    }
    List<List<Object>> batch = (List<List<Object>>) message.parameters.get("params");
    try {
        List<Long> updateCounts = new ArrayList<>(batch.size());
        List<Map<String, Object>> otherDatas = new ArrayList<>(batch.size());
        for (int i = 0; i < batch.size(); i++) {
            List<Object> parameters = batch.get(i);
            TransactionContext transactionContext = new TransactionContext(transactionId);
            TranslatedQuery translatedQuery = server.getManager().getPlanner().translate(tableSpace, query, parameters, false, true, returnValues, -1);
            Statement statement = translatedQuery.plan.mainStatement;
            StatementExecutionResult result = server.getManager().executePlan(translatedQuery.plan, translatedQuery.context, transactionContext);
            if (transactionId > 0 && result.transactionId > 0 && transactionId != result.transactionId) {
                throw new StatementExecutionException("transactionid changed during batch execution, " + transactionId + "<>" + result.transactionId);
            }
            transactionId = result.transactionId;
            if (result instanceof DMLStatementExecutionResult) {
                DMLStatementExecutionResult dml = (DMLStatementExecutionResult) result;
                Map<String, Object> otherData = Collections.emptyMap();
                if (returnValues && dml.getKey() != null) {
                    TableAwareStatement tableStatement = (TableAwareStatement) statement;
                    Table table = server.getManager().getTableSpaceManager(statement.getTableSpace()).getTableManager(tableStatement.getTable()).getTable();
                    Object key = RecordSerializer.deserializePrimaryKey(dml.getKey().data, table);
                    otherData = new HashMap<>();
                    otherData.put("key", key);
                    if (dml.getNewvalue() != null) {
                        Map<String, Object> newvalue = RecordSerializer.toBean(new Record(dml.getKey(), dml.getNewvalue()), table);
                        otherData.put("newvalue", newvalue);
                    }
                }
                updateCounts.add(Long.valueOf(dml.getUpdateCount()));
                otherDatas.add(otherData);
            } else {
                _channel.sendReplyMessage(message, Message.ERROR(null, new Exception("bad result type " + result.getClass() + " (" + result + ")")));
            }
        }
        _channel.sendReplyMessage(message, Message.EXECUTE_STATEMENT_RESULTS(updateCounts, otherDatas, transactionId));
    } catch (HerdDBInternalException err) {
        Message error = Message.ERROR(null, err);
        if (err instanceof NotLeaderException) {
            error.setParameter("notLeader", "true");
        }
        _channel.sendReplyMessage(message, error);
    }
}
Also used : NotLeaderException(herddb.model.NotLeaderException) HerdDBInternalException(herddb.core.HerdDBInternalException) Message(herddb.network.Message) ArrayList(java.util.ArrayList) StatementExecutionException(herddb.model.StatementExecutionException) DDLStatementExecutionResult(herddb.model.DDLStatementExecutionResult) DMLStatementExecutionResult(herddb.model.DMLStatementExecutionResult) StatementExecutionResult(herddb.model.StatementExecutionResult) List(java.util.List) TuplesList(herddb.utils.TuplesList) ArrayList(java.util.ArrayList) Record(herddb.model.Record) TranslatedQuery(herddb.sql.TranslatedQuery) Table(herddb.model.Table) RollbackTransactionStatement(herddb.model.commands.RollbackTransactionStatement) TableAwareStatement(herddb.model.TableAwareStatement) ScanStatement(herddb.model.commands.ScanStatement) Statement(herddb.model.Statement) SQLPlannedOperationStatement(herddb.model.commands.SQLPlannedOperationStatement) TableAwareStatement(herddb.model.TableAwareStatement) DuplicatePrimaryKeyException(herddb.model.DuplicatePrimaryKeyException) HerdDBInternalException(herddb.core.HerdDBInternalException) StatementExecutionException(herddb.model.StatementExecutionException) NotLeaderException(herddb.model.NotLeaderException) DataScannerException(herddb.model.DataScannerException) DMLStatementExecutionResult(herddb.model.DMLStatementExecutionResult) TransactionContext(herddb.model.TransactionContext) AtomicLong(java.util.concurrent.atomic.AtomicLong) Map(java.util.Map) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) ConcurrentMap(java.util.concurrent.ConcurrentMap)

Example 10 with HerdDBInternalException

use of herddb.core.HerdDBInternalException in project herddb by diennea.

the class JMXUtils method registerTableSpaceManagerStatsMXBean.

public static void registerTableSpaceManagerStatsMXBean(String tableSpaceName, TableSpaceManagerStatsMXBean bean) {
    if (platformMBeanServer == null) {
        throw new HerdDBInternalException("PlatformMBeanServer not available", mBeanServerLookupError);
    }
    String safeTableSpaceName = safeName(tableSpaceName);
    try {
        ObjectName name = new ObjectName("herddb.server:type=TableSpace,Name=" + safeTableSpaceName);
        LOG.log(Level.FINE, "Publishing stats for table {0} at {1}", new Object[] { tableSpaceName, name });
        if (platformMBeanServer.isRegistered(name)) {
            try {
                platformMBeanServer.unregisterMBean(name);
            } catch (InstanceNotFoundException noProblem) {
            }
        }
        platformMBeanServer.registerMBean(bean, name);
    } catch (MalformedObjectNameException | InstanceAlreadyExistsException | MBeanRegistrationException | NotCompliantMBeanException e) {
        throw new HerdDBInternalException("Could not register MXBean " + e);
    }
}
Also used : MalformedObjectNameException(javax.management.MalformedObjectNameException) HerdDBInternalException(herddb.core.HerdDBInternalException) NotCompliantMBeanException(javax.management.NotCompliantMBeanException) InstanceNotFoundException(javax.management.InstanceNotFoundException) InstanceAlreadyExistsException(javax.management.InstanceAlreadyExistsException) MBeanRegistrationException(javax.management.MBeanRegistrationException) ObjectName(javax.management.ObjectName)

Aggregations

HerdDBInternalException (herddb.core.HerdDBInternalException)23 TransactionContext (herddb.model.TransactionContext)8 HDBException (herddb.client.HDBException)5 DataScannerException (herddb.model.DataScannerException)5 SQLPlannedOperationStatement (herddb.model.commands.SQLPlannedOperationStatement)5 ScanStatement (herddb.model.commands.ScanStatement)5 TranslatedQuery (herddb.sql.TranslatedQuery)5 RawString (herddb.utils.RawString)5 TuplesList (herddb.utils.TuplesList)5 DataScanner (herddb.model.DataScanner)4 StatementExecutionException (herddb.model.StatementExecutionException)4 RollbackTransactionStatement (herddb.model.commands.RollbackTransactionStatement)4 DataStorageManagerException (herddb.storage.DataStorageManagerException)4 TableStatus (herddb.storage.TableStatus)4 ArrayList (java.util.ArrayList)4 DDLStatementExecutionResult (herddb.model.DDLStatementExecutionResult)3 DMLStatementExecutionResult (herddb.model.DMLStatementExecutionResult)3 Record (herddb.model.Record)3 Statement (herddb.model.Statement)3 StatementExecutionResult (herddb.model.StatementExecutionResult)3