0

I'm using the guide at https://www.baeldung.com/rest-api-search-language-rsql-fiql to build an RSQL based JPA specification.

The like clause looks like the following:

return builder.like(root.get(property), argument.toString().replace('*', '%'));

My question is, what is the best way to handle escaping special characters in the user's input?

For example, if the user supplied the string:

*my-search%-term*

the above code would translate this to:

%my-search%-term%

I would want to escape the % in the string so that it is not evaluated as the % wildcard in the LIKE clause.

The following post states the LIKE special characters for each database:

List of special characters for SQL LIKE clause

and also note this comment from one of the answers:

It's impossible to write DBMS-independent code here, because you don't know what characters you're going to have to escape, and the standard says you can't escape things that don't need to be escaped. (See section 8.5/General Rules/3.a.ii.)

I am wondering what the best way to handle this is? I'm using postgres in production, and h2 in testing, but ideally don't want the solution tied to either of these.

rmf
  • 625
  • 2
  • 9
  • 39
  • The comment you quote is wrong. There are exactly two characters that require escaping `_` and `%` –  Mar 26 '20 at 13:16
  • "*I'm using postgres in production, and h2 in testing*" which itself is a bad idea because you can never be sure that your code works correctly in production –  Mar 26 '20 at 13:19

2 Answers2

0

Why not use regular expression matching instead of like?

where col ~ <user input>

It sounds like your users may be more familiar with regular expressions.

If you just want an exact match that ignores all wildcard functionality, you can use position:

where position(<user input> in col) > 0
Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
0

In standard SQL you only need to escape the % and _ characters as those are the only wildcards supported by the LIKE operator.

So *my-search%-term* should be used like this in SQL

WHERE some_column LIKE '%my-search\%-term%' escape '\'