We have some code that we use inside unit tests. This particular code has some code which checks to see if the function was run inside a cftransaction block. This is done as a safety mechanism to make sure the function is always called inside a transaction block.
If ACF, we could use the following code:
createObject(“java”, “coldfusion.tagext.sql.TransactionTag”).getCurrent()
If the getCurrent() returns null, then we know the code is not running inside a transaction block.
I’m trying to find some way to do something equivalent in Lucee. I think maybe I could try setting a “savepoint” using cftransaction, but that doesn’t throw an exception when not inside a transaction block.
I’ve been poking around the source code, but I’m not seeing anything that would appear to help me.
Is there a way to determine if the current executing call is inside a transaction block?
Ok, so it appears I can use the following to determine if code is within a transaction block:
var isInTransactionBlock = getPageContext().getDataSourceManager().isAutoCommit() ? false : true;
If isAutoCommit()
is false, then the code is inside a transaction block because the “autoCommit” property on the DataSourceManager gets set to false as soon as the transaction action="begin"
is called. As soon as the code is committed, then the isAutoCommit()
would return true.
5 Likes
I know I’m late to the party here, but I found another method which works from Hibernate v3.x through Hibernate v5.x:
ORMGetSession().isTransactionInProgress();
On Adobe, we need to get the “real” session object instead of the session wrapper, so this becomes:
ORMGetSession().getActualSession().isTransactionInProgress();
Putting these two together, we get the following cross-engine snippet:
public boolean function isInTransaction(){
if ( listFindNoCase( "Lucee", server.coldfusion.productname ) ) {
return ORMGetSession().isTransactionInProgress();
} else {
return ORMGetSession().getActualSession().isTransactionInProgress();
}
}