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