Search code examples
python-3.xdiscord.pyasyncpg

Issue getting a number of rows


Hi I'm moving to asyncpg from psycopg2 and I'm having an issue trying to return a number of rows in asyncpg in this case 10. In psycopg2 I would do this by the following:

psycopg2

cursor.execute(f"SELECT user_id,lvl,xp,total_xp FROM levels WHERE guild_id = {str(701547632666525246)} ORDER BY GREATEST(total_xp) DESC")
        res = cursor.fetchmany(10)

asycpg

res = await conn.fetch("SELECT user_id,lvl,xp,total_xp FROM levels WHERE guild_id = $1 ORDER BY GREATEST(total_xp) DESC", ctx.guild.id)

I'm a bit stuck on the asyncpg part help would be appreciated.

Here is what I'm working with:

@commands.command()
async def ranking(self, ctx):
    """Displays top 10 Active Members in the server"""
    if ctx.message.channel.name == "commands":
        async with self.bot.pool.acquire() as conn:
            res = await conn.fetch("SELECT user_id,lvl,xp,total_xp FROM levels WHERE guild_id = $1 ORDER BY GREATEST(total_xp) DESC", ctx.guild.id)
            #0: user_id, 1: lvl
            mess = "Top 10 active members"
            x = 1
            for ele in res:
                user = self.bot.get_user(int(ele[0]))
                mess += "**{}.** {} on **Level {: <3}** with **{: <4} XP**\n\n".format(x,user.name,ele[1], ele[2])
                x+=1
            embed = discord.Embed(title="Leaderboard", description=f"{mess}")
            await ctx.send(embed=embed)
    else:
        await ctx.send("Can't use this command in this channel.")

Solution

  • You can simply use the LIMIT clause

    query = """
        SELECT user_id,lvl, xp, total_xp 
        FROM levels 
        WHERE guild_id = $1 
        ORDER BY GREATEST(total_xp) DESC
        LIMIT 10
    """
    await conn.fetch(query, ctx.guild.id)
    

    It will work with both psycopg2 and asyncpg