Ben Scott Ben Scott - 2 months ago 16
Python Question

Return PosgreSQL UUID array as list with psycopg2

I have an SQL statement which contains a subquery embedded in an

ARRAY()
like so:

SELECT foo, ARRAY(SELECT x from y) AS bar ...


The query works fine, however in the psycopg2 results cursor the array is returned as a string (as in
"{1,2,3}"
), not a list.

My question is, what would be the best way to convert strings like these into python lists?

Answer

It works for me without the need for parsing:

import psycopg2

query = """
    select array(select * from (values (1), (2)) s);
"""

conn = psycopg2.connect('dbname=cpn user=cpn')
cursor = conn.cursor()
cursor.execute(query)
rs = cursor.fetchall()

for l in rs:
    print l[0]

cursor.close()
conn.close()

Result when executed:

$ python stackoverflow_select_array.py 
[1, 2]

Update

You need to register the uuid type:

import psycopg2, psycopg2.extras

query = """
    select array(
        select *
        from (values
            ('A0EEBC99-9C0B-4EF8-BB6D-6BB9BD380A11'::uuid),
            ('A0EEBC99-9C0B-4EF8-BB6D-6BB9BD380A11'::uuid)
        )s
    );
"""

psycopg2.extras.register_uuid()

conn = psycopg2.connect('dbname=cpn user=cpn')
cursor = conn.cursor()
cursor.execute(query)
rs = cursor.fetchall()

for l in rs:
    print l[0]

cursor.close()
conn.close()

Result:

$ python stackoverflow_select_array.py 
[UUID('a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11'), UUID('a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11')]