September 26, 2024: PostgreSQL 17 Released!
Unsupported versions: 7.2 / 7.1
This documentation is for an unsupported version of PostgreSQL.
You may want to view the same page for the current version, or one of the other supported versions listed above instead.

3.7. Functions Associated with the COPY Command

The COPY command in PostgreSQL has options to read from or write to the network connection used by libpq++. Therefore, functions are necessary to access this network connection directly so applications may take full advantage of this capability.

  • PgDatabase::GetLine reads a newline-terminated line of characters (transmitted by the backend server) into a buffer string of size length.

    int PgDatabase::GetLine(char* string, int length)
    

    Like the Unix system routine fgets(), this routine copies up to length-1 characters into string. It is like gets(), however, in that it converts the terminating newline into a zero byte.

    PgDatabase::GetLine returns EOF at end of file, 0 if the entire line has been read, and 1 if the buffer is full but the terminating newline has not yet been read.

    Notice that the application must check to see if a new line consists of a backslash followed by a period (\.), which indicates that the backend server has finished sending the results of the COPY. Therefore, if the application ever expects to receive lines that are more than length-1 characters long, the application must be sure to check the return value of PgDatabase::GetLine very carefully.

  • PgDatabase::PutLine Sends a null-terminated string to the backend server.

    void PgDatabase::PutLine(char* string)
    

    The application must explicitly send the characters \. to indicate to the backend that it has finished sending its data.

  • PgDatabase::EndCopy synchronizes with the backend.

    int PgDatabase::EndCopy()
    

    This function waits until the backend has finished processing the COPY. It should either be issued when the last string has been sent to the backend using PgDatabase::PutLine or when the last string has been received from the backend using PgDatabase::GetLine. It must be issued or the backend may get "out of sync" with the frontend. Upon return from this function, the backend is ready to receive the next command.

    The return value is 0 on successful completion, nonzero otherwise.

As an example:

PgDatabase data;
data.Exec("CREATE TABLE foo (a int4, b char(16), d double precision)");
data.Exec("COPY foo FROM STDIN");
data.PutLine("3\tHello World\t4.5\n");
data.PutLine("4\tGoodbye World\t7.11\n");
...
data.PutLine("\\.\n");
data.EndCopy();