Search code examples
postgresqlasyncpg

asyncpg: How to construct SET strings with parameters


What is the correct way to pass in parameters in a SET query?

this will return asyncpg.exceptions.PostgresSyntaxError: syntax error at or near "$1"

import asyncio

import asyncpg


async def main():
    conn = await asyncpg.connect(user="xx", password="yy", host="127.0.0.1", database="my_db")

    # works
    await conn.execute("select $1", "1")

    identity = "arn:aws:sts::123456:assumed-role/thing_1"

    # fails
    await conn.execute("set session iam.identity = $1", identity)

asyncio.run(main())


Solution

  • asyncpg has a function for this:

    await conn.execute("select set_config('iam.identity', $1, false)", identity)