Psycopg2: (col1, col2) IN my_list: ProgrammingError: syntax error in or near "ARRAY"

I want to execute this sql via psyopg2:

select indexname from pg_indexes where (tablename, indexname) in ( 
      ('tab1', 'index1'),
      ('tab2', 'index2') 
);

Here is the code:

cursor.execute(
'select tablename, indexname from pg_indexes where (tablename, indexname) IN %s;', [
    [('tab1', 'col1'), ('tab2', 'col2')],
               ])

I get this exception:

ProgrammingError: syntax error at or near "ARRAY"
LINE 1: ...e from pg_indexes where (tablename, indexname) IN ARRAY[('ta...

How to pass a list of PostgreSQL tuples to psyopg2?

+4
source share
1 answer

If you pass a tuple instead of a list, it works:

cursor.execute(
'select tablename, indexname from pg_indexes where (tablename, indexname) IN %s;', [
    tuple([('tab1', 'col1'), ('tab2', 'col2')]),
               ])

Do not ask me why it fails if you pass the list.

+4
source

Source: https://habr.com/ru/post/1613620/


All Articles