Search in sources :

Example 1 with ReactiveConnection

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

the class ReactiveImprovedExtractionContextImpl method getQueryResultSet.

private ResultSet getQueryResultSet(String queryString, Object[] positionalParameters, CompletionStage<ReactiveConnection> connectionStage) {
    final Object[] parametersToUse = positionalParameters != null ? positionalParameters : new Object[0];
    final Parameters parametersDialectSpecific = Parameters.instance(getJdbcEnvironment().getDialect());
    final String queryToUse = parametersDialectSpecific.process(queryString, parametersToUse.length);
    return connectionStage.thenCompose(c -> c.selectJdbcOutsideTransaction(queryToUse, parametersToUse)).whenComplete((resultSet, err) -> logSqlException(err, () -> "could not execute query ", queryToUse)).thenApply(ResultSetWorkaround::new).toCompletableFuture().join();
}
Also used : JdbcEnvironment(org.hibernate.engine.jdbc.env.spi.JdbcEnvironment) Connection(java.sql.Connection) Time(java.sql.Time) SqlStringGenerationContext(org.hibernate.boot.model.relational.SqlStringGenerationContext) URL(java.net.URL) CompletionStages.logSqlException(org.hibernate.reactive.util.impl.CompletionStages.logSqlException) SQLXML(java.sql.SQLXML) DatabaseMetaData(java.sql.DatabaseMetaData) ImprovedExtractionContextImpl(org.hibernate.tool.schema.internal.exec.ImprovedExtractionContextImpl) ReactiveConnectionPool(org.hibernate.reactive.pool.ReactiveConnectionPool) Array(java.sql.Array) BigDecimal(java.math.BigDecimal) SQLException(java.sql.SQLException) Calendar(java.util.Calendar) DdlTransactionIsolator(org.hibernate.resource.transaction.spi.DdlTransactionIsolator) ResultSet(java.sql.ResultSet) Map(java.util.Map) JdbcContext(org.hibernate.tool.schema.internal.exec.JdbcContext) SQLType(java.sql.SQLType) Struct(java.sql.Struct) NClob(java.sql.NClob) SQLWarning(java.sql.SQLWarning) CompletionStages.voidFuture(org.hibernate.reactive.util.impl.CompletionStages.voidFuture) Clob(java.sql.Clob) Properties(java.util.Properties) Parameters(org.hibernate.reactive.pool.impl.Parameters) Executor(java.util.concurrent.Executor) Timestamp(java.sql.Timestamp) Reader(java.io.Reader) PreparedStatement(java.sql.PreparedStatement) Savepoint(java.sql.Savepoint) ServiceRegistry(org.hibernate.service.ServiceRegistry) Date(java.sql.Date) CompletionStage(java.util.concurrent.CompletionStage) RowId(java.sql.RowId) Statement(java.sql.Statement) CallableStatement(java.sql.CallableStatement) Ref(java.sql.Ref) Blob(java.sql.Blob) ResultSetMetaData(java.sql.ResultSetMetaData) InputStream(java.io.InputStream) ReactiveConnection(org.hibernate.reactive.pool.ReactiveConnection) Parameters(org.hibernate.reactive.pool.impl.Parameters)

Example 2 with ReactiveConnection

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

the class ReactiveAbstractEntityPersister method processGeneratedProperties.

default CompletionStage<Void> processGeneratedProperties(Serializable id, Object entity, Object[] state, SharedSessionContractImplementor session, String selectionSQL, GenerationTiming matchTiming) {
    ReactiveConnection connection = getReactiveConnection(session);
    // force immediate execution of the insert batch (if one)
    return connection.executeBatch().thenCompose(v -> connection.selectJdbc(selectionSQL, bind(ps -> getIdentifierType().nullSafeSet(ps, id, 1, session)))).thenAccept(rs -> {
        try {
            if (!rs.next()) {
                throw log.unableToRetrieveGeneratedProperties(infoString(this, id, getFactory()));
            }
            int propertyIndex = -1;
            for (NonIdentifierAttribute attribute : getEntityMetamodel().getProperties()) {
                propertyIndex++;
                if (isValueGenerationRequired(attribute, matchTiming)) {
                    final Object hydratedState = attribute.getType().hydrate(rs, getPropertyAliases("", propertyIndex), session, entity);
                    state[propertyIndex] = attribute.getType().resolve(hydratedState, session, entity);
                    setPropertyValue(entity, propertyIndex, state[propertyIndex]);
                }
            }
        } catch (SQLException sqle) {
            // can never happen
            throw new JDBCException("unable to select generated column values: " + selectionSQL, sqle);
        }
    });
}
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) JDBCException(org.hibernate.JDBCException) SQLException(java.sql.SQLException) ReactiveConnection(org.hibernate.reactive.pool.ReactiveConnection) NonIdentifierAttribute(org.hibernate.tuple.NonIdentifierAttribute)

