Unsupported versions: 7.0
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.

Functions Associated with the COPY Command

The copy command in Postgres 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 (3), this routine copies up to length-1 characters into string. It is like gets (3), however, in that it converts the terminating newline into a null character.

    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 single 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 a single period character (".") to indicate to the backend that it has finished sending its data.

  • PgDatabase::EndCopy syncs 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 query.

    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 float8)");
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();