01: package liquibase.database.sql;
02:
03: import liquibase.database.Database;
04:
05: import java.sql.CallableStatement;
06: import java.sql.SQLException;
07: import java.util.ArrayList;
08: import java.util.Collections;
09: import java.util.List;
10:
11: public class StoredProcedureStatement implements SqlStatement,
12: CallableSqlStatement {
13:
14: private String procedureName;
15: private List<String> parameters = new ArrayList<String>();
16: private List<Integer> types = new ArrayList<Integer>();
17:
18: public StoredProcedureStatement(String procedureName) {
19: this .procedureName = procedureName;
20: }
21:
22: public String getProcedureName() {
23: return procedureName;
24: }
25:
26: public List<String> getParameters() {
27: return Collections.unmodifiableList(parameters);
28: }
29:
30: public void addParameter(String param, int type) {
31: parameters.add(param);
32: types.add(type);
33: }
34:
35: public boolean supportsDatabase(Database database) {
36: return true;
37: }
38:
39: public String getSqlStatement(Database database) {
40: StringBuffer string = new StringBuffer();
41: string.append("exec (").append(procedureName);
42: for (String param : getParameters()) {
43: string.append(" ").append(param).append(",");
44: }
45: return string.toString().replaceFirst(",$", ")");
46: }
47:
48: public CallableStatement createCallableStatement(Database database)
49: throws SQLException {
50: StringBuffer sql = new StringBuffer("{call "
51: + getProcedureName());
52:
53: if (parameters.size() > 0) {
54: sql.append("(");
55: //noinspection UnusedDeclaration
56: for (Object param : parameters) {
57: sql.append("?,");
58: }
59: sql.deleteCharAt(sql.lastIndexOf(","));
60: sql.append(")");
61: }
62:
63: sql.append("}");
64:
65: CallableStatement pstmt = database.getConnection().prepareCall(
66: sql.toString());
67:
68: for (int i = 0; i < parameters.size(); i++) {
69: Object param = parameters.get(i);
70: int type = database.getDatabaseType(types.get(i));
71:
72: if (param == null) {
73: pstmt.setNull(i + 1, type);
74: } else {
75: pstmt.setObject(i + 1, param, type);
76: }
77: }
78:
79: return pstmt;
80: }
81:
82: public String getEndDelimiter(Database database) {
83: return ";";
84: }
85: }
|