In PostgreSQL INSERT support RETURNING values, but asyncpg on con.exec returns only success result of inserting, how to support returning values in asyncpg (except with() select)?
The Connection execute method returns the status of the last SQL command. Use the fetch, fetchrow, or fetchval methods which return a Record, Records, or a value. Here's an example:
post_id = await conn.fetchval("""
INSERT INTO post (title, content)
VALUES ($1, $2)
RETURNING id""", title, content)
Hello can you add this to the documentation FAQ please? I spent the last 30 mins searching for this. Thanks.
RETURNING clause is well documented in PostgreSQL documentation:
The allowed contents of a RETURNING clause are the same as a SELECT command's output list (see Section 7.3). It can contain column names of the command's target table, or value expressions using those columns. A common shorthand is RETURNING *, which selects all columns of the target table in order.
So there's no need for additional documentation in any PostgreSQL driver including this one.
I mean it wasn't obvious you can use fetch*() for anything except SELECT statements. The 14 thumbs up should indicate many people agree.
The 14 thumbs up should indicate many people ageee
Please submit a PR to add an entry to the FAQ.
Most helpful comment
The Connection execute method returns the status of the last SQL command. Use the fetch, fetchrow, or fetchval methods which return a Record, Records, or a value. Here's an example: