PostgreSQL Source Code  git master
fe-protocol3.c
Go to the documentation of this file.
1 /*-------------------------------------------------------------------------
2  *
3  * fe-protocol3.c
4  * functions that are specific to frontend/backend protocol version 3
5  *
6  * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
7  * Portions Copyright (c) 1994, Regents of the University of California
8  *
9  *
10  * IDENTIFICATION
11  * src/interfaces/libpq/fe-protocol3.c
12  *
13  *-------------------------------------------------------------------------
14  */
15 #include "postgres_fe.h"
16 
17 #include <ctype.h>
18 #include <fcntl.h>
19 
20 #ifdef WIN32
21 #include "win32.h"
22 #else
23 #include <unistd.h>
24 #include <netinet/tcp.h>
25 #endif
26 
27 #include "libpq-fe.h"
28 #include "libpq-int.h"
29 #include "mb/pg_wchar.h"
30 #include "port/pg_bswap.h"
31 
32 /*
33  * This macro lists the backend message types that could be "long" (more
34  * than a couple of kilobytes).
35  */
36 #define VALID_LONG_MESSAGE_TYPE(id) \
37  ((id) == PqMsg_CopyData || \
38  (id) == PqMsg_DataRow || \
39  (id) == PqMsg_ErrorResponse || \
40  (id) == PqMsg_FunctionCallResponse || \
41  (id) == PqMsg_NoticeResponse || \
42  (id) == PqMsg_NotificationResponse || \
43  (id) == PqMsg_RowDescription)
44 
45 
46 static void handleSyncLoss(PGconn *conn, char id, int msgLength);
47 static int getRowDescriptions(PGconn *conn, int msgLength);
48 static int getParamDescriptions(PGconn *conn, int msgLength);
49 static int getAnotherTuple(PGconn *conn, int msgLength);
50 static int getParameterStatus(PGconn *conn);
51 static int getNotify(PGconn *conn);
52 static int getCopyStart(PGconn *conn, ExecStatusType copytype);
53 static int getReadyForQuery(PGconn *conn);
54 static void reportErrorPosition(PQExpBuffer msg, const char *query,
55  int loc, int encoding);
56 static int build_startup_packet(const PGconn *conn, char *packet,
58 
59 
60 /*
61  * parseInput: if appropriate, parse input data from backend
62  * until input is exhausted or a stopping state is reached.
63  * Note that this function will NOT attempt to read more data from the backend.
64  */
65 void
67 {
68  char id;
69  int msgLength;
70  int avail;
71 
72  /*
73  * Loop to parse successive complete messages available in the buffer.
74  */
75  for (;;)
76  {
77  /*
78  * Try to read a message. First get the type code and length. Return
79  * if not enough data.
80  */
82  if (pqGetc(&id, conn))
83  return;
84  if (pqGetInt(&msgLength, 4, conn))
85  return;
86 
87  /*
88  * Try to validate message type/length here. A length less than 4 is
89  * definitely broken. Large lengths should only be believed for a few
90  * message types.
91  */
92  if (msgLength < 4)
93  {
94  handleSyncLoss(conn, id, msgLength);
95  return;
96  }
97  if (msgLength > 30000 && !VALID_LONG_MESSAGE_TYPE(id))
98  {
99  handleSyncLoss(conn, id, msgLength);
100  return;
101  }
102 
103  /*
104  * Can't process if message body isn't all here yet.
105  */
106  msgLength -= 4;
107  avail = conn->inEnd - conn->inCursor;
108  if (avail < msgLength)
109  {
110  /*
111  * Before returning, enlarge the input buffer if needed to hold
112  * the whole message. This is better than leaving it to
113  * pqReadData because we can avoid multiple cycles of realloc()
114  * when the message is large; also, we can implement a reasonable
115  * recovery strategy if we are unable to make the buffer big
116  * enough.
117  */
118  if (pqCheckInBufferSpace(conn->inCursor + (size_t) msgLength,
119  conn))
120  {
121  /*
122  * XXX add some better recovery code... plan is to skip over
123  * the message using its length, then report an error. For the
124  * moment, just treat this like loss of sync (which indeed it
125  * might be!)
126  */
127  handleSyncLoss(conn, id, msgLength);
128  }
129  return;
130  }
131 
132  /*
133  * NOTIFY and NOTICE messages can happen in any state; always process
134  * them right away.
135  *
136  * Most other messages should only be processed while in BUSY state.
137  * (In particular, in READY state we hold off further parsing until
138  * the application collects the current PGresult.)
139  *
140  * However, if the state is IDLE then we got trouble; we need to deal
141  * with the unexpected message somehow.
142  *
143  * ParameterStatus ('S') messages are a special case: in IDLE state we
144  * must process 'em (this case could happen if a new value was adopted
145  * from config file due to SIGHUP), but otherwise we hold off until
146  * BUSY state.
147  */
148  if (id == PqMsg_NotificationResponse)
149  {
150  if (getNotify(conn))
151  return;
152  }
153  else if (id == PqMsg_NoticeResponse)
154  {
155  if (pqGetErrorNotice3(conn, false))
156  return;
157  }
158  else if (conn->asyncStatus != PGASYNC_BUSY)
159  {
160  /* If not IDLE state, just wait ... */
161  if (conn->asyncStatus != PGASYNC_IDLE)
162  return;
163 
164  /*
165  * Unexpected message in IDLE state; need to recover somehow.
166  * ERROR messages are handled using the notice processor;
167  * ParameterStatus is handled normally; anything else is just
168  * dropped on the floor after displaying a suitable warning
169  * notice. (An ERROR is very possibly the backend telling us why
170  * it is about to close the connection, so we don't want to just
171  * discard it...)
172  */
173  if (id == PqMsg_ErrorResponse)
174  {
175  if (pqGetErrorNotice3(conn, false /* treat as notice */ ))
176  return;
177  }
178  else if (id == PqMsg_ParameterStatus)
179  {
181  return;
182  }
183  else
184  {
185  /* Any other case is unexpected and we summarily skip it */
187  "message type 0x%02x arrived from server while idle",
188  id);
189  /* Discard the unexpected message */
190  conn->inCursor += msgLength;
191  }
192  }
193  else
194  {
195  /*
196  * In BUSY state, we can process everything.
197  */
198  switch (id)
199  {
201  if (pqGets(&conn->workBuffer, conn))
202  return;
204  {
207  if (!conn->result)
208  {
209  libpq_append_conn_error(conn, "out of memory");
211  }
212  }
213  if (conn->result)
215  CMDSTATUS_LEN);
217  break;
218  case PqMsg_ErrorResponse:
219  if (pqGetErrorNotice3(conn, true))
220  return;
222  break;
223  case PqMsg_ReadyForQuery:
224  if (getReadyForQuery(conn))
225  return;
227  {
230  if (!conn->result)
231  {
232  libpq_append_conn_error(conn, "out of memory");
234  }
235  else
236  {
239  }
240  }
241  else
242  {
243  /*
244  * In simple query protocol, advance the command queue
245  * (see PQgetResult).
246  */
247  if (conn->cmd_queue_head &&
251  }
252  break;
255  {
258  if (!conn->result)
259  {
260  libpq_append_conn_error(conn, "out of memory");
262  }
263  }
265  break;
266  case PqMsg_ParseComplete:
267  /* If we're doing PQprepare, we're done; else ignore */
268  if (conn->cmd_queue_head &&
270  {
272  {
275  if (!conn->result)
276  {
277  libpq_append_conn_error(conn, "out of memory");
279  }
280  }
282  }
283  break;
284  case PqMsg_BindComplete:
285  /* Nothing to do for this message type */
286  break;
287  case PqMsg_CloseComplete:
288  /* If we're doing PQsendClose, we're done; else ignore */
289  if (conn->cmd_queue_head &&
291  {
293  {
296  if (!conn->result)
297  {
298  libpq_append_conn_error(conn, "out of memory");
300  }
301  }
303  }
304  break;
307  return;
308  break;
310 
311  /*
312  * This is expected only during backend startup, but it's
313  * just as easy to handle it as part of the main loop.
314  * Save the data and continue processing.
315  */
316  if (pqGetInt(&(conn->be_pid), 4, conn))
317  return;
318  if (pqGetInt(&(conn->be_key), 4, conn))
319  return;
320  break;
322  if (conn->error_result ||
323  (conn->result != NULL &&
325  {
326  /*
327  * We've already choked for some reason. Just discard
328  * the data till we get to the end of the query.
329  */
330  conn->inCursor += msgLength;
331  }
332  else if (conn->result == NULL ||
333  (conn->cmd_queue_head &&
335  {
336  /* First 'T' in a query sequence */
337  if (getRowDescriptions(conn, msgLength))
338  return;
339  }
340  else
341  {
342  /*
343  * A new 'T' message is treated as the start of
344  * another PGresult. (It is not clear that this is
345  * really possible with the current backend.) We stop
346  * parsing until the application accepts the current
347  * result.
348  */
350  return;
351  }
352  break;
353  case PqMsg_NoData:
354 
355  /*
356  * NoData indicates that we will not be seeing a
357  * RowDescription message because the statement or portal
358  * inquired about doesn't return rows.
359  *
360  * If we're doing a Describe, we have to pass something
361  * back to the client, so set up a COMMAND_OK result,
362  * instead of PGRES_TUPLES_OK. Otherwise we can just
363  * ignore this message.
364  */
365  if (conn->cmd_queue_head &&
367  {
369  {
372  if (!conn->result)
373  {
374  libpq_append_conn_error(conn, "out of memory");
376  }
377  }
379  }
380  break;
382  if (getParamDescriptions(conn, msgLength))
383  return;
384  break;
385  case PqMsg_DataRow:
386  if (conn->result != NULL &&
388  {
389  /* Read another tuple of a normal query response */
390  if (getAnotherTuple(conn, msgLength))
391  return;
392  }
393  else if (conn->error_result ||
394  (conn->result != NULL &&
396  {
397  /*
398  * We've already choked for some reason. Just discard
399  * tuples till we get to the end of the query.
400  */
401  conn->inCursor += msgLength;
402  }
403  else
404  {
405  /* Set up to report error at end of query */
406  libpq_append_conn_error(conn, "server sent data (\"D\" message) without prior row description (\"T\" message)");
408  /* Discard the unexpected message */
409  conn->inCursor += msgLength;
410  }
411  break;
414  return;
416  break;
419  return;
421  conn->copy_already_done = 0;
422  break;
425  return;
427  conn->copy_already_done = 0;
428  break;
429  case PqMsg_CopyData:
430 
431  /*
432  * If we see Copy Data, just silently drop it. This would
433  * only occur if application exits COPY OUT mode too
434  * early.
435  */
436  conn->inCursor += msgLength;
437  break;
438  case PqMsg_CopyDone:
439 
440  /*
441  * If we see Copy Done, just silently drop it. This is
442  * the normal case during PQendcopy. We will keep
443  * swallowing data, expecting to see command-complete for
444  * the COPY command.
445  */
446  break;
447  default:
448  libpq_append_conn_error(conn, "unexpected response from server; first received character was \"%c\"", id);
449  /* build an error result holding the error message */
451  /* not sure if we will see more, so go to ready state */
453  /* Discard the unexpected message */
454  conn->inCursor += msgLength;
455  break;
456  } /* switch on protocol character */
457  }
458  /* Successfully consumed this message */
459  if (conn->inCursor == conn->inStart + 5 + msgLength)
460  {
461  /* trace server-to-client message */
462  if (conn->Pfdebug)
464 
465  /* Normal case: parsing agrees with specified length */
467  }
468  else
469  {
470  /* Trouble --- report it */
471  libpq_append_conn_error(conn, "message contents do not agree with length in message type \"%c\"", id);
472  /* build an error result holding the error message */
475  /* trust the specified message length as what to skip */
476  conn->inStart += 5 + msgLength;
477  }
478  }
479 }
480 
481 /*
482  * handleSyncLoss: clean up after loss of message-boundary sync
483  *
484  * There isn't really a lot we can do here except abandon the connection.
485  */
486 static void
487 handleSyncLoss(PGconn *conn, char id, int msgLength)
488 {
489  libpq_append_conn_error(conn, "lost synchronization with server: got message type \"%c\", length %d",
490  id, msgLength);
491  /* build an error result holding the error message */
493  conn->asyncStatus = PGASYNC_READY; /* drop out of PQgetResult wait loop */
494  /* flush input data since we're giving up on processing it */
495  pqDropConnection(conn, true);
496  conn->status = CONNECTION_BAD; /* No more connection to backend */
497 }
498 
499 /*
500  * parseInput subroutine to read a 'T' (row descriptions) message.
501  * We'll build a new PGresult structure (unless called for a Describe
502  * command for a prepared statement) containing the attribute data.
503  * Returns: 0 if processed message successfully, EOF to suspend parsing
504  * (the latter case is not actually used currently).
505  */
506 static int
508 {
509  PGresult *result;
510  int nfields;
511  const char *errmsg;
512  int i;
513 
514  /*
515  * When doing Describe for a prepared statement, there'll already be a
516  * PGresult created by getParamDescriptions, and we should fill data into
517  * that. Otherwise, create a new, empty PGresult.
518  */
519  if (!conn->cmd_queue_head ||
520  (conn->cmd_queue_head &&
522  {
523  if (conn->result)
524  result = conn->result;
525  else
527  }
528  else
530  if (!result)
531  {
532  errmsg = NULL; /* means "out of memory", see below */
533  goto advance_and_error;
534  }
535 
536  /* parseInput already read the 'T' label and message length. */
537  /* the next two bytes are the number of fields */
538  if (pqGetInt(&(result->numAttributes), 2, conn))
539  {
540  /* We should not run out of data here, so complain */
541  errmsg = libpq_gettext("insufficient data in \"T\" message");
542  goto advance_and_error;
543  }
544  nfields = result->numAttributes;
545 
546  /* allocate space for the attribute descriptors */
547  if (nfields > 0)
548  {
549  result->attDescs = (PGresAttDesc *)
550  pqResultAlloc(result, nfields * sizeof(PGresAttDesc), true);
551  if (!result->attDescs)
552  {
553  errmsg = NULL; /* means "out of memory", see below */
554  goto advance_and_error;
555  }
556  MemSet(result->attDescs, 0, nfields * sizeof(PGresAttDesc));
557  }
558 
559  /* result->binary is true only if ALL columns are binary */
560  result->binary = (nfields > 0) ? 1 : 0;
561 
562  /* get type info */
563  for (i = 0; i < nfields; i++)
564  {
565  int tableid;
566  int columnid;
567  int typid;
568  int typlen;
569  int atttypmod;
570  int format;
571 
572  if (pqGets(&conn->workBuffer, conn) ||
573  pqGetInt(&tableid, 4, conn) ||
574  pqGetInt(&columnid, 2, conn) ||
575  pqGetInt(&typid, 4, conn) ||
576  pqGetInt(&typlen, 2, conn) ||
577  pqGetInt(&atttypmod, 4, conn) ||
578  pqGetInt(&format, 2, conn))
579  {
580  /* We should not run out of data here, so complain */
581  errmsg = libpq_gettext("insufficient data in \"T\" message");
582  goto advance_and_error;
583  }
584 
585  /*
586  * Since pqGetInt treats 2-byte integers as unsigned, we need to
587  * coerce these results to signed form.
588  */
589  columnid = (int) ((int16) columnid);
590  typlen = (int) ((int16) typlen);
591  format = (int) ((int16) format);
592 
593  result->attDescs[i].name = pqResultStrdup(result,
594  conn->workBuffer.data);
595  if (!result->attDescs[i].name)
596  {
597  errmsg = NULL; /* means "out of memory", see below */
598  goto advance_and_error;
599  }
600  result->attDescs[i].tableid = tableid;
601  result->attDescs[i].columnid = columnid;
602  result->attDescs[i].format = format;
603  result->attDescs[i].typid = typid;
604  result->attDescs[i].typlen = typlen;
605  result->attDescs[i].atttypmod = atttypmod;
606 
607  if (format != 1)
608  result->binary = 0;
609  }
610 
611  /* Success! */
612  conn->result = result;
613 
614  /*
615  * If we're doing a Describe, we're done, and ready to pass the result
616  * back to the client.
617  */
618  if ((!conn->cmd_queue_head) ||
619  (conn->cmd_queue_head &&
621  {
623  return 0;
624  }
625 
626  /*
627  * We could perform additional setup for the new result set here, but for
628  * now there's nothing else to do.
629  */
630 
631  /* And we're done. */
632  return 0;
633 
634 advance_and_error:
635  /* Discard unsaved result, if any */
636  if (result && result != conn->result)
637  PQclear(result);
638 
639  /*
640  * Replace partially constructed result with an error result. First
641  * discard the old result to try to win back some memory.
642  */
644 
645  /*
646  * If preceding code didn't provide an error message, assume "out of
647  * memory" was meant. The advantage of having this special case is that
648  * freeing the old result first greatly improves the odds that gettext()
649  * will succeed in providing a translation.
650  */
651  if (!errmsg)
652  errmsg = libpq_gettext("out of memory for query result");
653 
656 
657  /*
658  * Show the message as fully consumed, else pqParseInput3 will overwrite
659  * our error with a complaint about that.
660  */
661  conn->inCursor = conn->inStart + 5 + msgLength;
662 
663  /*
664  * Return zero to allow input parsing to continue. Subsequent "D"
665  * messages will be ignored until we get to end of data, since an error
666  * result is already set up.
667  */
668  return 0;
669 }
670 
671 /*
672  * parseInput subroutine to read a 't' (ParameterDescription) message.
673  * We'll build a new PGresult structure containing the parameter data.
674  * Returns: 0 if processed message successfully, EOF to suspend parsing
675  * (the latter case is not actually used currently).
676  */
677 static int
679 {
680  PGresult *result;
681  const char *errmsg = NULL; /* means "out of memory", see below */
682  int nparams;
683  int i;
684 
686  if (!result)
687  goto advance_and_error;
688 
689  /* parseInput already read the 't' label and message length. */
690  /* the next two bytes are the number of parameters */
691  if (pqGetInt(&(result->numParameters), 2, conn))
692  goto not_enough_data;
693  nparams = result->numParameters;
694 
695  /* allocate space for the parameter descriptors */
696  if (nparams > 0)
697  {
698  result->paramDescs = (PGresParamDesc *)
699  pqResultAlloc(result, nparams * sizeof(PGresParamDesc), true);
700  if (!result->paramDescs)
701  goto advance_and_error;
702  MemSet(result->paramDescs, 0, nparams * sizeof(PGresParamDesc));
703  }
704 
705  /* get parameter info */
706  for (i = 0; i < nparams; i++)
707  {
708  int typid;
709 
710  if (pqGetInt(&typid, 4, conn))
711  goto not_enough_data;
712  result->paramDescs[i].typid = typid;
713  }
714 
715  /* Success! */
716  conn->result = result;
717 
718  return 0;
719 
720 not_enough_data:
721  errmsg = libpq_gettext("insufficient data in \"t\" message");
722 
723 advance_and_error:
724  /* Discard unsaved result, if any */
725  if (result && result != conn->result)
726  PQclear(result);
727 
728  /*
729  * Replace partially constructed result with an error result. First
730  * discard the old result to try to win back some memory.
731  */
733 
734  /*
735  * If preceding code didn't provide an error message, assume "out of
736  * memory" was meant. The advantage of having this special case is that
737  * freeing the old result first greatly improves the odds that gettext()
738  * will succeed in providing a translation.
739  */
740  if (!errmsg)
741  errmsg = libpq_gettext("out of memory");
744 
745  /*
746  * Show the message as fully consumed, else pqParseInput3 will overwrite
747  * our error with a complaint about that.
748  */
749  conn->inCursor = conn->inStart + 5 + msgLength;
750 
751  /*
752  * Return zero to allow input parsing to continue. Essentially, we've
753  * replaced the COMMAND_OK result with an error result, but since this
754  * doesn't affect the protocol state, it's fine.
755  */
756  return 0;
757 }
758 
759 /*
760  * parseInput subroutine to read a 'D' (row data) message.
761  * We fill rowbuf with column pointers and then call the row processor.
762  * Returns: 0 if processed message successfully, EOF to suspend parsing
763  * (the latter case is not actually used currently).
764  */
765 static int
766 getAnotherTuple(PGconn *conn, int msgLength)
767 {
768  PGresult *result = conn->result;
769  int nfields = result->numAttributes;
770  const char *errmsg;
771  PGdataValue *rowbuf;
772  int tupnfields; /* # fields from tuple */
773  int vlen; /* length of the current field value */
774  int i;
775 
776  /* Get the field count and make sure it's what we expect */
777  if (pqGetInt(&tupnfields, 2, conn))
778  {
779  /* We should not run out of data here, so complain */
780  errmsg = libpq_gettext("insufficient data in \"D\" message");
781  goto advance_and_error;
782  }
783 
784  if (tupnfields != nfields)
785  {
786  errmsg = libpq_gettext("unexpected field count in \"D\" message");
787  goto advance_and_error;
788  }
789 
790  /* Resize row buffer if needed */
791  rowbuf = conn->rowBuf;
792  if (nfields > conn->rowBufLen)
793  {
794  rowbuf = (PGdataValue *) realloc(rowbuf,
795  nfields * sizeof(PGdataValue));
796  if (!rowbuf)
797  {
798  errmsg = NULL; /* means "out of memory", see below */
799  goto advance_and_error;
800  }
801  conn->rowBuf = rowbuf;
802  conn->rowBufLen = nfields;
803  }
804 
805  /* Scan the fields */
806  for (i = 0; i < nfields; i++)
807  {
808  /* get the value length */
809  if (pqGetInt(&vlen, 4, conn))
810  {
811  /* We should not run out of data here, so complain */
812  errmsg = libpq_gettext("insufficient data in \"D\" message");
813  goto advance_and_error;
814  }
815  rowbuf[i].len = vlen;
816 
817  /*
818  * rowbuf[i].value always points to the next address in the data
819  * buffer even if the value is NULL. This allows row processors to
820  * estimate data sizes more easily.
821  */
822  rowbuf[i].value = conn->inBuffer + conn->inCursor;
823 
824  /* Skip over the data value */
825  if (vlen > 0)
826  {
827  if (pqSkipnchar(vlen, conn))
828  {
829  /* We should not run out of data here, so complain */
830  errmsg = libpq_gettext("insufficient data in \"D\" message");
831  goto advance_and_error;
832  }
833  }
834  }
835 
836  /* Process the collected row */
837  errmsg = NULL;
838  if (pqRowProcessor(conn, &errmsg))
839  return 0; /* normal, successful exit */
840 
841  /* pqRowProcessor failed, fall through to report it */
842 
843 advance_and_error:
844 
845  /*
846  * Replace partially constructed result with an error result. First
847  * discard the old result to try to win back some memory.
848  */
850 
851  /*
852  * If preceding code didn't provide an error message, assume "out of
853  * memory" was meant. The advantage of having this special case is that
854  * freeing the old result first greatly improves the odds that gettext()
855  * will succeed in providing a translation.
856  */
857  if (!errmsg)
858  errmsg = libpq_gettext("out of memory for query result");
859 
862 
863  /*
864  * Show the message as fully consumed, else pqParseInput3 will overwrite
865  * our error with a complaint about that.
866  */
867  conn->inCursor = conn->inStart + 5 + msgLength;
868 
869  /*
870  * Return zero to allow input parsing to continue. Subsequent "D"
871  * messages will be ignored until we get to end of data, since an error
872  * result is already set up.
873  */
874  return 0;
875 }
876 
877 
878 /*
879  * Attempt to read an Error or Notice response message.
880  * This is possible in several places, so we break it out as a subroutine.
881  * Entry: 'E' or 'N' message type and length have already been consumed.
882  * Exit: returns 0 if successfully consumed message.
883  * returns EOF if not enough data.
884  */
885 int
887 {
888  PGresult *res = NULL;
889  bool have_position = false;
890  PQExpBufferData workBuf;
891  char id;
892 
893  /* If in pipeline mode, set error indicator for it */
894  if (isError && conn->pipelineStatus != PQ_PIPELINE_OFF)
896 
897  /*
898  * If this is an error message, pre-emptively clear any incomplete query
899  * result we may have. We'd just throw it away below anyway, and
900  * releasing it before collecting the error might avoid out-of-memory.
901  */
902  if (isError)
904 
905  /*
906  * Since the fields might be pretty long, we create a temporary
907  * PQExpBuffer rather than using conn->workBuffer. workBuffer is intended
908  * for stuff that is expected to be short. We shouldn't use
909  * conn->errorMessage either, since this might be only a notice.
910  */
911  initPQExpBuffer(&workBuf);
912 
913  /*
914  * Make a PGresult to hold the accumulated fields. We temporarily lie
915  * about the result status, so that PQmakeEmptyPGresult doesn't uselessly
916  * copy conn->errorMessage.
917  *
918  * NB: This allocation can fail, if you run out of memory. The rest of the
919  * function handles that gracefully, and we still try to set the error
920  * message as the connection's error message.
921  */
923  if (res)
925 
926  /*
927  * Read the fields and save into res.
928  *
929  * While at it, save the SQLSTATE in conn->last_sqlstate, and note whether
930  * we saw a PG_DIAG_STATEMENT_POSITION field.
931  */
932  for (;;)
933  {
934  if (pqGetc(&id, conn))
935  goto fail;
936  if (id == '\0')
937  break; /* terminator found */
938  if (pqGets(&workBuf, conn))
939  goto fail;
940  pqSaveMessageField(res, id, workBuf.data);
941  if (id == PG_DIAG_SQLSTATE)
942  strlcpy(conn->last_sqlstate, workBuf.data,
943  sizeof(conn->last_sqlstate));
944  else if (id == PG_DIAG_STATEMENT_POSITION)
945  have_position = true;
946  }
947 
948  /*
949  * Save the active query text, if any, into res as well; but only if we
950  * might need it for an error cursor display, which is only true if there
951  * is a PG_DIAG_STATEMENT_POSITION field.
952  */
953  if (have_position && res && conn->cmd_queue_head && conn->cmd_queue_head->query)
955 
956  /*
957  * Now build the "overall" error message for PQresultErrorMessage.
958  */
959  resetPQExpBuffer(&workBuf);
961 
962  /*
963  * Either save error as current async result, or just emit the notice.
964  */
965  if (isError)
966  {
967  pqClearAsyncResult(conn); /* redundant, but be safe */
968  if (res)
969  {
970  pqSetResultError(res, &workBuf, 0);
971  conn->result = res;
972  }
973  else
974  {
975  /* Fall back to using the internal-error processing paths */
976  conn->error_result = true;
977  }
978 
979  if (PQExpBufferDataBroken(workBuf))
980  libpq_append_conn_error(conn, "out of memory");
981  else
983  }
984  else
985  {
986  /* if we couldn't allocate the result set, just discard the NOTICE */
987  if (res)
988  {
989  /*
990  * We can cheat a little here and not copy the message. But if we
991  * were unlucky enough to run out of memory while filling workBuf,
992  * insert "out of memory", as in pqSetResultError.
993  */
994  if (PQExpBufferDataBroken(workBuf))
995  res->errMsg = libpq_gettext("out of memory\n");
996  else
997  res->errMsg = workBuf.data;
998  if (res->noticeHooks.noticeRec != NULL)
1000  PQclear(res);
1001  }
1002  }
1003 
1004  termPQExpBuffer(&workBuf);
1005  return 0;
1006 
1007 fail:
1008  PQclear(res);
1009  termPQExpBuffer(&workBuf);
1010  return EOF;
1011 }
1012 
1013 /*
1014  * Construct an error message from the fields in the given PGresult,
1015  * appending it to the contents of "msg".
1016  */
1017 void
1019  PGVerbosity verbosity, PGContextVisibility show_context)
1020 {
1021  const char *val;
1022  const char *querytext = NULL;
1023  int querypos = 0;
1024 
1025  /* If we couldn't allocate a PGresult, just say "out of memory" */
1026  if (res == NULL)
1027  {
1028  appendPQExpBufferStr(msg, libpq_gettext("out of memory\n"));
1029  return;
1030  }
1031 
1032  /*
1033  * If we don't have any broken-down fields, just return the base message.
1034  * This mainly applies if we're given a libpq-generated error result.
1035  */
1036  if (res->errFields == NULL)
1037  {
1038  if (res->errMsg && res->errMsg[0])
1040  else
1041  appendPQExpBufferStr(msg, libpq_gettext("no error message available\n"));
1042  return;
1043  }
1044 
1045  /* Else build error message from relevant fields */
1047  if (val)
1048  appendPQExpBuffer(msg, "%s: ", val);
1049 
1050  if (verbosity == PQERRORS_SQLSTATE)
1051  {
1052  /*
1053  * If we have a SQLSTATE, print that and nothing else. If not (which
1054  * shouldn't happen for server-generated errors, but might possibly
1055  * happen for libpq-generated ones), fall back to TERSE format, as
1056  * that seems better than printing nothing at all.
1057  */
1059  if (val)
1060  {
1061  appendPQExpBuffer(msg, "%s\n", val);
1062  return;
1063  }
1064  verbosity = PQERRORS_TERSE;
1065  }
1066 
1067  if (verbosity == PQERRORS_VERBOSE)
1068  {
1070  if (val)
1071  appendPQExpBuffer(msg, "%s: ", val);
1072  }
1074  if (val)
1075  appendPQExpBufferStr(msg, val);
1077  if (val)
1078  {
1079  if (verbosity != PQERRORS_TERSE && res->errQuery != NULL)
1080  {
1081  /* emit position as a syntax cursor display */
1082  querytext = res->errQuery;
1083  querypos = atoi(val);
1084  }
1085  else
1086  {
1087  /* emit position as text addition to primary message */
1088  /* translator: %s represents a digit string */
1089  appendPQExpBuffer(msg, libpq_gettext(" at character %s"),
1090  val);
1091  }
1092  }
1093  else
1094  {
1096  if (val)
1097  {
1099  if (verbosity != PQERRORS_TERSE && querytext != NULL)
1100  {
1101  /* emit position as a syntax cursor display */
1102  querypos = atoi(val);
1103  }
1104  else
1105  {
1106  /* emit position as text addition to primary message */
1107  /* translator: %s represents a digit string */
1108  appendPQExpBuffer(msg, libpq_gettext(" at character %s"),
1109  val);
1110  }
1111  }
1112  }
1113  appendPQExpBufferChar(msg, '\n');
1114  if (verbosity != PQERRORS_TERSE)
1115  {
1116  if (querytext && querypos > 0)
1117  reportErrorPosition(msg, querytext, querypos,
1118  res->client_encoding);
1120  if (val)
1121  appendPQExpBuffer(msg, libpq_gettext("DETAIL: %s\n"), val);
1123  if (val)
1124  appendPQExpBuffer(msg, libpq_gettext("HINT: %s\n"), val);
1126  if (val)
1127  appendPQExpBuffer(msg, libpq_gettext("QUERY: %s\n"), val);
1128  if (show_context == PQSHOW_CONTEXT_ALWAYS ||
1129  (show_context == PQSHOW_CONTEXT_ERRORS &&
1131  {
1133  if (val)
1134  appendPQExpBuffer(msg, libpq_gettext("CONTEXT: %s\n"),
1135  val);
1136  }
1137  }
1138  if (verbosity == PQERRORS_VERBOSE)
1139  {
1141  if (val)
1142  appendPQExpBuffer(msg,
1143  libpq_gettext("SCHEMA NAME: %s\n"), val);
1145  if (val)
1146  appendPQExpBuffer(msg,
1147  libpq_gettext("TABLE NAME: %s\n"), val);
1149  if (val)
1150  appendPQExpBuffer(msg,
1151  libpq_gettext("COLUMN NAME: %s\n"), val);
1153  if (val)
1154  appendPQExpBuffer(msg,
1155  libpq_gettext("DATATYPE NAME: %s\n"), val);
1157  if (val)
1158  appendPQExpBuffer(msg,
1159  libpq_gettext("CONSTRAINT NAME: %s\n"), val);
1160  }
1161  if (verbosity == PQERRORS_VERBOSE)
1162  {
1163  const char *valf;
1164  const char *vall;
1165 
1169  if (val || valf || vall)
1170  {
1171  appendPQExpBufferStr(msg, libpq_gettext("LOCATION: "));
1172  if (val)
1173  appendPQExpBuffer(msg, libpq_gettext("%s, "), val);
1174  if (valf && vall) /* unlikely we'd have just one */
1175  appendPQExpBuffer(msg, libpq_gettext("%s:%s"),
1176  valf, vall);
1177  appendPQExpBufferChar(msg, '\n');
1178  }
1179  }
1180 }
1181 
1182 /*
1183  * Add an error-location display to the error message under construction.
1184  *
1185  * The cursor location is measured in logical characters; the query string
1186  * is presumed to be in the specified encoding.
1187  */
1188 static void
1189 reportErrorPosition(PQExpBuffer msg, const char *query, int loc, int encoding)
1190 {
1191 #define DISPLAY_SIZE 60 /* screen width limit, in screen cols */
1192 #define MIN_RIGHT_CUT 10 /* try to keep this far away from EOL */
1193 
1194  char *wquery;
1195  int slen,
1196  cno,
1197  i,
1198  *qidx,
1199  *scridx,
1200  qoffset,
1201  scroffset,
1202  ibeg,
1203  iend,
1204  loc_line;
1205  bool mb_encoding,
1206  beg_trunc,
1207  end_trunc;
1208 
1209  /* Convert loc from 1-based to 0-based; no-op if out of range */
1210  loc--;
1211  if (loc < 0)
1212  return;
1213 
1214  /* Need a writable copy of the query */
1215  wquery = strdup(query);
1216  if (wquery == NULL)
1217  return; /* fail silently if out of memory */
1218 
1219  /*
1220  * Each character might occupy multiple physical bytes in the string, and
1221  * in some Far Eastern character sets it might take more than one screen
1222  * column as well. We compute the starting byte offset and starting
1223  * screen column of each logical character, and store these in qidx[] and
1224  * scridx[] respectively.
1225  */
1226 
1227  /* we need a safe allocation size... */
1228  slen = strlen(wquery) + 1;
1229 
1230  qidx = (int *) malloc(slen * sizeof(int));
1231  if (qidx == NULL)
1232  {
1233  free(wquery);
1234  return;
1235  }
1236  scridx = (int *) malloc(slen * sizeof(int));
1237  if (scridx == NULL)
1238  {
1239  free(qidx);
1240  free(wquery);
1241  return;
1242  }
1243 
1244  /* We can optimize a bit if it's a single-byte encoding */
1245  mb_encoding = (pg_encoding_max_length(encoding) != 1);
1246 
1247  /*
1248  * Within the scanning loop, cno is the current character's logical
1249  * number, qoffset is its offset in wquery, and scroffset is its starting
1250  * logical screen column (all indexed from 0). "loc" is the logical
1251  * character number of the error location. We scan to determine loc_line
1252  * (the 1-based line number containing loc) and ibeg/iend (first character
1253  * number and last+1 character number of the line containing loc). Note
1254  * that qidx[] and scridx[] are filled only as far as iend.
1255  */
1256  qoffset = 0;
1257  scroffset = 0;
1258  loc_line = 1;
1259  ibeg = 0;
1260  iend = -1; /* -1 means not set yet */
1261 
1262  for (cno = 0; wquery[qoffset] != '\0'; cno++)
1263  {
1264  char ch = wquery[qoffset];
1265 
1266  qidx[cno] = qoffset;
1267  scridx[cno] = scroffset;
1268 
1269  /*
1270  * Replace tabs with spaces in the writable copy. (Later we might
1271  * want to think about coping with their variable screen width, but
1272  * not today.)
1273  */
1274  if (ch == '\t')
1275  wquery[qoffset] = ' ';
1276 
1277  /*
1278  * If end-of-line, count lines and mark positions. Each \r or \n
1279  * counts as a line except when \r \n appear together.
1280  */
1281  else if (ch == '\r' || ch == '\n')
1282  {
1283  if (cno < loc)
1284  {
1285  if (ch == '\r' ||
1286  cno == 0 ||
1287  wquery[qidx[cno - 1]] != '\r')
1288  loc_line++;
1289  /* extract beginning = last line start before loc. */
1290  ibeg = cno + 1;
1291  }
1292  else
1293  {
1294  /* set extract end. */
1295  iend = cno;
1296  /* done scanning. */
1297  break;
1298  }
1299  }
1300 
1301  /* Advance */
1302  if (mb_encoding)
1303  {
1304  int w;
1305 
1306  w = pg_encoding_dsplen(encoding, &wquery[qoffset]);
1307  /* treat any non-tab control chars as width 1 */
1308  if (w <= 0)
1309  w = 1;
1310  scroffset += w;
1311  qoffset += PQmblenBounded(&wquery[qoffset], encoding);
1312  }
1313  else
1314  {
1315  /* We assume wide chars only exist in multibyte encodings */
1316  scroffset++;
1317  qoffset++;
1318  }
1319  }
1320  /* Fix up if we didn't find an end-of-line after loc */
1321  if (iend < 0)
1322  {
1323  iend = cno; /* query length in chars, +1 */
1324  qidx[iend] = qoffset;
1325  scridx[iend] = scroffset;
1326  }
1327 
1328  /* Print only if loc is within computed query length */
1329  if (loc <= cno)
1330  {
1331  /* If the line extracted is too long, we truncate it. */
1332  beg_trunc = false;
1333  end_trunc = false;
1334  if (scridx[iend] - scridx[ibeg] > DISPLAY_SIZE)
1335  {
1336  /*
1337  * We first truncate right if it is enough. This code might be
1338  * off a space or so on enforcing MIN_RIGHT_CUT if there's a wide
1339  * character right there, but that should be okay.
1340  */
1341  if (scridx[ibeg] + DISPLAY_SIZE >= scridx[loc] + MIN_RIGHT_CUT)
1342  {
1343  while (scridx[iend] - scridx[ibeg] > DISPLAY_SIZE)
1344  iend--;
1345  end_trunc = true;
1346  }
1347  else
1348  {
1349  /* Truncate right if not too close to loc. */
1350  while (scridx[loc] + MIN_RIGHT_CUT < scridx[iend])
1351  {
1352  iend--;
1353  end_trunc = true;
1354  }
1355 
1356  /* Truncate left if still too long. */
1357  while (scridx[iend] - scridx[ibeg] > DISPLAY_SIZE)
1358  {
1359  ibeg++;
1360  beg_trunc = true;
1361  }
1362  }
1363  }
1364 
1365  /* truncate working copy at desired endpoint */
1366  wquery[qidx[iend]] = '\0';
1367 
1368  /* Begin building the finished message. */
1369  i = msg->len;
1370  appendPQExpBuffer(msg, libpq_gettext("LINE %d: "), loc_line);
1371  if (beg_trunc)
1372  appendPQExpBufferStr(msg, "...");
1373 
1374  /*
1375  * While we have the prefix in the msg buffer, compute its screen
1376  * width.
1377  */
1378  scroffset = 0;
1379  for (; i < msg->len; i += PQmblenBounded(&msg->data[i], encoding))
1380  {
1381  int w = pg_encoding_dsplen(encoding, &msg->data[i]);
1382 
1383  if (w <= 0)
1384  w = 1;
1385  scroffset += w;
1386  }
1387 
1388  /* Finish up the LINE message line. */
1389  appendPQExpBufferStr(msg, &wquery[qidx[ibeg]]);
1390  if (end_trunc)
1391  appendPQExpBufferStr(msg, "...");
1392  appendPQExpBufferChar(msg, '\n');
1393 
1394  /* Now emit the cursor marker line. */
1395  scroffset += scridx[loc] - scridx[ibeg];
1396  for (i = 0; i < scroffset; i++)
1397  appendPQExpBufferChar(msg, ' ');
1398  appendPQExpBufferChar(msg, '^');
1399  appendPQExpBufferChar(msg, '\n');
1400  }
1401 
1402  /* Clean up. */
1403  free(scridx);
1404  free(qidx);
1405  free(wquery);
1406 }
1407 
1408 
1409 /*
1410  * Attempt to read a NegotiateProtocolVersion message.
1411  * Entry: 'v' message type and length have already been consumed.
1412  * Exit: returns 0 if successfully consumed message.
1413  * returns EOF if not enough data.
1414  */
1415 int
1417 {
1418  int tmp;
1419  ProtocolVersion their_version;
1420  int num;
1422 
1423  if (pqGetInt(&tmp, 4, conn) != 0)
1424  return EOF;
1425  their_version = tmp;
1426 
1427  if (pqGetInt(&num, 4, conn) != 0)
1428  return EOF;
1429 
1430  initPQExpBuffer(&buf);
1431  for (int i = 0; i < num; i++)
1432  {
1433  if (pqGets(&conn->workBuffer, conn))
1434  {
1435  termPQExpBuffer(&buf);
1436  return EOF;
1437  }
1438  if (buf.len > 0)
1439  appendPQExpBufferChar(&buf, ' ');
1441  }
1442 
1443  if (their_version < conn->pversion)
1444  libpq_append_conn_error(conn, "protocol version not supported by server: client uses %u.%u, server supports up to %u.%u",
1446  PG_PROTOCOL_MAJOR(their_version), PG_PROTOCOL_MINOR(their_version));
1447  if (num > 0)
1448  {
1450  libpq_ngettext("protocol extension not supported by server: %s",
1451  "protocol extensions not supported by server: %s", num),
1452  buf.data);
1454  }
1455 
1456  /* neither -- server shouldn't have sent it */
1457  if (!(their_version < conn->pversion) && !(num > 0))
1458  libpq_append_conn_error(conn, "invalid %s message", "NegotiateProtocolVersion");
1459 
1460  termPQExpBuffer(&buf);
1461  return 0;
1462 }
1463 
1464 
1465 /*
1466  * Attempt to read a ParameterStatus message.
1467  * This is possible in several places, so we break it out as a subroutine.
1468  * Entry: 'S' message type and length have already been consumed.
1469  * Exit: returns 0 if successfully consumed message.
1470  * returns EOF if not enough data.
1471  */
1472 static int
1474 {
1475  PQExpBufferData valueBuf;
1476 
1477  /* Get the parameter name */
1478  if (pqGets(&conn->workBuffer, conn))
1479  return EOF;
1480  /* Get the parameter value (could be large) */
1481  initPQExpBuffer(&valueBuf);
1482  if (pqGets(&valueBuf, conn))
1483  {
1484  termPQExpBuffer(&valueBuf);
1485  return EOF;
1486  }
1487  /* And save it */
1489  termPQExpBuffer(&valueBuf);
1490  return 0;
1491 }
1492 
1493 
1494 /*
1495  * Attempt to read a Notify response message.
1496  * This is possible in several places, so we break it out as a subroutine.
1497  * Entry: 'A' message type and length have already been consumed.
1498  * Exit: returns 0 if successfully consumed Notify message.
1499  * returns EOF if not enough data.
1500  */
1501 static int
1503 {
1504  int be_pid;
1505  char *svname;
1506  int nmlen;
1507  int extralen;
1508  PGnotify *newNotify;
1509 
1510  if (pqGetInt(&be_pid, 4, conn))
1511  return EOF;
1512  if (pqGets(&conn->workBuffer, conn))
1513  return EOF;
1514  /* must save name while getting extra string */
1515  svname = strdup(conn->workBuffer.data);
1516  if (!svname)
1517  return EOF;
1518  if (pqGets(&conn->workBuffer, conn))
1519  {
1520  free(svname);
1521  return EOF;
1522  }
1523 
1524  /*
1525  * Store the strings right after the PGnotify structure so it can all be
1526  * freed at once. We don't use NAMEDATALEN because we don't want to tie
1527  * this interface to a specific server name length.
1528  */
1529  nmlen = strlen(svname);
1530  extralen = strlen(conn->workBuffer.data);
1531  newNotify = (PGnotify *) malloc(sizeof(PGnotify) + nmlen + extralen + 2);
1532  if (newNotify)
1533  {
1534  newNotify->relname = (char *) newNotify + sizeof(PGnotify);
1535  strcpy(newNotify->relname, svname);
1536  newNotify->extra = newNotify->relname + nmlen + 1;
1537  strcpy(newNotify->extra, conn->workBuffer.data);
1538  newNotify->be_pid = be_pid;
1539  newNotify->next = NULL;
1540  if (conn->notifyTail)
1541  conn->notifyTail->next = newNotify;
1542  else
1543  conn->notifyHead = newNotify;
1544  conn->notifyTail = newNotify;
1545  }
1546 
1547  free(svname);
1548  return 0;
1549 }
1550 
1551 /*
1552  * getCopyStart - process CopyInResponse, CopyOutResponse or
1553  * CopyBothResponse message
1554  *
1555  * parseInput already read the message type and length.
1556  */
1557 static int
1559 {
1560  PGresult *result;
1561  int nfields;
1562  int i;
1563 
1564  result = PQmakeEmptyPGresult(conn, copytype);
1565  if (!result)
1566  goto failure;
1567 
1568  if (pqGetc(&conn->copy_is_binary, conn))
1569  goto failure;
1570  result->binary = conn->copy_is_binary;
1571  /* the next two bytes are the number of fields */
1572  if (pqGetInt(&(result->numAttributes), 2, conn))
1573  goto failure;
1574  nfields = result->numAttributes;
1575 
1576  /* allocate space for the attribute descriptors */
1577  if (nfields > 0)
1578  {
1579  result->attDescs = (PGresAttDesc *)
1580  pqResultAlloc(result, nfields * sizeof(PGresAttDesc), true);
1581  if (!result->attDescs)
1582  goto failure;
1583  MemSet(result->attDescs, 0, nfields * sizeof(PGresAttDesc));
1584  }
1585 
1586  for (i = 0; i < nfields; i++)
1587  {
1588  int format;
1589 
1590  if (pqGetInt(&format, 2, conn))
1591  goto failure;
1592 
1593  /*
1594  * Since pqGetInt treats 2-byte integers as unsigned, we need to
1595  * coerce these results to signed form.
1596  */
1597  format = (int) ((int16) format);
1598  result->attDescs[i].format = format;
1599  }
1600 
1601  /* Success! */
1602  conn->result = result;
1603  return 0;
1604 
1605 failure:
1606  PQclear(result);
1607  return EOF;
1608 }
1609 
1610 /*
1611  * getReadyForQuery - process ReadyForQuery message
1612  */
1613 static int
1615 {
1616  char xact_status;
1617 
1618  if (pqGetc(&xact_status, conn))
1619  return EOF;
1620  switch (xact_status)
1621  {
1622  case 'I':
1624  break;
1625  case 'T':
1627  break;
1628  case 'E':
1630  break;
1631  default:
1633  break;
1634  }
1635 
1636  return 0;
1637 }
1638 
1639 /*
1640  * getCopyDataMessage - fetch next CopyData message, process async messages
1641  *
1642  * Returns length word of CopyData message (> 0), or 0 if no complete
1643  * message available, -1 if end of copy, -2 if error.
1644  */
1645 static int
1647 {
1648  char id;
1649  int msgLength;
1650  int avail;
1651 
1652  for (;;)
1653  {
1654  /*
1655  * Do we have the next input message? To make life simpler for async
1656  * callers, we keep returning 0 until the next message is fully
1657  * available, even if it is not Copy Data.
1658  */
1659  conn->inCursor = conn->inStart;
1660  if (pqGetc(&id, conn))
1661  return 0;
1662  if (pqGetInt(&msgLength, 4, conn))
1663  return 0;
1664  if (msgLength < 4)
1665  {
1666  handleSyncLoss(conn, id, msgLength);
1667  return -2;
1668  }
1669  avail = conn->inEnd - conn->inCursor;
1670  if (avail < msgLength - 4)
1671  {
1672  /*
1673  * Before returning, enlarge the input buffer if needed to hold
1674  * the whole message. See notes in parseInput.
1675  */
1676  if (pqCheckInBufferSpace(conn->inCursor + (size_t) msgLength - 4,
1677  conn))
1678  {
1679  /*
1680  * XXX add some better recovery code... plan is to skip over
1681  * the message using its length, then report an error. For the
1682  * moment, just treat this like loss of sync (which indeed it
1683  * might be!)
1684  */
1685  handleSyncLoss(conn, id, msgLength);
1686  return -2;
1687  }
1688  return 0;
1689  }
1690 
1691  /*
1692  * If it's a legitimate async message type, process it. (NOTIFY
1693  * messages are not currently possible here, but we handle them for
1694  * completeness.) Otherwise, if it's anything except Copy Data,
1695  * report end-of-copy.
1696  */
1697  switch (id)
1698  {
1700  if (getNotify(conn))
1701  return 0;
1702  break;
1703  case PqMsg_NoticeResponse:
1704  if (pqGetErrorNotice3(conn, false))
1705  return 0;
1706  break;
1707  case PqMsg_ParameterStatus:
1708  if (getParameterStatus(conn))
1709  return 0;
1710  break;
1711  case PqMsg_CopyData:
1712  return msgLength;
1713  case PqMsg_CopyDone:
1714 
1715  /*
1716  * If this is a CopyDone message, exit COPY_OUT mode and let
1717  * caller read status with PQgetResult(). If we're in
1718  * COPY_BOTH mode, return to COPY_IN mode.
1719  */
1722  else
1724  return -1;
1725  default: /* treat as end of copy */
1726 
1727  /*
1728  * Any other message terminates either COPY_IN or COPY_BOTH
1729  * mode.
1730  */
1732  return -1;
1733  }
1734 
1735  /* trace server-to-client message */
1736  if (conn->Pfdebug)
1738 
1739  /* Drop the processed message and loop around for another */
1740  conn->inStart = conn->inCursor;
1741  }
1742 }
1743 
1744 /*
1745  * PQgetCopyData - read a row of data from the backend during COPY OUT
1746  * or COPY BOTH
1747  *
1748  * If successful, sets *buffer to point to a malloc'd row of data, and
1749  * returns row length (always > 0) as result.
1750  * Returns 0 if no row available yet (only possible if async is true),
1751  * -1 if end of copy (consult PQgetResult), or -2 if error (consult
1752  * PQerrorMessage).
1753  */
1754 int
1755 pqGetCopyData3(PGconn *conn, char **buffer, int async)
1756 {
1757  int msgLength;
1758 
1759  for (;;)
1760  {
1761  /*
1762  * Collect the next input message. To make life simpler for async
1763  * callers, we keep returning 0 until the next message is fully
1764  * available, even if it is not Copy Data.
1765  */
1766  msgLength = getCopyDataMessage(conn);
1767  if (msgLength < 0)
1768  return msgLength; /* end-of-copy or error */
1769  if (msgLength == 0)
1770  {
1771  /* Don't block if async read requested */
1772  if (async)
1773  return 0;
1774  /* Need to load more data */
1775  if (pqWait(true, false, conn) ||
1776  pqReadData(conn) < 0)
1777  return -2;
1778  continue;
1779  }
1780 
1781  /*
1782  * Drop zero-length messages (shouldn't happen anyway). Otherwise
1783  * pass the data back to the caller.
1784  */
1785  msgLength -= 4;
1786  if (msgLength > 0)
1787  {
1788  *buffer = (char *) malloc(msgLength + 1);
1789  if (*buffer == NULL)
1790  {
1791  libpq_append_conn_error(conn, "out of memory");
1792  return -2;
1793  }
1794  memcpy(*buffer, &conn->inBuffer[conn->inCursor], msgLength);
1795  (*buffer)[msgLength] = '\0'; /* Add terminating null */
1796 
1797  /* Mark message consumed */
1798  conn->inStart = conn->inCursor + msgLength;
1799 
1800  return msgLength;
1801  }
1802 
1803  /* Empty, so drop it and loop around for another */
1804  conn->inStart = conn->inCursor;
1805  }
1806 }
1807 
1808 /*
1809  * PQgetline - gets a newline-terminated string from the backend.
1810  *
1811  * See fe-exec.c for documentation.
1812  */
1813 int
1814 pqGetline3(PGconn *conn, char *s, int maxlen)
1815 {
1816  int status;
1817 
1818  if (conn->sock == PGINVALID_SOCKET ||
1822  {
1823  libpq_append_conn_error(conn, "PQgetline: not doing text COPY OUT");
1824  *s = '\0';
1825  return EOF;
1826  }
1827 
1828  while ((status = PQgetlineAsync(conn, s, maxlen - 1)) == 0)
1829  {
1830  /* need to load more data */
1831  if (pqWait(true, false, conn) ||
1832  pqReadData(conn) < 0)
1833  {
1834  *s = '\0';
1835  return EOF;
1836  }
1837  }
1838 
1839  if (status < 0)
1840  {
1841  /* End of copy detected; gin up old-style terminator */
1842  strcpy(s, "\\.");
1843  return 0;
1844  }
1845 
1846  /* Add null terminator, and strip trailing \n if present */
1847  if (s[status - 1] == '\n')
1848  {
1849  s[status - 1] = '\0';
1850  return 0;
1851  }
1852  else
1853  {
1854  s[status] = '\0';
1855  return 1;
1856  }
1857 }
1858 
1859 /*
1860  * PQgetlineAsync - gets a COPY data row without blocking.
1861  *
1862  * See fe-exec.c for documentation.
1863  */
1864 int
1865 pqGetlineAsync3(PGconn *conn, char *buffer, int bufsize)
1866 {
1867  int msgLength;
1868  int avail;
1869 
1872  return -1; /* we are not doing a copy... */
1873 
1874  /*
1875  * Recognize the next input message. To make life simpler for async
1876  * callers, we keep returning 0 until the next message is fully available
1877  * even if it is not Copy Data. This should keep PQendcopy from blocking.
1878  * (Note: unlike pqGetCopyData3, we do not change asyncStatus here.)
1879  */
1880  msgLength = getCopyDataMessage(conn);
1881  if (msgLength < 0)
1882  return -1; /* end-of-copy or error */
1883  if (msgLength == 0)
1884  return 0; /* no data yet */
1885 
1886  /*
1887  * Move data from libpq's buffer to the caller's. In the case where a
1888  * prior call found the caller's buffer too small, we use
1889  * conn->copy_already_done to remember how much of the row was already
1890  * returned to the caller.
1891  */
1893  avail = msgLength - 4 - conn->copy_already_done;
1894  if (avail <= bufsize)
1895  {
1896  /* Able to consume the whole message */
1897  memcpy(buffer, &conn->inBuffer[conn->inCursor], avail);
1898  /* Mark message consumed */
1899  conn->inStart = conn->inCursor + avail;
1900  /* Reset state for next time */
1901  conn->copy_already_done = 0;
1902  return avail;
1903  }
1904  else
1905  {
1906  /* We must return a partial message */
1907  memcpy(buffer, &conn->inBuffer[conn->inCursor], bufsize);
1908  /* The message is NOT consumed from libpq's buffer */
1910  return bufsize;
1911  }
1912 }
1913 
1914 /*
1915  * PQendcopy
1916  *
1917  * See fe-exec.c for documentation.
1918  */
1919 int
1921 {
1922  PGresult *result;
1923 
1924  if (conn->asyncStatus != PGASYNC_COPY_IN &&
1927  {
1928  libpq_append_conn_error(conn, "no COPY in progress");
1929  return 1;
1930  }
1931 
1932  /* Send the CopyDone message if needed */
1933  if (conn->asyncStatus == PGASYNC_COPY_IN ||
1935  {
1936  if (pqPutMsgStart(PqMsg_CopyDone, conn) < 0 ||
1937  pqPutMsgEnd(conn) < 0)
1938  return 1;
1939 
1940  /*
1941  * If we sent the COPY command in extended-query mode, we must issue a
1942  * Sync as well.
1943  */
1944  if (conn->cmd_queue_head &&
1946  {
1947  if (pqPutMsgStart(PqMsg_Sync, conn) < 0 ||
1948  pqPutMsgEnd(conn) < 0)
1949  return 1;
1950  }
1951  }
1952 
1953  /*
1954  * make sure no data is waiting to be sent, abort if we are non-blocking
1955  * and the flush fails
1956  */
1957  if (pqFlush(conn) && pqIsnonblocking(conn))
1958  return 1;
1959 
1960  /* Return to active duty */
1962 
1963  /*
1964  * Non blocking connections may have to abort at this point. If everyone
1965  * played the game there should be no problem, but in error scenarios the
1966  * expected messages may not have arrived yet. (We are assuming that the
1967  * backend's packetizing will ensure that CommandComplete arrives along
1968  * with the CopyDone; are there corner cases where that doesn't happen?)
1969  */
1970  if (pqIsnonblocking(conn) && PQisBusy(conn))
1971  return 1;
1972 
1973  /* Wait for the completion response */
1974  result = PQgetResult(conn);
1975 
1976  /* Expecting a successful result */
1977  if (result && result->resultStatus == PGRES_COMMAND_OK)
1978  {
1979  PQclear(result);
1980  return 0;
1981  }
1982 
1983  /*
1984  * Trouble. For backwards-compatibility reasons, we issue the error
1985  * message as if it were a notice (would be nice to get rid of this
1986  * silliness, but too many apps probably don't handle errors from
1987  * PQendcopy reasonably). Note that the app can still obtain the error
1988  * status from the PGconn object.
1989  */
1990  if (conn->errorMessage.len > 0)
1991  {
1992  /* We have to strip the trailing newline ... pain in neck... */
1993  char svLast = conn->errorMessage.data[conn->errorMessage.len - 1];
1994 
1995  if (svLast == '\n')
1996  conn->errorMessage.data[conn->errorMessage.len - 1] = '\0';
1998  conn->errorMessage.data[conn->errorMessage.len - 1] = svLast;
1999  }
2000 
2001  PQclear(result);
2002 
2003  return 1;
2004 }
2005 
2006 
2007 /*
2008  * PQfn - Send a function call to the POSTGRES backend.
2009  *
2010  * See fe-exec.c for documentation.
2011  */
2012 PGresult *
2014  int *result_buf, int *actual_result_len,
2015  int result_is_int,
2016  const PQArgBlock *args, int nargs)
2017 {
2018  bool needInput = false;
2020  char id;
2021  int msgLength;
2022  int avail;
2023  int i;
2024 
2025  /* already validated by PQfn */
2027 
2028  /* PQfn already validated connection state */
2029 
2031  pqPutInt(fnid, 4, conn) < 0 || /* function id */
2032  pqPutInt(1, 2, conn) < 0 || /* # of format codes */
2033  pqPutInt(1, 2, conn) < 0 || /* format code: BINARY */
2034  pqPutInt(nargs, 2, conn) < 0) /* # of args */
2035  {
2036  /* error message should be set up already */
2037  return NULL;
2038  }
2039 
2040  for (i = 0; i < nargs; ++i)
2041  { /* len.int4 + contents */
2042  if (pqPutInt(args[i].len, 4, conn))
2043  return NULL;
2044  if (args[i].len == -1)
2045  continue; /* it's NULL */
2046 
2047  if (args[i].isint)
2048  {
2049  if (pqPutInt(args[i].u.integer, args[i].len, conn))
2050  return NULL;
2051  }
2052  else
2053  {
2054  if (pqPutnchar((char *) args[i].u.ptr, args[i].len, conn))
2055  return NULL;
2056  }
2057  }
2058 
2059  if (pqPutInt(1, 2, conn) < 0) /* result format code: BINARY */
2060  return NULL;
2061 
2062  if (pqPutMsgEnd(conn) < 0 ||
2063  pqFlush(conn))
2064  return NULL;
2065 
2066  for (;;)
2067  {
2068  if (needInput)
2069  {
2070  /* Wait for some data to arrive (or for the channel to close) */
2071  if (pqWait(true, false, conn) ||
2072  pqReadData(conn) < 0)
2073  break;
2074  }
2075 
2076  /*
2077  * Scan the message. If we run out of data, loop around to try again.
2078  */
2079  needInput = true;
2080 
2081  conn->inCursor = conn->inStart;
2082  if (pqGetc(&id, conn))
2083  continue;
2084  if (pqGetInt(&msgLength, 4, conn))
2085  continue;
2086 
2087  /*
2088  * Try to validate message type/length here. A length less than 4 is
2089  * definitely broken. Large lengths should only be believed for a few
2090  * message types.
2091  */
2092  if (msgLength < 4)
2093  {
2094  handleSyncLoss(conn, id, msgLength);
2095  break;
2096  }
2097  if (msgLength > 30000 && !VALID_LONG_MESSAGE_TYPE(id))
2098  {
2099  handleSyncLoss(conn, id, msgLength);
2100  break;
2101  }
2102 
2103  /*
2104  * Can't process if message body isn't all here yet.
2105  */
2106  msgLength -= 4;
2107  avail = conn->inEnd - conn->inCursor;
2108  if (avail < msgLength)
2109  {
2110  /*
2111  * Before looping, enlarge the input buffer if needed to hold the
2112  * whole message. See notes in parseInput.
2113  */
2114  if (pqCheckInBufferSpace(conn->inCursor + (size_t) msgLength,
2115  conn))
2116  {
2117  /*
2118  * XXX add some better recovery code... plan is to skip over
2119  * the message using its length, then report an error. For the
2120  * moment, just treat this like loss of sync (which indeed it
2121  * might be!)
2122  */
2123  handleSyncLoss(conn, id, msgLength);
2124  break;
2125  }
2126  continue;
2127  }
2128 
2129  /*
2130  * We should see V or E response to the command, but might get N
2131  * and/or A notices first. We also need to swallow the final Z before
2132  * returning.
2133  */
2134  switch (id)
2135  {
2136  case 'V': /* function result */
2137  if (pqGetInt(actual_result_len, 4, conn))
2138  continue;
2139  if (*actual_result_len != -1)
2140  {
2141  if (result_is_int)
2142  {
2143  if (pqGetInt(result_buf, *actual_result_len, conn))
2144  continue;
2145  }
2146  else
2147  {
2148  if (pqGetnchar((char *) result_buf,
2149  *actual_result_len,
2150  conn))
2151  continue;
2152  }
2153  }
2154  /* correctly finished function result message */
2155  status = PGRES_COMMAND_OK;
2156  break;
2157  case 'E': /* error return */
2158  if (pqGetErrorNotice3(conn, true))
2159  continue;
2160  status = PGRES_FATAL_ERROR;
2161  break;
2162  case 'A': /* notify message */
2163  /* handle notify and go back to processing return values */
2164  if (getNotify(conn))
2165  continue;
2166  break;
2167  case 'N': /* notice */
2168  /* handle notice and go back to processing return values */
2169  if (pqGetErrorNotice3(conn, false))
2170  continue;
2171  break;
2172  case 'Z': /* backend is ready for new query */
2173  if (getReadyForQuery(conn))
2174  continue;
2175  /* consume the message and exit */
2176  conn->inStart += 5 + msgLength;
2177 
2178  /*
2179  * If we already have a result object (probably an error), use
2180  * that. Otherwise, if we saw a function result message,
2181  * report COMMAND_OK. Otherwise, the backend violated the
2182  * protocol, so complain.
2183  */
2184  if (!pgHavePendingResult(conn))
2185  {
2186  if (status == PGRES_COMMAND_OK)
2187  {
2188  conn->result = PQmakeEmptyPGresult(conn, status);
2189  if (!conn->result)
2190  {
2191  libpq_append_conn_error(conn, "out of memory");
2193  }
2194  }
2195  else
2196  {
2197  libpq_append_conn_error(conn, "protocol error: no function result");
2199  }
2200  }
2201  return pqPrepareAsyncResult(conn);
2202  case 'S': /* parameter status */
2203  if (getParameterStatus(conn))
2204  continue;
2205  break;
2206  default:
2207  /* The backend violates the protocol. */
2208  libpq_append_conn_error(conn, "protocol error: id=0x%x", id);
2210  /* trust the specified message length as what to skip */
2211  conn->inStart += 5 + msgLength;
2212  return pqPrepareAsyncResult(conn);
2213  }
2214 
2215  /* trace server-to-client message */
2216  if (conn->Pfdebug)
2218 
2219  /* Completed this message, keep going */
2220  /* trust the specified message length as what to skip */
2221  conn->inStart += 5 + msgLength;
2222  needInput = false;
2223  }
2224 
2225  /*
2226  * We fall out of the loop only upon failing to read data.
2227  * conn->errorMessage has been set by pqWait or pqReadData. We want to
2228  * append it to any already-received error message.
2229  */
2231  return pqPrepareAsyncResult(conn);
2232 }
2233 
2234 
2235 /*
2236  * Construct startup packet
2237  *
2238  * Returns a malloc'd packet buffer, or NULL if out of memory
2239  */
2240 char *
2243 {
2244  char *startpacket;
2245 
2246  *packetlen = build_startup_packet(conn, NULL, options);
2247  startpacket = (char *) malloc(*packetlen);
2248  if (!startpacket)
2249  return NULL;
2250  *packetlen = build_startup_packet(conn, startpacket, options);
2251  return startpacket;
2252 }
2253 
2254 /*
2255  * Build a startup packet given a filled-in PGconn structure.
2256  *
2257  * We need to figure out how much space is needed, then fill it in.
2258  * To avoid duplicate logic, this routine is called twice: the first time
2259  * (with packet == NULL) just counts the space needed, the second time
2260  * (with packet == allocated space) fills it in. Return value is the number
2261  * of bytes used.
2262  */
2263 static int
2264 build_startup_packet(const PGconn *conn, char *packet,
2266 {
2267  int packet_len = 0;
2268  const PQEnvironmentOption *next_eo;
2269  const char *val;
2270 
2271  /* Protocol version comes first. */
2272  if (packet)
2273  {
2275 
2276  memcpy(packet + packet_len, &pv, sizeof(ProtocolVersion));
2277  }
2278  packet_len += sizeof(ProtocolVersion);
2279 
2280  /* Add user name, database name, options */
2281 
2282 #define ADD_STARTUP_OPTION(optname, optval) \
2283  do { \
2284  if (packet) \
2285  strcpy(packet + packet_len, optname); \
2286  packet_len += strlen(optname) + 1; \
2287  if (packet) \
2288  strcpy(packet + packet_len, optval); \
2289  packet_len += strlen(optval) + 1; \
2290  } while(0)
2291 
2292  if (conn->pguser && conn->pguser[0])
2293  ADD_STARTUP_OPTION("user", conn->pguser);
2294  if (conn->dbName && conn->dbName[0])
2295  ADD_STARTUP_OPTION("database", conn->dbName);
2296  if (conn->replication && conn->replication[0])
2297  ADD_STARTUP_OPTION("replication", conn->replication);
2298  if (conn->pgoptions && conn->pgoptions[0])
2299  ADD_STARTUP_OPTION("options", conn->pgoptions);
2300  if (conn->send_appname)
2301  {
2302  /* Use appname if present, otherwise use fallback */
2304  if (val && val[0])
2305  ADD_STARTUP_OPTION("application_name", val);
2306  }
2307 
2309  ADD_STARTUP_OPTION("client_encoding", conn->client_encoding_initial);
2310 
2311  /* Add any environment-driven GUC settings needed */
2312  for (next_eo = options; next_eo->envName; next_eo++)
2313  {
2314  if ((val = getenv(next_eo->envName)) != NULL)
2315  {
2316  if (pg_strcasecmp(val, "default") != 0)
2317  ADD_STARTUP_OPTION(next_eo->pgName, val);
2318  }
2319  }
2320 
2321  /* Add trailing terminator */
2322  if (packet)
2323  packet[packet_len] = '\0';
2324  packet_len++;
2325 
2326  return packet_len;
2327 }
signed short int16
Definition: c.h:482
#define MemSet(start, val, len)
Definition: c.h:1009
int errmsg(const char *fmt,...)
Definition: elog.c:1069
void pqDropConnection(PGconn *conn, bool flushInput)
Definition: fe-connect.c:467
void pqSaveMessageField(PGresult *res, char code, const char *value)
Definition: fe-exec.c:1055
void pqSetResultError(PGresult *res, PQExpBuffer errorMessage, int offset)
Definition: fe-exec.c:689
void pqSaveErrorResult(PGconn *conn)
Definition: fe-exec.c:800
char * pqResultStrdup(PGresult *res, const char *str)
Definition: fe-exec.c:672
int pqRowProcessor(PGconn *conn, const char **errmsgp)
Definition: fe-exec.c:1206
int PQgetlineAsync(PGconn *conn, char *buffer, int bufsize)
Definition: fe-exec.c:2867
void pqInternalNotice(const PGNoticeHooks *hooks, const char *fmt,...)
Definition: fe-exec.c:933
PGresult * PQmakeEmptyPGresult(PGconn *conn, ExecStatusType status)
Definition: fe-exec.c:157
void pqSaveParameterStatus(PGconn *conn, const char *name, const char *value)
Definition: fe-exec.c:1076
void pqClearAsyncResult(PGconn *conn)
Definition: fe-exec.c:776
int PQisBusy(PGconn *conn)
Definition: fe-exec.c:2004
void * pqResultAlloc(PGresult *res, size_t nBytes, bool isBinary)
Definition: fe-exec.c:560
char * PQresultErrorField(const PGresult *res, int fieldcode)
Definition: fe-exec.c:3380
PGresult * PQgetResult(PGconn *conn)
Definition: fe-exec.c:2035
PGresult * pqPrepareAsyncResult(PGconn *conn)
Definition: fe-exec.c:846
void pqCommandQueueAdvance(PGconn *conn)
Definition: fe-exec.c:3095
int pqReadData(PGconn *conn)
Definition: fe-misc.c:566
int pqPutInt(int value, size_t bytes, PGconn *conn)
Definition: fe-misc.c:254
int pqFlush(PGconn *conn)
Definition: fe-misc.c:954
int pqPutMsgStart(char msg_type, PGconn *conn)
Definition: fe-misc.c:459
int pqSkipnchar(size_t len, PGconn *conn)
Definition: fe-misc.c:188
int pqGetc(char *result, PGconn *conn)
Definition: fe-misc.c:78
int pqGetInt(int *result, size_t bytes, PGconn *conn)
Definition: fe-misc.c:217
int pqGetnchar(char *s, size_t len, PGconn *conn)
Definition: fe-misc.c:166
int pqWait(int forRead, int forWrite, PGconn *conn)
Definition: fe-misc.c:979
int pqGets(PQExpBuffer buf, PGconn *conn)
Definition: fe-misc.c:137
int pqCheckInBufferSpace(size_t bytes_needed, PGconn *conn)
Definition: fe-misc.c:352
int pqPutnchar(const char *s, size_t len, PGconn *conn)
Definition: fe-misc.c:203
int PQmblenBounded(const char *s, int encoding)
Definition: fe-misc.c:1187
void libpq_append_conn_error(PGconn *conn, const char *fmt,...)
Definition: fe-misc.c:1312
int pqPutMsgEnd(PGconn *conn)
Definition: fe-misc.c:518
#define DISPLAY_SIZE
void pqBuildErrorMessage3(PQExpBuffer msg, const PGresult *res, PGVerbosity verbosity, PGContextVisibility show_context)
void pqParseInput3(PGconn *conn)
Definition: fe-protocol3.c:66
static int build_startup_packet(const PGconn *conn, char *packet, const PQEnvironmentOption *options)
int pqEndcopy3(PGconn *conn)
static int getNotify(PGconn *conn)
PGresult * pqFunctionCall3(PGconn *conn, Oid fnid, int *result_buf, int *actual_result_len, int result_is_int, const PQArgBlock *args, int nargs)
static int getAnotherTuple(PGconn *conn, int msgLength)
Definition: fe-protocol3.c:766
static int getRowDescriptions(PGconn *conn, int msgLength)
Definition: fe-protocol3.c:507
static void reportErrorPosition(PQExpBuffer msg, const char *query, int loc, int encoding)
#define MIN_RIGHT_CUT
int pqGetlineAsync3(PGconn *conn, char *buffer, int bufsize)
int pqGetCopyData3(PGconn *conn, char **buffer, int async)
int pqGetNegotiateProtocolVersion3(PGconn *conn)
static int getParameterStatus(PGconn *conn)
#define VALID_LONG_MESSAGE_TYPE(id)
Definition: fe-protocol3.c:36
static int getCopyStart(PGconn *conn, ExecStatusType copytype)
static void handleSyncLoss(PGconn *conn, char id, int msgLength)
Definition: fe-protocol3.c:487
static int getReadyForQuery(PGconn *conn)
#define ADD_STARTUP_OPTION(optname, optval)
static int getCopyDataMessage(PGconn *conn)
static int getParamDescriptions(PGconn *conn, int msgLength)
Definition: fe-protocol3.c:678
int pqGetline3(PGconn *conn, char *s, int maxlen)
int pqGetErrorNotice3(PGconn *conn, bool isError)
Definition: fe-protocol3.c:886
char * pqBuildStartupPacket3(PGconn *conn, int *packetlen, const PQEnvironmentOption *options)
void pqTraceOutputMessage(PGconn *conn, const char *message, bool toServer)
Definition: fe-trace.c:529
#define realloc(a, b)
Definition: header.h:60
#define free(a)
Definition: header.h:65
#define malloc(a)
Definition: header.h:50
#define bufsize
Definition: indent_globs.h:36
long val
Definition: informix.c:664
int i
Definition: isn.c:73
@ CONNECTION_BAD
Definition: libpq-fe.h:61
ExecStatusType
Definition: libpq-fe.h:95
@ PGRES_COPY_IN
Definition: libpq-fe.h:104
@ PGRES_COPY_BOTH
Definition: libpq-fe.h:109
@ PGRES_COMMAND_OK
Definition: libpq-fe.h:97
@ PGRES_FATAL_ERROR
Definition: libpq-fe.h:108
@ PGRES_COPY_OUT
Definition: libpq-fe.h:103
@ PGRES_EMPTY_QUERY
Definition: libpq-fe.h:96
@ PGRES_PIPELINE_SYNC
Definition: libpq-fe.h:111
@ PGRES_NONFATAL_ERROR
Definition: libpq-fe.h:107
@ PGRES_TUPLES_OK
Definition: libpq-fe.h:100
PGContextVisibility
Definition: libpq-fe.h:134
@ PQSHOW_CONTEXT_ALWAYS
Definition: libpq-fe.h:137
@ PQSHOW_CONTEXT_ERRORS
Definition: libpq-fe.h:136
@ PQTRANS_INTRANS
Definition: libpq-fe.h:120
@ PQTRANS_IDLE
Definition: libpq-fe.h:118
@ PQTRANS_UNKNOWN
Definition: libpq-fe.h:122
@ PQTRANS_INERROR
Definition: libpq-fe.h:121
@ PQ_PIPELINE_OFF
Definition: libpq-fe.h:158
@ PQ_PIPELINE_ABORTED
Definition: libpq-fe.h:160
@ PQ_PIPELINE_ON
Definition: libpq-fe.h:159
PGVerbosity
Definition: libpq-fe.h:126
@ PQERRORS_VERBOSE
Definition: libpq-fe.h:129
@ PQERRORS_TERSE
Definition: libpq-fe.h:127
@ PQERRORS_SQLSTATE
Definition: libpq-fe.h:130
@ PGASYNC_COPY_OUT
Definition: libpq-int.h:229
@ PGASYNC_READY
Definition: libpq-int.h:223
@ PGASYNC_COPY_BOTH
Definition: libpq-int.h:230
@ PGASYNC_IDLE
Definition: libpq-int.h:221
@ PGASYNC_COPY_IN
Definition: libpq-int.h:228
@ PGASYNC_BUSY
Definition: libpq-int.h:222
#define libpq_gettext(x)
Definition: libpq-int.h:900
@ PGQUERY_SIMPLE
Definition: libpq-int.h:320
@ PGQUERY_DESCRIBE
Definition: libpq-int.h:323
@ PGQUERY_CLOSE
Definition: libpq-int.h:325
@ PGQUERY_PREPARE
Definition: libpq-int.h:322
#define CMDSTATUS_LEN
Definition: libpq-int.h:89
#define libpq_ngettext(s, p, n)
Definition: libpq-int.h:901
#define pqIsnonblocking(conn)
Definition: libpq-int.h:889
#define pgHavePendingResult(conn)
Definition: libpq-int.h:882
Assert(fmt[strlen(fmt) - 1] !='\n')
static char format
#define pg_hton32(x)
Definition: pg_bswap.h:121
const void size_t len
int32 encoding
Definition: pg_database.h:41
static char * buf
Definition: pg_test_fsync.c:67
int pg_strcasecmp(const char *s1, const char *s2)
Definition: pgstrcasecmp.c:36
#define PGINVALID_SOCKET
Definition: port.h:31
size_t strlcpy(char *dst, const char *src, size_t siz)
Definition: strlcpy.c:45
#define PG_DIAG_INTERNAL_QUERY
Definition: postgres_ext.h:62
#define PG_DIAG_SCHEMA_NAME
Definition: postgres_ext.h:64
#define PG_DIAG_CONSTRAINT_NAME
Definition: postgres_ext.h:68
#define PG_DIAG_DATATYPE_NAME
Definition: postgres_ext.h:67
unsigned int Oid
Definition: postgres_ext.h:31
#define PG_DIAG_SOURCE_LINE
Definition: postgres_ext.h:70
#define PG_DIAG_STATEMENT_POSITION
Definition: postgres_ext.h:60
#define PG_DIAG_SOURCE_FILE
Definition: postgres_ext.h:69
#define PG_DIAG_MESSAGE_HINT
Definition: postgres_ext.h:59
#define PG_DIAG_SQLSTATE
Definition: postgres_ext.h:56
#define PG_DIAG_TABLE_NAME
Definition: postgres_ext.h:65
#define PG_DIAG_MESSAGE_PRIMARY
Definition: postgres_ext.h:57
#define PG_DIAG_COLUMN_NAME
Definition: postgres_ext.h:66
#define PG_DIAG_MESSAGE_DETAIL
Definition: postgres_ext.h:58
#define PG_DIAG_CONTEXT
Definition: postgres_ext.h:63
#define PG_DIAG_SEVERITY
Definition: postgres_ext.h:54
#define PG_DIAG_SOURCE_FUNCTION
Definition: postgres_ext.h:71
#define PG_DIAG_INTERNAL_POSITION
Definition: postgres_ext.h:61
#define PG_PROTOCOL_MAJOR(v)
Definition: pqcomm.h:87
uint32 ProtocolVersion
Definition: pqcomm.h:99
#define PG_PROTOCOL_MINOR(v)
Definition: pqcomm.h:88
void initPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:90
void resetPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:146
void appendPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:265
void appendPQExpBufferChar(PQExpBuffer str, char ch)
Definition: pqexpbuffer.c:378
void appendPQExpBufferStr(PQExpBuffer str, const char *data)
Definition: pqexpbuffer.c:367
void termPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:129
#define PQExpBufferDataBroken(buf)
Definition: pqexpbuffer.h:67
#define PqMsg_CloseComplete
Definition: protocol.h:40
#define PqMsg_CopyDone
Definition: protocol.h:64
#define PqMsg_NotificationResponse
Definition: protocol.h:41
#define PqMsg_BindComplete
Definition: protocol.h:39
#define PqMsg_CopyData
Definition: protocol.h:65
#define PqMsg_ParameterDescription
Definition: protocol.h:58
#define PqMsg_FunctionCall
Definition: protocol.h:23
#define PqMsg_ReadyForQuery
Definition: protocol.h:55
#define PqMsg_CopyInResponse
Definition: protocol.h:45
#define PqMsg_EmptyQueryResponse
Definition: protocol.h:47
#define PqMsg_RowDescription
Definition: protocol.h:52
#define PqMsg_CopyBothResponse
Definition: protocol.h:54
#define PqMsg_ParameterStatus
Definition: protocol.h:51
#define PqMsg_NoData
Definition: protocol.h:56
#define PqMsg_Sync
Definition: protocol.h:27
#define PqMsg_BackendKeyData
Definition: protocol.h:48
#define PqMsg_CommandComplete
Definition: protocol.h:42
#define PqMsg_ErrorResponse
Definition: protocol.h:44
#define PqMsg_DataRow
Definition: protocol.h:43
#define PqMsg_NoticeResponse
Definition: protocol.h:49
#define PqMsg_CopyOutResponse
Definition: protocol.h:46
#define PqMsg_ParseComplete
Definition: protocol.h:38
PGconn * conn
Definition: streamutil.c:54
PQnoticeReceiver noticeRec
Definition: libpq-int.h:155
void * noticeRecArg
Definition: libpq-int.h:156
PGQueryClass queryclass
Definition: libpq-int.h:333
const char * pgName
Definition: libpq-int.h:265
const char * envName
Definition: libpq-int.h:264
const char * value
Definition: libpq-int.h:303
struct pgNotify * next
Definition: libpq-fe.h:193
int be_pid
Definition: libpq-fe.h:190
char * relname
Definition: libpq-fe.h:189
char * extra
Definition: libpq-fe.h:191
char * replication
Definition: libpq-int.h:378
PGnotify * notifyHead
Definition: libpq-int.h:436
PGdataValue * rowBuf
Definition: libpq-int.h:525
pgsocket sock
Definition: libpq-int.h:459
char * inBuffer
Definition: libpq-int.h:508
ProtocolVersion pversion
Definition: libpq-int.h:463
char * pgoptions
Definition: libpq-int.h:374
bool send_appname
Definition: libpq-int.h:491
PGTransactionStatusType xactStatus
Definition: libpq-int.h:427
int inCursor
Definition: libpq-int.h:511
int be_pid
Definition: libpq-int.h:494
char * dbName
Definition: libpq-int.h:377
int inEnd
Definition: libpq-int.h:512
char * fbappname
Definition: libpq-int.h:376
int be_key
Definition: libpq-int.h:495
PGnotify * notifyTail
Definition: libpq-int.h:437
int copy_already_done
Definition: libpq-int.h:435
PQExpBufferData workBuffer
Definition: libpq-int.h:621
int inStart
Definition: libpq-int.h:510
char * pguser
Definition: libpq-int.h:379
PGresult * result
Definition: libpq-int.h:537
PGVerbosity verbosity
Definition: libpq-int.h:501
char * client_encoding_initial
Definition: libpq-int.h:373
char * appname
Definition: libpq-int.h:375
PQExpBufferData errorMessage
Definition: libpq-int.h:617
bool error_result
Definition: libpq-int.h:538
int rowBufLen
Definition: libpq-int.h:526
char last_sqlstate[6]
Definition: libpq-int.h:428
PGAsyncStatusType asyncStatus
Definition: libpq-int.h:426
PGpipelineStatus pipelineStatus
Definition: libpq-int.h:432
char copy_is_binary
Definition: libpq-int.h:434
PGNoticeHooks noticeHooks
Definition: libpq-int.h:417
FILE * Pfdebug
Definition: libpq-int.h:413
PGcmdQueueEntry * cmd_queue_head
Definition: libpq-int.h:449
PGContextVisibility show_context
Definition: libpq-int.h:502
ConnStatusType status
Definition: libpq-int.h:425
int binary
Definition: libpq-int.h:182
PGNoticeHooks noticeHooks
Definition: libpq-int.h:189
char * errMsg
Definition: libpq-int.h:199
int numParameters
Definition: libpq-int.h:178
PGresAttDesc * attDescs
Definition: libpq-int.h:174
int numAttributes
Definition: libpq-int.h:173
char cmdStatus[CMDSTATUS_LEN]
Definition: libpq-int.h:181
PGMessageField * errFields
Definition: libpq-int.h:200
PGresParamDesc * paramDescs
Definition: libpq-int.h:179
ExecStatusType resultStatus
Definition: libpq-int.h:180
char * errQuery
Definition: libpq-int.h:201
int client_encoding
Definition: libpq-int.h:192
char * name
Definition: libpq-fe.h:263
int columnid
Definition: libpq-fe.h:265
int atttypmod
Definition: libpq-fe.h:269
int pg_encoding_dsplen(int encoding, const char *mbstr)
Definition: wchar.c:2151
int pg_encoding_max_length(int encoding)
Definition: wchar.c:2188