python-3.xsqlalchemydiscord.py

Query returns ChunkedIteratorResult object instead of ORM object


so problem in that i want to get query result that i can use for other actions, but instead of result i get <sqlalchemy.engine.result.ChunkedIteratorResult object at 0x000002A7F7F4A150> or model object, can you help me please, im using async with discord.py, and i had no such problem in aiogram without async, i was getting result and was able to get info with something like " log_result = log.entry_id " Code sample :

async def legit(ctx):
    engine = create_async_engine("sqlite+aiosqlite:///BD.sqlite", echo = True)
    print(ctx.message.author.global_name, ctx.message.author.id, ctx.message.author.guild.name.lower(),
          "---legit check---")
    async with AsyncSession(engine) as db:
        query = sqlalchemy.select(users).where(users.user_id == ctx.message.author.id)
        result = await db.execute(query)
        print(result, "RESULT CHECK")
        if result.block == 0:
            access = True
        if result.block == 1:
            access = False
        else:
            print("error")
        await db.close()

and result :

2024-08-04 20:03:50,488 INFO sqlalchemy.engine.Engine BEGIN (implicit)
2024-08-04 20:03:50,489 INFO sqlalchemy.engine.Engine SELECT users.id, users.username, users.user_id, users.server, users.mod, users.block 
FROM users 
WHERE users.user_id = ?
2024-08-04 20:03:50,489 INFO sqlalchemy.engine.Engine [generated in 0.00010s] (317714120898248715,)
<sqlalchemy.engine.result.ChunkedIteratorResult object at 0x000002A7F7F4A150> RESULT CHECK
2024-08-04 20:03:50,490 INFO sqlalchemy.engine.Engine ROLLBACK

Tried using async with engine.begin() as db and got result but as list, and also tried to use MYSQL instead of sqlite, the same result


Solution

  • As noted,

    result = await db.execute(query)
    

    returns a sqlalchemy.engine.result.ChunkedIteratorResult object. As the name suggests, it is an iterator that can be used to retrieve the returned values using methods like .one(), .all(), .first(), etc..

    Since you appear to be looking for a single users object you can retrieve it with

    author = result.scalars().one()
    

    after which you can access its attributes like author.block.