001: package liquibase.database.sql;
002:
003: import liquibase.database.Database;
004:
005: import java.util.*;
006:
007: public class UpdateStatement implements SqlStatement {
008: private String schemaName;
009: private String tableName;
010: private Map<String, Object> newColumnValues = new HashMap<String, Object>();
011: private String whereClause;
012: private List<Object> whereParameters = new ArrayList<Object>();
013:
014: public UpdateStatement(String schemaName, String tableName) {
015: this .schemaName = schemaName;
016: this .tableName = tableName;
017: }
018:
019: public String getSchemaName() {
020: return schemaName;
021: }
022:
023: public String getTableName() {
024: return tableName;
025: }
026:
027: public UpdateStatement addNewColumnValue(String columnName,
028: Object newValue) {
029: newColumnValues.put(columnName, newValue);
030:
031: return this ;
032: }
033:
034: public String getWhereClause() {
035: return whereClause;
036: }
037:
038: public UpdateStatement setWhereClause(String whereClause) {
039: this .whereClause = whereClause;
040:
041: return this ;
042: }
043:
044: public void addWhereParameter(Object value) {
045: this .whereParameters.add(value);
046: }
047:
048: public boolean supportsDatabase(Database database) {
049: return true;
050: }
051:
052: public Map<String, Object> getNewColumnValues() {
053: return newColumnValues;
054: }
055:
056: public String getSqlStatement(Database database) {
057: StringBuffer sql = new StringBuffer("UPDATE "
058: + database.escapeTableName(getSchemaName(),
059: getTableName()) + " SET");
060: for (String column : newColumnValues.keySet()) {
061: sql.append(" ").append(database.escapeColumnName(column))
062: .append(" = ");
063: sql.append(convertToString(newColumnValues.get(column),
064: database));
065: sql.append(",");
066: }
067:
068: sql.deleteCharAt(sql.lastIndexOf(","));
069: if (whereClause != null) {
070: String fixedWhereClause = "WHERE " + whereClause;
071: for (Object param : whereParameters) {
072: fixedWhereClause = fixedWhereClause.replaceFirst("\\?",
073: convertToString(param, database));
074: }
075: sql.append(" ").append(fixedWhereClause);
076: }
077:
078: return sql.toString();
079: }
080:
081: private String convertToString(Object newValue, Database database) {
082: String sqlString;
083: if (newValue == null) {
084: sqlString = "NULL";
085: } else if (newValue instanceof String
086: && database.shouldQuoteValue(((String) newValue))) {
087: sqlString = "'" + newValue + "'";
088: } else if (newValue instanceof Date) {
089: sqlString = database.getDateLiteral(((Date) newValue));
090: } else if (newValue instanceof Boolean) {
091: if (((Boolean) newValue)) {
092: sqlString = database.getTrueBooleanValue();
093: } else {
094: sqlString = database.getFalseBooleanValue();
095: }
096: } else {
097: sqlString = newValue.toString();
098: }
099: return sqlString;
100: }
101:
102: public String getEndDelimiter(Database database) {
103: return ";";
104: }
105: }
|