Postgres syntax error when using 'like' in single quote - sql

I am getting a syntax error in a PostgreSQL query. I am working on a project developed in YII1, I am getting an error
CDbCommand failed to execute the SQL statement: SQLSTATE[42601]:
Syntax error: 7 ERROR: syntax error at or near "s" LINE 1: ...OT NULL
AND sub_heading like '%Women and Children's Voices%'.
As you can see above, I am using the like operator in single quotes, and in the string there is another single quote (Children's). So PostgreSQL is throwing me an error. Please provide me a solution to escape the string.

You can escape a single quote in a string by using another single quote (i.e., '' instead of '. Note that these are two ' characters, not a single " character):
sub_heading LIKE '%Women and Children''s Voices%'
-- Here -----------------------------^

You should use the format function to construct the SQL statement, using the %L placeholder for the pattern.

I solved this problem by replacing the single quote with double quotes using PHP. Here is the code
There is a variable $var with value Women and Children's Voices. I replace that single quote using the str_replace() function.
$var = str_replace("'", "''", $var);

Related

Syntax error in my SQL when inserting a JSON field

Why this query is not working:
UPDATE country SET timezones="[{"zoneName":'Asia\/Kabul',"gmtOffset":16200,"gmtOffsetName":'UTC+04:30',"abbreviation":'AFT',"tzName":'Afghanistan Time'}] " where name='Afghanistan'
Error I get:
ERROR: syntax error at or near "zoneName"
LINE 1: UPDATE country SET timezones="[{"zoneName":'Asia/Kabul',"gm...
^
SQL state: 42601
Character: 34
the issue with your SQL statement is that the literal string you are trying to set timezones to contains improperly formatted escape characters. if you wanted to avoid that first error you can double up on quotes like timezones="[{""zoneName"": ...
you can go to the link to see more about string formating in SQL. good luck!
You're trying to update the value wrapping the string in quotes. You need to wrap the string in single quotes timezones='[{"zoneName":'Asia...}]'
However, to TitledTeapot's point, you will also have to escape the existing single quotes in your string, so you'd end up with something like this:
'[{"zoneName":''Asia\/Kabul'',"gmtOffset":16200,"gmtOffsetName":''UTC+04:30'',"abbreviation":''AFT'',"tzName":''Afghanistan Time''}]'

PostgreSQL RETURNING fails with REGEXP_REPLACE

I'm running PostgreSQL 9.4 and are inserting a lot of records into my database. I use the RETURNING clause for further use after an insert.
When I simply run:
... RETURNING my_car, brand, color, contact
everything works, but if I try to use REGEXP_REPLACE it fails:
... RETURNing my_car, brand, color, REGEXP_REPLACE(contact, '^(\+?|00)', '') AS contact
it fails with:
ERROR: invalid regular expression: quantifier operand invalid
If I simply run the query directly in PostgreSQL it does work and return a nice output.
Tried to reproduce and failed:
t=# create table s1(t text);
CREATE TABLE
t=# insert into s1 values ('+4422848566') returning REGEXP_REPLACE(t, '^(\+?|00)', '');
regexp_replace
----------------
4422848566
(1 row)
INSERT 0 1
So elaborated #pozs suggested reason:
set standard_conforming_strings to off;
leads to
WARNING: nonstandard use of escape in a string literal
LINE 1: ...alues ('+4422848566') returning REGEXP_REPLACE(t, '^(\+?|00)...
^
HINT: Use the escape string syntax for escapes, e.g., E'\r\n'.
ERROR: invalid regular expression: quantifier operand invalid
update
As OP author says standard_conforming_strings is on as supposed from 9.1 by default working with psql and is off working with pg-prommise
update from vitaly-t
The issue is simply with the JavaScript literal escaping, not with the
flag.
He elaborates further in his answer
The current value of environment variable standard_conforming_strings is inconsequential here. You can see it if you prefix your query with SET standard_conforming_strings = true;, which will change nothing.
Passing in a regEx string unescaped from the client is the same as using E prefix from the command line: E'^(\+?|00)'.
In JavaScript \ is treated as a special symbol, and you simply always have to provide \\ to indicate the symbol, which is what needed for your regular expressions.
Other than that, pg-promise will escape everything correctly, here's an example:
db.any("INSERT INTO users(name) VALUES('hello') RETURNING REGEXP_REPLACE(name, $1, $2)", ['^(\\+?|00)', 'replaced'])
To understand how the command-line works, prefix the regex string with E:
db.any("INSERT INTO users(name) VALUES('hello') RETURNING REGEXP_REPLACE(name, E$1, $2)", ['^(\\+?|00)', 'replaced'])
And you will get the same error: invalid regular expression: quantifier operand invalid.

REGEXP_REPLACE Punctuation in Redshift

I'm trying to use REGEXP_REPLACE to remove all punctuation from a varchar. I'm using the following:
regexp_replace(d.NAME, [.,\/#!$%\^&\*;:{}=\-_`~()])
But it gives me an error, saying:
Statement 1 is not valid. ERROR: syntax error at or near "."
How can I fix this to remove all punctuation?
Firstly, the dash in a character class means a range, except when it's first or last... so put it there:
[.,\/#!$%\^&\*;:{}=\_`~()-]
And, you have to put it in quotes, and most characters don't need escaping:
regexp_replace(d.NAME, '[.,/#!$%^&*;:{}=_`~()-]')

escape quote in django extra clause

In Django, the following statement
entity_name = "a string with a ' quote"
Fiche.objects.extra(where=["'%s' LIKE fiche_name+'%s' " % (entity_name,'%%')])
causes the Database error:
DatabaseError: ('42000', '[42000] [FreeTDS][SQL Server]Statement(s) could not be prepared. (8180) (SQLExecDirectW)')
If I print the sql that is sent to db backend, I see something like this:
... 'a string with a ' quote' LIKE fiche_name+'%%'
so I tried to escape the quote in my string with a backslash
entity_name = "a string with a \\\' quote"
This time, the query seems to be well prepared for the DB backend (quote escaped):
... 'a string with a \' quote' LIKE fiche_name+'%%'
but this results in the same database error.
Does someone know how to escape properly the quote?
EDIT: I found a solution to my problem: I replace in my string each quote by two quotes and it works now:
entity_name = entity_name.replace("'","''")
Way too late, but the right way to do this is to pass the variables as arguments to .extra():
entity_name = "a string with a ' quote"
Fiche.objects.extra(where=["%s LIKE fiche_name + '%%'")], params=[entity_name])
Note: what you are doing is the opposite of what is normally done (field LIKE 'pattern%'), but it's possible nonetheless. Also note that this is database-specific code, not all databases use + as string concatenator (you may have to switch it to || or CONCAT()).

syntax error at or near "http" in INSERT statement (sql)

Getting error when trying to RUN:
INSERT INTO dtb_order VALUES (
14,1920,NULL,
'テスト',NULL,'03','6302','0215',NULL,NULL,NULL,'160','0023',NULL,0,13,
'新宿区西新宿','セントラルパークタワー・ラ・トゥール',6,
'1972-09-02 00:00:00',NULL,3150,0,1,500,0,0,0,0,150,3650,3650,8,
'NP後払い',NULL,9000,'2013-09-12 18:42:56',
'2013-09-23 19:42:22',NULL,NULL,10,1,NULL,
'a:2:{s:5:\"title\";a:2:{s:4:\"name\";s:32:\"NP後払いでのお支払情報\";s:5:\"value\";b:1;}s:3:\"msg\";a:2:{s:4:\"name\";s:15:\"ご注意事項\";s:5:\"value\";s:388:\"株式会社ネットxxxションズより、商品とは別に郵送されます。\n主要コンビニ・銀行・郵便局でお支払いできますので、商品の到着を確認してから、\nお支払いをお願いいたします。\nNP後払いの詳しいご案内はこちら⇒ <a href=\'http://np-someurl.jp/about/\' target=\'_blank\'>http://np-someurl.jp/about/</a>\n\";}}',
NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL
);
Error message:
Error : ERROR: syntax error at or near "http"
LINE 1: ...ます。\nNP後払いの詳しいご案内はこちら⇒ <a href=\'http://np-...
^
Tried http:\/\/np-... no luck.
++++++++
is there other way except $$ (my string with http) $$, because I have almost 200 000 INSERTs and only some of them have http://, I just want to fix "http://" with substitution by vim or something like that, not manually.
You do not show the whole command. My guess is that it is not properly escaped. Use dollar quoting $$ in instead of single quotes so it is not necessary to escape single quotes in the string. Also use escape string E syntax to have the new lines \n
E$$a:2:{s:5:"title";a:2:{s:4:"name";s:32:"NP後払いでのお支払情報";s:5:"value";b:1;}s:3:"msg";a:2:{s:4:"name";s:15:"ご注意事項";s:5:"value";s:388:"株式会社ネットxxxションズより、商品とは別に郵送されます。\n主要コンビニ・銀行・郵便局でお支払いできますので、商品の到着を確認してから、\nお支払いをお願いいたします。\nNP後払いの詳しいご案内はこちら⇒ <a href='http://np-someurl.jp/about/' target='_blank'>http://np-someurl.jp/about/</a>\n";}}$$,
http://www.postgresql.org/docs/current/static/sql-syntax-lexical.html#SQL-SYNTAX-CONSTANTS
Changing \' to " & \" to " did the trick.
VIM
:%s/\\'/"/gc
:%s/\\"/"/gc