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