Example 3 with ReactiveConnection

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

the class TableReactiveIdentifierGenerator method nextHiValue.

@Override
protected CompletionStage<Long> nextHiValue(ReactiveConnectionSupplier session) {
    // We need to read the current hi value from the table
    // and update it by the specified increment, but we
    // need to do it atomically, and without depending on
    // transaction rollback.
    ReactiveConnection connection = session.getReactiveConnection();
    // 1) select the current hi value
    return connection.selectIdentifier(selectQuery, selectParameters(), Long.class).thenCompose(result -> {
        Object[] params;
        String sql;
        long id;
        if (result == null) {
            // if there is no row in the table, insert one
            // TODO: This not threadsafe, and can result in
            // multiple rows being inserted simultaneously.
            // It might be better to just throw an exception
            // here, and require that the table was populated
            // when it was created
            id = initialValue;
            long insertedValue = storeLastUsedValue ? id - increment : id;
            params = insertParameters(insertedValue);
            sql = insertQuery;
        } else {
            // otherwise, update the existing row
            long currentValue = result;
            long updatedValue = currentValue + increment;
            id = storeLastUsedValue ? updatedValue : currentValue;
            params = updateParameters(currentValue, updatedValue);
            sql = updateQuery;
        }
        return connection.update(sql, params).thenCompose(rowCount -> {
            switch(rowCount) {
                case 1:
                    // we successfully obtained the next hi value
                    return completedFuture(id);
                case 0:
                    // so retry everything from scratch
                    return nextHiValue(session);
                default:
                    throw new TooManyRowsAffectedException("multiple rows in id table", 1, rowCount);
            }
        });
    });
}
Also used : ReactiveConnection(org.hibernate.reactive.pool.ReactiveConnection) TooManyRowsAffectedException(org.hibernate.jdbc.TooManyRowsAffectedException) ConfigurationHelper.getString(org.hibernate.internal.util.config.ConfigurationHelper.getString)

Example 4 with ReactiveConnection

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

the class ReactiveAbstractCollectionPersister method recreateReactive.

/**
 * @see org.hibernate.persister.collection.AbstractCollectionPersister#recreate(PersistentCollection, Serializable, SharedSessionContractImplementor)
 */
default CompletionStage<Void> recreateReactive(PersistentCollection collection, Serializable id, SharedSessionContractImplementor session) throws HibernateException {
    if (isInverse() || !isRowInsertEnabled()) {
        return voidFuture();
    }
    if (LOG.isDebugEnabled()) {
        LOG.debugf("Inserting collection: %s", collectionInfoString(this, collection, id, session));
    }
    ReactiveConnection connection = getReactiveConnection(session);
    // TODO: compose() reactive version of collection.preInsert()
    Iterator<?> entries = collection.entries(this);
    Expectation expectation = appropriateExpectation(getInsertCheckStyle());
    return loop(entries, collection::entryExists, (entry, index) -> connection.update(getSQLInsertRowString(), insertRowsParamValues(entry, index, collection, id, session), expectation.canBeBatched(), new ExpectationAdaptor(expectation, getSQLInsertRowString(), getSqlExceptionConverter())));
// TODO: compose() reactive version of collection.afterRowInsert()
}
Also used : ReactiveConnection(org.hibernate.reactive.pool.ReactiveConnection) Expectations.appropriateExpectation(org.hibernate.jdbc.Expectations.appropriateExpectation) Expectation(org.hibernate.jdbc.Expectation)

Example 5 with ReactiveConnection

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

the class ReactiveAbstractCollectionPersister method reactiveDeleteRows.

/**
 * @see org.hibernate.persister.collection.AbstractCollectionPersister#deleteRows(PersistentCollection, Serializable, SharedSessionContractImplementor)
 */
@Override
default CompletionStage<Void> reactiveDeleteRows(PersistentCollection collection, Serializable id, SharedSessionContractImplementor session) {
    if (isInverse() || !isRowDeleteEnabled()) {
        return voidFuture();
    }
    Iterator<?> deletes = collection.getDeletes(this, !deleteByIndex());
    if (!deletes.hasNext()) {
        return voidFuture();
    }
    ReactiveConnection connection = getReactiveConnection(session);
    Expectation expectation = appropriateExpectation(getDeleteCheckStyle());
    return loop(deletes, (entry, index) -> connection.update(getSQLDeleteRowString(), deleteRowsParamValues(entry, 1, id, session), expectation.canBeBatched(), new ExpectationAdaptor(expectation, getSQLDeleteRowString(), getSqlExceptionConverter())));
}
Also used : ReactiveConnection(org.hibernate.reactive.pool.ReactiveConnection) Expectations.appropriateExpectation(org.hibernate.jdbc.Expectations.appropriateExpectation) Expectation(org.hibernate.jdbc.Expectation)

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