* CopyGetData reads data from the source (file or frontend) * * We attempt to read at least minread, and at most maxread, bytes from * the source. The actual number of bytes read is returned; if this is * less than minread, EOF was detected. * * Note: when copying from the frontend, we expect a proper EOF mark per * protocol; if the frontend simply drops the connection, we raise error. *
| 228 | * NB: no data conversion is applied here. |
| 229 | */ |
| 230 | int |
| 231 | CopyGetData(CopyFromState cstate, void *databuf, int minread, int maxread) |
| 232 | { |
| 233 | int bytesread = 0; |
| 234 | |
| 235 | switch (cstate->copy_src) |
| 236 | { |
| 237 | case COPY_FILE: |
| 238 | bytesread = fread(databuf, 1, maxread, cstate->copy_file); |
| 239 | if (ferror(cstate->copy_file)) |
| 240 | { |
| 241 | if (cstate->is_program) |
| 242 | { |
| 243 | int olderrno = errno; |
| 244 | if (cstate->copy_file) |
| 245 | { |
| 246 | fclose(cstate->copy_file); |
| 247 | cstate->copy_file = NULL; |
| 248 | } |
| 249 | close_program_pipes(cstate->program_pipes, true); |
| 250 | |
| 251 | /* |
| 252 | * If close_program_pipes() didn't throw an error, |
| 253 | * the program terminated normally, but closed the |
| 254 | * pipe first. Restore errno, and throw an error. |
| 255 | */ |
| 256 | errno = olderrno; |
| 257 | |
| 258 | ereport(ERROR, |
| 259 | (errcode_for_file_access(), |
| 260 | errmsg("could not read from COPY program: %m"))); |
| 261 | } |
| 262 | else |
| 263 | ereport(ERROR, |
| 264 | (errcode_for_file_access(), |
| 265 | errmsg("could not read from COPY file: %m"))); |
| 266 | } |
| 267 | if (bytesread == 0) |
| 268 | cstate->raw_reached_eof = true; |
| 269 | break; |
| 270 | case COPY_FRONTEND: |
| 271 | while (maxread > 0 && bytesread < minread && !cstate->raw_reached_eof) |
| 272 | { |
| 273 | int avail; |
| 274 | |
| 275 | while (cstate->fe_msgbuf->cursor >= cstate->fe_msgbuf->len) |
| 276 | { |
| 277 | /* Try to receive another message */ |
| 278 | int mtype; |
| 279 | int maxmsglen; |
| 280 | |
| 281 | readmessage: |
| 282 | HOLD_CANCEL_INTERRUPTS(); |
| 283 | pq_startmsgread(); |
| 284 | mtype = pq_getbyte(); |
| 285 | if (mtype == EOF) |
| 286 | ereport(ERROR, |
| 287 | (errcode(ERRCODE_CONNECTION_FAILURE), |
no test coverage detected