P15GEN2\59518
2024-05-29 d4210c7c4b04abde20037ea8aa0f54ef8a2649aa
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
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";
    }
    
}