Search code examples
c++postgresqllibpqxx

How to use pqxx::stateless_cursor class from libpqxx?


I'm learning libpqxx, the C++ API to PostgreSQL. I'd like to use the pqxx::stateless_cursor class, but 1) I find the Doxygen output unhelpful in this case, and 2) the pqxx.org website has been down for some time now.

Anyone know how to use it?

I believe this is how I construct one:

pqxx::stateless_cursor <pqxx::cursor_base::read_only, pqxx::cursor_base::owned>
    cursor( work, "SELECT * FROM mytable", ?, ? );

The last two parms are called cname and hold, but are not documented.

And once the cursor is created, how would I go about using it in a for() loop to get each row, one at a time?


Solution

  • Thanks @Eelke for the comments on cname and hold.

    I figured out how to make pqxx::stateless_cursor work. I have no idea if there is a cleaner or more obvious way but here is an example:

    pqxx::work work( conn );
    pqxx::stateless_cursor<pqxx::cursor_base::read_only, pqxx::cursor_base::owned>
        cursor( work, "SELECT * FROM mytable", "mycursor", false );
    
    for ( size_t idx = 0; true; idx ++ )
    {
        pqxx::result result = cursor.retrieve( idx, idx + 1 );
        if ( result.empty() )
        {
            // nothing left to read
            break;
        }
    
        // Do something with "result" which contains a single
        // row in this example since we told the cursor to
        // retrieve row #idx (inclusive) to idx+1 (exclusive).
        std::cout << result[ 0 ][ "name" ].as<std::string>() << std::endl;
    }