Search in sources :

Example 6 with NotLeaderException

use of herddb.model.NotLeaderException 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 7 with NotLeaderException

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

the class ServerSideConnectionPeer method handlePushTableData.

private void handlePushTableData(Message message, Channel _channel) {
    try {
        String tableSpace = (String) message.parameters.get("tableSpace");
        String table = (String) message.parameters.get("table");
        List<KeyValue> data = (List<KeyValue>) message.parameters.get("data");
        LOGGER.log(Level.INFO, "Received " + data.size() + " records for restore of table " + table + " in tableSpace " + tableSpace);
        long _start = System.currentTimeMillis();
        List<Record> records = new ArrayList<>(data.size());
        for (KeyValue kv : data) {
            records.add(new Record(Bytes.from_array(kv.key), Bytes.from_array(kv.value)));
        }
        TableManager tableManager = (TableManager) server.getManager().getTableSpaceManager(tableSpace).getTableManager(table);
        tableManager.writeFromDump(records);
        long _stop = System.currentTimeMillis();
        LOGGER.log(Level.INFO, "Time restore " + data.size() + " records: data " + (_stop - _start) + " ms");
        _channel.sendReplyMessage(message, Message.ACK(null));
    } catch (StatementExecutionException 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) KeyValue(herddb.network.KeyValue) Message(herddb.network.Message) ArrayList(java.util.ArrayList) TableManager(herddb.core.TableManager) List(java.util.List) TuplesList(herddb.utils.TuplesList) ArrayList(java.util.ArrayList) Record(herddb.model.Record) StatementExecutionException(herddb.model.StatementExecutionException)

Example 8 with NotLeaderException

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

the class ServerSideConnectionPeer method handleExecuteStatement.

private void handleExecuteStatement(Pdu message, Channel channel) {
    long txId = PduCodec.ExecuteStatement.readTx(message);
    String tablespace = PduCodec.ExecuteStatement.readTablespace(message);
    long statementId = PduCodec.ExecuteStatement.readStatementId(message);
    String query = statementId > 0 ? preparedStatements.resolveQuery(tablespace, statementId) : PduCodec.ExecuteStatement.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.ExecuteStatement.readReturnValues(message);
    PduCodec.ObjectListReader parametersReader = PduCodec.ExecuteStatement.startReadParameters(message);
    List<Object> parameters = new ArrayList<>(parametersReader.getNumParams());
    for (int i = 0; i < parametersReader.getNumParams(); i++) {
        parameters.add(parametersReader.nextObject());
    }
    if (LOGGER.isLoggable(Level.FINEST)) {
        LOGGER.log(Level.FINEST, "query {0} with {1}", new Object[] { query, parameters });
    }
    RunningStatementInfo statementInfo = new RunningStatementInfo(query, System.currentTimeMillis(), tablespace, "", 1);
    TransactionContext transactionContext = new TransactionContext(txId);
    TranslatedQuery translatedQuery;
    try {
        translatedQuery = server.getManager().getPlanner().translate(tablespace, query, parameters, false, true, returnValues, -1);
    } catch (StatementExecutionException ex) {
        ByteBuf error = composeErrorResponse(message.messageId, ex);
        channel.sendReplyMessage(message.messageId, error);
        message.close();
        return;
    }
    Statement statement = translatedQuery.plan.mainStatement;
    // LOGGER.log(Level.SEVERE, "query " + query + ", " + parameters + ", plan: " + translatedQuery.plan);
    RunningStatementsStats runningStatements = server.getManager().getRunningStatements();
    runningStatements.registerRunningStatement(statementInfo);
    CompletableFuture<StatementExecutionResult> res = server.getManager().executePlanAsync(translatedQuery.plan, translatedQuery.context, transactionContext);
    // LOGGER.log(Level.SEVERE, "query " + query + ", " + parameters + ", result:" + result);
    res.whenComplete((result, err) -> {
        try {
            runningStatements.unregisterRunningStatement(statementInfo);
            if (err != null) {
                while (err instanceof CompletionException) {
                    err = err.getCause();
                }
                if (err instanceof DuplicatePrimaryKeyException) {
                    ByteBuf error = PduCodec.ErrorResponse.writeSqlIntegrityConstraintsViolation(message.messageId, new SQLIntegrityConstraintViolationException(err));
                    channel.sendReplyMessage(message.messageId, error);
                } else 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 query " + query + ", parameters: " + parameters + ":" + err, err);
                    ByteBuf error = composeErrorResponse(message.messageId, err);
                    channel.sendReplyMessage(message.messageId, error);
                }
                return;
            }
            if (result instanceof DMLStatementExecutionResult) {
                DMLStatementExecutionResult dml = (DMLStatementExecutionResult) result;
                Map<String, Object> newRecord = null;
                if (returnValues && dml.getKey() != null) {
                    TableAwareStatement tableStatement = statement.unwrap(TableAwareStatement.class);
                    Table table = server.getManager().getTableSpaceManager(statement.getTableSpace()).getTableManager(tableStatement.getTable()).getTable();
                    newRecord = new HashMap<>();
                    Object newKey = RecordSerializer.deserializePrimaryKey(dml.getKey(), table);
                    newRecord.put("_key", newKey);
                    if (dml.getNewvalue() != null) {
                        newRecord.putAll(RecordSerializer.toBean(new Record(dml.getKey(), dml.getNewvalue()), table));
                    }
                }
                channel.sendReplyMessage(message.messageId, PduCodec.ExecuteStatementResult.write(message.messageId, dml.getUpdateCount(), dml.transactionId, newRecord));
            } else if (result instanceof GetResult) {
                GetResult get = (GetResult) result;
                if (!get.found()) {
                    channel.sendReplyMessage(message.messageId, PduCodec.ExecuteStatementResult.write(message.messageId, 0, get.transactionId, null));
                } else {
                    Map<String, Object> record = get.getRecord().toBean(get.getTable());
                    channel.sendReplyMessage(message.messageId, PduCodec.ExecuteStatementResult.write(message.messageId, 1, get.transactionId, record));
                }
            } else if (result instanceof TransactionResult) {
                TransactionResult txresult = (TransactionResult) result;
                channel.sendReplyMessage(message.messageId, PduCodec.ExecuteStatementResult.write(message.messageId, 1, txresult.getTransactionId(), null));
            } else if (result instanceof DDLStatementExecutionResult) {
                DDLStatementExecutionResult ddl = (DDLStatementExecutionResult) result;
                channel.sendReplyMessage(message.messageId, PduCodec.ExecuteStatementResult.write(message.messageId, 1, ddl.transactionId, null));
            } else if (result instanceof DataConsistencyStatementResult) {
                channel.sendReplyMessage(message.messageId, PduCodec.ExecuteStatementResult.write(message.messageId, 0, 0, null));
            } 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) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) ArrayList(java.util.ArrayList) DataConsistencyStatementResult(herddb.model.DataConsistencyStatementResult) RawString(herddb.utils.RawString) ByteBuf(io.netty.buffer.ByteBuf) RunningStatementInfo(herddb.core.RunningStatementInfo) StatementExecutionException(herddb.model.StatementExecutionException) DDLStatementExecutionResult(herddb.model.DDLStatementExecutionResult) DMLStatementExecutionResult(herddb.model.DMLStatementExecutionResult) StatementExecutionResult(herddb.model.StatementExecutionResult) DuplicatePrimaryKeyException(herddb.model.DuplicatePrimaryKeyException) Record(herddb.model.Record) RunningStatementsStats(herddb.core.RunningStatementsStats) TransactionResult(herddb.model.TransactionResult) TranslatedQuery(herddb.sql.TranslatedQuery) Table(herddb.model.Table) GetResult(herddb.model.GetResult) 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) CompletionException(java.util.concurrent.CompletionException) SQLIntegrityConstraintViolationException(java.sql.SQLIntegrityConstraintViolationException) Map(java.util.Map) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) ConcurrentMap(java.util.concurrent.ConcurrentMap)

