Escape colon (':') in custom h2 Query - java

So I am trying to write a custom query for h2 using its JSON_OBJECT function. JSON_OBJECT uses a format of JSON_OBJECT(key:value) so as a simple example in my Spring repository I am writing a query like #Query(value = "SELECT JSON_OBJECT('id':1)", nativeQuery = true)
When executing that same query in the h2-console it operates as expected but in Spring the colon(':') is treated as a special character for variable insertion so when testing it, it tries to map the following value as a variable which of course throws an error.
I've tried escaping the colon with \\ and \\\\ and putting a space between the colon and the value but doesnt seem to help.
Any ideas on how to either escape the char or make spring think the colon is an acceptable character?

Actually you can simply use the alternative syntax JSON_OBJECT(KEY 'id' VALUE 1), there is no need to use escaped \\:, escape sequences make your query less readable.

Related

Can I escape escape sequences in MySQL string literals during scripts generating?

My pre-production task is to create tools to parse MySQL database schema and generate scripts to recreate it completely or partially. I've implemented first part of the task by fetching metadata from INFORMATION_SCHEMA tables and storing it in form of tree-like structure in memory. Now I'm busy generating scripts for each database objects. The issue I encountered is escaping Special Character Escape Sequences (as noted at this page, table 9.1) such as ' and " during writing string literals. Literals can be met in trigger and routine body or in SELECT part of view definition.
When I generate script for creating, say, trigger, literals with unescaped quotes corrupt the query and I cannot run it without manual correction. I get something like this.
Query with syntax error
I would like to be able to run my queries immediately after generating, so I need to write them with escaped quotes. I deviced two possible solution.
Fetch metadata of triggers, routines and views in the way that MySQL escape special sequences in literals. I've been browsing SO and docs for a while and yet to find an appropriate function on the MySQL side. (QUOTE() is not the case as it'll escape every escapable character in routine/trigger definition and even the ones that should not be escaped)
Escape that sequences manually just before script generating. I've tried to figure out the regexp to find and replace such units and here is what I got.
Pattern pattern = Pattern.compile("\'(.+)\'");
Matcher matcher = pattern.matcher("IF (NEW.AccountBalance <> 0 OR NEW.BlockedAmount <> 0) THEN SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT='The account can't be closed!' END IF;");
StringBuilder sb = new StringBuilder();
while (matcher.find()) {
sb.append("'").append(matcher.group(1).replace("'", "\\\'")).append("'");
}
System.out.println(sb.toString());`
Certainly, this will not work if you've got several literals as I have in my example. It'll escape all single quotes between first and last single quote character and turn two or more literals into one senseless string. I'm guessing is it's possible at all to do it on the app side as regex cannot know where the literal starts and ends. Only me and MySQL can.
I've tried Walid's regexp solution from here and it escaped all target characters in my string, even starting and ending quotes for literals.
I'd highly appreciate any advice how to do it on the app or MySQL side.

Escaping special characters using hibernate criterias

I'm facing a non usual issue while using criterias. I want to do a criteria with a like clause but the text contains special chars like the bracket char "[" and it seems that it's a special char in MSSQL database.
From an sql query I must use the special wording ESCAPE see example :
AND file1.FILE_NAME like '%[Main profile picture]%' **ESCAPE '['**
But I dont know how I can do the same using criteria. I'm currently using this clause temporarily :
criteria.add(Restrictions.like("files.fileName", "%Main profile picture%"));
but that's not what I want I really need to escape the '[' char.
Can somebody help me with this please...?
Thank you for your help!

Hibernate 4 escape colon character in createSQLQuery

The following hibernate query fails:
select 1 as "{jsonprop:'string'}" from dual
with the following exception:
org.hibernate.QueryException: Space is not allowed after parameter prefix ':' [ select 1 as "{json:'string'}" from dual]
Is there no way to escape the colon character in Hibernate 4? Ive tried \: and :: but neither worked. Ive seen mention that this might have been corrected in the v3 parser, but its still failing - even though the colon is inside a constant.
I don't have a quick way to test this, but I believe '\:' is what you need.
select 1 as "{jsonprop\\:'string'}" from dual
See https://stackoverflow.com/a/11971764/3684299
If that doesn't work, where are you defining your query: in a named query file or within a String in code?
If you're using hibernate 5+ i believe you can use '::' to escape ':'. see here
If you're using 4.x a solution i've used is to use like/ilike and the '_' character.

JPQL LIKE syntax with Strings

EDIT:
I changed the hard coded query to be:
query.setParameter("desc", "%unplug //your// server... enjoy the freedom%" ESCAPE '//')
and now I am getting an com.sun.jdi.InvocationException occurred invoking method.
There's no stacktrace produced either.
I have a description column in my PostgreSQL database and I am trying to query it with a 'LIKE' clause, however I am unable to get any results. Here's an example:
Query query = em.createQuery("from MyClass c WHERE c.description LIKE :desc");
query.setParameter("desc", "%unplug /your/ server... enjoy the freedom%");
In the database I have many descriptions containing a substring of the above text. I've done a lot of research and looked into escaping special chars etc, but nothing has worked.
I am missing something, I just cannot figure out what that is.
Most likely the slash / is messing up the parsing in PG. Turn the parameter into a quoted literal. Unless you are certain that no special characters go into string arguments (i.e. you control the strings), this is always a good idea to avoid SQL injection.
query.setParameter("desc", "quote_literal('%unplug /your/ server... enjoy the freedom%')");

Oracle parses text of "'{S}Paris2" as a string literal then finds {S} which it is treating as a SQL Escape Sequence which it doesn't recognize

I am getting the following error after running the jsp report.
Query Tag:doAfterBody(),0,Non supported SQL92 token at position: 3477: S
I know that the following snippet causing the problem ‘{S}’:
…….. AND (L.Applicable_Location_Region_ID IN (N'PARIS2', N'{S}Paris2'))
As per my investigation, I came to know following:
Oracle parses the SQL and treats the text of "'{S}Paris2" as a string literal then finds {S} which it is treating as a SQL Escape Sequence which it doesn't recognize.
The following link explains well about “Escape Characters”:
http://docs.oracle.com/cd/F49540_01/DOC/inter.815/a67843/cqspcl.htm
we must use {S} followed by name.
The above AND statement works fine with SQL Server and MySQL, but causes problem with Oracle as “When you use braces to escape a single character, the escaped character becomes a separate token in the query.”
Due to above reason the application treats {S}, as the escaped a single character with braces becomes a separate token in the query.
So please could you help me how can I escape single character with braces in oracle or any suggestion please.
Try
AND (L.Applicable_Location_Region_ID IN (N'PARIS2', N'\{S\}Paris2'))
EDIT:
Running this query from Toad
select (N'{S}test2') from dual where ((N'{S}test2') IN (N'test2', N'{S}test2'))
does work for me.
Are you sure that the problem is in Oracle database and not in the class/driver accessing it ?

Categories