Re: [psycopg] Parse record type into tuple - Mailing list psycopg

From Rory Campbell-Lange
Subject Re: [psycopg] Parse record type into tuple
Date
Msg-id 20170905213910.66odqm65zbonm3ie@campbell-lange.net
Whole thread Raw
In response to [psycopg] Parse record type into tuple  (Dmytro Starosud <d.starosud@gmail.com>)
Responses Re: [psycopg] Parse record type into tuple  (Rory Campbell-Lange <rory@campbell-lange.net>)
List psycopg
Hi Dmytro

I think your query is using row query syntax, the same as

    => select row(1,2);
      row
    -------
     (1,2)

in Postgres (which is not a common thing to want to do).
https://www.postgresql.org/docs/9.6/static/sql-expressions.html#SQL-SYNTAX-ROW-CONSTRUCTORS

If you want to select an array from Postgres, you need different syntax,
e.g.

    => select array[1,2];
     array
    -------
     {1,2}
    (1 row)


https://www.postgresql.org/docs/9.6/static/arrays.htmlttps://www.postgresql.org/docs/9.2/static/sql-expressions.html#SQL-SYNTAX-ROW-CONSTRUCTORS

In psycopg2:

In [1]: import psycopg2
In [2]: conn = psycopg2.connect(dbname='template1', user='dbuser', password='xxx')
In [3]: c = conn.cursor()
In [5]: c.execute("select array[1,2] as ar")
In [6]: c.fetchone()
Out[6]: ([1, 2],)

In [7]: from psycopg2.extras import NamedTupleCursor
In [8]: c = conn.cursor(cursor_factory=NamedTupleCursor)
In [9]: c.execute("select array[1,2] as ar")
In [10]: c.fetchone()
Out[10]: Record(ar=[1, 2])


I put in the NamedTupleCursor example in there as I find it invaluable.

Kind regards
Rory



On 05/09/17, Dmytro Starosud (d.starosud@gmail.com) wrote:
> I do following interactions with DB:
>
> In [48]: conn = psycopg2.connect("dbname=... user=... password=...")
> In [49]: cur = conn.cursor()
> In [50]: cur.execute("select (1, 2)")
> In [51]: cur.fetchone()
> Out[51]: ('(1,2)',)
>
> Is it possible to get that tuple parsed into python tuple in the same way
> array works?
>
> In [55]: cur.execute("select array[1, 2]")
> In [56]: cur.fetchone()
> Out[56]: ([1, 2],)
>
> Looks like that can be done if I register composite type for that tuple.
> But I would like it to work with any tuple.
>
> Please assist.
>
> Thanks in advance!
> Dmytro


psycopg by date:

Previous
From: Dmytro Starosud
Date:
Subject: [psycopg] Parse record type into tuple
Next
From: Rory Campbell-Lange
Date:
Subject: Re: [psycopg] Parse record type into tuple