liveBook · Manning

Cursor

As explained in Python Concurrency with asyncio

A database cursor is an object that traverses and retrieves rows from a database query result, potentially incrementally.

A database cursor acts as a pointer into a query result, advancing as rows are retrieved. Streaming avoids loading a large result set into application memory, though it increases database round trips. section 5.7

With asyncpg, a streaming cursor supports several retrieval patterns:

  • Iterate one row at a time with async for. section 5.7.2
  • Move forward with forward and retrieve a batch with fetch. section 5.7.2
  • Adjust prefetching when creating the cursor directly; awaitable cursor creation does not accept prefetch. section 5.7.2
Listing 5.15 Streaming results one by one
import asyncpg
import asyncio
import asyncpg
 
 
async def main():
    connection = await asyncpg.connect(host='127.0.0.1',
                                       port=5432,
                                       user='postgres',
                                       database='products',
                                       password='password')
 
    query = 'SELECT product_id, product_name FROM product'
    async with connection.transaction():
        async for product in connection.cursor(query):
            print(product)
 
    await connection.close()
 
 
asyncio.run(main())

Streams product rows inside a transaction and prints each row without retaining the entire result set. section 5.7.2

How Python Concurrency with asyncio covers it

How deep it goes
Explains pointer-style traversal, asynchronous iteration, prefetching, skipping, and batching, but not cursor internals.
Examples
Uses a product query to stream 1,000 rows, skip 500 rows, fetch 100, or print the first five.
What you can do after
Operate/configure asyncpg cursors inside transactions to stream, skip, batch, and limit retrieved rows.
How it connects
Connects cursors to PostgreSQL, asyncpg, asynchronous generators, async for, transactions, and pagination.

Also explained in

Compare how 7 books explain cursor →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Python Concurrency with asyncio. The section links point to the parts of the book it draws on.