Anorm: Escape { for Postgres - postgresql

I want to execute query like this:
SELECT '{"a":[1,2,3],"b":[4,5,6]}'::json#>>'{a,2}'
But anorm can not prepare the query and raise the parse error.
How to escape the '{' and '}' symbols in SQL text for anorm?

Update:
the solution is a pretty simple (like RTFM:) )
SELECT '{"a":[1,2,3],"b":[4,5,6]}'::json#>>'{a,2}'
should be
SELECT '{"a":[1,2,3],"b":[4,5,6]}'::json->'a'->>2
there are no symbols '{', '}' so Anorm is happy.

You can pass the values as stings which contain curly braces
Look at this example
SELECT '{}'::jsonb;
so I replaced it with binding
SELECT {empty}::jsonb;
And passed this named param on executing the query
NamedParameter("empty", "{}")

Related

POSTGRESQL Dollar Quotes in Where Clause

For people who tried or needed a solution to escape every special character (even $) in a WHERE CLAUSE in POSTGRESQL, here is how it should be use
the documentation can be somehow hard to understand, and there is no proper example of it so here is mine
e.g : if you want to make a request looking as
SELECT
*
FROM
<TableName>
WHERE
<ColumnName> = 'string with ' character';
it will throw an error cause "character'" is outside the string
So here is how it should be written:
SELECT
*
FROM
<TableName>
WHERE
<ColumnName> = $$string with ' character$$;
The WHERE CONDITION will take the string literally; the interface may look broken but the following instruction will still be interpreted as expected.
SELECT
*
FROM
<TableName>
WHERE
<ColumnName> = $$string with ' character$$ AND <OtherColumnName> IS NOT NULL;
This could even be another escaped string with $$.
For details about dollar quoting, look at the documentation.

Postgres replacing 'text' with e'text'

I inserted a bunch of rows with a text field like content='...\n...\n...'.
I didn't use e in front, like conent=e'...\n...\n..., so now \n is not actually displayed as a newline - it's printed as text.
How do I fix this, i.e. how to change every row's content field from '...' to e'...'?
The syntax variant E'string' makes Postgres interpret the given string as Posix escape string. \n encoding a newline is only one of many interpreted escape sequences (even if the most common one). See:
Insert text with single quotes in PostgreSQL
To "re-evaluate" your Posix escape string, you could use a simple function with dynamic SQL like this:
CREATE OR REPLACE FUNCTION f_eval_posix_escapes(INOUT _string text)
LANGUAGE plpgsql AS
$func$
BEGIN
EXECUTE 'SELECT E''' || _string || '''' INTO _string;
END
$func$;
WARNING 1: This is inherently unsafe! We have to evaluate input strings dynamically without quoting and escaping, which allows SQL injection. Only use this in a safe environment.
WARNING 2: Don't apply repeatedly. Or it will misinterpret your actual string with genuine \ characters, etc.
WARNING 3: This simple function is imperfect as it cannot cope with nested single quotes properly. If you have some of those, consider instead:
Unescape a string with escaped newlines and carriage returns
Apply:
UPDATE tbl
SET content = f_eval_posix_escapes(content)
WHERE content IS DISTINCT FROM f_eval_posix_escapes(content);
db<>fiddle here
Note the added WHERE clause to skip updates that would not change anything. See:
How do I (or can I) SELECT DISTINCT on multiple columns?
Use REPLACE in an update query. Something like this: (I'm on mobile so please ignore any typo or syntax erro)
UPDATE table
SET
column = REPLACE(column, '\n', e'\n')

How to match a backslash with the like operator in Redshift

How can I match a backslash with the like operator in Redshift?
I tried below, but they didn't work…
-- syntax error
select 'a\a' like '\';
-- false
select 'a\a' like '\\';
-- syntax error
select 'a\a' like '\\\';
-- syntax error
select 'a\a' like '\' escape '^';
-- syntax error
select 'a\a' like '^\' escape '^';
Envelope it with %:
select 'a\a' like '%\\%';

Postgres escaping backslash in SIMILAR TO syntax

I have table containing 4 lines as follow:
Audit\\subfolder\System2.log
Audit\\subfolder/System1.log
Audit\\System2.log
Audit\\System1.log
Running the following query:
select * from table where file_location SIMILAR TO
'Audit\\[^/]*'
will yield:
Audit\\subfolder\System2.log
Audit\\System2.log
Audit\\System1.log
However running the following query:
select * from table where file_location SIMILAR TO
'Audit\\[^\\]*'
yields me nothing.
What would be the correct way to escape \\ in SIMILAR TO clause?
What would be the correct way to escape \ in SIMILAR TO clause?
Using ESCAPE might be a natural choice:
SELECT *
FROM table1
WHERE file_location SIMILAR TO 'Audit\\[^!\]*' ESCAPE '!'
Here is SQLFiddle demo

How to update a record with literal percent literal (%) in PostgreSQL without saving it as "\%"

I need to update a record, which contains literal percent signs, using PostgreSQL in Railo. The query looks like
<cfquery>
update foo set bar = 'string with % in it %'
</cfQuery>
It throws error as ColdFusion normally interprets it as a wildcard character. I can escape it using the following query.
<cfquery>
update foo set bar = 'string with escaped \% in it \%'
</cfQuery>
However, the record now contains "\%" in the database and will be displayed on the page as "\%".
I found a documentation with an example of escaping percent sign in a SELECT. But it does not work for me: syntax error at or near "ESCAPE".
SELECT emp_discount
FROM Benefits
WHERE emp_discount LIKE '10\%'
ESCAPE '\';
Is there a better to achieve the same goal? The underlining database is PostgreSQL. Thanks!
Queryparameters escape special characters. Yet another reason to use them.