Knowing if both row exists and there's a value (or null) with asyncpg

525 views Asked by At

I want to provide descriptive error/information messages when configuring a news feed on one of my Discord bots:

  • One for when there's no feed configured (Row doesn't exist.)
  • One for when a specific column has a NULL value.

While this is simple to do with two queries, I want to simplify this to one query and if possible simple and I came up with one approach: Use fetchrow which will return a Record object. This meets my two conditions, if there's no row in the database I will get None as a result but if there's a row I will get the Record object with the column I selected, which will or won't be NULL. For example:

update = await self.bot.database.fetchrow('UPDATE NewsFeed SET role_id = NULL '
                                          'WHERE guild_id = $1 AND key = $2 '
                                          'RETURNING role_id', ctx.guild.id, key)

Which I can just do if not update to check whether the Record exists and then if not update["role_id"] to check if the role_id column is NULL.

My question is: Is there a different/simpler approach for this or this is good to go?

0

There are 0 answers