All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.sap.cds.impl.sql.ContainsToLike Maven / Gradle / Ivy

There is a newer version: 3.4.0
Show newest version
/************************************************************************
 * © 2021-2024 SAP SE or an SAP affiliate company. All rights reserved. *
 ************************************************************************/
package com.sap.cds.impl.sql;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.sap.cds.jdbc.spi.FunctionMapper;
import com.sap.cds.ql.CQL;
import com.sap.cds.ql.Predicate;
import com.sap.cds.ql.cqn.CqnContainmentTest.Position;
import com.sap.cds.ql.cqn.CqnLiteral;
import com.sap.cds.ql.cqn.CqnPredicate;
import com.sap.cds.ql.cqn.CqnValue;
import com.sap.cds.ql.cqn.Modifier;
import com.sap.cds.ql.impl.ExpressionVisitor;

public class ContainsToLike {

	private static Pattern asteriskPattern = Pattern.compile("(? literal) {
				if (literal.isString()) {
					String term = SQLHelper.escapeLikePattern(ESCAPE_CHAR, literal.asString().value());

					return CQL.val(switch (position) {
						case ANY -> '%' + term + '%';
						case START -> term + '%';
						case END -> '%' + term;
						case SEARCH -> toLikeTerm(term, true);
						case MATCH -> toLikeTerm(term, false);
					});
				} else {
					return literal;
				}
			}
		});
	}

	private static String toLikeTerm(String term, boolean fallbackToContains) {
		boolean wildcard = false;
		Matcher asteriskMatcher = asteriskPattern.matcher(term);
		if (asteriskMatcher.find()) {
			term = asteriskMatcher.replaceAll("$1%");
			wildcard = true;
		}
		Matcher questionmarkMatcher = questionmarkPattern.matcher(term);
		if (questionmarkMatcher.find()) {
			term = questionmarkMatcher.replaceAll("$1_");
			wildcard = true;
		}
		if (!wildcard && fallbackToContains) {
			term = '%' + term + '%';
		}
		return term;
	}
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy