1

All I am trying to achieve is to replace comparative equals with ILIKE, but not assignment statements.

i.e.

SELECT * FROM db WHERE SUBJECT_TYPE = 'Person';

should be replaced as

SELECT * FROM db WHERE SUBJECT_TYPE ILIKE 'Person';

However

SET session ABC.VAR = 5;

should remain untouched.

For this I am trying to use lookahead such that there is no SET before equals (=).

Java

String str = "SELECT * FROM db WHERE SUBJECT_TYPE = 'Person' AND PREDICATE = 'name' AND OBJECT_VALUE = 'John' AND VERSION = '0' "
final Pattern EQUALS_ILIKE_PATTERN = Pattern.compile("(?i)((^((?!SET)[^=])+?)\\s*)=");

final Matcher matcher = EQUALS_ILIKE_PATTERN .matcher(str);

while (matcher.find())
{
    final String fromString = matcher.group(0);

    str = matcher.replaceAll("$1 ILIKE");
}

System.out.println(str);

Actual outcome:

SELECT * FROM db WHERE SUBJECT_TYPE ILIKE 'Person' AND PREDICATE = 'name' AND OBJECT_VALUE = 'John' AND VERSION = '0'

Expected outcome:

SELECT * FROM db WHERE SUBJECT_TYPE ILIKE 'Person' AND PREDICATE ILIKE 'name' AND OBJECT_VALUE ILIKE 'John' AND VERSION ILIKE '0'

The actual outcome here doesn't replace all necessary equals (=).

0

1 Answer 1

1

We can do this with a one-liner call to String#replaceAll:

 String str = "SELECT * FROM db WHERE SUBJECT_TYPE = 'Person' AND PREDICATE = 'name' AND OBJECT_VALUE = 'John' AND VERSION = '0' ";
str = str.replaceAll("(WHERE|AND)\\s+(\\S+)\\s+=(?=\\s*'[^'+]+')", "$1 $2 ILIKE");
System.out.println(str);

This outputs (formatted for readability):

SELECT *
FROM db
WHERE
    SUBJECT_TYPE ILIKE 'Person' AND
    PREDICATE ILIKE 'name' AND
    OBJECT_VALUE ILIKE 'John' AND
    VERSION ILIKE '0'
Sign up to request clarification or add additional context in comments.

6 Comments

This regex won't take care of assignment thing i.e. the one which contains 'SET'.
Updated to target only the WHERE clause. Now the SET clause won't be updated.
I am not really concerned about WHERE|AND , Just want to negate SET. Also I am wondering why my regex is not working for this ?
(?!SET) is a zero width negative lookahead. You never actually match any content after the lookahead, so it doesn't make much sense. If you want a more robust solution, you would have to write a SQL parser, so I won't update my answer again.
would you like to update the answer with working solution at least ?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.