* handleCopyOut * receives data as a result of a COPY ... TO STDOUT command * * conn should be a database connection that you just issued COPY TO on * and got back a PGRES_COPY_OUT result. * * copystream is the file stream for the data to go to. * copystream can be NULL to eat the data without writing it anywhere. * * The final status for the COPY is returned into *res (but note * we alr
| 516 | * result is true if successful, false if not. |
| 517 | */ |
| 518 | bool |
| 519 | handleCopyOut(PGconn *conn, FILE *copystream, PGresult **res) |
| 520 | { |
| 521 | bool OK = true; |
| 522 | char *buf; |
| 523 | int ret; |
| 524 | |
| 525 | for (;;) |
| 526 | { |
| 527 | ret = PQgetCopyData(conn, &buf, 0); |
| 528 | |
| 529 | if (ret < 0) |
| 530 | break; /* done or server/connection error */ |
| 531 | |
| 532 | if (buf) |
| 533 | { |
| 534 | if (OK && copystream && fwrite(buf, 1, ret, copystream) != ret) |
| 535 | { |
| 536 | pg_log_error("could not write COPY data: %m"); |
| 537 | /* complain only once, keep reading data from server */ |
| 538 | OK = false; |
| 539 | } |
| 540 | PQfreemem(buf); |
| 541 | } |
| 542 | } |
| 543 | |
| 544 | if (OK && copystream && fflush(copystream)) |
| 545 | { |
| 546 | pg_log_error("could not write COPY data: %m"); |
| 547 | OK = false; |
| 548 | } |
| 549 | |
| 550 | if (ret == -2) |
| 551 | { |
| 552 | pg_log_error("COPY data transfer failed: %s", PQerrorMessage(conn)); |
| 553 | OK = false; |
| 554 | } |
| 555 | |
| 556 | /* |
| 557 | * Check command status and return to normal libpq state. |
| 558 | * |
| 559 | * If for some reason libpq is still reporting PGRES_COPY_OUT state, we |
| 560 | * would like to forcibly exit that state, since our caller would be |
| 561 | * unable to distinguish that situation from reaching the next COPY in a |
| 562 | * command string that happened to contain two consecutive COPY TO STDOUT |
| 563 | * commands. However, libpq provides no API for doing that, and in |
| 564 | * principle it's a libpq bug anyway if PQgetCopyData() returns -1 or -2 |
| 565 | * but hasn't exited COPY_OUT state internally. So we ignore the |
| 566 | * possibility here. |
| 567 | */ |
| 568 | *res = PQgetResult(conn); |
| 569 | if (PQresultStatus(*res) != PGRES_COMMAND_OK) |
| 570 | { |
| 571 | pg_log_info("%s", PQerrorMessage(conn)); |
| 572 | OK = false; |
| 573 | } |
| 574 | |
| 575 | return OK; |
no test coverage detected