Search in sources :

Example 6 with ReactiveConnection

use of org.hibernate.reactive.pool.ReactiveConnection in project hibernate-reactive by hibernate.

the class ReactiveAbstractEntityPersister method lockReactive.

@Override
default CompletionStage<Void> lockReactive(Serializable id, Object version, Object object, LockOptions lockOptions, SharedSessionContractImplementor session) throws HibernateException {
    LockMode lockMode = lockOptions.getLockMode();
    Object nextVersion = nextVersionForLock(lockMode, id, version, object, session);
    String sql;
    boolean writeLock;
    switch(lockMode) {
        // 0) noop
        case NONE:
            return voidFuture();
        // 1) select ... for share
        case PESSIMISTIC_READ:
        // 2) select ... for update
        case PESSIMISTIC_WRITE:
        case UPGRADE:
        // 3) select ... for nowait
        case UPGRADE_NOWAIT:
        // 4) select ... for update skip locked
        case UPGRADE_SKIPLOCKED:
            // TODO: introduce separate support for PESSIMISTIC_READ
            // the current implementation puts the version number in
            // the where clause and the id in the select list, whereas
            // it would be better to actually select and check the
            // version number (same problem in hibernate-core)
            sql = generateSelectLockString(lockOptions);
            writeLock = false;
            break;
        // 5) update ... set version
        case PESSIMISTIC_FORCE_INCREMENT:
        case FORCE:
            sql = generateUpdateLockString(lockOptions);
            writeLock = true;
            break;
        // locks obtained in the before completion phase
        case OPTIMISTIC:
        case OPTIMISTIC_FORCE_INCREMENT:
            throw new AssertionFailure("optimistic lock mode is not supported here");
        // other operations
        case READ:
        case WRITE:
            throw new AssertionFailure("implicit lock mode is not supported here");
        default:
            throw new AssertionFailure("illegal lock mode");
    }
    Object[] arguments = PreparedStatementAdaptor.bind(statement -> {
        int offset = 1;
        if (writeLock) {
            getVersionType().nullSafeSet(statement, nextVersion, offset, session);
            offset++;
        }
        getIdentifierType().nullSafeSet(statement, id, offset, session);
        offset += getIdentifierType().getColumnSpan(getFactory());
        if (isVersioned()) {
            getVersionType().nullSafeSet(statement, version, offset, session);
        }
    });
    ReactiveConnection connection = getReactiveConnection(session);
    CompletionStage<Boolean> lock = writeLock ? connection.update(sql, arguments).thenApply(affected -> affected > 0) : connection.select(sql, arguments).thenApply(Iterator::hasNext);
    return lock.thenAccept(rowExisted -> {
        if (!rowExisted) {
            throw new StaleObjectStateException(getEntityName(), id);
        }
    }).handle((r, e) -> {
        logSqlException(e, () -> "could not lock: " + infoString(this, id, getFactory()), sql);
        return returnOrRethrow(e, r);
    });
}
Also used : Arrays(java.util.Arrays) CompletionStages.completedFuture(org.hibernate.reactive.util.impl.CompletionStages.completedFuture) ReactiveDynamicBatchingEntityLoaderBuilder(org.hibernate.reactive.loader.entity.impl.ReactiveDynamicBatchingEntityLoaderBuilder) Expectations.appropriateExpectation(org.hibernate.jdbc.Expectations.appropriateExpectation) EventSource(org.hibernate.event.spi.EventSource) Log(org.hibernate.reactive.logging.impl.Log) PersistenceContext(org.hibernate.engine.spi.PersistenceContext) LoggerFactory(org.hibernate.reactive.logging.impl.LoggerFactory) ReactiveConnectionSupplier(org.hibernate.reactive.session.ReactiveConnectionSupplier) NonIdentifierAttribute(org.hibernate.tuple.NonIdentifierAttribute) PersistentCollection(org.hibernate.collection.spi.PersistentCollection) JDBCException(org.hibernate.JDBCException) PersistentAttributeInterceptor(org.hibernate.engine.spi.PersistentAttributeInterceptor) ResultSet(java.sql.ResultSet) SessionFactoryImpl(org.hibernate.internal.SessionFactoryImpl) CompletionStages.voidFuture(org.hibernate.reactive.util.impl.CompletionStages.voidFuture) SessionFactoryImplementor(org.hibernate.engine.spi.SessionFactoryImplementor) Mutiny(org.hibernate.reactive.mutiny.Mutiny) LockOptions(org.hibernate.LockOptions) Attribute(javax.persistence.metamodel.Attribute) PersistentAttributeInterceptable(org.hibernate.engine.spi.PersistentAttributeInterceptable) MethodHandles(java.lang.invoke.MethodHandles) StaleObjectStateException(org.hibernate.StaleObjectStateException) LazyAttributeDescriptor(org.hibernate.bytecode.enhance.spi.interceptor.LazyAttributeDescriptor) Set(java.util.Set) ReactiveEntityLoader(org.hibernate.reactive.loader.entity.impl.ReactiveEntityLoader) MutinyValueGenerator(org.hibernate.reactive.tuple.MutinyValueGenerator) PreparedStatement(java.sql.PreparedStatement) Serializable(java.io.Serializable) LoadQueryInfluencers(org.hibernate.engine.spi.LoadQueryInfluencers) ArrayHelper(org.hibernate.internal.util.collections.ArrayHelper) Lockable(org.hibernate.persister.entity.Lockable) MessageHelper.infoString(org.hibernate.pretty.MessageHelper.infoString) List(java.util.List) CompletionStage(java.util.concurrent.CompletionStage) Expectation(org.hibernate.jdbc.Expectation) Dialect(org.hibernate.dialect.Dialect) CompletionStages.loop(org.hibernate.reactive.util.impl.CompletionStages.loop) AbstractEntityPersister(org.hibernate.persister.entity.AbstractEntityPersister) SessionImplementor(org.hibernate.engine.spi.SessionImplementor) Update(org.hibernate.sql.Update) HibernateException(org.hibernate.HibernateException) PreparedStatementAdaptor(org.hibernate.reactive.adaptor.impl.PreparedStatementAdaptor) SharedSessionContractImplementor(org.hibernate.engine.spi.SharedSessionContractImplementor) AbstractEntityPersister.determineValueNullness(org.hibernate.persister.entity.AbstractEntityPersister.determineValueNullness) OptimisticLockStyle(org.hibernate.engine.OptimisticLockStyle) AssertionFailure(org.hibernate.AssertionFailure) CompletionStages.logSqlException(org.hibernate.reactive.util.impl.CompletionStages.logSqlException) Session(org.hibernate.Session) StageSessionFactoryImpl(org.hibernate.reactive.stage.impl.StageSessionFactoryImpl) InMemoryValueGenerationStrategy(org.hibernate.tuple.InMemoryValueGenerationStrategy) EntityType(org.hibernate.type.EntityType) UniqueEntityLoader(org.hibernate.loader.entity.UniqueEntityLoader) MultiLoadOptions(org.hibernate.persister.entity.MultiLoadOptions) SQLException(java.sql.SQLException) PreparedStatementAdaptor.bind(org.hibernate.reactive.adaptor.impl.PreparedStatementAdaptor.bind) StageValueGenerator(org.hibernate.reactive.tuple.StageValueGenerator) ArrayHelper.trim(org.hibernate.internal.util.collections.ArrayHelper.trim) StageSessionImpl(org.hibernate.reactive.stage.impl.StageSessionImpl) ReactiveSession(org.hibernate.reactive.session.ReactiveSession) ArrayHelper.join(org.hibernate.internal.util.collections.ArrayHelper.join) MutinySessionFactoryImpl(org.hibernate.reactive.mutiny.impl.MutinySessionFactoryImpl) LockMode(org.hibernate.LockMode) Iterator(java.util.Iterator) Parameters(org.hibernate.reactive.pool.impl.Parameters) Versioning(org.hibernate.engine.internal.Versioning) SimpleSelect(org.hibernate.sql.SimpleSelect) MutinySessionImpl(org.hibernate.reactive.mutiny.impl.MutinySessionImpl) ValueGenerator(org.hibernate.tuple.ValueGenerator) CompletionStages.returnOrRethrow(org.hibernate.reactive.util.impl.CompletionStages.returnOrRethrow) EntityKey(org.hibernate.engine.spi.EntityKey) Delete(org.hibernate.sql.Delete) IdentifierGeneration.castToIdentifierType(org.hibernate.reactive.id.impl.IdentifierGeneration.castToIdentifierType) AbstractEntityPersister.isValueGenerationRequired(org.hibernate.persister.entity.AbstractEntityPersister.isValueGenerationRequired) Stage(org.hibernate.reactive.stage.Stage) GenerationTiming(org.hibernate.tuple.GenerationTiming) VERSION_COLUMN_ALIAS(org.hibernate.persister.entity.AbstractEntityPersister.VERSION_COLUMN_ALIAS) OuterJoinLoadable(org.hibernate.persister.entity.OuterJoinLoadable) VersionType(org.hibernate.type.VersionType) EntityEntry(org.hibernate.engine.spi.EntityEntry) Type(org.hibernate.type.Type) ReactiveConnection(org.hibernate.reactive.pool.ReactiveConnection) AssertionFailure(org.hibernate.AssertionFailure) ReactiveConnection(org.hibernate.reactive.pool.ReactiveConnection) LockMode(org.hibernate.LockMode) MessageHelper.infoString(org.hibernate.pretty.MessageHelper.infoString) StaleObjectStateException(org.hibernate.StaleObjectStateException)

