Search in sources :

Example 36 with StatementExecutionResult

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

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

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

the class TableManager method executeDeleteAsync.

private CompletableFuture<StatementExecutionResult> executeDeleteAsync(DeleteStatement delete, Transaction transaction, StatementEvaluationContext context) {
    AtomicInteger updateCount = new AtomicInteger();
    Holder<Bytes> lastKey = new Holder<>();
    Holder<Bytes> lastValue = new Holder<>();
    long transactionId = transaction != null ? transaction.transactionId : 0;
    Predicate predicate = delete.getPredicate();
    List<CompletableFuture<PendingLogEntryWork>> writes = new ArrayList<>();
    Map<String, AbstractIndexManager> indexes = tableSpaceManager.getIndexesOnTable(table.name);
    ScanStatement scan = new ScanStatement(table.tablespace, table, predicate);
    try {
        accessTableData(scan, context, new ScanResultOperation() {

            @Override
            public void accept(Record current, LockHandle lockHandle) throws StatementExecutionException, LogNotAvailableException, DataStorageManagerException {
                // ensure we are holding the write locks on every unique index
                List<UniqueIndexLockReference> uniqueIndexes = null;
                try {
                    if (indexes != null || childrenTables != null) {
                        DataAccessor dataAccessor = current.getDataAccessor(table);
                        if (childrenTables != null) {
                            for (Table childTable : childrenTables) {
                                executeForeignKeyConstraintsAsParentTable(childTable, dataAccessor, context, transaction, true);
                            }
                        }
                        if (indexes != null) {
                            for (AbstractIndexManager index : indexes.values()) {
                                if (index.isUnique()) {
                                    Bytes indexKey = RecordSerializer.serializeIndexKey(dataAccessor, index.getIndex(), index.getColumnNames());
                                    if (uniqueIndexes == null) {
                                        uniqueIndexes = new ArrayList<>(1);
                                    }
                                    UniqueIndexLockReference uniqueIndexLock = new UniqueIndexLockReference(index, indexKey);
                                    uniqueIndexes.add(uniqueIndexLock);
                                    LockHandle lockForIndex = lockForWrite(uniqueIndexLock.key, transaction, index.getIndexName(), index.getLockManager());
                                    if (transaction == null) {
                                        uniqueIndexLock.lockHandle = lockForIndex;
                                    }
                                }
                            }
                        }
                    }
                } catch (IllegalArgumentException | herddb.utils.IllegalDataAccessException | StatementExecutionException err) {
                    locksManager.releaseLock(lockHandle);
                    StatementExecutionException finalError;
                    if (!(err instanceof StatementExecutionException)) {
                        finalError = new StatementExecutionException(err.getMessage(), err);
                    } else {
                        finalError = (StatementExecutionException) err;
                    }
                    CompletableFuture<PendingLogEntryWork> res = Futures.exception(finalError);
                    if (uniqueIndexes != null) {
                        for (UniqueIndexLockReference lock : uniqueIndexes) {
                            res = releaseWriteLock(res, lockHandle, lock.indexManager.getLockManager());
                        }
                    }
                    writes.add(res);
                    return;
                }
                LogEntry entry = LogEntryFactory.delete(table, current.key, transaction);
                CommitLogResult pos = log.log(entry, entry.transactionId <= 0);
                final List<UniqueIndexLockReference> _uniqueIndexes = uniqueIndexes;
                writes.add(pos.logSequenceNumber.thenApply(lsn -> new PendingLogEntryWork(entry, pos, lockHandle, _uniqueIndexes)));
                lastKey.value = current.key;
                lastValue.value = current.value;
                updateCount.incrementAndGet();
            }
        }, transaction, true, true);
    } catch (HerdDBInternalException err) {
        LOGGER.log(Level.SEVERE, "bad error during a delete", err);
        return Futures.exception(err);
    }
    if (writes.isEmpty()) {
        return CompletableFuture.completedFuture(new DMLStatementExecutionResult(transactionId, 0, null, null));
    }
    if (writes.size() == 1) {
        return writes.get(0).whenCompleteAsync((pending, error) -> {
            try {
                // apply any of the DML operations
                if (error == null) {
                    apply(pending.pos, pending.entry, false);
                }
            } finally {
                releaseMultiplePendingLogEntryWorks(writes);
            }
        }, tableSpaceManager.getCallbacksExecutor()).thenApply((pending) -> {
            return new DMLStatementExecutionResult(transactionId, updateCount.get(), lastKey.value, delete.isReturnValues() ? lastValue.value : null);
        });
    } else {
        return Futures.collect(writes).whenCompleteAsync((pendings, error) -> {
            try {
                // apply any of the DML operations
                if (error == null) {
                    for (PendingLogEntryWork pending : pendings) {
                        apply(pending.pos, pending.entry, false);
                    }
                }
            } finally {
                releaseMultiplePendingLogEntryWorks(writes);
            }
        }, tableSpaceManager.getCallbacksExecutor()).thenApply((pendings) -> {
            return new DMLStatementExecutionResult(transactionId, updateCount.get(), lastKey.value, delete.isReturnValues() ? lastValue.value : null);
        });
    }
}
Also used : Arrays(java.util.Arrays) NullLockManager(herddb.utils.NullLockManager) Table(herddb.model.Table) TruncateTableStatement(herddb.model.commands.TruncateTableStatement) DuplicatePrimaryKeyException(herddb.model.DuplicatePrimaryKeyException) TableStatus(herddb.storage.TableStatus) Map(java.util.Map) DataAccessor(herddb.utils.DataAccessor) LogNotAvailableException(herddb.log.LogNotAvailableException) CommitLogResult(herddb.log.CommitLogResult) LogSequenceNumber(herddb.log.LogSequenceNumber) UniqueIndexContraintViolationException(herddb.model.UniqueIndexContraintViolationException) Set(java.util.Set) RecordSerializer(herddb.codec.RecordSerializer) JSQLParserPlanner.delimit(herddb.sql.JSQLParserPlanner.delimit) DataPageMetaData(herddb.core.PageSet.DataPageMetaData) ScanStatement(herddb.model.commands.ScanStatement) Stream(java.util.stream.Stream) StatsLogger(org.apache.bookkeeper.stats.StatsLogger) Bytes(herddb.utils.Bytes) Holder(herddb.utils.Holder) LockHandle(herddb.utils.LockHandle) ForeignKeyViolationException(herddb.model.ForeignKeyViolationException) LogEntry(herddb.log.LogEntry) ArrayList(java.util.ArrayList) TransactionContext(herddb.model.TransactionContext) Transaction(herddb.model.Transaction) ThreadLocalRandom(java.util.concurrent.ThreadLocalRandom) Projection(herddb.model.Projection) ForeignKeyDef(herddb.model.ForeignKeyDef) EnsureLongIncrementAccumulator(herddb.utils.EnsureLongIncrementAccumulator) LogEntryType(herddb.log.LogEntryType) Record(herddb.model.Record) LogEntryFactory(herddb.log.LogEntryFactory) KeyToPageIndex(herddb.index.KeyToPageIndex) DataStorageManager(herddb.storage.DataStorageManager) ColumnTypes(herddb.model.ColumnTypes) ILocalLockManager(herddb.utils.ILocalLockManager) AtomicLong(java.util.concurrent.atomic.AtomicLong) Lock(java.util.concurrent.locks.Lock) IndexOperation(herddb.index.IndexOperation) Column(herddb.model.Column) StampedLock(java.util.concurrent.locks.StampedLock) UpdateStatement(herddb.model.commands.UpdateStatement) ScanLimitsImpl(herddb.model.ScanLimitsImpl) TupleComparator(herddb.model.TupleComparator) ServerConfiguration(herddb.server.ServerConfiguration) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) RecordTooBigException(herddb.model.RecordTooBigException) DMLStatementExecutionResult(herddb.model.DMLStatementExecutionResult) LocalLockManager(herddb.utils.LocalLockManager) Futures(herddb.utils.Futures) DataStorageManagerException(herddb.storage.DataStorageManagerException) Index(herddb.model.Index) InsertStatement(herddb.model.commands.InsertStatement) DataScanner(herddb.model.DataScanner) DDLException(herddb.model.DDLException) RecordFunction(herddb.model.RecordFunction) StatementExecutionException(herddb.model.StatementExecutionException) TableContext(herddb.model.TableContext) Collection(java.util.Collection) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Logger(java.util.logging.Logger) Collectors(java.util.stream.Collectors) List(java.util.List) FullTableScanConsumer(herddb.storage.FullTableScanConsumer) GetStatement(herddb.model.commands.GetStatement) Entry(java.util.Map.Entry) Statement(herddb.model.Statement) LongAdder(java.util.concurrent.atomic.LongAdder) DataScannerException(herddb.model.DataScannerException) GetResult(herddb.model.GetResult) PrimaryIndexSeek(herddb.index.PrimaryIndexSeek) HashMap(java.util.HashMap) CompletableFuture(java.util.concurrent.CompletableFuture) Function(java.util.function.Function) BatchOrderedExecutor(herddb.utils.BatchOrderedExecutor) ConcurrentMap(java.util.concurrent.ConcurrentMap) Level(java.util.logging.Level) HashSet(java.util.HashSet) BooleanHolder(herddb.utils.BooleanHolder) ScanLimits(herddb.model.ScanLimits) DeleteStatement(herddb.model.commands.DeleteStatement) Iterator(java.util.Iterator) ReentrantLock(java.util.concurrent.locks.ReentrantLock) Semaphore(java.util.concurrent.Semaphore) DataPageDoesNotExistException(herddb.storage.DataPageDoesNotExistException) Counter(org.apache.bookkeeper.stats.Counter) StatementExecutionResult(herddb.model.StatementExecutionResult) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) CommitLog(herddb.log.CommitLog) AbstractMap(java.util.AbstractMap) TableConsistencyCheckStatement(herddb.model.commands.TableConsistencyCheckStatement) Predicate(herddb.model.Predicate) StatementEvaluationContext(herddb.model.StatementEvaluationContext) Comparator(java.util.Comparator) Collections(java.util.Collections) SECONDS(java.util.concurrent.TimeUnit.SECONDS) TableManagerStats(herddb.core.stats.TableManagerStats) SystemProperties(herddb.utils.SystemProperties) DataStorageManagerException(herddb.storage.DataStorageManagerException) DataAccessor(herddb.utils.DataAccessor) ArrayList(java.util.ArrayList) CommitLogResult(herddb.log.CommitLogResult) StatementExecutionException(herddb.model.StatementExecutionException) Predicate(herddb.model.Predicate) Bytes(herddb.utils.Bytes) CompletableFuture(java.util.concurrent.CompletableFuture) Record(herddb.model.Record) ArrayList(java.util.ArrayList) List(java.util.List) LogEntry(herddb.log.LogEntry) ScanStatement(herddb.model.commands.ScanStatement) LockHandle(herddb.utils.LockHandle) Table(herddb.model.Table) Holder(herddb.utils.Holder) BooleanHolder(herddb.utils.BooleanHolder) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) DMLStatementExecutionResult(herddb.model.DMLStatementExecutionResult) LogNotAvailableException(herddb.log.LogNotAvailableException)

