1 package groovy.sql; 2 3 import java.util.ArrayList ; 4 import java.util.List ; 5 6 import org.codehaus.groovy.ast.CodeVisitorSupport; 7 import org.codehaus.groovy.ast.expr.BinaryExpression; 8 import org.codehaus.groovy.ast.expr.BooleanExpression; 9 import org.codehaus.groovy.ast.expr.ConstantExpression; 10 import org.codehaus.groovy.ast.expr.Expression; 11 import org.codehaus.groovy.ast.expr.PropertyExpression; 12 import org.codehaus.groovy.ast.stmt.ReturnStatement; 13 import org.codehaus.groovy.syntax.Token; 14 import org.codehaus.groovy.syntax.Types; 15 16 20 public class SqlWhereVisitor extends CodeVisitorSupport { 21 22 private StringBuffer buffer = new StringBuffer (); 23 private List parameters = new ArrayList (); 24 25 public String getWhere() { 26 return buffer.toString(); 27 } 28 29 public void visitReturnStatement(ReturnStatement statement) { 30 statement.getExpression().visit(this); 31 } 32 33 public void visitBinaryExpression(BinaryExpression expression) { 34 Expression left = expression.getLeftExpression(); 35 Expression right = expression.getRightExpression(); 36 37 left.visit(this); 38 buffer.append(" "); 39 40 Token token = expression.getOperation(); 41 buffer.append(tokenAsSql(token)); 42 43 buffer.append(" "); 44 right.visit(this); 45 } 46 47 public void visitBooleanExpression(BooleanExpression expression) { 48 expression.getExpression().visit(this); 49 } 50 51 public void visitConstantExpression(ConstantExpression expression) { 52 getParameters().add(expression.getValue()); 53 buffer.append("?"); 54 } 55 56 public void visitPropertyExpression(PropertyExpression expression) { 57 buffer.append(expression.getProperty()); 58 } 59 60 public List getParameters() { 61 return parameters; 62 } 63 64 protected String tokenAsSql(Token token) { 65 switch (token.getType()) { 66 case Types.COMPARE_EQUAL : 67 return "="; 68 case Types.LOGICAL_AND : 69 return "and"; 70 case Types.LOGICAL_OR : 71 return "or"; 72 default : 73 return token.getText(); 74 } 75 } 76 } 77 | Popular Tags |