Example 7 with ReactiveConnection

use of org.hibernate.reactive.pool.ReactiveConnection in project hibernate-reactive by hibernate.

the class ReactiveAbstractCollectionPersister method reactiveInsertRows.

/**
 * @see org.hibernate.persister.collection.AbstractCollectionPersister#insertRows(PersistentCollection, Serializable, SharedSessionContractImplementor)
 */
@Override
default CompletionStage<Void> reactiveInsertRows(PersistentCollection collection, Serializable id, SharedSessionContractImplementor session) {
    if (isInverse() || !isRowDeleteEnabled()) {
        return voidFuture();
    }
    if (LOG.isDebugEnabled()) {
        LOG.debugf("Inserting rows of collection: %s", collectionInfoString(this, collection, id, session));
    }
    ReactiveConnection connection = getReactiveConnection(session);
    // TODO: compose() reactive version of collection.preInsert()
    List<Object> entries = entryList(collection);
    if (!needsInsert(collection, entries)) {
        return voidFuture();
    }
    Expectation expectation = appropriateExpectation(getInsertCheckStyle());
    return loop(entries.iterator(), (entry, index) -> collection.needsInserting(entry, index, getElementType()), (entry, index) -> connection.update(getSQLInsertRowString(), insertRowsParamValues(entry, index, collection, id, session), expectation.canBeBatched(), new ExpectationAdaptor(expectation, getSQLInsertRowString(), getSqlExceptionConverter()))).thenAccept(total -> LOG.debugf("Done inserting rows: %s inserted", total));
}
Also used : Iterator(java.util.Iterator) MethodHandles(java.lang.invoke.MethodHandles) Expectations.appropriateExpectation(org.hibernate.jdbc.Expectations.appropriateExpectation) Log(org.hibernate.reactive.logging.impl.Log) PreparedStatement(java.sql.PreparedStatement) LoggerFactory(org.hibernate.reactive.logging.impl.LoggerFactory) ReactiveConnectionSupplier(org.hibernate.reactive.session.ReactiveConnectionSupplier) Serializable(java.io.Serializable) ArrayList(java.util.ArrayList) SQLExceptionConverter(org.hibernate.exception.spi.SQLExceptionConverter) PersistentCollection(org.hibernate.collection.spi.PersistentCollection) SQLException(java.sql.SQLException) List(java.util.List) CompletionStage(java.util.concurrent.CompletionStage) Expectation(org.hibernate.jdbc.Expectation) ExecuteUpdateResultCheckStyle(org.hibernate.engine.spi.ExecuteUpdateResultCheckStyle) CompletionStages.loop(org.hibernate.reactive.util.impl.CompletionStages.loop) HibernateException(org.hibernate.HibernateException) CompletionStages.voidFuture(org.hibernate.reactive.util.impl.CompletionStages.voidFuture) PreparedStatementAdaptor(org.hibernate.reactive.adaptor.impl.PreparedStatementAdaptor) SharedSessionContractImplementor(org.hibernate.engine.spi.SharedSessionContractImplementor) ReactiveConnection(org.hibernate.reactive.pool.ReactiveConnection) MessageHelper.collectionInfoString(org.hibernate.pretty.MessageHelper.collectionInfoString) ReactiveConnection(org.hibernate.reactive.pool.ReactiveConnection) Expectations.appropriateExpectation(org.hibernate.jdbc.Expectations.appropriateExpectation) Expectation(org.hibernate.jdbc.Expectation)

