DatastoreIdentifier tableIdentifier, String columnName, int initialValue)
throws SQLException
{
PreparedStatement ps = null;
Long nextVal = null;
SQLController sqlControl = storeMgr.getSQLController();
try
{
ps = sqlControl.getStatementForQuery(conn, fetchStmt);
sequenceNameMapping.setString(null, ps, new int[]{1}, sequenceName);
ResultSet rs = sqlControl.executeStatementQuery(conn, fetchStmt, ps);
try
{
if (!rs.next())
{
// No data in the SEQUENCE_TABLE for this sequence currently
boolean addedSequence = false;
if (columnName != null && tableIdentifier != null)
{
// Table/Column specified so find the current max value for the field being generated
PreparedStatement ps2 = null;
ResultSet rs2 = null;
try
{
String fetchInitStmt = "SELECT MAX(" + columnName + ") FROM " + tableIdentifier.getFullyQualifiedName(false);
ps2 = sqlControl.getStatementForQuery(conn, fetchInitStmt);
rs2 = sqlControl.executeStatementQuery(conn, fetchInitStmt, ps2);
if (rs2.next())
{
long val = rs2.getLong(1);
addSequence(sequenceName, new Long(incrementBy + 1 + val), conn);
nextVal = new Long(1 + val);
addedSequence = true;
}
}
catch (Exception e)
{
// Do nothing - since if the table is empty we get this
}
finally
{
if (rs2 != null)
{
rs2.close();
}
if (ps2 != null)
{
sqlControl.closeStatement(conn, ps2);
}
}
}
if (!addedSequence)
{
// Just start at "initialValue"
addSequence(sequenceName, new Long(incrementBy + initialValue), conn);
nextVal = new Long(initialValue);
}
}
else
{
// Data already exists in sequence table for this key so increment it
nextVal = new Long(rs.getLong(1));
incrementSequence(sequenceName, incrementBy, conn);
}
}
finally
{
rs.close();
}
}
catch (SQLException e)
{
throw new PoidException(LOCALISER.msg("061001", e.getMessage()),e);
}
finally
{
if (ps != null)
{
sqlControl.closeStatement(conn, ps);
}
}
return nextVal;
}