Search code examples
pythonpostgresqlasyncpg

Is the fetchval in asyncpg safly for sql injections?


Is the fetchval in asyncpg safly for sql injections?

https://magicstack.github.io/asyncpg/current/api/index.html?highlight=fetch#asyncpg.connection.Connection.fetch

async def get_user_id_by_bot_id(self, bot_id):
        record: Record = await self.pool.fetchval(self.GET_USER_ID_BY_BOT_ID, (bot_id))
        print(record)
        return record 

Thank You for answers.


Solution

  • Yes, asyncpg uses PostgreSQL's syntax for parameter substitution. As long as you use that feature, by passing the arguments and using $ followed by the index of the argument, you should be safe!

    You shouldn't put the args in a tuple like you show in your code, but do this:

    record: Record = await self.pool.fetchval(self.GET_USER_ID_BY_BOT_ID, bot_id)
    

    Some more examples of how you should correctly use parameter substitution:

    record = await self.pool.fetchval("SELECT * FROM table WHERE id = $1;", my_id)
    
    record = await self.pool.fetchval("UPDATE table SET name = $1 WHERE id = $2 AND username = $3;", new_name, my_id, username)