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/** SQL 'LIKE' operator. Returns true if the data in the specified SqlColumn (in the first
017 *  argument) matches the supplied LIKE pattern (in the second argument)
018 */
019public class LikeFunction extends com.randomnoun.common.jexl.eval.function.LikeFunction implements SqlFunction 
020{
021        /** @inheritdoc */
022        public String toSql(String functionName, EvalContext evalContext, List<Object> arguments) {
023                if (arguments.size() != 2) { throw new EvalException(functionName + "() must contain two parameters"); }
024                if (!(arguments.get(0) instanceof SqlColumn)) { throw new EvalException(functionName + "() parameter 1 must be an SQL column"); }
025                if (!(arguments.get(1) instanceof String || arguments.get(1) instanceof SqlText)) { throw new EvalException(functionName + "() parameter 2 must be a string type"); }
026
027                SqlColumn arg0 = (SqlColumn) arguments.get(0);
028                Object arg1 = arguments.get(1);
029                if (arg0 == null) { throw new EvalException(functionName + "() first parameter cannot be null"); }
030                if (arg1 == null) { throw new EvalException(functionName + "() second parameter cannot be null"); }
031
032                return "(" + arg0.getFullName() + " LIKE " + SqlGenerator.toSql(evalContext, arg1) + ")";
033        }
034}