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