1

I have a list of strings of format:

cols = ['col1', 'col2', 'col3', 'col4']

converting the above to tuple(cols) gives me:

('col1', 'col2', 'col3', 'col4')

but I need them without quotes, (col1, col2, col3, col4) Reason why is I use the above in postgres query like:

UPDATE table SET (col1,col2,col3,col4)=('v1','v2','v3','v4') where id = 99

Using with quotes gives syntax error

What exactly I have before send the query:

sql_stmt = 'UPDATE public.sample_table SET %s = %s ' + where_clause
logger.info(cur.mogrify(sql_stmt,(columns,values)))

which logs:

"UPDATE public.sample_table SET ('col1', 'col2', 'col3', 'col4') = ('v1', 'v2', 'v3'::timestamp, 'v4') WHERE col1 IN ('ABC',) AND col2 IN ('ASDF', 'BSDF')"
2
  • It's unclear to me if you want the left side of the SET assignment or the right side. If it's the left side, you will have to use dynamic SQL. In that case you should show us the complete function where you are using this. Commented Jun 24, 2020 at 14:08
  • left side of SET assignment Commented Jun 24, 2020 at 14:39

2 Answers 2

2

Assuming you are using psycopg2 to execute the query:

import psycopg2
from psycopg2 import sql 

cols = ['col1', 'col2', 'col3', 'col4']

query = sql.SQL("""UPDATE table SET ({}) =('v1','v2','v3','v4') where id = 99""").format(sql.SQL(', ').join(map(sql.Identifier, cols)))

con = psycopg2.connect("dbname=test host=localhost user=aklaver") 

print(query.as_string(con))                                                                                                                                                
UPDATE table SET ("col1", "col2", "col3", "col4") =('v1','v2','v3','v4') where id = 99

For more information see:

https://www.psycopg.org/docs/sql.html

Sign up to request clarification or add additional context in comments.

Comments

0

If you use PL/pgSQL you could do:

select * from mytable;
 col1 | col2 | col3 | col4 
------+------+------+------
 c1   | c2   | c3   | c4
(1 row)

do
$$
declare
 ca text[];
 va text[];
begin
 ca  = array ['col1','col2','col3','col4'];
 va  = array ['v1','v2','v3','v4'];
 execute format('update mytable set (%I,%I,%I,%I) = (%L,%L,%L,%L)', 
                 ca[1], ca[2], ca[3], ca[4], va[1], va[2], va[3], va[4]);
end;
$$;
DO

select * from mytable;
 col1 | col2 | col3 | col4 
------+------+------+------
 v1   | v2   | v3   | v4
(1 row)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.