package foundation.data.object;
|
|
import java.sql.CallableStatement;
|
import java.sql.Connection;
|
import java.sql.SQLException;
|
import java.sql.Types;
|
|
import foundation.persist.NamedSQL;
|
import foundation.persist.SQLRunner;
|
import foundation.persist.source.NamedDataSource;
|
import foundation.server.config.DBaseType;
|
|
public class Sequence {
|
|
private NamedDataSource dataSource;
|
private String tableName;
|
private String nextSQL;
|
private String currentSQL;
|
|
public Sequence(String tableName) throws Exception {
|
this(NamedDataSource.getInstance(), tableName);
|
}
|
|
public Sequence(NamedDataSource dataSource, String tableName) throws Exception {
|
this.dataSource = dataSource;
|
this.tableName = tableName;
|
|
DBaseType type = dataSource.getDBaseType();
|
|
//1. create next SQL
|
NamedSQL namedSQL = NamedSQL.getInstance(type, "nextval");
|
namedSQL.setTableName(tableName);
|
nextSQL = namedSQL.toString();
|
|
//2. create current SQL
|
namedSQL = NamedSQL.getInstance(type, "currval");
|
namedSQL.setTableName(tableName);
|
currentSQL = namedSQL.toString();
|
}
|
|
public long next() throws Exception {
|
long value = SQLRunner.getSequence(dataSource, this, SequenceValue.Next);
|
return value;
|
}
|
|
public long current() throws Exception {
|
long value = SQLRunner.getSequence(dataSource, this, SequenceValue.Current);
|
return value;
|
}
|
|
public long exec(Connection conn, SequenceValue value) throws SQLException {
|
long result = 0;
|
|
String sql = (SequenceValue.Current == value) ? currentSQL : nextSQL;
|
|
CallableStatement stmt = conn.prepareCall(sql);
|
try {
|
stmt.setString(1, tableName);
|
stmt.registerOutParameter(2, Types.BIGINT);
|
stmt.execute();
|
|
result = stmt.getLong(2);
|
}
|
finally {
|
try {
|
if (stmt != null) {
|
stmt.close();
|
}
|
} catch (SQLException e) {
|
}
|
}
|
|
return result;
|
}
|
|
public String getNextSQL() {
|
return nextSQL;
|
}
|
|
public String getCurrentSQL() {
|
return currentSQL;
|
}
|
|
@Override
|
public String toString() {
|
return tableName + " sequence";
|
}
|
|
}
|