You can actually do this is a single statement. The technique is create a CTE to receives the parameters. In this case tree type and an array of owners. Then a second CTE to insert the tree_header and return the generated id. Finally, join the parameters with the with the resulting header. See Demo.
with parms (tree, owners) as
( values ('<tree type>', array ['<Owner_Array>']) )
, make_tree as
( insert into tree_header(tree_type)
select tree from parms
returning tree_id, tree_type
)
insert into tree_detail(owner_name, tree_id)
select unnest (p.Owner_Array), mt.tree_id
from parms p
join make_tree mt on (mt.tree_type = p.tree);
Now since I do not write your obsurfication language (Python?) I am not exactly how it translates. But I guess something like:
import psycopg2
class MyData():
def __init__(self, host="10.0.80.85", db="hhh", user="postgres", password="5bebfakee11"):
self.conn = psycopg2.connect(host=host, database=db, user=user, password=password)
self.cur = self.conn.cursor()
def close(self):
self.cur.close()
self.conn.close()
db = MyData()
statement = "with parms (tree, owners) as \
( values ('%', array [%]) ) \
, make_tree as \
( insert into tree_header(tree_type) \
select tree from parms \
returning tree_id, tree_type \
) \
insert into tree_detail(owner_name, tree_id) \
select unnest (p.owners), mt.tree_id \
from parms p \
join make_tree mt on (mt.tree_type = p.tree);"
db.cur.execute(statement, (last_header_id,list_owner_array))
db.conn.commit()
db.close()
Note: There is nothing returned from the statement, it either works of Postgres throws and exception.