Liferay 6.2 Sharding Issue

Issue

Recently I worked on a Liferay 6.1 to 6.2 upgrade project. The Liferay was configured to use sharding with three database schemas. During the upgrade process, an exception is thrown:

 

Analysis

The cause of the problem is: the upgrade process tries to upgrade the default shard twice. There is a similar issue in Liferay 6.1 which is marked as fixed: https://issues.liferay.com/browse/LPS-31817 But I believe the issue is not fixed completely.

After debugging I found that during the upgrade of the second shard, after the ClassNameLocalService got called, the shard datasource always switches to the default shard and never switch back to the second shard. It caused the rest of the upgrade process to try to upgrade the default shard instead of the second shard.

The problem does not only impact the upgrade process, it also impacts the normal CRUD operations. Whenever there is a call to  ClassNameLocalService, CompanyPersistence etc, the subsequent CRUD call within the same thread will always use the default shard, which may cause problems such as data object not found or the data is stored in the wrong shard.

 

Solution

The cause of the problem is in the class com.liferay.portal.dao.shard.advice.ShardPersistenceAdvice from line 59 to line 88 (most importantly, line 70):

The correct code from line 59 to line 88 should be:

When calling ClassNamePersistence, CompanyPersistence etc, we should use the default shard as the datasource, but after the call is finished, we should switch back to the *current* shard.