001 package biz.hammurapi.sql.syntax; 002 003 import java.io.Serializable; 004 import java.sql.PreparedStatement; 005 import java.sql.SQLException; 006 import java.util.ArrayList; 007 import java.util.Iterator; 008 import java.util.List; 009 010 import biz.hammurapi.sql.Parameterizer; 011 012 public class StatementBuilder implements StatementFragment, Serializable { 013 014 private StringBuffer sql = new StringBuffer(); 015 private List parameterizers = new ArrayList(); 016 017 public StatementBuilder(String sql) { 018 this(sql, null); 019 } 020 021 public StatementBuilder(String sql, Parameterizer parameterizer) { 022 if (sql!=null) { 023 this.sql.append(sql); 024 } 025 026 if (parameterizer!=null) { 027 parameterizers.add(parameterizer); 028 } 029 } 030 031 public StatementBuilder() { 032 033 } 034 035 public StatementBuilder(StatementFragment fragment) { 036 this(fragment==null ? null : fragment.toSqlString(), fragment); 037 } 038 039 public void append(String sql) { 040 if (sql!=null) { 041 if (this.sql.length()>0) { 042 this.sql.append(" "); 043 } 044 this.sql.append(sql); 045 } 046 } 047 048 public void append(String sql, Parameterizer parameterizer) { 049 append(sql); 050 if (parameterizer!=null) { 051 parameterizers.add(parameterizer); 052 } 053 } 054 055 public void append(StatementFragment fragment) { 056 if (fragment!=null) { 057 append(fragment.toSqlString(), fragment); 058 } 059 } 060 061 public String toSqlString() { 062 return sql.toString(); 063 } 064 065 public int parameterize(PreparedStatement ps, int idx) throws SQLException { 066 Iterator it = parameterizers.iterator(); 067 while (it.hasNext()) { 068 idx=((Parameterizer) it.next()).parameterize(ps, idx); 069 } 070 return idx; 071 } 072 073 public static StatementBuilder assemble(String sql, Parameterizer parameterizer, StatementFragment fragment) { 074 StatementBuilder ret = new StatementBuilder(sql, parameterizer); 075 if (fragment!=null) { 076 ret.append(fragment); 077 } 078 return ret; 079 } 080 081 public int hashCode() { 082 final int prime = 31; 083 int result = 1; 084 result = prime * result 085 + ((parameterizers == null) ? 0 : parameterizers.hashCode()); 086 result = prime * result + ((sql == null) ? 0 : sql.toString().hashCode()); 087 return result; 088 } 089 090 public boolean equals(Object obj) { 091 if (this == obj) 092 return true; 093 if (obj == null) 094 return false; 095 if (getClass() != obj.getClass()) 096 return false; 097 final StatementBuilder other = (StatementBuilder) obj; 098 if (parameterizers == null) { 099 if (other.parameterizers != null) 100 return false; 101 } else if (!parameterizers.equals(other.parameterizers)) 102 return false; 103 if (sql == null) { 104 if (other.sql != null) 105 return false; 106 } else if (other.sql==null || !sql.toString().equals(other.sql.toString())) 107 return false; 108 return true; 109 } 110 111 }