如何更改with子句中的游标类型

问题描述 投票:0回答:1

我有以下声明

    statement = """
    INSERT INTO rag.chunks (project_id, document_id, model_id, text, metadata)
    VALUES {}
    RETURNING *;
    """

    async with pool.connection() as conn:
        async with conn.cursor() as cur:
            values = ', '.join(
                cur.mogrify("(%s, %s, %s, %s, %s)",
                            (c.project_id, c.document_id, c.model_id, c.text, Jsonb(c.metadata)))
                for c in chunks
            )

            statement = statement.format(values)
            await cur.execute(statement)
            chunks = await cur.fetchall()
            return chunks

我使用

cur.mogrify
,因为execute_many不返回所有行,只返回最后一行(讨论)。

但是,因为这是一个 AsyncConnectionPool,所以返回的游标是 AsyncCursor,它没有

mogrify
方法。

AttributeError: 'AsyncCursor' object has no attribute 'mogrify'

但是,AsyncClientCursor类确实有

mogrify

如何指定我要使用 AsyncClientCursor? 例如:

async with pool.connection() as conn:
    async with conn.cursor(cursorClass=AsyncClientCursor) as cur:    

但这失败了

TypeError: AsyncConnection.cursor() got an unexpected keyword argument 'cursorClass'
python psycopg2 psycopg3
1个回答
0
投票

想通了 - 不确定是否理想,但可以这样设置

async with pool.connection() as conn:
    conn.cursor_factory = AsyncClientCursor
    async with conn.cursor() as cur:
        ...
© www.soinside.com 2019 - 2024. All rights reserved.