com.sap.cds.impl.sql.ContainsToLike Maven / Gradle / Ivy
/************************************************************************
* © 2021-2023 SAP SE or an SAP affiliate company. All rights reserved. *
************************************************************************/
package com.sap.cds.impl.sql;
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.impl.ExpressionVisitor;
import com.sap.cds.ql.impl.LeanModifier;
public class ContainsToLike {
private static final char ESCAPE_CHAR = '\\';
public static CqnPredicate transform(FunctionMapper functionMapper, CqnPredicate pred) {
return CQL.copy(pred, new LeanModifier() {
@Override
public Predicate containment(Position position, CqnValue value, CqnValue term, boolean caseInsensitive) {
CqnValue pattern = escapeTerm(position, term);
return functionMapper.like(value, pattern, "" + ESCAPE_CHAR, caseInsensitive);
}
});
}
private static CqnValue escapeTerm(Position position, CqnValue term) {
return ExpressionVisitor.copy(term, new LeanModifier() {
@Override
public CqnValue literal(CqnLiteral> literal) {
if (literal.isString()) {
String term = SQLHelper.escapeLikePattern(ESCAPE_CHAR, literal.asString().value());
switch (position) {
case START:
term = term + '%';
break;
case ANY:
term = '%' + term + '%';
break;
case END:
term = '%' + term;
break;
default:
throw new IllegalArgumentException("unexpected position: " + position);
}
return CQL.val(term);
} else {
return literal;
}
}
});
}
}