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);
}
}
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);
}
}
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();
}
});
}
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;
}
Aggregations