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/** 'EndsWith' function. Returns true if the data in the specified SqlColumn (in the first
017 *  argument) ends with the text in the second argument.
018 */
019public class EndsWithFunction extends com.randomnoun.common.jexl.eval.function.EndsWithFunction  implements SqlFunction {
020        /** @inheritdoc */
021        public String toSql(String functionName, EvalContext evalContext, List<Object> arguments) {
022                if (arguments.size() != 2) { throw new EvalException(functionName + "() must contain two parameters"); }
023                if (!(arguments.get(0) instanceof SqlColumn)) { throw new EvalException(functionName + "() parameter 1 must be an SQL column"); }
024                if (!(arguments.get(1) instanceof String || arguments.get(1) instanceof SqlText)) { throw new EvalException(functionName + "() parameter 2 must be a string type"); }
025
026                SqlColumn arg0 = (SqlColumn) arguments.get(0);
027                String likePattern = "";
028
029                if (arguments.get(1) instanceof String) {
030                        likePattern = "%" + SqlGenerator.escapeLikeLiteral(evalContext, (String) arguments.get(1));
031                } else {
032                        // could conceivably concat result with '%'                    
033                        throw new EvalException("Cannot translate " + functionName + "(a,b) where 'b' is a dynamically-generated value");
034                }
035
036                Object arg1 = arguments.get(1);
037
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}