01: package liquibase.database.sql;
02:
03: import liquibase.database.Database;
04: import liquibase.exception.StatementNotSupportedOnDatabaseException;
05:
06: import java.util.Date;
07: import java.util.HashMap;
08: import java.util.Map;
09:
10: public class InsertStatement implements SqlStatement {
11: private String schemaName;
12: private String tableName;
13: private Map<String, Object> newColumnValues = new HashMap<String, Object>();
14:
15: public InsertStatement(String schemaName, String tableName) {
16: this .schemaName = schemaName;
17: this .tableName = tableName;
18: }
19:
20: public String getSchemaName() {
21: return schemaName;
22: }
23:
24: public String getTableName() {
25: return tableName;
26: }
27:
28: public InsertStatement addColumnValue(String columnName,
29: Object newValue) {
30: newColumnValues.put(columnName, newValue);
31:
32: return this ;
33: }
34:
35: public Object getColumnValue(String columnName) {
36: return newColumnValues.get(columnName);
37: }
38:
39: public String getSqlStatement(Database database)
40: throws StatementNotSupportedOnDatabaseException {
41: if (getSchemaName() != null && !database.supportsSchemas()) {
42: throw new StatementNotSupportedOnDatabaseException(
43: "Database does not support schemas", this , database);
44: }
45: StringBuffer sql = new StringBuffer("INSERT INTO "
46: + database.escapeTableName(getSchemaName(),
47: getTableName()) + " (");
48: for (String column : newColumnValues.keySet()) {
49: sql.append(database.escapeColumnName(column)).append(", ");
50: }
51: sql.deleteCharAt(sql.lastIndexOf(" "));
52: sql.deleteCharAt(sql.lastIndexOf(","));
53:
54: sql.append(") VALUES (");
55:
56: for (String column : newColumnValues.keySet()) {
57: Object newValue = newColumnValues.get(column);
58: if (newValue == null) {
59: sql.append("NULL");
60: } else if (newValue instanceof String
61: && database.shouldQuoteValue(((String) newValue))) {
62: sql
63: .append("'")
64: .append(
65: database
66: .escapeStringForDatabase((String) newValue))
67: .append("'");
68: } else if (newValue instanceof Date) {
69: sql.append(database.getDateLiteral(((Date) newValue)));
70: } else if (newValue instanceof Boolean) {
71: if (((Boolean) newValue)) {
72: sql.append(database.getTrueBooleanValue());
73: } else {
74: sql.append(database.getFalseBooleanValue());
75: }
76: } else {
77: sql.append(newValue);
78: }
79: sql.append(", ");
80: }
81:
82: sql.deleteCharAt(sql.lastIndexOf(" "));
83: sql.deleteCharAt(sql.lastIndexOf(","));
84:
85: sql.append(")");
86: return sql.toString();
87: }
88:
89: public String getEndDelimiter(Database database) {
90: return ";";
91: }
92:
93: public boolean supportsDatabase(Database database) {
94: return true;
95: }
96: }
|