Re: Parse record type into tuple

From: Rory Campbell-Lange <rory(at)campbell-lange(dot)net>
To: Dmytro Starosud <d(dot)starosud(at)gmail(dot)com>
Cc: psycopg(at)postgresql(dot)org
Subject: Re: Parse record type into tuple
Date: 2017-09-05 21:39:10
Message-ID: 20170905213910.66odqm65zbonm3ie@campbell-lange.net
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: 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(dot)starosud(at)gmail(dot)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

In response to

Responses

Browse psycopg by date

  From Date Subject
Next Message Rory Campbell-Lange 2017-09-05 22:33:47 Re: Parse record type into tuple
Previous Message Dmytro Starosud 2017-09-05 15:40:17 Parse record type into tuple