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