View Javadoc
1   package com.randomnoun.common.jexl.sql.function;
2   
3   /* (c) 2013-2018 randomnoun. All Rights Reserved. This work is licensed under a
4    * BSD Simplified License. (http://www.randomnoun.com/bsd-simplified.html)
5    */
6   
7   import java.util.List;
8   
9   import com.randomnoun.common.jexl.eval.EvalContext;
10  import com.randomnoun.common.jexl.eval.EvalException;
11  import com.randomnoun.common.jexl.sql.SqlColumn;
12  import com.randomnoun.common.jexl.sql.SqlFunction;
13  import com.randomnoun.common.jexl.sql.SqlGenerator;
14  import com.randomnoun.common.jexl.sql.SqlText;
15  
16  /** 'StartsWith' function. Returns true if the data in the specified SqlColumn (in the first
17   *  argument) starts with the text in the second argument.
18   */
19  public class StartsWithFunction
20  	extends com.randomnoun.common.jexl.eval.function.StartsWithFunction
21  	implements SqlFunction {
22  	/** @inheritdoc */
23  	public String toSql(String functionName, EvalContext evalContext, List<Object> arguments) {
24  		if (arguments.size() != 2) { throw new EvalException(functionName + "() must contain two parameters"); }
25  		if (!(arguments.get(0) instanceof SqlColumn)) { throw new EvalException(functionName + "() parameter 1 must be an SQL column"); }
26  		if (!(arguments.get(1) instanceof String || arguments.get(1) instanceof SqlText)) { throw new EvalException(functionName + "() parameter 2 must be a string type"); }
27  
28  		SqlColumn arg0 = (SqlColumn) arguments.get(0);
29  		String likePattern = "";
30  		if (arguments.get(1) instanceof String) {
31  			likePattern = SqlGenerator.escapeLikeLiteral(evalContext, (String) arguments.get(1)) + "%";
32  		} else {
33  			// could conceivably concat result with '%'                    
34  			throw new EvalException("Cannot translate startsWith(a,b) where 'b' is a dynamically-generated value");
35  		}
36  
37  		Object arg1 = arguments.get(1);
38  		if (arg0 == null) { throw new EvalException(functionName + "() first parameter cannot be null"); }
39  		if (arg1 == null) { throw new EvalException(functionName + "() second parameter cannot be null"); }
40  		return "(" + arg0.getFullName() + " LIKE " + SqlGenerator.toSql(evalContext, likePattern) + ")";
41  	}
42  }