I\'d like to use psycopg2 to INSERT multiple rows and then return all the ids (in order) using a single query. This is what PostgreSQL\'s RET
The trick is to use mogrify. It uses a single execute and id therefore faster than executemany anyways:
def insert_many(self, table: str, id_column: str, values: list):
if not values:
return []
keys = values[0].keys()
query = cursor.mogrify("INSERT INTO {} ({}) VALUES {} RETURNING {}".format(
table,
', '.join(keys),
', '.join(['%s'] * len(values)),
id_column
), [tuple(v.values()) for v in values])
conn = psycopg2.connect("host=localhost4 port=5432 dbname=cpn")
cursor = conn.cursor()
cursor.execute(query)
return [t[0] for t in (cursor.fetchall()]