postgresql_16:5.1.10.2 Functions for Receiving COPY Data
PostgreSQL 16 > Client Interfaces > libpq — C Library > Functions Associated with the COPY Command > Functions for Receiving COPY Data
These functions are used to receive data during COPY TO STDOUT. They will fail if called when the connection is not in COPY_OUT state.
PQgetCopyData
Receives data from the server during COPY_OUT state. int PQgetCopyData(PGconn *conn, char **buffer, int async);
Attempts to obtain another row of data from the server during a COPY. Data is always returned one data row at a time; if only a partial row is available, it is not returned. Successful return of a data row involves allocating a chunk of memory to hold the data. The buffer parameter must be non-NULL. *buffer is set to point to the allocated memory, or to NULL in cases where no buffer is returned. A non-NULL result buffer should be freed using (see libpq-PQfreemem) when no longer needed.
When a row is successfully returned, the return value is the number of data bytes in the row (this will always be greater than zero). The returned string is always null-terminated, though this is probably only useful for textual COPY. A result of zero indicates that the COPY is still in progress, but no row is yet available (this is only possible when async is true). A result of -1 indicates that the COPY is done. A result of -2 indicates that an error occurred (consult (see libpq-PQerrorMessage) for the reason).
When async is true (not zero), (see libpq-PQgetCopyData) will not block waiting for input; it will return zero if the COPY is still in progress but no complete row is available. (In this case wait for read-ready and then call (see libpq-PQconsumeInput) before calling (see libpq-PQgetCopyData) again.) When async is false (zero), (see libpq-PQgetCopyData) will block until data is available or the operation completes.
After (see libpq-PQgetCopyData) returns -1, call (see libpq-PQgetResult) to obtain the final result status of the COPY command. One can wait for this result to be available in the usual way. Then return to normal operation.