How to escape '(' in Karate feature file - karate

I am trying to do an assertion in my feature file where my expected value is having '('
Is there any escape character to be used in the feature file. I have used '\' as escape character but no luck
Karate feature file statement:
And match response ProcessCustomer/header/status/description == 'Successful(EFT Payment)'
Getting below error:
com.intuit.karate.exception.KarateException: ESB_PaymentCardPayment.feature:20 - syntax error, expected '==' for match
The same statement works if I use 'contains' instead of '=='

You must be missing something, maybe unpack the XML value first into a string and try again. There is no special behavior for strings, try the following two lines and see it work:
* def test = 'Successful(EFT Payment)'
* match test == 'Successful(EFT Payment)'
* def xml = <root>Successful(EFT Payment)</root>
* match xml/root == 'Successful(EFT Payment)'

Related

Ingres SQL illegal pattern match and illegal escape sequence, unexpected results

I am querying a database that uses Ingres 10.2. I cannot seem to get any of my pattern matching code to work as I expect it to.
For example:
SELECT TOP 20 *
FROM table_name
WHERE variable_name IN ('XaKDG', 'XaKDH')
returns both XaKDG and XaKDH as expected.
However, when trying this:
SELECT TOP 5 *
FROM table_name
WHERE variable_name LIKE 'XaKD\[GH\]' escape '\'
I get the following errors:
ERROR '22025' 1315172
Illegal pattern match specified
Illegal ESCAPE sequence.
I am baffled, as the user guide states the following:
"To match any string starting with 0 through 4, followed by an uppercase letter, then a [, any two characters and a final ]:"
name like '\[01234\]\[A-Z\][__]' escape '\'
As far as I can tell, my query should be correct. I also tried without the escape characters at all, and with double escape characters. These didn't produce any errors, but also did not return anything.
I appreciate any help.
The User guide is here: https://supportactian.secure.force.com/help/servlet/fileField?id=0BEf3000000PLPf

ParseException when trying to concatenate a string containing HTML in Hive query

I'm trying to concatenate two strings in Hive like below, but it keeps complaining about a ParseException
select concat('', cast(77 as varchar), '') as page_url
;
The message says:
FAILED: ParseException line 1:13 cannot recognize input near 'concat' '(' ''<a href="'' in expression specification
I tried using backticks around the strings and also escaping any potential special characters, but no luck. How can I get the concatenation to work?
I'm using Hive version 2.0.4
In this particular case, the problem was arising because I was using cast as varchar when I should have been using string

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.

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()).

psycopg2 equivalent of mysqldb.escape_string?

I'm passing some values into a postgres character field using psycopg2 in Python. Some of the string values contain periods, slashes, quotes etc.
With MySQL I'd just escape the string with
MySQLdb.escape_string(my_string)
Is there an equivalent for psycopg2?
Escaping is automatic, you just have to call:
cursor.execute("query with params %s %s", ("param1", "pa'ram2"))
(notice that the python % operator is not used) and the values will be correctly escaped.
You can escape manually a variable using extensions.adapt(var), but this would be error prone and not keep into account the connection encoding: it is not supposed to be used in regular client code.
Like piro said, escaping is automatic. But there's a method to also return the full sql escaped by psycopg2 using cursor.mogrify(sql, [params])
In the unlikely event that query parameters aren't sufficient and you need to escape strings yourself, you can use Postgres escaped string constants along with Python's repr (because Python's rules for escaping non-ascii and unicode characters are the same as Postgres's):
def postgres_escape_string(s):
if not isinstance(s, basestring):
raise TypeError("%r must be a str or unicode" %(s, ))
escaped = repr(s)
if isinstance(s, unicode):
assert escaped[:1] == 'u'
escaped = escaped[1:]
if escaped[:1] == '"':
escaped = escaped.replace("'", "\\'")
elif escaped[:1] != "'":
raise AssertionError("unexpected repr: %s", escaped)
return "E'%s'" %(escaped[1:-1], )
Psycopg2 doesn't have such a method. It has an extension for adapting Python values to ISQLQuote objects, and these objects have a getquoted() method to return PostgreSQL-compatible values.
See this blog for an example of how to use it:
Quoting bound values in SQL statements using psycopg2
Update 2019-03-03: changed the link to archive.org, because after nine years, the original is no longer available.
psycopg2 added a method in version 2.7 it seems:
http://initd.org/psycopg/docs/extensions.html#psycopg2.extensions.quote_ident
from psycopg2.extensions import quote_ident
with psycopg2.connect(<db config>) as conn:
with conn.cursor() as curs:
ident = quote_ident('foo', curs)
If you get an error like:
TypeError: argument 2 must be a connection or a cursor, try either:
ident = quote_ident('foo', curs.cursor)
# or
ident = quote_ident('food', curs.__wrapper__)