diff --git a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/AbstractOuterSessionLifecycleStrategy.java b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/AbstractOuterSessionLifecycleStrategy.java new file mode 100644 index 00000000000..805b752ad4b --- /dev/null +++ b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/AbstractOuterSessionLifecycleStrategy.java @@ -0,0 +1,142 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.grails.orm.hibernate; + +import java.util.List; + +import javax.sql.DataSource; + +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.hibernate.engine.jdbc.spi.JdbcCoordinator; +import org.hibernate.engine.spi.SessionImplementor; +import org.hibernate.resource.jdbc.spi.LogicalConnectionImplementor; + +import org.springframework.jdbc.datasource.ConnectionHolder; +import org.springframework.transaction.support.TransactionSynchronization; + +import org.grails.orm.hibernate.support.hibernate7.SessionHolder; +import org.grails.orm.hibernate.support.hibernate7.TransactionResources; + +/** + * Base strategy handling symmetric capture, unbinding, and restoration of session and connection holders + * as well as Spring transaction synchronizations. + */ +abstract class AbstractOuterSessionLifecycleStrategy implements OuterSessionLifecycleStrategy { + + protected final SessionFactory sessionFactory; + protected final DataSource dataSource; + protected final TransactionResources txResources; + protected final SessionHolder previousHolder; + protected final boolean lazyConnection; + + protected boolean wasPhysicallyConnectedAtPrepare = false; + protected ConnectionHolder previousConnectionHolder; + protected boolean previousActiveSynchronization; + protected List transactionSynchronizations; + + AbstractOuterSessionLifecycleStrategy( + SessionFactory sessionFactory, + DataSource dataSource, + TransactionResources txResources, + SessionHolder previousHolder, + boolean lazyConnection) { + this.sessionFactory = sessionFactory; + this.dataSource = dataSource; + this.txResources = txResources; + this.previousHolder = previousHolder; + this.lazyConnection = lazyConnection; + } + + protected LogicalConnectionImplementor getLogicalConnection() { + if (previousHolder == null || previousHolder.getSession() == null || !previousHolder.getSession().isOpen()) { + return null; + } + + Session previousSession = previousHolder.getSession(); + if (!(previousSession instanceof SessionImplementor sessionImpl)) { + return null; + } + + JdbcCoordinator jdbcCoordinator = sessionImpl.getJdbcCoordinator(); + if (jdbcCoordinator == null) { + return null; + } + + return jdbcCoordinator.getLogicalConnection(); + } + + protected void disconnectIfConnected() { + LogicalConnectionImplementor logicalConnection = getLogicalConnection(); + if (logicalConnection != null && logicalConnection.isOpen() && logicalConnection.isPhysicallyConnected()) { + logicalConnection.manualDisconnect(); + } + } + + @Override + public void prepare() { + LogicalConnectionImplementor logicalConnection = getLogicalConnection(); + if (logicalConnection != null) { + this.wasPhysicallyConnectedAtPrepare = logicalConnection.isPhysicallyConnected(); + } + } + + @Override + public void suspendAndUnbind() { + previousConnectionHolder = dataSource != null ? (ConnectionHolder) txResources.getResource(dataSource) : null; + previousActiveSynchronization = txResources.isSynchronizationActive(); + transactionSynchronizations = previousActiveSynchronization ? txResources.getSynchronizations() : null; + + if (previousActiveSynchronization) { + txResources.clearSynchronization(); + txResources.initSynchronization(); + } + + if (previousHolder != null) { + txResources.unbindResource(sessionFactory); + } + + if (previousConnectionHolder != null && dataSource != null) { + txResources.unbindResource(dataSource); + } + } + + @Override + public void restore() { + if (previousActiveSynchronization) { + txResources.initSynchronization(); + if (transactionSynchronizations != null) { + for (TransactionSynchronization transactionSynchronization : transactionSynchronizations) { + txResources.registerSynchronization(transactionSynchronization); + } + } + } + + if (previousHolder != null) { + txResources.bindResource(sessionFactory, previousHolder); + if (!wasPhysicallyConnectedAtPrepare && (!lazyConnection || !previousActiveSynchronization)) { + disconnectIfConnected(); + } + } + + if (previousConnectionHolder != null && dataSource != null) { + txResources.bindResource(dataSource, previousConnectionHolder); + } + } +} diff --git a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/ActiveTransactionOuterSessionStrategy.java b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/ActiveTransactionOuterSessionStrategy.java new file mode 100644 index 00000000000..637e1da1b2d --- /dev/null +++ b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/ActiveTransactionOuterSessionStrategy.java @@ -0,0 +1,52 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.grails.orm.hibernate; + +import javax.sql.DataSource; + +import org.hibernate.SessionFactory; + +import org.grails.orm.hibernate.support.hibernate7.SessionHolder; +import org.grails.orm.hibernate.support.hibernate7.TransactionResources; + +/** + * Strategy applied when the outer session is bound to an active write-bearing physical transaction + * (such as {@code PROPAGATION_REQUIRED} or {@code PROPAGATION_MANDATORY}). + * + *

Invariant: Never disconnect an active outer transaction during beforeCompletion or suspension, + * as doing so drops uncommitted entity dirty checks and pending flushes.

+ */ +class ActiveTransactionOuterSessionStrategy extends AbstractOuterSessionLifecycleStrategy { + + ActiveTransactionOuterSessionStrategy( + SessionFactory sessionFactory, + DataSource dataSource, + TransactionResources txResources, + SessionHolder previousHolder, + boolean lazyConnection) { + super(sessionFactory, dataSource, txResources, previousHolder, lazyConnection); + } + + @Override + public void prepare() { + this.wasPhysicallyConnectedAtPrepare = true; + // No preparation needed: the active transaction already manages its physical connection. + // We explicitly do NOT disconnect or register disconnect synchronizations here. + } +} diff --git a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/DefaultOuterSessionStrategy.java b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/DefaultOuterSessionStrategy.java new file mode 100644 index 00000000000..2b4e5384bd8 --- /dev/null +++ b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/DefaultOuterSessionStrategy.java @@ -0,0 +1,51 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.grails.orm.hibernate; + +import javax.sql.DataSource; + +import org.hibernate.SessionFactory; + +import org.grails.orm.hibernate.support.hibernate7.SessionHolder; +import org.grails.orm.hibernate.support.hibernate7.TransactionResources; + +/** + * Strategy applied when an outer session exists but no Spring transaction synchronization is active. + * + *

Unbinds the outer session and connection holders while the new session runs and rebinds them afterwards. + * It does not prime the outer session, so an idle session never checks out a pooled connection. If the outer + * session was not connected on entry and is connected when the scope ends, it is disconnected on restore so + * that connection returns to the pool. A bound holder whose session is closed is unbound and rebound the same way.

+ */ +class DefaultOuterSessionStrategy extends AbstractOuterSessionLifecycleStrategy { + + DefaultOuterSessionStrategy( + SessionFactory sessionFactory, + DataSource dataSource, + TransactionResources txResources, + SessionHolder previousHolder, + boolean lazyConnection) { + super(sessionFactory, dataSource, txResources, previousHolder, lazyConnection); + } + + @Override + public void prepare() { + super.prepare(); + } +} diff --git a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/GrailsHibernateTemplate.java b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/GrailsHibernateTemplate.java index 4f1f3fd68c3..b523d28af34 100644 --- a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/GrailsHibernateTemplate.java +++ b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/GrailsHibernateTemplate.java @@ -46,7 +46,6 @@ import org.hibernate.engine.spi.SessionFactoryImplementor; import org.hibernate.engine.spi.SessionImplementor; import org.hibernate.event.spi.EventSource; -import org.hibernate.exception.GenericJDBCException; import org.hibernate.query.Query; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -59,7 +58,6 @@ import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; import org.springframework.jdbc.support.SQLErrorCodeSQLExceptionTranslator; import org.springframework.jdbc.support.SQLExceptionTranslator; -import org.springframework.transaction.support.TransactionSynchronization; import org.springframework.util.Assert; import org.grails.orm.hibernate.support.hibernate7.DefaultTransactionResources; @@ -146,6 +144,7 @@ public class GrailsHibernateTemplate implements IHibernateTemplate { private boolean osivReadOnly; private boolean passReadOnlyToHibernate = false; private boolean applyFlushModeOnlyToNonExistingTransactions = false; + private boolean lazyConnection = false; protected TransactionResources txResources = new DefaultTransactionResources(); protected GrailsHibernateTemplate() { @@ -159,13 +158,21 @@ public GrailsHibernateTemplate(SessionFactory sessionFactory) { ConnectionProvider connectionProvider = ((SessionFactoryImplementor) sessionFactory) .getServiceRegistry() .getService(ConnectionProvider.class); - this.dataSource = connectionProvider != null ? connectionProvider.unwrap(DataSource.class) : null; - if (this.dataSource != null) { - if (this.dataSource instanceof TransactionAwareDataSourceProxy) { - DataSource target = ((TransactionAwareDataSourceProxy) this.dataSource).getTargetDataSource(); + DataSource ds = connectionProvider != null ? connectionProvider.unwrap(DataSource.class) : null; + if (ds != null) { + if (ds instanceof TransactionAwareDataSourceProxy transactionAwareProxy) { + DataSource target = transactionAwareProxy.getTargetDataSource(); + if (target instanceof org.springframework.jdbc.datasource.LazyConnectionDataSourceProxy) { + this.lazyConnection = true; + } if (target != null) { this.dataSource = target; } + } else { + if (ds instanceof org.springframework.jdbc.datasource.LazyConnectionDataSourceProxy) { + this.lazyConnection = true; + } + this.dataSource = ds; } jdbcExceptionTranslator = new SQLErrorCodeSQLExceptionTranslator(this.dataSource); } else { @@ -219,98 +226,65 @@ public T execute(Closure callable) { @Override public T executeWithNewSession(final Closure callable) { SessionHolder sessionHolder = (SessionHolder) txResources.getResource(sessionFactory); - SessionHolder previousHolder = sessionHolder; - ConnectionHolder previousConnectionHolder = - (ConnectionHolder) txResources.getResource(dataSource); + OuterSessionLifecycleStrategy strategy = OuterSessionLifecycleStrategy.from( + sessionHolder, sessionFactory, dataSource, txResources, lazyConnection); + + strategy.prepare(); Session newSession = null; - boolean previousActiveSynchronization = txResources.isSynchronizationActive(); - List transactionSynchronizations = - previousActiveSynchronization ? txResources.getSynchronizations() : null; try { - // if there are any previous synchronizations active we need to clear them and restore them - // later (see finally block) - if (previousActiveSynchronization) { - txResources.clearSynchronization(); - // init a new synchronization to ensure that any opened database connections are closed by - // the synchronization - txResources.initSynchronization(); - } + strategy.suspendAndUnbind(); - // if there are already bound holders, unbind them so they can be restored later - if (sessionHolder != null) { - txResources.unbindResource(sessionFactory); - } - // Unbind any pre-existing connection holder independently of the session holder: a - // DataSource binding can exist without a matching SessionFactory binding when, for - // example, Spring's SQLErrorCodesFactory eagerly acquires a connection via - // DataSourceUtils during SQLErrorCodeSQLExceptionTranslator initialisation while a - // parent-transaction synchronisation is already active. Leaving it bound causes - // HibernateTransactionManager.doBegin to throw "Already value bound" at line 565. - if (previousConnectionHolder != null) { - txResources.unbindResource(dataSource); - } - - // create and bind a new session holder for the new session newSession = sessionFactory.openSession(); applyFlushMode(newSession, false); sessionHolder = new SessionHolder(newSession); txResources.bindResource(sessionFactory, sessionHolder); - return callable.call(newSession); + final Session scopedSession = newSession; + return doExecute(callable::call, false, scopedSession, true); } finally { + boolean cleaned = false; try { - // if an active synchronization was registered during the life time of the new session clear - // it - if (txResources.isSynchronizationActive()) { - txResources.clearSynchronization(); - } - // If there is a synchronization active then leave it to the synchronization to close the - // session - // Clear any bound sessions and connections - txResources.unbindResource(sessionFactory); - ConnectionHolder connectionHolder = - (ConnectionHolder) txResources.unbindResourceIfPossible(dataSource); - // if there is a connection holder and it holds an open connection close it - try { - if (connectionHolder != null && - !(dataSource instanceof org.grails.datastore.gorm.jdbc.MultiTenantDataSource) && - !connectionHolder.getConnection().isClosed()) { - Connection conn = connectionHolder.getConnection(); - DataSourceUtils.releaseConnection(conn, dataSource); - } - } catch (SQLException e) { - // ignore, connection closed already? - if (LOG.isDebugEnabled()) { - LOG.debug( - "Could not close opened JDBC connection. Did the application close the connection manually?: " + - e.getMessage()); - } - } - - if (newSession != null) { - SessionFactoryUtils.closeSession(newSession); - } + cleanupNewSession(newSession); + cleaned = true; } finally { - // if there were previously active synchronizations then register those again - if (previousActiveSynchronization) { - txResources.initSynchronization(); - for (TransactionSynchronization transactionSynchronization : transactionSynchronizations) { - txResources.registerSynchronization(transactionSynchronization); + if (!cleaned) { + // the cleanup failed part-way: what it left bound for the new session would make binding the + // outer one fail, and the outer session goes back whether or not the new one could be cleaned up + txResources.unbindResourceIfPossible(sessionFactory); + if (dataSource != null) { + txResources.unbindResourceIfPossible(dataSource); } } + strategy.restore(); + } + } + } - // now restore any previous state - if (previousHolder != null) { - txResources.bindResource(sessionFactory, previousHolder); - } - // Restore the connection holder independently of the session holder so that - // the parent-transaction's ConnectionSynchronization (re-registered above) can - // still release it when the outer transaction completes. - if (previousConnectionHolder != null) { - txResources.bindResource(dataSource, previousConnectionHolder); - } + private void cleanupNewSession(Session newSession) { + if (txResources.isSynchronizationActive()) { + txResources.clearSynchronization(); + } + txResources.unbindResourceIfPossible(sessionFactory); + ConnectionHolder connectionHolder = dataSource != null ? + (ConnectionHolder) txResources.unbindResourceIfPossible(dataSource) : null; + try { + if (connectionHolder != null && dataSource != null && + !(dataSource instanceof org.grails.datastore.gorm.jdbc.MultiTenantDataSource) && + !connectionHolder.getConnection().isClosed()) { + Connection conn = connectionHolder.getConnection(); + DataSourceUtils.releaseConnection(conn, dataSource); + } + } catch (SQLException e) { + if (LOG.isDebugEnabled()) { + LOG.debug( + "Could not close opened JDBC connection. Did the application close the connection manually?: " + + e.getMessage()); } } + + if (newSession != null) { + SessionFactoryUtils.closeSession(newSession); + } } @Override @@ -392,7 +366,21 @@ protected T doExecute(HibernateCallback action, boolean enforceNativeSess Assert.notNull(action, "Callback object must not be null"); - Session session = getSession(); + return doExecute(action, enforceNativeSession, getSession(), false); + } + + /** + * Runs the callback against the given session. {@link #getSession()} is not called for a session the caller + * has just bound itself: it would register the holder with the surrounding synchronization, and a transaction + * manager that begins inside the callback would then open a second session instead of using this one. + */ + /** + * @param newSessionScope true when the session was opened by {@code withNewSession}: the closure may begin and + * commit its own write transaction on it, so the session is not marked read-only, and it is flushed + * after the callback only while a transaction is still active on it + */ + private T doExecute(HibernateCallback action, boolean enforceNativeSession, Session session, + boolean newSessionScope) throws DataAccessException { boolean existingTransaction = isSessionTransactional(session); if (existingTransaction) { LOG.debug("Found thread-bound Session for HibernateTemplate"); @@ -401,13 +389,15 @@ protected T doExecute(HibernateCallback action, boolean enforceNativeSess FlushMode previousFlushMode = null; try { previousFlushMode = applyFlushMode(session, existingTransaction); - if (shouldPassReadOnlyToHibernate()) { + if (!newSessionScope && shouldPassReadOnlyToHibernate()) { session.setDefaultReadOnly(true); } Session sessionToExpose = (enforceNativeSession || exposeNativeSession ? session : createSessionProxy(session)); T result = action.doInHibernate(sessionToExpose); - flushIfNecessary(session, existingTransaction); + if (!newSessionScope || hasActiveTransaction(session)) { + flushIfNecessary(session, existingTransaction); + } return result; } catch (HibernateException ex) { throw convertHibernateAccessException(ex); @@ -431,6 +421,11 @@ protected T doExecute(HibernateCallback action, boolean enforceNativeSess } } + private static boolean hasActiveTransaction(Session session) { + org.hibernate.Transaction transaction = session.getTransaction(); + return transaction != null && transaction.isActive(); + } + protected boolean isSessionTransactional(Session session) { SessionHolder sessionHolder = (SessionHolder) txResources.getResource(sessionFactory); return sessionHolder != null && sessionHolder.getSession() == session; @@ -680,10 +675,8 @@ protected void flushIfNecessary(Session session, boolean existingTransaction) th @SuppressWarnings("ConstantConditions") protected DataAccessException convertHibernateAccessException(HibernateException ex) { if (ex instanceof JDBCException) { - return convertJdbcAccessException((JDBCException) ex, jdbcExceptionTranslator); - } - if (GenericJDBCException.class.equals(ex.getClass())) { - return convertJdbcAccessException((GenericJDBCException) ex, jdbcExceptionTranslator); + DataAccessException dae = convertJdbcAccessException((JDBCException) ex, jdbcExceptionTranslator); + return dae != null ? dae : SessionFactoryUtils.convertHibernateAccessException(ex); } return SessionFactoryUtils.convertHibernateAccessException(ex); } diff --git a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/NoOpOuterSessionStrategy.java b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/NoOpOuterSessionStrategy.java new file mode 100644 index 00000000000..c820f232702 --- /dev/null +++ b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/NoOpOuterSessionStrategy.java @@ -0,0 +1,40 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.grails.orm.hibernate; + +/** + * Strategy applied when no outer session exists or the outer session is closed. + */ +class NoOpOuterSessionStrategy implements OuterSessionLifecycleStrategy { + + @Override + public void prepare() { + // No-op + } + + @Override + public void suspendAndUnbind() { + // No-op + } + + @Override + public void restore() { + // No-op + } +} diff --git a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/NonTransactionalSynchronizationOuterSessionStrategy.java b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/NonTransactionalSynchronizationOuterSessionStrategy.java new file mode 100644 index 00000000000..093e6025295 --- /dev/null +++ b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/NonTransactionalSynchronizationOuterSessionStrategy.java @@ -0,0 +1,77 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.grails.orm.hibernate; + +import javax.sql.DataSource; + +import org.hibernate.SessionFactory; + +import org.springframework.transaction.support.TransactionSynchronization; + +import org.grails.orm.hibernate.support.hibernate7.SessionFactoryUtils; +import org.grails.orm.hibernate.support.hibernate7.SessionHolder; +import org.grails.orm.hibernate.support.hibernate7.TransactionResources; + +/** + * Strategy applied when an outer session exists within an active Spring synchronization scope + * that is not an actual physical transaction (such as {@code PROPAGATION_SUPPORTS} or read-only scopes). + * + *

Leaves a disconnected outer session disconnected: it takes no connection of its own, so a pool of one + * connection still serves a transaction in the nested session. Coordinates via {@link TransactionSynchronization} + * to disconnect the outer session if it connects later, both on suspension (when a nested {@code REQUIRED} + * transaction begins) and on beforeCompletion (before Spring's {@code ConnectionSynchronization} closes the + * physical connection), preventing closed-connection failures on subsequent outer session access.

+ */ +class NonTransactionalSynchronizationOuterSessionStrategy extends AbstractOuterSessionLifecycleStrategy { + + NonTransactionalSynchronizationOuterSessionStrategy( + SessionFactory sessionFactory, + DataSource dataSource, + TransactionResources txResources, + SessionHolder previousHolder, + boolean lazyConnection) { + super(sessionFactory, dataSource, txResources, previousHolder, lazyConnection); + } + + @Override + public void prepare() { + super.prepare(); + if (lazyConnection && !wasPhysicallyConnectedAtPrepare) { + // When nothing in this scope uses the outer session, no session synchronization is registered, and + // Spring's JDBC ConnectionSynchronization would close the connection the primed session still holds. + // Disconnect the session first (on suspend, for a nested REQUIRED transaction, and before completion). + txResources.registerSynchronization(new TransactionSynchronization() { + @Override + public int getOrder() { + return SessionFactoryUtils.SESSION_SYNCHRONIZATION_ORDER; + } + + @Override + public void suspend() { + disconnectIfConnected(); + } + + @Override + public void beforeCompletion() { + disconnectIfConnected(); + } + }); + } + } +} diff --git a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/OuterSessionLifecycleStrategy.java b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/OuterSessionLifecycleStrategy.java new file mode 100644 index 00000000000..a3074de778e --- /dev/null +++ b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/OuterSessionLifecycleStrategy.java @@ -0,0 +1,87 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.grails.orm.hibernate; + +import javax.sql.DataSource; + +import org.hibernate.SessionFactory; + +import org.grails.orm.hibernate.support.hibernate7.SessionHolder; +import org.grails.orm.hibernate.support.hibernate7.TransactionResources; + +/** + * Strategy interface governing outer session lifecycle preparation, suspension, and restoration + * across nested {@code withNewSession} invocations. + */ +interface OuterSessionLifecycleStrategy { + + /** + * Prepares the outer session before unbinding and opening the new session. + */ + void prepare(); + + /** + * Suspends any active Spring synchronizations and unbinds outer session and connection holders. + */ + void suspendAndUnbind(); + + /** + * Restores previously suspended synchronizations and rebinds outer session and connection holders. + */ + void restore(); + + /** + * Factory method creating the appropriate strategy based on the outer session, connection, and transaction context. + * + * @param previousHolder the session holder bound to the outer scope, or null + * @param sessionFactory the current Hibernate SessionFactory + * @param dataSource the underlying DataSource + * @param txResources the transaction synchronization and resource manager + * @param lazyConnection whether the datasource is configured with a lazy connection proxy + * @return the appropriate {@link OuterSessionLifecycleStrategy} + */ + static OuterSessionLifecycleStrategy from( + SessionHolder previousHolder, + SessionFactory sessionFactory, + DataSource dataSource, + TransactionResources txResources, + boolean lazyConnection) { + + boolean hasOpenSession = previousHolder != null && previousHolder.getSession() != null && previousHolder.getSession().isOpen(); + boolean hasConnectionHolder = dataSource != null && txResources.getResource(dataSource) != null; + boolean hasSynchronization = txResources.isSynchronizationActive(); + + if (previousHolder == null && !hasConnectionHolder && !hasSynchronization) { + return new NoOpOuterSessionStrategy(); + } + + if (txResources.isActualTransactionActive()) { + return new ActiveTransactionOuterSessionStrategy( + sessionFactory, dataSource, txResources, previousHolder, lazyConnection); + } + + if (hasSynchronization && hasOpenSession) { + return new NonTransactionalSynchronizationOuterSessionStrategy( + sessionFactory, dataSource, txResources, previousHolder, lazyConnection); + } + + return new DefaultOuterSessionStrategy( + sessionFactory, dataSource, txResources, previousHolder, lazyConnection); + } +} diff --git a/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/WithNewSessionLazyLoadSpec.groovy b/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/WithNewSessionLazyLoadSpec.groovy new file mode 100644 index 00000000000..02ceb6726a0 --- /dev/null +++ b/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/WithNewSessionLazyLoadSpec.groovy @@ -0,0 +1,240 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package grails.gorm.tests + +import grails.gorm.annotation.Entity +import org.apache.grails.data.hibernate7.core.GrailsDataHibernate7TckManager +import org.apache.grails.data.testing.tck.base.GrailsDataTckSpec +import org.grails.orm.hibernate.proxy.HibernateProxyHandler +import org.grails.orm.hibernate.support.hibernate7.SessionHolder +import org.springframework.transaction.TransactionDefinition +import org.springframework.transaction.support.TransactionSynchronizationManager +import spock.lang.Issue + +/** + * Verifies that the request-bound session remains valid after a lazy load + * occurs within a nested withNewSession { withTransaction { ... } } block. + */ +@Issue('https://github.com/apache/grails-core/issues/16571') +class WithNewSessionLazyLoadSpec extends GrailsDataTckSpec { + + void setupSpec() { + manager.isTransactional = false + manager.registerDomainClasses(WnsllBook, WnsllAuthor) + } + + void cleanup() { + WnsllAuthor.withTransaction { + WnsllBook.where {}.deleteAll() + WnsllAuthor.where {}.deleteAll() + } + manager.sessionFactory.currentSession.clear() + } + + void "request-bound session remains usable after lazy load inside withNewSession with inner transaction"() { + given: "a seeded author and book" + WnsllAuthor.withTransaction { + WnsllAuthor author = new WnsllAuthor(name: 'Stephen King').save() + new WnsllBook(title: 'The Stand', author: author).save() + } + manager.sessionFactory.currentSession.clear() + + and: "an active request-bound session in TSM" + manager.sessionFactory.currentSession + SessionHolder requestSessionHolder = TransactionSynchronizationManager.getResource(manager.sessionFactory) + + when: "loading an entity in the request session without a transaction" + WnsllBook book = WnsllBook.first() + HibernateProxyHandler proxyHandler = new HibernateProxyHandler() + assert !proxyHandler.isInitialized(book, 'author') + + and: "running and ending a transaction on the request session" + WnsllAuthor.withTransaction { WnsllAuthor.count() } + + and: "calling withNewSession with an inner transaction that lazy-loads an association on the request session entity" + WnsllBook.withNewSession { + WnsllBook.withTransaction { + assert book.author.name == 'Stephen King' + new WnsllAuthor(name: 'Tenar').save() + } + } + + then: "the request-bound session remains open and usable" + requestSessionHolder.session.isOpen() + WnsllBook.count() == 1 + WnsllAuthor.count() == 2 + book.refresh() + book.title == 'The Stand' + book.author.name == 'Stephen King' + } + + void "request-bound session remains usable after nested withNewSession inside SUPPORTS transaction"() { + given: "a seeded author and book" + WnsllAuthor.withTransaction { + WnsllAuthor author = new WnsllAuthor(name: 'Ursula').save() + new WnsllBook(title: 'Earthsea', author: author).save() + } + manager.sessionFactory.currentSession.clear() + + and: "an active request-bound session in TSM" + manager.sessionFactory.currentSession + SessionHolder requestSessionHolder = TransactionSynchronizationManager.getResource(manager.sessionFactory) + + when: "disconnecting the request session via an initial transaction" + WnsllAuthor.withTransaction { WnsllAuthor.count() } + + and: "running a SUPPORTS read-only transaction with a nested withNewSession and inner transaction" + WnsllBook.withTransaction(propagationBehavior: TransactionDefinition.PROPAGATION_SUPPORTS, readOnly: true) { + WnsllBook.withNewSession { + WnsllBook.withTransaction { new WnsllAuthor(name: 'Tenar').save(flush: true) } + } + assert WnsllBook.count() == 1 + } + + then: "the request-bound session remains open and usable" + requestSessionHolder.session.isOpen() + WnsllBook.count() == 1 + WnsllAuthor.count() == 2 + } + + void "request-bound session remains usable after nested withNewSession inside SUPPORTS transaction without in-scope query"() { + given: "a seeded author and book" + WnsllAuthor.withTransaction { + WnsllAuthor author = new WnsllAuthor(name: 'Ursula').save() + new WnsllBook(title: 'Earthsea', author: author).save() + } + manager.sessionFactory.currentSession.clear() + + and: "an active request-bound session in TSM" + manager.sessionFactory.currentSession + SessionHolder requestSessionHolder = TransactionSynchronizationManager.getResource(manager.sessionFactory) + + when: "disconnecting the request session via an initial transaction" + WnsllAuthor.withTransaction { WnsllAuthor.count() } + + and: "running a SUPPORTS read-only transaction with a nested withNewSession without in-scope query" + WnsllBook.withTransaction(propagationBehavior: TransactionDefinition.PROPAGATION_SUPPORTS, readOnly: true) { + WnsllBook.withNewSession { WnsllAuthor.count() } + } + + then: "the request-bound session remains open and usable after the scope completes" + requestSessionHolder.session.isOpen() + WnsllBook.count() == 1 + } + + void "request-bound session remains usable after lazy load inside withNewSession under SUPPORTS transaction"() { + given: "a seeded author and book" + WnsllAuthor.withTransaction { + WnsllAuthor author = new WnsllAuthor(name: 'Ursula').save() + new WnsllBook(title: 'Earthsea', author: author).save() + } + manager.sessionFactory.currentSession.clear() + + and: "an active request-bound session in TSM" + manager.sessionFactory.currentSession + SessionHolder requestSessionHolder = TransactionSynchronizationManager.getResource(manager.sessionFactory) + + when: "loading an entity in the request session without a transaction" + WnsllBook book = WnsllBook.first() + HibernateProxyHandler proxyHandler = new HibernateProxyHandler() + assert !proxyHandler.isInitialized(book, 'author') + + and: "disconnecting the request session via an initial transaction" + WnsllAuthor.withTransaction { WnsllAuthor.count() } + + and: "calling withNewSession under a SUPPORTS scope with an inner transaction that lazy-loads" + WnsllBook.withTransaction(propagationBehavior: TransactionDefinition.PROPAGATION_SUPPORTS, readOnly: true) { + WnsllBook.withNewSession { + WnsllBook.withTransaction { + assert book.author.name == 'Ursula' + new WnsllAuthor(name: 'Tenar').save(flush: true) + } + } + } + + then: "the request-bound session remains open and usable" + requestSessionHolder.session.isOpen() + WnsllBook.count() == 1 + WnsllAuthor.count() == 2 + book.refresh() + book.title == 'Earthsea' + book.author.name == 'Ursula' + } + + void "active outer transaction commits uncommitted writes when nested withNewSession is executed"() { + when: "starting an active transaction, inserting without flush, calling withNewSession, and inserting after" + WnsllAuthor.withTransaction { + new WnsllAuthor(name: 'Brandon').save() + WnsllBook.withNewSession { + assert WnsllBook.count() == 0 + } + new WnsllAuthor(name: 'Patrick').save() + } + + then: "both inserted authors are committed and persisted" + WnsllAuthor.count() == 2 + WnsllAuthor.findByName('Brandon') != null + WnsllAuthor.findByName('Patrick') != null + } + + void "request-bound session remains usable when SUPPORTS scope executes nested withNewSession and starts REQUIRED transaction"() { + given: "a seeded author and book" + WnsllAuthor.withTransaction { + WnsllAuthor author = new WnsllAuthor(name: 'Ursula').save() + new WnsllBook(title: 'Earthsea', author: author).save() + } + manager.sessionFactory.currentSession.clear() + + and: "an active request-bound session in TSM" + manager.sessionFactory.currentSession + SessionHolder requestSessionHolder = TransactionSynchronizationManager.getResource(manager.sessionFactory) + + when: "disconnecting the request session via an initial transaction" + WnsllAuthor.withTransaction { WnsllAuthor.count() } + + and: "running a SUPPORTS scope that calls withNewSession, followed by a REQUIRED transaction that suspends the scope" + WnsllBook.withTransaction(propagationBehavior: TransactionDefinition.PROPAGATION_SUPPORTS, readOnly: true) { + WnsllBook.withNewSession { + WnsllAuthor.count() + } + WnsllAuthor.withTransaction(propagationBehavior: TransactionDefinition.PROPAGATION_REQUIRED) { + new WnsllAuthor(name: 'Tenar').save(flush: true) + } + } + + then: "the request-bound session remains open and can execute subsequent queries without closed-connection errors" + requestSessionHolder.session.isOpen() + WnsllBook.count() == 1 + WnsllAuthor.count() == 2 + } +} + +@Entity +class WnsllAuthor { + String name +} + +@Entity +class WnsllBook { + String title + WnsllAuthor author + static constraints = { + author nullable: true + } +} diff --git a/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/GrailsHibernateTemplateSpec.groovy b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/GrailsHibernateTemplateSpec.groovy index 18dabb98e0b..499f3b763a9 100644 --- a/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/GrailsHibernateTemplateSpec.groovy +++ b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/GrailsHibernateTemplateSpec.groovy @@ -18,18 +18,26 @@ */ package org.grails.orm.hibernate +import java.sql.SQLException import java.util.UUID import grails.gorm.annotation.Entity import grails.gorm.hibernate.HibernateEntity import grails.gorm.tests.HibernateGormDatastoreSpec import jakarta.persistence.PersistenceException +import org.grails.orm.hibernate.support.hibernate7.DefaultTransactionResources +import org.grails.orm.hibernate.support.hibernate7.HibernateJdbcException +import org.grails.orm.hibernate.support.hibernate7.SessionHolder import org.grails.orm.hibernate.support.hibernate7.TransactionResources import org.hibernate.FlushMode import org.hibernate.HibernateException import org.hibernate.LockMode import org.hibernate.Session +import org.hibernate.engine.spi.SessionFactoryImplementor +import org.hibernate.exception.GenericJDBCException +import org.hibernate.service.spi.ServiceRegistryImplementor import org.springframework.dao.DataAccessException +import org.springframework.dao.DataIntegrityViolationException import org.springframework.transaction.support.TransactionSynchronizationManager class GrailsHibernateTemplateSpec extends HibernateGormDatastoreSpec { @@ -38,7 +46,7 @@ class GrailsHibernateTemplateSpec extends HibernateGormDatastoreSpec { @Override void setupSpec() { - manager.registerDomainClasses(TemplateBook) + manager.registerDomainClasses(TemplateBook, TemplateLengthOverrunEntity) } void setup() { @@ -166,6 +174,87 @@ class GrailsHibernateTemplateSpec extends HibernateGormDatastoreSpec { count >= 0L } + void "executeWithNewSession flushes eagerly and translates HibernateException to DataAccessException"() { + given: + template.flushMode = GrailsHibernateTemplate.FLUSH_EAGER + + when: "an entity exceeding column length is persisted and flushed inside executeWithNewSession" + template.executeWithNewSession { Session session -> + session.beginTransaction() + TemplateLengthOverrunEntity entity = new TemplateLengthOverrunEntity(code: 'this string is much too long for varchar 5') + session.persist(entity) + null + } + + then: + thrown(DataIntegrityViolationException) + } + + void "executeWithNewSession does not flush after the closure committed its own transaction"() { + given: + template.flushMode = GrailsHibernateTemplate.FLUSH_EAGER + + when: 'the closure begins and commits a transaction, so none is active when the callback returns' + template.executeWithNewSession { Session session -> + session.beginTransaction() + session.persist(new TemplateBook(title: 'committed', author: 'someone')) + session.transaction.commit() + null + } + + then: 'the flush after the callback does not throw for a missing transaction' + noExceptionThrown() + } + + void "executeWithNewSession restores the outer session when the cleanup of the new session throws"() { + given: + SessionHolder outerHolder = (SessionHolder) TransactionSynchronizationManager.getResource(sessionFactory) + boolean failedOnce = false + DefaultTransactionResources failing = Spy(DefaultTransactionResources) { + unbindResourceIfPossible(_) >> { args -> + if (!failedOnce) { + failedOnce = true + throw new IllegalStateException('Simulated cleanup failure') + } + callRealMethod() + } + } + template.txResources = failing + + when: + template.executeWithNewSession { Session s -> 'done' } + + then: 'the failure of the cleanup is reported, and the outer session is bound again all the same' + IllegalStateException e = thrown(IllegalStateException) + e.message == 'Simulated cleanup failure' + TransactionSynchronizationManager.getResource(sessionFactory) == outerHolder + } + + void "executeWithNewSession restores outer session and propagates exception when openSession fails"() { + given: + Session outerSession = sessionFactory.openSession() + SessionHolder outerHolder = new SessionHolder(outerSession) + + SessionFactoryImplementor mockFactory = Mock(SessionFactoryImplementor) + ServiceRegistryImplementor registry = Mock(ServiceRegistryImplementor) + mockFactory.getServiceRegistry() >> registry + mockFactory.openSession() >> { throw new RuntimeException("Simulated openSession failure") } + GrailsHibernateTemplate mockTemplate = new GrailsHibernateTemplate(mockFactory, manager.hibernateDatastore) + TransactionSynchronizationManager.bindResource(mockFactory, outerHolder) + + when: + mockTemplate.executeWithNewSession { Session s -> 'unreachable' } + + then: + RuntimeException ex = thrown(RuntimeException) + ex.message == "Simulated openSession failure" + TransactionSynchronizationManager.getResource(mockFactory) == outerHolder + + cleanup: + TransactionSynchronizationManager.unbindResourceIfPossible(mockFactory) + outerSession?.close() + } + // ------------------------------------------------------------------------- // get // ------------------------------------------------------------------------- @@ -1007,6 +1096,14 @@ class GrailsHibernateTemplateSpec extends HibernateGormDatastoreSpec { thrown(DataAccessException) } + void "doExecute wraps untranslatable GenericJDBCException as HibernateJdbcException"() { + when: + template.execute { sess -> throw new GenericJDBCException('msg', new SQLException('untranslatable')) } + + then: + thrown(HibernateJdbcException) + } + void "doExecute wraps PersistenceException with HibernateException cause as DataAccessException"() { when: template.execute { sess -> @@ -1123,6 +1220,18 @@ class GrailsHibernateTemplateSpec extends HibernateGormDatastoreSpec { converted instanceof DataAccessException } + void "convertHibernateAccessException falls back to SessionFactoryUtils when translator returns null"() { + given: + GenericJDBCException genericEx = new GenericJDBCException('msg', new SQLException('untranslatable')) + + when: + DataAccessException converted = template.convertHibernateAccessException(genericEx) + + then: + converted instanceof HibernateJdbcException + converted.cause == genericEx + } + void "createSessionProxy handles EventSource"() { given: def mockEventSourceSession = Mock(org.hibernate.event.spi.EventSource) @@ -1215,11 +1324,14 @@ class GrailsHibernateTemplateSpec extends HibernateGormDatastoreSpec { def templateUnderTest = new GrailsHibernateTemplate(mockSessionFactory) templateUnderTest.txResources = mockTxResources + def mockSession = Mock(org.hibernate.engine.spi.SessionImplementor) + mockSessionFactory.getCurrentSession() >> mockSession + when: "executeWithNewSession is called" templateUnderTest.executeWithNewSession { session -> } then: "The multi-tenant data source is handled correctly" - 1 * mockSessionFactory.openSession() >> Mock(org.hibernate.engine.spi.SessionImplementor) + 1 * mockSessionFactory.openSession() >> mockSession // Ensure the resource is unbound 1 * mockTxResources.unbindResourceIfPossible(mockMultiTenantDataSource) >> null @@ -1239,3 +1351,14 @@ class H7TemplateTsmBook implements HibernateEntity { String title String author } + +@Entity +class TemplateLengthOverrunEntity implements HibernateEntity { + Long id + Long version + String code + + static mapping = { + code length: 5 + } +} diff --git a/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/OuterSessionLifecycleStrategySpec.groovy b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/OuterSessionLifecycleStrategySpec.groovy new file mode 100644 index 00000000000..f5890114bab --- /dev/null +++ b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/OuterSessionLifecycleStrategySpec.groovy @@ -0,0 +1,487 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.grails.orm.hibernate + +import java.sql.Connection +import java.sql.SQLException +import javax.sql.DataSource + +import org.hibernate.Session +import org.hibernate.SessionFactory +import org.hibernate.engine.jdbc.spi.JdbcCoordinator +import org.hibernate.engine.spi.SessionImplementor +import org.hibernate.resource.jdbc.spi.LogicalConnectionImplementor +import org.springframework.jdbc.datasource.ConnectionHolder +import org.springframework.transaction.support.TransactionSynchronization +import spock.lang.Specification + +import org.grails.orm.hibernate.support.hibernate7.SessionFactoryUtils +import org.grails.orm.hibernate.support.hibernate7.SessionHolder +import org.grails.orm.hibernate.support.hibernate7.TransactionResources + +class OuterSessionLifecycleStrategySpec extends Specification { + + SessionFactory sessionFactory = Mock(SessionFactory) + DataSource dataSource = Mock(DataSource) + TransactionResources txResources = Mock(TransactionResources) + Session session = Mock(Session) + SessionHolder sessionHolder = new SessionHolder(session) + + // ------------------------------------------------------------------------- + // Strategy selection via factory + // ------------------------------------------------------------------------- + + void "from returns NoOpOuterSessionStrategy when previousHolder is null"() { + when: + OuterSessionLifecycleStrategy strategy = OuterSessionLifecycleStrategy.from( + null, sessionFactory, dataSource, txResources, false) + + then: + strategy instanceof NoOpOuterSessionStrategy + } + + void "from returns DefaultOuterSessionStrategy when session is null with bound holder"() { + given: + SessionHolder emptyHolder = Mock(SessionHolder) + emptyHolder.getSession() >> null + + when: + OuterSessionLifecycleStrategy strategy = OuterSessionLifecycleStrategy.from( + emptyHolder, sessionFactory, dataSource, txResources, false) + + then: + strategy instanceof DefaultOuterSessionStrategy + } + + void "from returns DefaultOuterSessionStrategy when session is closed with bound holder"() { + given: + session.isOpen() >> false + + when: + OuterSessionLifecycleStrategy strategy = OuterSessionLifecycleStrategy.from( + sessionHolder, sessionFactory, dataSource, txResources, false) + + then: + strategy instanceof DefaultOuterSessionStrategy + } + + void "from returns ActiveTransactionOuterSessionStrategy when previousHolder is null but transaction is active and DataSource holder is bound"() { + given: + ConnectionHolder connectionHolder = new ConnectionHolder(Mock(Connection)) + txResources.getResource(dataSource) >> connectionHolder + txResources.isActualTransactionActive() >> true + + when: + OuterSessionLifecycleStrategy strategy = OuterSessionLifecycleStrategy.from( + null, sessionFactory, dataSource, txResources, false) + + then: + strategy instanceof ActiveTransactionOuterSessionStrategy + } + + void "from returns DefaultOuterSessionStrategy when previousHolder is null but DataSource holder is bound without synchronization"() { + given: + ConnectionHolder connectionHolder = new ConnectionHolder(Mock(Connection)) + txResources.getResource(dataSource) >> connectionHolder + txResources.isActualTransactionActive() >> false + txResources.isSynchronizationActive() >> false + + when: + OuterSessionLifecycleStrategy strategy = OuterSessionLifecycleStrategy.from( + null, sessionFactory, dataSource, txResources, false) + + then: + strategy instanceof DefaultOuterSessionStrategy + } + + void "from returns ActiveTransactionOuterSessionStrategy when actual transaction is active"() { + given: + session.isOpen() >> true + txResources.isActualTransactionActive() >> true + + when: + OuterSessionLifecycleStrategy strategy = OuterSessionLifecycleStrategy.from( + sessionHolder, sessionFactory, dataSource, txResources, false) + + then: + strategy instanceof ActiveTransactionOuterSessionStrategy + } + + void "from returns NonTransactionalSynchronizationOuterSessionStrategy when synchronization is active but not actual transaction"() { + given: + session.isOpen() >> true + txResources.isActualTransactionActive() >> false + txResources.isSynchronizationActive() >> true + + when: + OuterSessionLifecycleStrategy strategy = OuterSessionLifecycleStrategy.from( + sessionHolder, sessionFactory, dataSource, txResources, false) + + then: + strategy instanceof NonTransactionalSynchronizationOuterSessionStrategy + } + + void "from returns DefaultOuterSessionStrategy when no synchronization is active"() { + given: + session.isOpen() >> true + txResources.isActualTransactionActive() >> false + txResources.isSynchronizationActive() >> false + + when: + OuterSessionLifecycleStrategy strategy = OuterSessionLifecycleStrategy.from( + sessionHolder, sessionFactory, dataSource, txResources, false) + + then: + strategy instanceof DefaultOuterSessionStrategy + } + + // ------------------------------------------------------------------------- + // NoOpOuterSessionStrategy + // ------------------------------------------------------------------------- + + void "NoOpOuterSessionStrategy performs no operations"() { + given: + NoOpOuterSessionStrategy strategy = new NoOpOuterSessionStrategy() + + when: + strategy.prepare() + strategy.suspendAndUnbind() + strategy.restore() + + then: + 0 * txResources._ + } + + // ------------------------------------------------------------------------- + // ActiveTransactionOuterSessionStrategy + // ------------------------------------------------------------------------- + + void "ActiveTransactionOuterSessionStrategy does not prime or disconnect connection during prepare"() { + given: + SessionImplementor sessionImpl = Mock(SessionImplementor) + JdbcCoordinator coordinator = Mock(JdbcCoordinator) + LogicalConnectionImplementor logicalConnection = Mock(LogicalConnectionImplementor) + sessionImpl.getJdbcCoordinator() >> coordinator + coordinator.getLogicalConnection() >> logicalConnection + SessionHolder holder = new SessionHolder(sessionImpl) + + ActiveTransactionOuterSessionStrategy strategy = new ActiveTransactionOuterSessionStrategy( + sessionFactory, dataSource, txResources, holder, false) + + when: + strategy.prepare() + + then: "neither physical connection acquisition nor manualDisconnect is called" + 0 * logicalConnection.getPhysicalConnection() + 0 * logicalConnection.manualDisconnect() + 0 * txResources.registerSynchronization(_) + } + + void "ActiveTransactionOuterSessionStrategy suspends and restores synchronizations and holders symmetrically"() { + given: + ConnectionHolder connectionHolder = new ConnectionHolder(Mock(Connection)) + TransactionSynchronization existingSync = Mock(TransactionSynchronization) + List syncList = [existingSync] + + txResources.getResource(dataSource) >> connectionHolder + txResources.isSynchronizationActive() >> true + txResources.getSynchronizations() >> syncList + + ActiveTransactionOuterSessionStrategy strategy = new ActiveTransactionOuterSessionStrategy( + sessionFactory, dataSource, txResources, sessionHolder, false) + + when: "suspending and unbinding" + strategy.suspendAndUnbind() + + then: "synchronizations are cleared and inited, and holders are unbound" + 1 * txResources.clearSynchronization() + 1 * txResources.initSynchronization() + 1 * txResources.unbindResource(sessionFactory) + 1 * txResources.unbindResource(dataSource) + + when: "restoring" + strategy.restore() + + then: "synchronizations are restored and holders are rebound" + 1 * txResources.initSynchronization() + 1 * txResources.registerSynchronization(existingSync) + 1 * txResources.bindResource(sessionFactory, sessionHolder) + 1 * txResources.bindResource(dataSource, connectionHolder) + } + + // ------------------------------------------------------------------------- + // NonTransactionalSynchronizationOuterSessionStrategy + // ------------------------------------------------------------------------- + + void "NonTransactionalSynchronizationOuterSessionStrategy leaves a disconnected session disconnected and registers synchronization when lazyConnection is true"() { + given: + SessionImplementor sessionImpl = Mock(SessionImplementor) + JdbcCoordinator coordinator = Mock(JdbcCoordinator) + LogicalConnectionImplementor logicalConnection = Mock(LogicalConnectionImplementor) + Connection physicalCon = Mock(Connection) + + sessionImpl.isOpen() >> true + sessionImpl.getJdbcCoordinator() >> coordinator + coordinator.getLogicalConnection() >> logicalConnection + logicalConnection.isPhysicallyConnected() >> false + logicalConnection.getPhysicalConnection() >> physicalCon + + SessionHolder holder = new SessionHolder(sessionImpl) + NonTransactionalSynchronizationOuterSessionStrategy strategy = + new NonTransactionalSynchronizationOuterSessionStrategy( + sessionFactory, dataSource, txResources, holder, true) + + TransactionSynchronization registeredSync = null + + when: + strategy.prepare() + + then: "the outer session takes no physical connection" + 0 * logicalConnection.getPhysicalConnection() + 0 * physicalCon.getAutoCommit() + + and: "synchronization is registered at SESSION_SYNCHRONIZATION_ORDER" + 1 * txResources.registerSynchronization(_ as TransactionSynchronization) >> { TransactionSynchronization sync -> + registeredSync = sync + } + registeredSync != null + registeredSync.order == SessionFactoryUtils.SESSION_SYNCHRONIZATION_ORDER + } + + void "NonTransactionalSynchronizationOuterSessionStrategy skips priming and synchronization when lazyConnection is false"() { + given: + SessionImplementor sessionImpl = Mock(SessionImplementor) + JdbcCoordinator coordinator = Mock(JdbcCoordinator) + LogicalConnectionImplementor logicalConnection = Mock(LogicalConnectionImplementor) + + sessionImpl.isOpen() >> true + sessionImpl.getJdbcCoordinator() >> coordinator + coordinator.getLogicalConnection() >> logicalConnection + logicalConnection.isPhysicallyConnected() >> false + + SessionHolder holder = new SessionHolder(sessionImpl) + NonTransactionalSynchronizationOuterSessionStrategy strategy = + new NonTransactionalSynchronizationOuterSessionStrategy( + sessionFactory, dataSource, txResources, holder, false) + + when: + strategy.prepare() + + then: + 0 * logicalConnection.getPhysicalConnection() + 0 * txResources.registerSynchronization(_) + } + + void "NonTransactionalSynchronizationOuterSessionStrategy disconnects on restore when lazyConnection is false and connection became physically connected"() { + given: + SessionImplementor sessionImpl = Mock(SessionImplementor) + JdbcCoordinator coordinator = Mock(JdbcCoordinator) + LogicalConnectionImplementor logicalConnection = Mock(LogicalConnectionImplementor) + + sessionImpl.isOpen() >> true + sessionImpl.getJdbcCoordinator() >> coordinator + coordinator.getLogicalConnection() >> logicalConnection + logicalConnection.isPhysicallyConnected() >>> [false, true] + logicalConnection.isOpen() >> true + + SessionHolder holder = new SessionHolder(sessionImpl) + NonTransactionalSynchronizationOuterSessionStrategy strategy = + new NonTransactionalSynchronizationOuterSessionStrategy( + sessionFactory, dataSource, txResources, holder, false) + + strategy.prepare() + + when: "restoring after session became physically connected during scope" + strategy.restore() + + then: "connection is manually disconnected to drop closed connection" + 1 * logicalConnection.manualDisconnect() + } + + void "NonTransactionalSynchronizationOuterSessionStrategy synchronization disconnects on suspend"() { + given: + SessionImplementor sessionImpl = Mock(SessionImplementor) + JdbcCoordinator coordinator = Mock(JdbcCoordinator) + LogicalConnectionImplementor logicalConnection = Mock(LogicalConnectionImplementor) + Connection physicalCon = Mock(Connection) + + sessionImpl.isOpen() >> true + sessionImpl.getJdbcCoordinator() >> coordinator + coordinator.getLogicalConnection() >> logicalConnection + logicalConnection.isOpen() >> true + logicalConnection.isPhysicallyConnected() >>> [false, true] + logicalConnection.getPhysicalConnection() >> physicalCon + + SessionHolder holder = new SessionHolder(sessionImpl) + NonTransactionalSynchronizationOuterSessionStrategy strategy = + new NonTransactionalSynchronizationOuterSessionStrategy( + sessionFactory, dataSource, txResources, holder, true) + + TransactionSynchronization registeredSync = null + txResources.registerSynchronization(_ as TransactionSynchronization) >> { TransactionSynchronization sync -> + registeredSync = sync + } + + strategy.prepare() + assert registeredSync != null + + when: "a nested REQUIRED transaction starts, suspending outer synchronizations" + registeredSync.suspend() + + then: "the outer connection is disconnected when the session had connected" + 1 * logicalConnection.manualDisconnect() + } + + void "NonTransactionalSynchronizationOuterSessionStrategy synchronization disconnects on beforeCompletion"() { + given: + SessionImplementor sessionImpl = Mock(SessionImplementor) + JdbcCoordinator coordinator = Mock(JdbcCoordinator) + LogicalConnectionImplementor logicalConnection = Mock(LogicalConnectionImplementor) + Connection physicalCon = Mock(Connection) + + sessionImpl.isOpen() >> true + sessionImpl.getJdbcCoordinator() >> coordinator + coordinator.getLogicalConnection() >> logicalConnection + logicalConnection.isOpen() >> true + logicalConnection.isPhysicallyConnected() >>> [false, true] + logicalConnection.getPhysicalConnection() >> physicalCon + + SessionHolder holder = new SessionHolder(sessionImpl) + NonTransactionalSynchronizationOuterSessionStrategy strategy = + new NonTransactionalSynchronizationOuterSessionStrategy( + sessionFactory, dataSource, txResources, holder, true) + + TransactionSynchronization registeredSync = null + txResources.registerSynchronization(_ as TransactionSynchronization) >> { TransactionSynchronization sync -> + registeredSync = sync + } + + strategy.prepare() + assert registeredSync != null + + when: "the scope finishes without suspension" + registeredSync.beforeCompletion() + + then: "the logical connection is disconnected before Spring closes the physical connection" + 1 * logicalConnection.manualDisconnect() + } + + void "NonTransactionalSynchronizationOuterSessionStrategy skips priming when logical connection is already physically connected"() { + given: + SessionImplementor sessionImpl = Mock(SessionImplementor) + JdbcCoordinator coordinator = Mock(JdbcCoordinator) + LogicalConnectionImplementor logicalConnection = Mock(LogicalConnectionImplementor) + + sessionImpl.isOpen() >> true + sessionImpl.getJdbcCoordinator() >> coordinator + coordinator.getLogicalConnection() >> logicalConnection + logicalConnection.isPhysicallyConnected() >> true + + SessionHolder holder = new SessionHolder(sessionImpl) + NonTransactionalSynchronizationOuterSessionStrategy strategy = + new NonTransactionalSynchronizationOuterSessionStrategy( + sessionFactory, dataSource, txResources, holder, true) + + when: + strategy.prepare() + + then: + 0 * logicalConnection.getPhysicalConnection() + 0 * txResources.registerSynchronization(_) + } + + // ------------------------------------------------------------------------- + // DefaultOuterSessionStrategy + // ------------------------------------------------------------------------- + + void "DefaultOuterSessionStrategy unbinds and restores holders without synchronization"() { + given: + ConnectionHolder connectionHolder = new ConnectionHolder(Mock(Connection)) + txResources.getResource(dataSource) >> connectionHolder + txResources.isSynchronizationActive() >> false + + DefaultOuterSessionStrategy strategy = new DefaultOuterSessionStrategy( + sessionFactory, dataSource, txResources, sessionHolder, false) + + when: + strategy.prepare() + strategy.suspendAndUnbind() + + then: + 1 * txResources.unbindResource(sessionFactory) + 1 * txResources.unbindResource(dataSource) + 0 * txResources.clearSynchronization() + + when: + strategy.restore() + + then: + 1 * txResources.bindResource(sessionFactory, sessionHolder) + 1 * txResources.bindResource(dataSource, connectionHolder) + 0 * txResources.initSynchronization() + } + + void "DefaultOuterSessionStrategy does not prime disconnected session during prepare"() { + given: + SessionImplementor sessionImpl = Mock(SessionImplementor) + JdbcCoordinator coordinator = Mock(JdbcCoordinator) + LogicalConnectionImplementor logicalConnection = Mock(LogicalConnectionImplementor) + + sessionImpl.isOpen() >> true + sessionImpl.getJdbcCoordinator() >> coordinator + coordinator.getLogicalConnection() >> logicalConnection + logicalConnection.isPhysicallyConnected() >> false + + SessionHolder holder = new SessionHolder(sessionImpl) + DefaultOuterSessionStrategy strategy = new DefaultOuterSessionStrategy( + sessionFactory, dataSource, txResources, holder, false) + + when: + strategy.prepare() + + then: "no physical connection checkout occurs" + 0 * logicalConnection.getPhysicalConnection() + 0 * txResources.registerSynchronization(_) + } + + void "DefaultOuterSessionStrategy disconnects on restore when session became physically connected during scope"() { + given: + SessionImplementor sessionImpl = Mock(SessionImplementor) + JdbcCoordinator coordinator = Mock(JdbcCoordinator) + LogicalConnectionImplementor logicalConnection = Mock(LogicalConnectionImplementor) + + sessionImpl.isOpen() >> true + sessionImpl.getJdbcCoordinator() >> coordinator + coordinator.getLogicalConnection() >> logicalConnection + logicalConnection.isPhysicallyConnected() >>> [false, true] + logicalConnection.isOpen() >> true + + SessionHolder holder = new SessionHolder(sessionImpl) + DefaultOuterSessionStrategy strategy = new DefaultOuterSessionStrategy( + sessionFactory, dataSource, txResources, holder, false) + + strategy.prepare() + + when: "restoring after session became physically connected during scope" + strategy.restore() + + then: "connection is returned to pool" + 1 * logicalConnection.manualDisconnect() + } +} diff --git a/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/WithNewSessionLazyPoolSpec.groovy b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/WithNewSessionLazyPoolSpec.groovy new file mode 100644 index 00000000000..46a20b7d483 --- /dev/null +++ b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/WithNewSessionLazyPoolSpec.groovy @@ -0,0 +1,112 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.grails.orm.hibernate + +import javax.sql.DataSource + +import grails.gorm.annotation.Entity +import org.grails.orm.hibernate.cfg.Settings +import org.grails.orm.hibernate.support.hibernate7.SessionHolder +import org.hibernate.Session +import org.hibernate.engine.spi.SessionImplementor +import org.hibernate.resource.jdbc.spi.LogicalConnectionImplementor +import org.springframework.jdbc.datasource.DelegatingDataSource +import org.springframework.transaction.TransactionDefinition +import org.springframework.transaction.support.TransactionSynchronizationManager +import spock.lang.AutoCleanup +import spock.lang.Issue +import spock.lang.Specification + +/** + * A lazy data source with a pool of one connection: withNewSession must not hold a second connection for the outer + * session, or a transaction in the closure that then reads the outer session waits for a connection that never comes. + */ +@Issue('https://github.com/apache/grails-core/issues/16571') +class WithNewSessionLazyPoolSpec extends Specification { + + @AutoCleanup + HibernateDatastore datastore + + org.apache.tomcat.jdbc.pool.DataSource tomcatDataSource + Session requestSession + + void setup() { + datastore = new HibernateDatastore([ + (Settings.SETTING_DB_CREATE): 'create-drop', + 'dataSource.url': 'jdbc:h2:mem:lazyPoolDB;LOCK_TIMEOUT=10000', + 'dataSource.lazy': true, + 'dataSource.pooled': true, + 'dataSource.properties.maxActive': '1', + 'dataSource.properties.maxWait': '500' + ], LazyPoolAuthor, LazyPoolBook) + DataSource current = datastore.connectionSources.defaultConnectionSource.dataSource + while (current instanceof DelegatingDataSource) { + current = ((DelegatingDataSource) current).targetDataSource + } + tomcatDataSource = (org.apache.tomcat.jdbc.pool.DataSource) current + LazyPoolAuthor.withTransaction { + LazyPoolAuthor author = new LazyPoolAuthor(name: 'Stephen King').save(flush: true) + new LazyPoolBook(title: 'The Stand', author: author).save(flush: true) + } + requestSession = datastore.sessionFactory.openSession() + TransactionSynchronizationManager.bindResource(datastore.sessionFactory, new SessionHolder(requestSession)) + } + + void cleanup() { + if (TransactionSynchronizationManager.hasResource(datastore.sessionFactory)) { + TransactionSynchronizationManager.unbindResource(datastore.sessionFactory) + } + requestSession?.close() + } + + void "a transaction in withNewSession that reads the outer session does not need a second connection"() { + given: 'the outer session holds a book whose author is lazy, and no connection' + LazyPoolBook book = LazyPoolBook.withTransaction { LazyPoolBook.first() } + LogicalConnectionImplementor logicalConnection = ((SessionImplementor) requestSession).jdbcCoordinator.logicalConnection + if (logicalConnection.isOpen() && logicalConnection.isPhysicallyConnected()) { + logicalConnection.manualDisconnect() + } + assert tomcatDataSource.pool.active == 0 + + when: 'a SUPPORTS scope runs a transaction in withNewSession and then reads the outer session' + String name = LazyPoolBook.withTransaction(propagationBehavior: TransactionDefinition.PROPAGATION_SUPPORTS, readOnly: true) { + LazyPoolBook.withNewSession { + LazyPoolBook.withTransaction { + LazyPoolBook.count() + book.author.name + } + } + } + + then: 'the pool of one served both' + name == 'Stephen King' + tomcatDataSource.pool.active == 0 + } +} + +@Entity +class LazyPoolAuthor { + String name +} + +@Entity +class LazyPoolBook { + String title + LazyPoolAuthor author +} diff --git a/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/WithNewSessionNonLazyPoolSpec.groovy b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/WithNewSessionNonLazyPoolSpec.groovy new file mode 100644 index 00000000000..90353bc6245 --- /dev/null +++ b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/WithNewSessionNonLazyPoolSpec.groovy @@ -0,0 +1,193 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.grails.orm.hibernate + +import javax.sql.DataSource + +import grails.gorm.annotation.Entity +import org.grails.orm.hibernate.cfg.Settings +import org.grails.orm.hibernate.support.hibernate7.SessionHolder +import org.hibernate.Session +import org.hibernate.engine.spi.SessionImplementor +import org.hibernate.resource.jdbc.spi.LogicalConnectionImplementor +import org.springframework.jdbc.datasource.DelegatingDataSource +import org.springframework.transaction.TransactionDefinition +import org.springframework.transaction.support.TransactionSynchronizationManager +import spock.lang.AutoCleanup +import spock.lang.Issue +import spock.lang.Specification + +@Issue('https://github.com/apache/grails-core/issues/16783') +class WithNewSessionNonLazyPoolSpec extends Specification { + + @AutoCleanup + HibernateDatastore datastore + + org.apache.tomcat.jdbc.pool.DataSource tomcatDataSource + org.hibernate.Session requestSession + + void setup() { + Map config = [ + (Settings.SETTING_DB_CREATE): 'create-drop', + 'dataSource.url': 'jdbc:h2:mem:nonlazyPoolDB;LOCK_TIMEOUT=10000', + 'dataSource.lazy': false, + 'dataSource.pooled': true, + 'dataSource.properties.maxActive': '1', + 'dataSource.properties.maxWait': '500' + ] + datastore = new HibernateDatastore(config, NonLazyAuthor, NonLazyBook) + DataSource ds = datastore.connectionSources.defaultConnectionSource.dataSource + DataSource current = ds + while (current instanceof DelegatingDataSource) { + current = ((DelegatingDataSource) current).targetDataSource + } + tomcatDataSource = (org.apache.tomcat.jdbc.pool.DataSource) current + + requestSession = datastore.sessionFactory.openSession() + TransactionSynchronizationManager.bindResource( + datastore.sessionFactory, new SessionHolder(requestSession)) + } + + void cleanup() { + if (TransactionSynchronizationManager.hasResource(datastore.sessionFactory)) { + TransactionSynchronizationManager.unbindResource(datastore.sessionFactory) + } + requestSession?.close() + datastore?.close() + } + + private void disconnectSession(Session session) { + if (session instanceof SessionImplementor) { + LogicalConnectionImplementor logicalConnection = ((SessionImplementor) session).jdbcCoordinator?.logicalConnection + if (logicalConnection != null && logicalConnection.isOpen() && logicalConnection.isPhysicallyConnected()) { + logicalConnection.manualDisconnect() + } + } + } + + void "withNewSession works with non-lazy single connection pool after initial transaction disconnects session"() { + given: + NonLazyAuthor.withTransaction { NonLazyAuthor.count() } + disconnectSession(requestSession) + assert tomcatDataSource.pool.active == 0 + + when: "withNewSession executes a query" + NonLazyBook.withNewSession { NonLazyAuthor.count() } + + then: "single connection pool does not exhaust and active connections return to zero" + tomcatDataSource.pool.active == 0 + } + + void "withNewSession with inner transaction works with non-lazy single connection pool"() { + given: + NonLazyAuthor.withTransaction { NonLazyAuthor.count() } + disconnectSession(requestSession) + assert tomcatDataSource.pool.active == 0 + + when: "calling withNewSession with inner transaction that saves" + NonLazyBook.withNewSession { + NonLazyBook.withTransaction { + new NonLazyAuthor(name: 'x').save(flush: true) + } + } + + then: "active connections return to zero and write is persisted" + tomcatDataSource.pool.active == 0 + NonLazyAuthor.count() == 1 + } + + void "withNewSession with inner transaction works under SUPPORTS transaction with non-lazy single connection pool"() { + given: + NonLazyAuthor.withTransaction { NonLazyAuthor.count() } + disconnectSession(requestSession) + assert tomcatDataSource.pool.active == 0 + + when: "calling withNewSession under SUPPORTS transaction with inner transaction" + NonLazyBook.withTransaction(propagationBehavior: TransactionDefinition.PROPAGATION_SUPPORTS, readOnly: true) { + NonLazyBook.withNewSession { + NonLazyBook.withTransaction { + new NonLazyAuthor(name: 'x').save(flush: true) + } + } + } + + then: "active connections return to zero and write is persisted" + tomcatDataSource.pool.active == 0 + NonLazyAuthor.count() == 1 + } + + void "lazy loading in inner transaction with non-lazy pool drops closed connection on restore"() { + given: "a seeded author and book" + NonLazyAuthor author = null + NonLazyAuthor.withTransaction { + author = new NonLazyAuthor(name: 'Stephen King').save(flush: true) + new NonLazyBook(title: 'The Stand', author: author).save(flush: true) + } + + and: "disconnecting the request session via an initial transaction" + NonLazyAuthor.withTransaction { NonLazyAuthor.count() } + disconnectSession(requestSession) + assert tomcatDataSource.pool.active == 0 + + when: "calling withNewSession where inner transaction fetches book and lazy-loads association" + NonLazyBook.withNewSession { + NonLazyBook.withTransaction { + NonLazyBook book = NonLazyBook.first() + assert book.author.name == 'Stephen King' + new NonLazyAuthor(name: 'Tenar').save(flush: true) + } + } + + then: "the request-bound session remains usable and pool active connections return to zero" + tomcatDataSource.pool.active == 0 + NonLazyBook.count() == 1 + NonLazyAuthor.count() == 2 + } + + void "withNewSession runs and rebinds holder when outer request session was closed before scope"() { + given: "a closed outer request session with holder still bound" + SessionHolder boundHolder = + (SessionHolder) TransactionSynchronizationManager.getResource(datastore.sessionFactory) + requestSession.close() + assert !requestSession.isOpen() + + when: "running withNewSession" + int count = NonLazyAuthor.withNewSession { + NonLazyAuthor.count() + } + + then: "the closure executes and the closed holder is restored" + count == 0 + TransactionSynchronizationManager.getResource(datastore.sessionFactory).is(boundHolder) + } +} + +@Entity +class NonLazyAuthor { + String name +} + +@Entity +class NonLazyBook { + String title + NonLazyAuthor author + static constraints = { + author nullable: true + } +} diff --git a/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/WithNewSessionReadOnlySpec.groovy b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/WithNewSessionReadOnlySpec.groovy new file mode 100644 index 00000000000..837f97aa6bc --- /dev/null +++ b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/WithNewSessionReadOnlySpec.groovy @@ -0,0 +1,85 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.grails.orm.hibernate + +import grails.gorm.annotation.Entity +import org.grails.orm.hibernate.cfg.Settings +import org.hibernate.Session +import org.grails.orm.hibernate.support.hibernate7.SessionHolder +import org.springframework.transaction.support.TransactionSynchronizationManager +import spock.lang.AutoCleanup +import spock.lang.Issue +import spock.lang.Specification + +/** + * With the open-session read-only setting on and a session bound for the request, withNewSession hands its closure a + * session that must stay writable: the closure commits its own write transaction on it. + */ +@Issue('https://github.com/apache/grails-core/issues/16571') +class WithNewSessionReadOnlySpec extends Specification { + + @AutoCleanup + HibernateDatastore datastore + + Session requestSession + + void setup() { + datastore = new HibernateDatastore([ + (Settings.SETTING_DB_CREATE): 'create-drop', + 'dataSource.url': 'jdbc:h2:mem:withNewSessionReadOnly;LOCK_TIMEOUT=10000', + 'hibernate.osiv.readonly': true + ], ReadOnlyScopeBook) + assert datastore.osivReadOnly + ReadOnlyScopeBook.withNewSession { Session session -> + session.beginTransaction() + session.persist(new ReadOnlyScopeBook(title: 'before')) + session.transaction.commit() + } + requestSession = datastore.sessionFactory.openSession() + TransactionSynchronizationManager.bindResource(datastore.sessionFactory, new SessionHolder(requestSession)) + } + + void cleanup() { + if (TransactionSynchronizationManager.hasResource(datastore.sessionFactory)) { + TransactionSynchronizationManager.unbindResource(datastore.sessionFactory) + } + requestSession?.close() + } + + void "a change the closure commits on the new session is kept"() { + when: + ReadOnlyScopeBook.withNewSession { Session session -> + session.beginTransaction() + ReadOnlyScopeBook book = session.createQuery("from ReadOnlyScopeBook b where b.title = 'before'", ReadOnlyScopeBook).uniqueResult() + book.title = 'after' + session.transaction.commit() + } + int changed = ReadOnlyScopeBook.withNewSession { Session session -> + session.createQuery("select count(b) from ReadOnlyScopeBook b where b.title = 'after'", Long).uniqueResult().intValue() + } + + then: + changed == 1 + } +} + +@Entity +class ReadOnlyScopeBook { + String title +}