Search in sources :

Example 6 with HDBException

use of herddb.client.HDBException 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 7 with HDBException

use of herddb.client.HDBException in project herddb by diennea.

the class ServerSideConnectionPeer method beginTransaction.

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

Example 8 with HDBException

use of herddb.client.HDBException in project herddb by diennea.

the class ServerSideConnectionPeer method executeUpdates.

public List<DMLResult> executeUpdates(String tableSpace, String query, long transactionId, boolean returnValues, List<List<Object>> originalBatch) throws HDBException {
    if (query == null) {
        throw new HDBException("bad query null");
    }
    List<List<Object>> batch = new ArrayList<>(originalBatch.size());
    for (int i = 0; i < originalBatch.size(); i++) {
        batch.add(PduCodec.normalizeParametersList(originalBatch.get(i)));
    }
    try {
        List<TranslatedQuery> queries = new ArrayList<>();
        for (int i = 0; i < batch.size(); 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<RawString, Object>> otherDatas = new CopyOnWriteArrayList<>();
        CompletableFuture<Long> finalResult = new CompletableFuture<>();
        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) {
                    finalResult.completeExceptionally(error);
                    return;
                }
                if (result instanceof DMLStatementExecutionResult) {
                    DMLStatementExecutionResult dml = (DMLStatementExecutionResult) result;
                    final Map<RawString, Object> otherData;
                    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(RAWSTRING_KEY, key);
                        if (dml.getNewvalue() != null) {
                            Map<String, Object> newvalue = RecordSerializer.toBean(new Record(dml.getKey(), dml.getNewvalue()), table);
                            newvalue.forEach((k, v) -> {
                                otherData.put(RawString.of(k), v);
                            });
                        }
                    } else {
                        otherData = Collections.emptyMap();
                    }
                    updateCounts.add((long) dml.getUpdateCount());
                    otherDatas.add(otherData);
                } else if (result instanceof DDLStatementExecutionResult) {
                    Map<RawString, Object> otherData = Collections.emptyMap();
                    updateCounts.add(1L);
                    otherDatas.add(otherData);
                } else {
                    finalResult.completeExceptionally(new Exception("bad result type " + result.getClass() + " (" + result + ")"));
                    return;
                }
                long newTransactionId = result.transactionId;
                if (current == queries.size()) {
                    try {
                        finalResult.complete(newTransactionId);
                    } catch (Throwable t) {
                        finalResult.completeExceptionally(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));
        long finalTransactionId = finalResult.get();
        List<DMLResult> returnedValues = new ArrayList<>();
        for (int i = 0; i < updateCounts.size(); i++) {
            returnedValues.add(new DMLResult(updateCounts.get(i), otherDatas.get(i).get(RAWSTRING_KEY), otherDatas.get(i), finalTransactionId));
        }
        return returnedValues;
    } catch (HerdDBInternalException err) {
        throw new HDBException(err);
    } catch (InterruptedException err) {
        Thread.currentThread().interrupt();
        throw new HDBException(err);
    } catch (ExecutionException err) {
        throw new HDBException(err.getCause());
    }
}
Also used : HerdDBInternalException(herddb.core.HerdDBInternalException) RawString(herddb.utils.RawString) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) ArrayList(java.util.ArrayList) RawString(herddb.utils.RawString) HDBException(herddb.client.HDBException) CompletableFuture(java.util.concurrent.CompletableFuture) DMLResult(herddb.client.DMLResult) 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) StatementExecutionException(herddb.model.StatementExecutionException) ExecutionException(java.util.concurrent.ExecutionException) 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) TableAwareStatement(herddb.model.TableAwareStatement) HDBException(herddb.client.HDBException) DuplicatePrimaryKeyException(herddb.model.DuplicatePrimaryKeyException) HerdDBInternalException(herddb.core.HerdDBInternalException) StatementExecutionException(herddb.model.StatementExecutionException) CompletionException(java.util.concurrent.CompletionException) EOFException(java.io.EOFException) ValidationException(org.apache.calcite.tools.ValidationException) NotLeaderException(herddb.model.NotLeaderException) DataScannerException(herddb.model.DataScannerException) SQLIntegrityConstraintViolationException(java.sql.SQLIntegrityConstraintViolationException) SQLException(java.sql.SQLException) ExecutionException(java.util.concurrent.ExecutionException) 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 HDBException

use of herddb.client.HDBException in project herddb by diennea.

the class ServerSideConnectionPeer method executeGet.

/**
 * This method is like {@link #handleExecuteStatement(herddb.proto.Pdu, herddb.network.Channel) } but in "local" mode,
 * we do not want here to marshal/unmarshal values, in order to save resources
 */
