* @see net.sf.hajdbc.sync.SynchronizationSupport#synchronizeSequences()
*/
@Override
public void synchronizeSequences() throws SQLException
{
SequenceSupport support = this.context.getDialect().getSequenceSupport();
if (support != null)
{
Collection<SequenceProperties> sequences = this.context.getSourceDatabaseProperties().getSequences();
if (!sequences.isEmpty())
{
D sourceDatabase = this.context.getSourceDatabase();
Set<D> databases = this.context.getActiveDatabaseSet();
ExecutorService executor = this.context.getExecutor();
Map<SequenceProperties, Long> sequenceMap = new HashMap<SequenceProperties, Long>();
Map<D, Future<Long>> futureMap = new HashMap<D, Future<Long>>();
for (SequenceProperties sequence: sequences)
{
final String sql = support.getNextSequenceValueSQL(sequence);
this.logger.log(Level.DEBUG, sql);
for (final D database: databases)
{
final SynchronizationContext<Z, D> context = this.context;
Callable<Long> task = new Callable<Long>()
{
@Override
public Long call() throws SQLException
{
Statement statement = context.getConnection(database).createStatement();
try
{
ResultSet resultSet = statement.executeQuery(sql);
resultSet.next();
return resultSet.getLong(1);
}
finally
{
Resources.close(statement);
}
}
};
futureMap.put(database, executor.submit(task));
}
try
{
Long sourceValue = futureMap.get(sourceDatabase).get();
sequenceMap.put(sequence, sourceValue);
for (D database: databases)
{
if (!database.equals(sourceDatabase))
{
Long value = futureMap.get(database).get();
if (!value.equals(sourceValue))
{
throw new SQLException(Messages.SEQUENCE_OUT_OF_SYNC.getMessage(sequence, database, value, sourceDatabase, sourceValue));
}
}
}
}
catch (InterruptedException e)
{
throw new SQLException(e);
}
catch (ExecutionException e)
{
throw ExceptionType.SQL.<SQLException>getExceptionFactory().createException(e.getCause());
}
}
Connection targetConnection = this.context.getConnection(this.context.getTargetDatabase());
Statement targetStatement = targetConnection.createStatement();
try
{
for (SequenceProperties sequence: sequences)
{
String sql = support.getAlterSequenceSQL(sequence, sequenceMap.get(sequence) + 1);
this.logger.log(Level.DEBUG, sql);
targetStatement.addBatch(sql);
}