001package com.randomnoun.common.jexl.sql.function;
002
003/* (c) 2013-2018 randomnoun. All Rights Reserved. This work is licensed under a
004 * BSD Simplified License. (http://www.randomnoun.com/bsd-simplified.html)
005 */
006
007import java.util.List;
008
009import com.randomnoun.common.jexl.eval.EvalContext;
010import com.randomnoun.common.jexl.eval.EvalException;
011import com.randomnoun.common.jexl.sql.SqlColumn;
012import com.randomnoun.common.jexl.sql.SqlFunction;
013import com.randomnoun.common.jexl.sql.SqlGenerator;
014import com.randomnoun.common.jexl.sql.SqlText;
015
016/** 'StartsWith' function. Returns true if the data in the specified SqlColumn (in the first
017 *  argument) starts with the text in the second argument.
018 */
019public class StartsWithFunction
020        extends com.randomnoun.common.jexl.eval.function.StartsWithFunction
021        implements SqlFunction {
022        /** @inheritdoc */
023        public String toSql(String functionName, EvalContext evalContext, List<Object> arguments) {
024                if (arguments.size() != 2) { throw new EvalException(functionName + "() must contain two parameters"); }
025                if (!(arguments.get(0) instanceof SqlColumn)) { throw new EvalException(functionName + "() parameter 1 must be an SQL column"); }
026                if (!(arguments.get(1) instanceof String || arguments.get(1) instanceof SqlText)) { throw new EvalException(functionName + "() parameter 2 must be a string type"); }
027
028                SqlColumn arg0 = (SqlColumn) arguments.get(0);
029                String likePattern = "";
030                if (arguments.get(1) instanceof String) {
031                        likePattern = SqlGenerator.escapeLikeLiteral(evalContext, (String) arguments.get(1)) + "%";
032                } else {
033                        // could conceivably concat result with '%'                    
034                        throw new EvalException("Cannot translate startsWith(a,b) where 'b' is a dynamically-generated value");
035                }
036
037                Object arg1 = arguments.get(1);
038                if (arg0 == null) { throw new EvalException(functionName + "() first parameter cannot be null"); }
039                if (arg1 == null) { throw new EvalException(functionName + "() second parameter cannot be null"); }
040                return "(" + arg0.getFullName() + " LIKE " + SqlGenerator.toSql(evalContext, likePattern) + ")";
041        }
042}