Example 39 with StatementExecutionResult

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

the class TableSpaceManager method executeTableAwareStatement.

private CompletableFuture<StatementExecutionResult> executeTableAwareStatement(Statement statement, Transaction transaction, StatementEvaluationContext context) throws StatementExecutionException {
    long lockStamp = context.getTableSpaceLock();
    boolean lockAcquired = false;
    if (lockStamp == 0) {
        lockStamp = acquireReadLock(statement);
        context.setTableSpaceLock(lockStamp);
        lockAcquired = true;
    }
    TableAwareStatement st = (TableAwareStatement) statement;
    String table = st.getTable();
    AbstractTableManager manager = tables.get(table);
    CompletableFuture<StatementExecutionResult> res;
    if (manager == null) {
        res = Futures.exception(new TableDoesNotExistException("no table " + table + " in tablespace " + tableSpaceName));
    } else if (manager.getCreatedInTransaction() > 0 && (transaction == null || transaction.transactionId != manager.getCreatedInTransaction())) {
        res = Futures.exception(new TableDoesNotExistException("no table " + table + " in tablespace " + tableSpaceName + ". created temporary in transaction " + manager.getCreatedInTransaction()));
    } else {
        res = manager.executeStatementAsync(statement, transaction, context);
    }
    if (lockAcquired) {
        res = releaseReadLock(res, lockStamp, statement).whenComplete((s, err) -> {
            context.setTableSpaceLock(0);
        });
    }
    return res;
}
Also used : TableDoesNotExistException(herddb.model.TableDoesNotExistException) HDBException(herddb.client.HDBException) SystablesTableManager(herddb.core.system.SystablesTableManager) CommitTransactionStatement(herddb.model.commands.CommitTransactionStatement) TableCheckpoint(herddb.core.AbstractTableManager.TableCheckpoint) Table(herddb.model.Table) ClientConfiguration(herddb.client.ClientConfiguration) SyslogstatusManager(herddb.core.system.SyslogstatusManager) OpStatsLogger(org.apache.bookkeeper.stats.OpStatsLogger) IndexAlreadyExistsException(herddb.model.IndexAlreadyExistsException) Map(java.util.Map) DDLStatementExecutionResult(herddb.model.DDLStatementExecutionResult) LogNotAvailableException(herddb.log.LogNotAvailableException) PduCodec(herddb.proto.PduCodec) CommitLogResult(herddb.log.CommitLogResult) ClientSideMetadataProviderException(herddb.client.ClientSideMetadataProviderException) LogSequenceNumber(herddb.log.LogSequenceNumber) Set(java.util.Set) ScanStatement(herddb.model.commands.ScanStatement) CountDownLatch(java.util.concurrent.CountDownLatch) Stream(java.util.stream.Stream) HDBClient(herddb.client.HDBClient) TranslatedQuery(herddb.sql.TranslatedQuery) StatsLogger(org.apache.bookkeeper.stats.StatsLogger) TableDataChecksum(herddb.data.consistency.TableDataChecksum) DropTableStatement(herddb.model.commands.DropTableStatement) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) Bytes(herddb.utils.Bytes) SysdualTableManager(herddb.core.system.SysdualTableManager) LogEntry(herddb.log.LogEntry) SysnodesTableManager(herddb.core.system.SysnodesTableManager) ArrayList(java.util.ArrayList) CreateIndexStatement(herddb.model.commands.CreateIndexStatement) TableSpaceDoesNotExistException(herddb.model.TableSpaceDoesNotExistException) TransactionContext(herddb.model.TransactionContext) Transaction(herddb.model.Transaction) BRINIndexManager(herddb.index.brin.BRINIndexManager) SystablestatsTableManager(herddb.core.system.SystablestatsTableManager) BiConsumer(java.util.function.BiConsumer) CommitLogListener(herddb.log.CommitLogListener) ForeignKeyDef(herddb.model.ForeignKeyDef) IndexDoesNotExistException(herddb.model.IndexDoesNotExistException) TableSpaceManagerStats(herddb.core.stats.TableSpaceManagerStats) LogEntryType(herddb.log.LogEntryType) LogEntryFactory(herddb.log.LogEntryFactory) IOException(java.io.IOException) DataStorageManager(herddb.storage.DataStorageManager) DropIndexStatement(herddb.model.commands.DropIndexStatement) ColumnTypes(herddb.model.ColumnTypes) ExecutionException(java.util.concurrent.ExecutionException) AtomicLong(java.util.concurrent.atomic.AtomicLong) Column(herddb.model.Column) KeyValue(herddb.utils.KeyValue) FullRecoveryNeededException(herddb.log.FullRecoveryNeededException) StampedLock(java.util.concurrent.locks.StampedLock) ServerHostData(herddb.network.ServerHostData) TableAlreadyExistsException(herddb.model.TableAlreadyExistsException) RollbackTransactionStatement(herddb.model.commands.RollbackTransactionStatement) CreateTableStatement(herddb.model.commands.CreateTableStatement) TimeoutException(java.util.concurrent.TimeoutException) JMXUtils(herddb.jmx.JMXUtils) TransactionResult(herddb.model.TransactionResult) MetadataStorageManager(herddb.metadata.MetadataStorageManager) Channel(herddb.network.Channel) ServerConfiguration(herddb.server.ServerConfiguration) Futures(herddb.utils.Futures) DataStorageManagerException(herddb.storage.DataStorageManagerException) Index(herddb.model.Index) TableDoesNotExistException(herddb.model.TableDoesNotExistException) AlterTableStatement(herddb.model.commands.AlterTableStatement) SysindexcolumnsTableManager(herddb.core.system.SysindexcolumnsTableManager) DataScanner(herddb.model.DataScanner) DDLException(herddb.model.DDLException) StatementExecutionException(herddb.model.StatementExecutionException) Collection(java.util.Collection) SysstatementsTableManager(herddb.core.system.SysstatementsTableManager) BeginTransactionStatement(herddb.model.commands.BeginTransactionStatement) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) CompletionException(java.util.concurrent.CompletionException) TableAwareStatement(herddb.model.TableAwareStatement) Logger(java.util.logging.Logger) EOFException(java.io.EOFException) Collectors(java.util.stream.Collectors) Objects(java.util.Objects) HDBConnection(herddb.client.HDBConnection) List(java.util.List) FullTableScanConsumer(herddb.storage.FullTableScanConsumer) SystransactionsTableManager(herddb.core.system.SystransactionsTableManager) NodeMetadata(herddb.model.NodeMetadata) Entry(java.util.Map.Entry) Optional(java.util.Optional) TableSpace(herddb.model.TableSpace) SysconfigTableManager(herddb.core.system.SysconfigTableManager) SuppressFBWarnings(edu.umd.cs.findbugs.annotations.SuppressFBWarnings) SysindexesTableManager(herddb.core.system.SysindexesTableManager) Statement(herddb.model.Statement) MetadataStorageManagerException(herddb.metadata.MetadataStorageManagerException) DataScannerException(herddb.model.DataScannerException) SystablespacesTableManager(herddb.core.system.SystablespacesTableManager) HashMap(java.util.HashMap) CompletableFuture(java.util.concurrent.CompletableFuture) Pdu(herddb.proto.Pdu) Level(java.util.logging.Level) HashSet(java.util.HashSet) SysclientsTableManager(herddb.core.system.SysclientsTableManager) TableChecksum(herddb.data.consistency.TableChecksum) ExecutorService(java.util.concurrent.ExecutorService) DumpedLogEntry(herddb.backup.DumpedLogEntry) SysforeignkeysTableManager(herddb.core.system.SysforeignkeysTableManager) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) StatementExecutionResult(herddb.model.StatementExecutionResult) TimeUnit(java.util.concurrent.TimeUnit) CommitLog(herddb.log.CommitLog) ClientSideMetadataProvider(herddb.client.ClientSideMetadataProvider) ConcurrentSkipListSet(java.util.concurrent.ConcurrentSkipListSet) SystablespacereplicastateTableManager(herddb.core.system.SystablespacereplicastateTableManager) SQLPlannedOperationStatement(herddb.model.commands.SQLPlannedOperationStatement) StatementEvaluationContext(herddb.model.StatementEvaluationContext) SyscolumnsTableManager(herddb.core.system.SyscolumnsTableManager) Comparator(java.util.Comparator) Collections(java.util.Collections) TableManagerStats(herddb.core.stats.TableManagerStats) MemoryHashIndexManager(herddb.index.MemoryHashIndexManager) SystemProperties(herddb.utils.SystemProperties) DDLStatementExecutionResult(herddb.model.DDLStatementExecutionResult) StatementExecutionResult(herddb.model.StatementExecutionResult) TableAwareStatement(herddb.model.TableAwareStatement)

