Sunday, April 3, 2011

Programatically finding the number of rows affected by a Postgres COPY

I'm using Postgres 8.2 and the associated libpq library for ANSI C. I've skimmed the documentation and not found something that would give me that specific information.

In the "COPY" section of the documentation, "Outputs" are described as such:

On successful completion, a COPY command returns a command tag of the form
COPY count
The count is the number of rows copied.

Assuming that conn refers to a valid PGconn*, I thought that I could use something like this to return the number of rows copied:

     sprintf(queryString, "COPY table FROM '%s' WITH DELIMITER '|'", 
            tempFileName);
    fprintf(stderr, "COPY all records: %s\n", queryString);
    res = PQexec(conn, queryString);
    bResultErr = (PQresultStatus(res) != PGRES_COMMAND_OK);
    if (bResultErr) {
        PQclear(res);
         fprintf(stderr, "Aborting:DELETE failed: %s\n", 
                 PQerrorMessage(conn));
         PQfinish (conn);
         exit (1);
    } else {
        // Display how many records were COPY'd
        fprintf(stderr, "COPY completed: %d rows imported\n", 
                PQntuples(res));
        PQclear(res);
    }

How ever, the ouput is always "COPY completed: 0 rows imported", despite the fact that the rows are imported.

I would appreciate any tips

From stackoverflow
  • I believe you need to use PQcmdTuples() instead of PQntuples().

  •  fprintf(stderr, "COPY completed: %s rows imported\n", PQcmdTuples(res));
    

    Note %s here, it's a string, not an integer.

0 comments:

Post a Comment