Example 8 with ReactiveConnection

use of org.hibernate.reactive.pool.ReactiveConnection in project hibernate-reactive by hibernate.

the class ReactiveBulkIdStrategy method release.

@Override
public void release(JdbcServices jdbcServices, JdbcConnectionAccess connectionAccess) {
    if (serviceRegistry != null && !dropGlobalTemporaryTables.isEmpty()) {
        boolean dropIdTables = serviceRegistry.getService(ConfigurationService.class).getSetting(GlobalTemporaryTableBulkIdStrategy.DROP_ID_TABLES, StandardConverters.BOOLEAN, false);
        if (dropIdTables) {
            ReactiveConnection connection = serviceRegistry.getService(ReactiveConnectionPool.class).getProxyConnection();
            loop(dropGlobalTemporaryTables, connection::execute).whenComplete((v, e) -> connection.close()).handle(CompletionStages::ignoreErrors).toCompletableFuture().join();
        }
    }
}
Also used : ReactiveConnectionPool(org.hibernate.reactive.pool.ReactiveConnectionPool) MetadataBuildingOptions(org.hibernate.boot.spi.MetadataBuildingOptions) StandardConverters(org.hibernate.engine.config.spi.StandardConverters) ParameterSpecification(org.hibernate.param.ParameterSpecification) MultiTableBulkIdStrategy(org.hibernate.hql.spi.id.MultiTableBulkIdStrategy) IdTableInfo(org.hibernate.hql.spi.id.IdTableInfo) GlobalTemporaryTableBulkIdStrategy(org.hibernate.hql.spi.id.global.GlobalTemporaryTableBulkIdStrategy) PersistentClass(org.hibernate.mapping.PersistentClass) AbstractTableBasedBulkIdHandler(org.hibernate.hql.spi.id.AbstractTableBasedBulkIdHandler) StatementsWithParameters(org.hibernate.reactive.bulk.StatementsWithParameters) SessionFactoryImplementor(org.hibernate.engine.spi.SessionFactoryImplementor) StandardServiceRegistry(org.hibernate.boot.registry.StandardServiceRegistry) AssignmentSpecification(org.hibernate.hql.internal.ast.tree.AssignmentSpecification) Set(java.util.Set) Collectors(java.util.stream.Collectors) DB297Dialect(org.hibernate.dialect.DB297Dialect) ArrayHelper(org.hibernate.internal.util.collections.ArrayHelper) List(java.util.List) CompletionStage(java.util.concurrent.CompletionStage) Dialect(org.hibernate.dialect.Dialect) UpdateStatement(org.hibernate.hql.internal.ast.tree.UpdateStatement) CompletionStages.loop(org.hibernate.reactive.util.impl.CompletionStages.loop) Update(org.hibernate.sql.Update) SharedSessionContractImplementor(org.hibernate.engine.spi.SharedSessionContractImplementor) CompletionStages(org.hibernate.reactive.util.impl.CompletionStages) JdbcConnectionAccess(org.hibernate.engine.jdbc.connections.spi.JdbcConnectionAccess) CoreMessageLogger(org.hibernate.internal.CoreMessageLogger) SqlStringGenerationContext(org.hibernate.boot.model.relational.SqlStringGenerationContext) Queryable(org.hibernate.persister.entity.Queryable) CollectionType(org.hibernate.type.CollectionType) SessionFactoryOptions(org.hibernate.boot.spi.SessionFactoryOptions) ReactiveConnectionPool(org.hibernate.reactive.pool.ReactiveConnectionPool) FromElement(org.hibernate.hql.internal.ast.tree.FromElement) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) AbstractCollectionPersister(org.hibernate.persister.collection.AbstractCollectionPersister) MetadataImplementor(org.hibernate.boot.spi.MetadataImplementor) DeleteStatement(org.hibernate.hql.internal.ast.tree.DeleteStatement) ConfigurationService(org.hibernate.engine.config.spi.ConfigurationService) AbstractMultiTableBulkIdStrategyImpl(org.hibernate.hql.spi.id.AbstractMultiTableBulkIdStrategyImpl) QueryParameters(org.hibernate.engine.spi.QueryParameters) Parameters(org.hibernate.reactive.pool.impl.Parameters) JdbcServices(org.hibernate.engine.jdbc.spi.JdbcServices) ReactiveQueryExecutor(org.hibernate.reactive.session.ReactiveQueryExecutor) Delete(org.hibernate.sql.Delete) Table(org.hibernate.mapping.Table) IdTableInfoImpl(org.hibernate.hql.spi.id.local.IdTableInfoImpl) AbstractRestrictableStatement(org.hibernate.hql.internal.ast.tree.AbstractRestrictableStatement) HqlSqlWalker(org.hibernate.hql.internal.ast.HqlSqlWalker) Collections(java.util.Collections) CoreLogging(org.hibernate.internal.CoreLogging) Type(org.hibernate.type.Type) ReactiveConnection(org.hibernate.reactive.pool.ReactiveConnection) CompletionStages.zeroFuture(org.hibernate.reactive.util.impl.CompletionStages.zeroFuture) CompletionStages(org.hibernate.reactive.util.impl.CompletionStages) ReactiveConnection(org.hibernate.reactive.pool.ReactiveConnection) ConfigurationService(org.hibernate.engine.config.spi.ConfigurationService)

Aggregations

ReactiveConnection (org.hibernate.reactive.pool.ReactiveConnection)8 CompletionStage (java.util.concurrent.CompletionStage)5 Expectation (org.hibernate.jdbc.Expectation)5 Expectations.appropriateExpectation (org.hibernate.jdbc.Expectations.appropriateExpectation)5 PreparedStatement (java.sql.PreparedStatement)4 SQLException (java.sql.SQLException)4 List (java.util.List)4 Parameters (org.hibernate.reactive.pool.impl.Parameters)4 CompletionStages.voidFuture (org.hibernate.reactive.util.impl.CompletionStages.voidFuture)4 Serializable (java.io.Serializable)3 MethodHandles (java.lang.invoke.MethodHandles)3 ResultSet (java.sql.ResultSet)3 Iterator (java.util.Iterator)3 SharedSessionContractImplementor (org.hibernate.engine.spi.SharedSessionContractImplementor)3 CompletionStages.loop (org.hibernate.reactive.util.impl.CompletionStages.loop)3 ArrayList (java.util.ArrayList)2 Arrays (java.util.Arrays)2 Set (java.util.Set)2 HibernateException (org.hibernate.HibernateException)2 PersistentCollection (org.hibernate.collection.spi.PersistentCollection)2