Example 40 with StatementExecutionResult

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

the class TableSpaceManager method beginTransactionAsync.

private CompletableFuture<StatementExecutionResult> beginTransactionAsync(StatementEvaluationContext context, boolean releaseLock) throws StatementExecutionException {
    long id = newTransactionId.incrementAndGet();
    LogEntry entry = LogEntryFactory.beginTransaction(id);
    CommitLogResult pos;
    boolean lockAcquired = false;
    if (context.getTableSpaceLock() == 0) {
        long lockStamp = acquireReadLock("begin transaction");
        context.setTableSpaceLock(lockStamp);
        lockAcquired = true;
    }
    pos = log.log(entry, false);
    CompletableFuture<StatementExecutionResult> res = pos.logSequenceNumber.thenApplyAsync((lsn) -> {
        apply(pos, entry, false);
        return new TransactionResult(id, TransactionResult.OutcomeType.BEGIN);
    }, callbacksExecutor);
    if (lockAcquired && releaseLock) {
        releaseReadLock(res, context.getTableSpaceLock(), "begin transaction");
    }
    return res;
}
Also used : TransactionResult(herddb.model.TransactionResult) DDLStatementExecutionResult(herddb.model.DDLStatementExecutionResult) StatementExecutionResult(herddb.model.StatementExecutionResult) CommitLogResult(herddb.log.CommitLogResult) LogEntry(herddb.log.LogEntry) DumpedLogEntry(herddb.backup.DumpedLogEntry)

Aggregations

StatementExecutionResult (herddb.model.StatementExecutionResult)43 StatementExecutionException (herddb.model.StatementExecutionException)35 TransactionContext (herddb.model.TransactionContext)32 DataScanner (herddb.model.DataScanner)27 Table (herddb.model.Table)26 DataScannerException (herddb.model.DataScannerException)25 DMLStatementExecutionResult (herddb.model.DMLStatementExecutionResult)23 DDLStatementExecutionResult (herddb.model.DDLStatementExecutionResult)20 ArrayList (java.util.ArrayList)20 Statement (herddb.model.Statement)18 ScanStatement (herddb.model.commands.ScanStatement)18 HashMap (java.util.HashMap)18 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)18 RollbackTransactionStatement (herddb.model.commands.RollbackTransactionStatement)17 Bytes (herddb.utils.Bytes)17 AtomicLong (java.util.concurrent.atomic.AtomicLong)17 CommitTransactionStatement (herddb.model.commands.CommitTransactionStatement)16 Map (java.util.Map)16 List (java.util.List)14 Column (herddb.model.Column)12