Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Escaping backslash in Postgresql

I'm trying to write an sql function in Postgresql that will parse a file path. I want to return just the file name.

I cannot get past getting an accurate text string in the function.

Here is the function:

Function:  job_page("inputText" text)
DECLARE
    $5 text;

BEGIN
    $5 = quote_literal("inputText");
    return $5;
END

When I run this:

select job_page('\\CAD_SVR\CADJOBS\7512-CEDARHURST ELEMENTARY SCHOOL\7512-20.DWG')

I get this result:

"E'\\CAD_SVRCADJOBSé2-CEDARHURST ELEMENTARY SCHOOLé2-20.DWG'"

Postgresql interprets the slash followed by certain characters as a special character.

How do I escape?

like image 383
mohnston Avatar asked Jun 15 '10 21:06

mohnston


People also ask

How do I escape special characters in PostgreSQL?

PostgreSQL also accepts “escape” string constants, which are an extension to the SQL standard. An escape string constant is specified by writing the letter E (upper or lower case) just before the opening single quote, e.g., E'foo' .

How do you escape $$ in Postgres?

Within an escape string, a backslash character (\) begins a C-like backslash escape sequence, in which the combination of backslash and following character(s) represents a special byte value. \b is a backspace, \f is a form feed, \n is a newline, \r is a carriage return, \t is a tab.

How do I escape reserved words in PostgreSQL?

Simply enclose year in double quotes to stop it being interpreted as a keyword: INSERT INTO table (id, name, "year") VALUES ( ... );

How do you escape double quotes in Postgres?

> Quotes and double quotes should be escaped using \.


2 Answers

You should use escape string syntax:

select E'\\CAD_SVR\\CADJOBS\\7512-CEDARHURST ELEMENTARY SCHOOL\\7512-20.DWG';

\CAD_SVR\CADJOBS\7512-CEDARHURST ELEMENTARY SCHOOL\7512-20.DWG

This will work in any case.

Or you can set standard_conforming_strings=on and use:

select '\CAD_SVR\CADJOBS\7512-CEDARHURST/ ELEMENTARY SCHOOL\7512-20.DWG';

\CAD_SVR\CADJOBS\7512-CEDARHURST/ ELEMENTARY SCHOOL\7512-20.DWG

quote_literal function should be used only when you will be constructing a query for exec call in pl/pgsql function. For constructing a query in a client you should use a client's library quoting function, like PQescapeStringConn in libpq or pg_escape_string in PHP. But the best option is to use prepared statements and use a string as an argument, which eliminates all quoting and is much safer too.

like image 180
Tometzky Avatar answered Sep 22 '22 12:09

Tometzky


You have to escape the \ with another \

i.e. \\

You can change this behavior off by setting the standard_conforming_strings option to on. By default it is off, but this default will change some time in the future.

I recommend the double backslash for the time being.

like image 35
Peter Tillemans Avatar answered Sep 19 '22 12:09

Peter Tillemans