/**********************************************************************
Copyright (c) 2003 Erik Bengtson and others. All rights reserved.
Licensed 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
http://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.
Contributors:
2003 Andy Jefferson - coding standards
2004 Andy Jefferson - changed to provide Sequence generator for all databases
2004 Andy Jefferson - removed the MetaData requirement
...
**********************************************************************/
package org.jpox.store.rdbms.poid;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import org.jpox.store.poid.PoidBlock;
import org.jpox.store.poid.PoidException;
import org.jpox.store.rdbms.RDBMSManager;
import org.jpox.store.rdbms.SQLController;
import org.jpox.store.rdbms.adapter.RDBMSAdapter;
import org.jpox.store.rdbms.sqlidentifier.RDBMSIdentifierFactory;
import org.jpox.store.rdbms.sqlidentifier.SQLIdentifier;
import org.jpox.util.JPOXLogger;
/**
* This generator utilises datastore sequences. It uses a statement like
* <PRE>"select <sequence>.nextval from dual"</PRE> to get the next value in the
* sequence. It is datastore-dependent since there is no RDBMS-independent statement.
* SequencePoidGenerator works with numbers, so clients using this Poid must cast the ID to Long
* <P>
* <B>Required user properties</B>
* <UL>
* </UL>
* </P>
* <P>
* <B>Optional user properties</B>
* <UL>
* <LI><U>sequence-catalog-name</U> - catalog for the sequence</LI>
* <LI><U>sequence-schema-name</U> - schema for the sequence</LI>
* <LI><U>key-cache-size</U> - number of unique identifiers to cache</LI>
* <LI><U>key-min-value</U> - determines the minimum value a sequence can generate</LI>
* <LI><U>key-max-value</U> - determines the maximum value a sequence can generate</LI>
* <LI><U>key-start-with</U> - the initial value for the sequence</LI>
* <LI><U>key-increment-by</U> - specifies which value is added to the current
* sequence value to create a new value (default is 1)</LI>
* <LI><U>key-database-cache-size</U> - specifies how many sequence numbers are to be
* preallocated and stored in memory for faster access</LI>
* </UL>
*
* @version $Revision: 1.21 $
*/
public final class SequencePoidGenerator extends AbstractRDBMSPoidGenerator
{
/** Name of the sequence that we are creating values for */
protected String sequenceName = null;
/**
* Constructor.
* @param name Symbolic name for the generator
* @param props Properties controlling the behaviour of the generator
*/
public SequencePoidGenerator(String name, Properties props)
{
super(name, props);
allocationSize = 1;
if (properties != null && properties.get("key-cache-size") != null)
{
try
{
allocationSize = Integer.parseInt((String)properties.get("key-cache-size"));
}
catch (Exception e)
{
throw new PoidException(LOCALISER.msg("040006",properties.get("key-cache-size")));
}
}
if (properties != null && properties.get("sequence-name") == null)
{
throw new PoidException(LOCALISER.msg("040007",properties.get("sequence-name")));
}
}
/**
* Reserve a block of ids.
* @param size Block size
* @return The reserved block
*/
protected synchronized PoidBlock reserveBlock(long size)
{
if (size < 1)
{
return null;
}
PreparedStatement ps = null;
ResultSet rs = null;
List oid = new ArrayList();
RDBMSManager srm = (RDBMSManager)storeMgr;
SQLController sqlControl = srm.getSQLController();
try
{
// Get next available id
RDBMSAdapter dba = (RDBMSAdapter) srm.getDatastoreAdapter();
String stmt = dba.getSequenceNextStmt(getSequenceName());
ps = sqlControl.getStatementForQuery(connection, stmt);
rs = sqlControl.executeStatementQuery(connection, stmt, ps);
Long nextId = new Long(0);
if (rs.next())
{
nextId = new Long(rs.getLong(1));
oid.add(nextId);
}
for (int i=1; i<size; i++)
{
// size must match key-increment-by otherwise it will
// cause duplicates keys
nextId = new Long(nextId.longValue()+1);
oid.add(nextId);
}
if (JPOXLogger.POID.isDebugEnabled())
{
JPOXLogger.POID.debug(LOCALISER.msg("040004", "" + size));
}
return new PoidBlock(oid);
}
catch (SQLException e)
{
throw new PoidException(LOCALISER_RDBMS.msg("061001",e.getMessage()));
}
finally
{
try
{
if (rs != null)
{
rs.close();
}
if (ps != null)
{
sqlControl.closeStatement(connection, ps);
}
}
catch (SQLException e)
{
// non-recoverable error
}
}
}
/**
* Accessor for the sequence name to use (fully qualified with catalog/schema).
* @return The sequence name
*/
protected String getSequenceName()
{
if (sequenceName == null)
{
// Set the name of the sequence (including catalog/schema as required)
String sequenceCatalogName = properties.getProperty("sequence-catalog-name");
if (sequenceCatalogName == null)
{
sequenceCatalogName = properties.getProperty("catalog-name");
}
String sequenceSchemaName = properties.getProperty("sequence-schema-name");
if (sequenceSchemaName == null)
{
sequenceSchemaName = properties.getProperty("schema-name");
}
String sequenceName = properties.getProperty("sequence-name");
RDBMSManager srm = (RDBMSManager)storeMgr;
RDBMSIdentifierFactory idFactory = (RDBMSIdentifierFactory)srm.getIdentifierFactory();
SQLIdentifier identifier = (SQLIdentifier)idFactory.newSequenceIdentifier(sequenceName);
if (((RDBMSAdapter)srm.getDatastoreAdapter()).supportsCatalogsInTableDefinitions() && sequenceCatalogName != null)
{
identifier.setCatalogName(sequenceCatalogName);
}
if (((RDBMSAdapter)srm.getDatastoreAdapter()).supportsSchemasInTableDefinitions() && sequenceSchemaName != null)
{
identifier.setSchemaName(sequenceSchemaName);
}
this.sequenceName = identifier.getFullyQualifiedName(true);
}
return sequenceName;
}
/**
* Indicator for whether the generator requires its own repository.
* This class needs a repository so returns true.
* @return Whether a repository is required.
*/
protected boolean requiresRepository()
{
return true;
}
/**
* Method to create the sequence.
* @return Whether it was created successfully.
*/
protected boolean createRepository()
{
PreparedStatement ps = null;
RDBMSManager srm = (RDBMSManager)storeMgr;
RDBMSAdapter dba = (RDBMSAdapter)srm.getDatastoreAdapter();
SQLController sqlControl = srm.getSQLController();
String stmt = dba.getSequenceCreateStmt(getSequenceName(),
(String) properties.get("key-min-value"),
(String) properties.get("key-max-value"),
(String) properties.get("key-start-with"),
(String) properties.get("key-increment-by"),
(String) properties.get("key-database-cache-size"));
try
{
ps = sqlControl.getStatementForUpdate(connection, stmt, false);
sqlControl.executeStatementUpdate(connection, stmt, ps, true);
}
catch (SQLException e)
{
JPOXLogger.DATASTORE.error(e);
throw new PoidException(LOCALISER_RDBMS.msg("061000",e.getMessage()) + stmt);
}
finally
{
try
{
if (ps != null)
{
sqlControl.closeStatement(connection, ps);
}
}
catch (SQLException e)
{
// non-recoverable error
}
}
return true;
}
}