Get table name for field in database result in Python (PostgreSQL) -


i'm trying table name field in result set got database (python, postgres). there function in php table name field, used , works know can done (in php). i'm looking similar function in python.

pg_field_table() function in php gets results , field number , "returns name of table field belongs to". need, in python.

simple exaple - create tables, insert rows, select data:

create table table_a (     id int,     name varchar(10) );  create table table_b (     id int,     name varchar(10) );  insert table_a (id, name) values (1, 'hello'); insert table_b (id, name) values (1, 'world'); 

when using psycopg2 or sqlalchemy got right data , right field names without information table name.

import psycopg2  query = '''     select *     table_a     left join table_b b         on a.id = b.id '''  con = psycopg2.connect('dbname=testdb user=postgres password=postgres') cur = con.cursor() cur.execute(query)  data = cur.fetchall() print('fields', [desc[0] desc in cur.description]) print('data', data) 

the example above prints field names. output is:

fields ['id', 'name', 'id', 'name'] data [(1, 'hello', 1, 'world')] 

i know there cursor.description, not contain table name, field name.

what need - way retrieve table names fields in result set when using raw sql query data.

edit 1: need know if "hello" came "table_a" or "table_b", both fields named same ("name"). without information table name can't tell in table value is.

edit 2: know there workarounds sql aliases: select table_a.name name1, table_b.name name2 i'm asking how retrieve table name result set.

edit 3: i'm looking solution allows me write raw sql query, select *, select a.id, b.id ... , after executing query field names , table names fields in result set.

it necessary query pg_attribute catalog table qualified column names:

query = '''     select         string_agg(format(             '%%1$s.%%2$s "%%1$s.%%2$s"',             attrelid::regclass, attname         ) , ', ')     pg_attribute     attrelid = (%s::regclass[]) , attnum > 0 , not attisdropped '''  cursor.execute(query, ([t t in ('a','b')],)) select_list = cursor.fetchone()[0]  query = '''     select {}     left join b on a.id = b.id '''.format(select_list)  print cursor.mogrify(query) cursor.execute(query) print [desc[0] desc in cursor.description] 

output:

    select a.id "a.id", a.name "a.name", b.id "b.id", b.name "b.name"     left join b on a.id = b.id  ['a.id', 'a.name', 'b.id', 'b.name'] 

Comments