Asyncpg: Support insert returning

Created on 25 Nov 2016  路  5Comments  路  Source: MagicStack/asyncpg

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)?

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:

post_id = await conn.fetchval("""
        INSERT INTO post (title, content)
        VALUES ($1, $2)
        RETURNING id""", title, content)

All 5 comments

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.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

mestrogov picture mestrogov  路  7Comments

inikolaev picture inikolaev  路  3Comments

samuelcolvin picture samuelcolvin  路  3Comments

ldgeo picture ldgeo  路  4Comments

filantus picture filantus  路  3Comments