public herddb.client.GetResult executeGet(String tablespace, String query, long txId, List<Object> parameters) throws HDBException {
    // ensure we are dealing with the same data types that we see when the request id coming from the wire
    parameters = PduCodec.normalizeParametersList(parameters);
    TransactionContext transactionContext = new TransactionContext(txId);
    TranslatedQuery translatedQuery;
    try {
        translatedQuery = server.getManager().getPlanner().translate(tablespace, query, parameters, false, true, true, -1);
        Statement statement = translatedQuery.plan.mainStatement;
        CompletableFuture<StatementExecutionResult> res = server.getManager().executePlanAsync(translatedQuery.plan, translatedQuery.context, transactionContext);
        CompletableFuture<herddb.client.GetResult> finalResult = res.handle((result, err) -> {
            if (err != null) {
                while (err instanceof CompletionException) {
                    err = err.getCause();
                }
                if (err instanceof DuplicatePrimaryKeyException) {
                    throw new CompletionException(new SQLIntegrityConstraintViolationException(err));
                } else {
                    throw new CompletionException(new SQLException(err));
                }
            }
            if (result instanceof GetResult) {
                GetResult get = (GetResult) result;
                if (!get.found()) {
                    return new herddb.client.GetResult(null, get.transactionId);
                } else {
                    Map<String, Object> record = get.getRecord().toBean(get.getTable());
                    Map<RawString, Object> recordForClient = new HashMap<>(record.size());
                    record.forEach((k, v) -> {
                        recordForClient.put(RawString.of(k), v);
                    });
                    return new herddb.client.GetResult(recordForClient, get.transactionId);
                }
            } else {
                throw new CompletionException(new SQLException("Unknown result type " + result.getClass() + ": " + result));
            }
        });
        return finalResult.get();
    } catch (Throwable err) {
        while (err instanceof CompletionException) {
            err = err.getCause();
        }
        throw new HDBException(err);
    }
}
Also used : TranslatedQuery(herddb.sql.TranslatedQuery) GetResult(herddb.model.GetResult) RawString(herddb.utils.RawString) SQLException(java.sql.SQLException) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) 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) RawString(herddb.utils.RawString) HDBException(herddb.client.HDBException) TransactionContext(herddb.model.TransactionContext) CompletionException(java.util.concurrent.CompletionException) SQLIntegrityConstraintViolationException(java.sql.SQLIntegrityConstraintViolationException) DDLStatementExecutionResult(herddb.model.DDLStatementExecutionResult) DMLStatementExecutionResult(herddb.model.DMLStatementExecutionResult) StatementExecutionResult(herddb.model.StatementExecutionResult) DuplicatePrimaryKeyException(herddb.model.DuplicatePrimaryKeyException)

Example 10 with HDBException

use of herddb.client.HDBException in project herddb by diennea.

the class ServerSideConnectionPeer method rollbackTransaction.

public void rollbackTransaction(String tableSpace, long txId) throws HDBException {
    try {
        RollbackTransactionStatement statement = new RollbackTransactionStatement(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) TransactionContext(herddb.model.TransactionContext) RollbackTransactionStatement(herddb.model.commands.RollbackTransactionStatement) HDBException(herddb.client.HDBException)

Aggregations

HDBException (herddb.client.HDBException)14 TransactionContext (herddb.model.TransactionContext)8 ClientSideMetadataProviderException (herddb.client.ClientSideMetadataProviderException)6 DMLResult (herddb.client.DMLResult)5 HerdDBInternalException (herddb.core.HerdDBInternalException)5 BeginTransactionStatement (herddb.model.commands.BeginTransactionStatement)5 CommitTransactionStatement (herddb.model.commands.CommitTransactionStatement)5 RollbackTransactionStatement (herddb.model.commands.RollbackTransactionStatement)5 SQLPlannedOperationStatement (herddb.model.commands.SQLPlannedOperationStatement)5 ScanStatement (herddb.model.commands.ScanStatement)5 TranslatedQuery (herddb.sql.TranslatedQuery)5 DDLStatementExecutionResult (herddb.model.DDLStatementExecutionResult)4 Statement (herddb.model.Statement)4 StatementExecutionResult (herddb.model.StatementExecutionResult)4 TableAwareStatement (herddb.model.TableAwareStatement)4 SQLException (java.sql.SQLException)4 HashMap (java.util.HashMap)4 CompletionException (java.util.concurrent.CompletionException)4 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)4 DMLStatementExecutionResult (herddb.model.DMLStatementExecutionResult)3