Example 9 with NotLeaderException

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

the class DBManager method executeStatementAsync.

public CompletableFuture<StatementExecutionResult> executeStatementAsync(Statement statement, StatementEvaluationContext context, TransactionContext transactionContext) {
    context.setDefaultTablespace(statement.getTableSpace());
    context.setManager(this);
    context.setTransactionContext(transactionContext);
    // LOGGER.log(Level.SEVERE, "executeStatement {0}", new Object[]{statement});
    String tableSpace = statement.getTableSpace();
    if (tableSpace == null) {
        return Futures.exception(new StatementExecutionException("invalid null tableSpace"));
    }
    if (statement instanceof CreateTableSpaceStatement) {
        if (transactionContext.transactionId > 0) {
            return Futures.exception(new StatementExecutionException("CREATE TABLESPACE cannot be issued inside a transaction"));
        }
        return CompletableFuture.completedFuture(createTableSpace((CreateTableSpaceStatement) statement));
    }
    if (statement instanceof AlterTableSpaceStatement) {
        if (transactionContext.transactionId > 0) {
            return Futures.exception(new StatementExecutionException("ALTER TABLESPACE cannot be issued inside a transaction"));
        }
        return CompletableFuture.completedFuture(alterTableSpace((AlterTableSpaceStatement) statement));
    }
    if (statement instanceof DropTableSpaceStatement) {
        if (transactionContext.transactionId > 0) {
            return Futures.exception(new StatementExecutionException("DROP TABLESPACE cannot be issued inside a transaction"));
        }
        return CompletableFuture.completedFuture(dropTableSpace((DropTableSpaceStatement) statement));
    }
    if (statement instanceof TableSpaceConsistencyCheckStatement) {
        if (transactionContext.transactionId > 0) {
            return Futures.exception(new StatementExecutionException("TABLESPACECONSISTENCYCHECK cannot be issue inside a transaction"));
        }
        return CompletableFuture.completedFuture(createTableSpaceCheckSum((TableSpaceConsistencyCheckStatement) statement));
    }
    TableSpaceManager manager = tablesSpaces.get(tableSpace);
    if (manager == null) {
        return Futures.exception(new NotLeaderException("No such tableSpace " + tableSpace + " here (at " + nodeId + "). " + "Maybe the server is starting "));
    }
    if (errorIfNotLeader && !manager.isLeader()) {
        return Futures.exception(new NotLeaderException("node " + nodeId + " is not leader for tableSpace " + tableSpace));
    }
    CompletableFuture<StatementExecutionResult> res = manager.executeStatementAsync(statement, context, transactionContext);
    if (statement instanceof DDLStatement) {
        res.whenComplete((s, err) -> {
            planner.clearCache();
        });
        planner.clearCache();
    }
    // });
    return res;
}
Also used : CreateTableSpaceStatement(herddb.model.commands.CreateTableSpaceStatement) DropTableSpaceStatement(herddb.model.commands.DropTableSpaceStatement) AlterTableSpaceStatement(herddb.model.commands.AlterTableSpaceStatement) TableSpaceConsistencyCheckStatement(herddb.model.commands.TableSpaceConsistencyCheckStatement) NotLeaderException(herddb.model.NotLeaderException) DDLStatement(herddb.model.DDLStatement) DDLStatementExecutionResult(herddb.model.DDLStatementExecutionResult) DMLStatementExecutionResult(herddb.model.DMLStatementExecutionResult) StatementExecutionResult(herddb.model.StatementExecutionResult) StatementExecutionException(herddb.model.StatementExecutionException)

Aggregations

NotLeaderException (herddb.model.NotLeaderException)9 StatementExecutionException (herddb.model.StatementExecutionException)9 Message (herddb.network.Message)6 ArrayList (java.util.ArrayList)6 DDLStatementExecutionResult (herddb.model.DDLStatementExecutionResult)5 DMLStatementExecutionResult (herddb.model.DMLStatementExecutionResult)5 DuplicatePrimaryKeyException (herddb.model.DuplicatePrimaryKeyException)5 StatementExecutionResult (herddb.model.StatementExecutionResult)5 TransactionContext (herddb.model.TransactionContext)5 SQLPlannedOperationStatement (herddb.model.commands.SQLPlannedOperationStatement)5 ScanStatement (herddb.model.commands.ScanStatement)5 TuplesList (herddb.utils.TuplesList)5 List (java.util.List)5 HerdDBInternalException (herddb.core.HerdDBInternalException)4 DataScannerException (herddb.model.DataScannerException)4 Record (herddb.model.Record)4 Statement (herddb.model.Statement)4 Table (herddb.model.Table)4 TableAwareStatement (herddb.model.TableAwareStatement)4 RollbackTransactionStatement (herddb.model.commands.RollbackTransactionStatement)4