PostgreSQL Source Code  git master
fe-exec.c
Go to the documentation of this file.
1 /*-------------------------------------------------------------------------
2  *
3  * fe-exec.c
4  * functions related to sending a query down to the backend
5  *
6  * Portions Copyright (c) 1996-2022, PostgreSQL Global Development Group
7  * Portions Copyright (c) 1994, Regents of the University of California
8  *
9  *
10  * IDENTIFICATION
11  * src/interfaces/libpq/fe-exec.c
12  *
13  *-------------------------------------------------------------------------
14  */
15 #include "postgres_fe.h"
16 
17 #include <ctype.h>
18 #include <fcntl.h>
19 #include <limits.h>
20 
21 #ifdef WIN32
22 #include "win32.h"
23 #else
24 #include <unistd.h>
25 #endif
26 
27 #include "libpq-fe.h"
28 #include "libpq-int.h"
29 #include "mb/pg_wchar.h"
30 
31 /* keep this in same order as ExecStatusType in libpq-fe.h */
32 char *const pgresStatus[] = {
33  "PGRES_EMPTY_QUERY",
34  "PGRES_COMMAND_OK",
35  "PGRES_TUPLES_OK",
36  "PGRES_COPY_OUT",
37  "PGRES_COPY_IN",
38  "PGRES_BAD_RESPONSE",
39  "PGRES_NONFATAL_ERROR",
40  "PGRES_FATAL_ERROR",
41  "PGRES_COPY_BOTH",
42  "PGRES_SINGLE_TUPLE",
43  "PGRES_PIPELINE_SYNC",
44  "PGRES_PIPELINE_ABORTED"
45 };
46 
47 /* We return this if we're unable to make a PGresult at all */
48 static const PGresult OOM_result = {
50  .client_encoding = PG_SQL_ASCII,
51  .errMsg = "out of memory\n",
52 };
53 
54 /*
55  * static state needed by PQescapeString and PQescapeBytea; initialize to
56  * values that result in backward-compatible behavior
57  */
59 static bool static_std_strings = false;
60 
61 
62 static PGEvent *dupEvents(PGEvent *events, int count, size_t *memSize);
63 static bool pqAddTuple(PGresult *res, PGresAttValue *tup,
64  const char **errmsgp);
65 static int PQsendQueryInternal(PGconn *conn, const char *query, bool newQuery);
66 static bool PQsendQueryStart(PGconn *conn, bool newQuery);
67 static int PQsendQueryGuts(PGconn *conn,
68  const char *command,
69  const char *stmtName,
70  int nParams,
71  const Oid *paramTypes,
72  const char *const *paramValues,
73  const int *paramLengths,
74  const int *paramFormats,
75  int resultFormat);
76 static void parseInput(PGconn *conn);
77 static PGresult *getCopyResult(PGconn *conn, ExecStatusType copytype);
78 static bool PQexecStart(PGconn *conn);
80 static int PQsendDescribe(PGconn *conn, char desc_type,
81  const char *desc_target);
82 static int check_field_number(const PGresult *res, int field_num);
83 static void pqPipelineProcessQueue(PGconn *conn);
84 static int pqPipelineFlush(PGconn *conn);
85 
86 
87 /* ----------------
88  * Space management for PGresult.
89  *
90  * Formerly, libpq did a separate malloc() for each field of each tuple
91  * returned by a query. This was remarkably expensive --- malloc/free
92  * consumed a sizable part of the application's runtime. And there is
93  * no real need to keep track of the fields separately, since they will
94  * all be freed together when the PGresult is released. So now, we grab
95  * large blocks of storage from malloc and allocate space for query data
96  * within these blocks, using a trivially simple allocator. This reduces
97  * the number of malloc/free calls dramatically, and it also avoids
98  * fragmentation of the malloc storage arena.
99  * The PGresult structure itself is still malloc'd separately. We could
100  * combine it with the first allocation block, but that would waste space
101  * for the common case that no extra storage is actually needed (that is,
102  * the SQL command did not return tuples).
103  *
104  * We also malloc the top-level array of tuple pointers separately, because
105  * we need to be able to enlarge it via realloc, and our trivial space
106  * allocator doesn't handle that effectively. (Too bad the FE/BE protocol
107  * doesn't tell us up front how many tuples will be returned.)
108  * All other subsidiary storage for a PGresult is kept in PGresult_data blocks
109  * of size PGRESULT_DATA_BLOCKSIZE. The overhead at the start of each block
110  * is just a link to the next one, if any. Free-space management info is
111  * kept in the owning PGresult.
112  * A query returning a small amount of data will thus require three malloc
113  * calls: one for the PGresult, one for the tuples pointer array, and one
114  * PGresult_data block.
115  *
116  * Only the most recently allocated PGresult_data block is a candidate to
117  * have more stuff added to it --- any extra space left over in older blocks
118  * is wasted. We could be smarter and search the whole chain, but the point
119  * here is to be simple and fast. Typical applications do not keep a PGresult
120  * around very long anyway, so some wasted space within one is not a problem.
121  *
122  * Tuning constants for the space allocator are:
123  * PGRESULT_DATA_BLOCKSIZE: size of a standard allocation block, in bytes
124  * PGRESULT_ALIGN_BOUNDARY: assumed alignment requirement for binary data
125  * PGRESULT_SEP_ALLOC_THRESHOLD: objects bigger than this are given separate
126  * blocks, instead of being crammed into a regular allocation block.
127  * Requirements for correct function are:
128  * PGRESULT_ALIGN_BOUNDARY must be a multiple of the alignment requirements
129  * of all machine data types. (Currently this is set from configure
130  * tests, so it should be OK automatically.)
131  * PGRESULT_SEP_ALLOC_THRESHOLD + PGRESULT_BLOCK_OVERHEAD <=
132  * PGRESULT_DATA_BLOCKSIZE
133  * pqResultAlloc assumes an object smaller than the threshold will fit
134  * in a new block.
135  * The amount of space wasted at the end of a block could be as much as
136  * PGRESULT_SEP_ALLOC_THRESHOLD, so it doesn't pay to make that too large.
137  * ----------------
138  */
139 
140 #define PGRESULT_DATA_BLOCKSIZE 2048
141 #define PGRESULT_ALIGN_BOUNDARY MAXIMUM_ALIGNOF /* from configure */
142 #define PGRESULT_BLOCK_OVERHEAD Max(sizeof(PGresult_data), PGRESULT_ALIGN_BOUNDARY)
143 #define PGRESULT_SEP_ALLOC_THRESHOLD (PGRESULT_DATA_BLOCKSIZE / 2)
144 
145 
146 /*
147  * PQmakeEmptyPGresult
148  * returns a newly allocated, initialized PGresult with given status.
149  * If conn is not NULL and status indicates an error, the conn's
150  * errorMessage is copied. Also, any PGEvents are copied from the conn.
151  *
152  * Note: the logic to copy the conn's errorMessage is now vestigial;
153  * no internal caller uses it. However, that behavior is documented for
154  * outside callers, so we'd better keep it.
155  */
156 PGresult *
158 {
159  PGresult *result;
160 
161  result = (PGresult *) malloc(sizeof(PGresult));
162  if (!result)
163  return NULL;
164 
165  result->ntups = 0;
166  result->numAttributes = 0;
167  result->attDescs = NULL;
168  result->tuples = NULL;
169  result->tupArrSize = 0;
170  result->numParameters = 0;
171  result->paramDescs = NULL;
172  result->resultStatus = status;
173  result->cmdStatus[0] = '\0';
174  result->binary = 0;
175  result->events = NULL;
176  result->nEvents = 0;
177  result->errMsg = NULL;
178  result->errFields = NULL;
179  result->errQuery = NULL;
180  result->null_field[0] = '\0';
181  result->curBlock = NULL;
182  result->curOffset = 0;
183  result->spaceLeft = 0;
184  result->memorySize = sizeof(PGresult);
185 
186  if (conn)
187  {
188  /* copy connection data we might need for operations on PGresult */
189  result->noticeHooks = conn->noticeHooks;
191 
192  /* consider copying conn's errorMessage */
193  switch (status)
194  {
195  case PGRES_EMPTY_QUERY:
196  case PGRES_COMMAND_OK:
197  case PGRES_TUPLES_OK:
198  case PGRES_COPY_OUT:
199  case PGRES_COPY_IN:
200  case PGRES_COPY_BOTH:
201  case PGRES_SINGLE_TUPLE:
202  /* non-error cases */
203  break;
204  default:
205  /* we intentionally do not use or modify errorReported here */
206  pqSetResultError(result, &conn->errorMessage, 0);
207  break;
208  }
209 
210  /* copy events last; result must be valid if we need to PQclear */
211  if (conn->nEvents > 0)
212  {
213  result->events = dupEvents(conn->events, conn->nEvents,
214  &result->memorySize);
215  if (!result->events)
216  {
217  PQclear(result);
218  return NULL;
219  }
220  result->nEvents = conn->nEvents;
221  }
222  }
223  else
224  {
225  /* defaults... */
226  result->noticeHooks.noticeRec = NULL;
227  result->noticeHooks.noticeRecArg = NULL;
228  result->noticeHooks.noticeProc = NULL;
229  result->noticeHooks.noticeProcArg = NULL;
230  result->client_encoding = PG_SQL_ASCII;
231  }
232 
233  return result;
234 }
235 
236 /*
237  * PQsetResultAttrs
238  *
239  * Set the attributes for a given result. This function fails if there are
240  * already attributes contained in the provided result. The call is
241  * ignored if numAttributes is zero or attDescs is NULL. If the
242  * function fails, it returns zero. If the function succeeds, it
243  * returns a non-zero value.
244  */
245 int
246 PQsetResultAttrs(PGresult *res, int numAttributes, PGresAttDesc *attDescs)
247 {
248  int i;
249 
250  /* Fail if argument is NULL or OOM_result */
251  if (!res || (const PGresult *) res == &OOM_result)
252  return false;
253 
254  /* If attrs already exist, they cannot be overwritten. */
255  if (res->numAttributes > 0)
256  return false;
257 
258  /* ignore no-op request */
259  if (numAttributes <= 0 || !attDescs)
260  return true;
261 
262  res->attDescs = (PGresAttDesc *)
263  PQresultAlloc(res, numAttributes * sizeof(PGresAttDesc));
264 
265  if (!res->attDescs)
266  return false;
267 
268  res->numAttributes = numAttributes;
269  memcpy(res->attDescs, attDescs, numAttributes * sizeof(PGresAttDesc));
270 
271  /* deep-copy the attribute names, and determine format */
272  res->binary = 1;
273  for (i = 0; i < res->numAttributes; i++)
274  {
275  if (res->attDescs[i].name)
277  else
279 
280  if (!res->attDescs[i].name)
281  return false;
282 
283  if (res->attDescs[i].format == 0)
284  res->binary = 0;
285  }
286 
287  return true;
288 }
289 
290 /*
291  * PQcopyResult
292  *
293  * Returns a deep copy of the provided 'src' PGresult, which cannot be NULL.
294  * The 'flags' argument controls which portions of the result will or will
295  * NOT be copied. The created result is always put into the
296  * PGRES_TUPLES_OK status. The source result error message is not copied,
297  * although cmdStatus is.
298  *
299  * To set custom attributes, use PQsetResultAttrs. That function requires
300  * that there are no attrs contained in the result, so to use that
301  * function you cannot use the PG_COPYRES_ATTRS or PG_COPYRES_TUPLES
302  * options with this function.
303  *
304  * Options:
305  * PG_COPYRES_ATTRS - Copy the source result's attributes
306  *
307  * PG_COPYRES_TUPLES - Copy the source result's tuples. This implies
308  * copying the attrs, seeing how the attrs are needed by the tuples.
309  *
310  * PG_COPYRES_EVENTS - Copy the source result's events.
311  *
312  * PG_COPYRES_NOTICEHOOKS - Copy the source result's notice hooks.
313  */
314 PGresult *
315 PQcopyResult(const PGresult *src, int flags)
316 {
317  PGresult *dest;
318  int i;
319 
320  if (!src)
321  return NULL;
322 
324  if (!dest)
325  return NULL;
326 
327  /* Always copy these over. Is cmdStatus really useful here? */
328  dest->client_encoding = src->client_encoding;
329  strcpy(dest->cmdStatus, src->cmdStatus);
330 
331  /* Wants attrs? */
332  if (flags & (PG_COPYRES_ATTRS | PG_COPYRES_TUPLES))
333  {
334  if (!PQsetResultAttrs(dest, src->numAttributes, src->attDescs))
335  {
336  PQclear(dest);
337  return NULL;
338  }
339  }
340 
341  /* Wants to copy tuples? */
342  if (flags & PG_COPYRES_TUPLES)
343  {
344  int tup,
345  field;
346 
347  for (tup = 0; tup < src->ntups; tup++)
348  {
349  for (field = 0; field < src->numAttributes; field++)
350  {
351  if (!PQsetvalue(dest, tup, field,
352  src->tuples[tup][field].value,
353  src->tuples[tup][field].len))
354  {
355  PQclear(dest);
356  return NULL;
357  }
358  }
359  }
360  }
361 
362  /* Wants to copy notice hooks? */
363  if (flags & PG_COPYRES_NOTICEHOOKS)
364  dest->noticeHooks = src->noticeHooks;
365 
366  /* Wants to copy PGEvents? */
367  if ((flags & PG_COPYRES_EVENTS) && src->nEvents > 0)
368  {
369  dest->events = dupEvents(src->events, src->nEvents,
370  &dest->memorySize);
371  if (!dest->events)
372  {
373  PQclear(dest);
374  return NULL;
375  }
376  dest->nEvents = src->nEvents;
377  }
378 
379  /* Okay, trigger PGEVT_RESULTCOPY event */
380  for (i = 0; i < dest->nEvents; i++)
381  {
382  /* We don't fire events that had some previous failure */
383  if (src->events[i].resultInitialized)
384  {
385  PGEventResultCopy evt;
386 
387  evt.src = src;
388  evt.dest = dest;
389  if (dest->events[i].proc(PGEVT_RESULTCOPY, &evt,
390  dest->events[i].passThrough))
391  dest->events[i].resultInitialized = true;
392  }
393  }
394 
395  return dest;
396 }
397 
398 /*
399  * Copy an array of PGEvents (with no extra space for more).
400  * Does not duplicate the event instance data, sets this to NULL.
401  * Also, the resultInitialized flags are all cleared.
402  * The total space allocated is added to *memSize.
403  */
404 static PGEvent *
405 dupEvents(PGEvent *events, int count, size_t *memSize)
406 {
407  PGEvent *newEvents;
408  size_t msize;
409  int i;
410 
411  if (!events || count <= 0)
412  return NULL;
413 
414  msize = count * sizeof(PGEvent);
415  newEvents = (PGEvent *) malloc(msize);
416  if (!newEvents)
417  return NULL;
418 
419  for (i = 0; i < count; i++)
420  {
421  newEvents[i].proc = events[i].proc;
422  newEvents[i].passThrough = events[i].passThrough;
423  newEvents[i].data = NULL;
424  newEvents[i].resultInitialized = false;
425  newEvents[i].name = strdup(events[i].name);
426  if (!newEvents[i].name)
427  {
428  while (--i >= 0)
429  free(newEvents[i].name);
430  free(newEvents);
431  return NULL;
432  }
433  msize += strlen(events[i].name) + 1;
434  }
435 
436  *memSize += msize;
437  return newEvents;
438 }
439 
440 
441 /*
442  * Sets the value for a tuple field. The tup_num must be less than or
443  * equal to PQntuples(res). If it is equal, a new tuple is created and
444  * added to the result.
445  * Returns a non-zero value for success and zero for failure.
446  * (On failure, we report the specific problem via pqInternalNotice.)
447  */
448 int
449 PQsetvalue(PGresult *res, int tup_num, int field_num, char *value, int len)
450 {
451  PGresAttValue *attval;
452  const char *errmsg = NULL;
453 
454  /* Fail if argument is NULL or OOM_result */
455  if (!res || (const PGresult *) res == &OOM_result)
456  return false;
457 
458  /* Invalid field_num? */
459  if (!check_field_number(res, field_num))
460  return false;
461 
462  /* Invalid tup_num, must be <= ntups */
463  if (tup_num < 0 || tup_num > res->ntups)
464  {
466  "row number %d is out of range 0..%d",
467  tup_num, res->ntups);
468  return false;
469  }
470 
471  /* need to allocate a new tuple? */
472  if (tup_num == res->ntups)
473  {
474  PGresAttValue *tup;
475  int i;
476 
477  tup = (PGresAttValue *)
479  true);
480 
481  if (!tup)
482  goto fail;
483 
484  /* initialize each column to NULL */
485  for (i = 0; i < res->numAttributes; i++)
486  {
487  tup[i].len = NULL_LEN;
488  tup[i].value = res->null_field;
489  }
490 
491  /* add it to the array */
492  if (!pqAddTuple(res, tup, &errmsg))
493  goto fail;
494  }
495 
496  attval = &res->tuples[tup_num][field_num];
497 
498  /* treat either NULL_LEN or NULL value pointer as a NULL field */
499  if (len == NULL_LEN || value == NULL)
500  {
501  attval->len = NULL_LEN;
502  attval->value = res->null_field;
503  }
504  else if (len <= 0)
505  {
506  attval->len = 0;
507  attval->value = res->null_field;
508  }
509  else
510  {
511  attval->value = (char *) pqResultAlloc(res, len + 1, true);
512  if (!attval->value)
513  goto fail;
514  attval->len = len;
515  memcpy(attval->value, value, len);
516  attval->value[len] = '\0';
517  }
518 
519  return true;
520 
521  /*
522  * Report failure via pqInternalNotice. If preceding code didn't provide
523  * an error message, assume "out of memory" was meant.
524  */
525 fail:
526  if (!errmsg)
527  errmsg = libpq_gettext("out of memory");
529 
530  return false;
531 }
532 
533 /*
534  * pqResultAlloc - exported routine to allocate local storage in a PGresult.
535  *
536  * We force all such allocations to be maxaligned, since we don't know
537  * whether the value might be binary.
538  */
539 void *
540 PQresultAlloc(PGresult *res, size_t nBytes)
541 {
542  /* Fail if argument is NULL or OOM_result */
543  if (!res || (const PGresult *) res == &OOM_result)
544  return NULL;
545 
546  return pqResultAlloc(res, nBytes, true);
547 }
548 
549 /*
550  * pqResultAlloc -
551  * Allocate subsidiary storage for a PGresult.
552  *
553  * nBytes is the amount of space needed for the object.
554  * If isBinary is true, we assume that we need to align the object on
555  * a machine allocation boundary.
556  * If isBinary is false, we assume the object is a char string and can
557  * be allocated on any byte boundary.
558  */
559 void *
560 pqResultAlloc(PGresult *res, size_t nBytes, bool isBinary)
561 {
562  char *space;
563  PGresult_data *block;
564 
565  if (!res)
566  return NULL;
567 
568  if (nBytes <= 0)
569  return res->null_field;
570 
571  /*
572  * If alignment is needed, round up the current position to an alignment
573  * boundary.
574  */
575  if (isBinary)
576  {
577  int offset = res->curOffset % PGRESULT_ALIGN_BOUNDARY;
578 
579  if (offset)
580  {
583  }
584  }
585 
586  /* If there's enough space in the current block, no problem. */
587  if (nBytes <= (size_t) res->spaceLeft)
588  {
589  space = res->curBlock->space + res->curOffset;
590  res->curOffset += nBytes;
591  res->spaceLeft -= nBytes;
592  return space;
593  }
594 
595  /*
596  * If the requested object is very large, give it its own block; this
597  * avoids wasting what might be most of the current block to start a new
598  * block. (We'd have to special-case requests bigger than the block size
599  * anyway.) The object is always given binary alignment in this case.
600  */
601  if (nBytes >= PGRESULT_SEP_ALLOC_THRESHOLD)
602  {
603  size_t alloc_size = nBytes + PGRESULT_BLOCK_OVERHEAD;
604 
605  block = (PGresult_data *) malloc(alloc_size);
606  if (!block)
607  return NULL;
608  res->memorySize += alloc_size;
609  space = block->space + PGRESULT_BLOCK_OVERHEAD;
610  if (res->curBlock)
611  {
612  /*
613  * Tuck special block below the active block, so that we don't
614  * have to waste the free space in the active block.
615  */
616  block->next = res->curBlock->next;
617  res->curBlock->next = block;
618  }
619  else
620  {
621  /* Must set up the new block as the first active block. */
622  block->next = NULL;
623  res->curBlock = block;
624  res->spaceLeft = 0; /* be sure it's marked full */
625  }
626  return space;
627  }
628 
629  /* Otherwise, start a new block. */
631  if (!block)
632  return NULL;
634  block->next = res->curBlock;
635  res->curBlock = block;
636  if (isBinary)
637  {
638  /* object needs full alignment */
641  }
642  else
643  {
644  /* we can cram it right after the overhead pointer */
645  res->curOffset = sizeof(PGresult_data);
647  }
648 
649  space = block->space + res->curOffset;
650  res->curOffset += nBytes;
651  res->spaceLeft -= nBytes;
652  return space;
653 }
654 
655 /*
656  * PQresultMemorySize -
657  * Returns total space allocated for the PGresult.
658  */
659 size_t
661 {
662  if (!res)
663  return 0;
664  return res->memorySize;
665 }
666 
667 /*
668  * pqResultStrdup -
669  * Like strdup, but the space is subsidiary PGresult space.
670  */
671 char *
673 {
674  char *space = (char *) pqResultAlloc(res, strlen(str) + 1, false);
675 
676  if (space)
677  strcpy(space, str);
678  return space;
679 }
680 
681 /*
682  * pqSetResultError -
683  * assign a new error message to a PGresult
684  *
685  * Copy text from errorMessage buffer beginning at given offset
686  * (it's caller's responsibility that offset is valid)
687  */
688 void
689 pqSetResultError(PGresult *res, PQExpBuffer errorMessage, int offset)
690 {
691  char *msg;
692 
693  if (!res)
694  return;
695 
696  /*
697  * We handle two OOM scenarios here. The errorMessage buffer might be
698  * marked "broken" due to having previously failed to allocate enough
699  * memory for the message, or it might be fine but pqResultStrdup fails
700  * and returns NULL. In either case, just make res->errMsg point directly
701  * at a constant "out of memory" string.
702  */
703  if (!PQExpBufferBroken(errorMessage))
704  msg = pqResultStrdup(res, errorMessage->data + offset);
705  else
706  msg = NULL;
707  if (msg)
708  res->errMsg = msg;
709  else
710  res->errMsg = libpq_gettext("out of memory\n");
711 }
712 
713 /*
714  * PQclear -
715  * free's the memory associated with a PGresult
716  */
717 void
719 {
720  PGresult_data *block;
721  int i;
722 
723  /* As a convenience, do nothing for a NULL pointer */
724  if (!res)
725  return;
726  /* Also, do nothing if the argument is OOM_result */
727  if ((const PGresult *) res == &OOM_result)
728  return;
729 
730  /* Close down any events we may have */
731  for (i = 0; i < res->nEvents; i++)
732  {
733  /* only send DESTROY to successfully-initialized event procs */
735  {
737 
738  evt.result = res;
739  (void) res->events[i].proc(PGEVT_RESULTDESTROY, &evt,
740  res->events[i].passThrough);
741  }
742  free(res->events[i].name);
743  }
744 
745  if (res->events)
746  free(res->events);
747 
748  /* Free all the subsidiary blocks */
749  while ((block = res->curBlock) != NULL)
750  {
751  res->curBlock = block->next;
752  free(block);
753  }
754 
755  /* Free the top-level tuple pointer array */
756  if (res->tuples)
757  free(res->tuples);
758 
759  /* zero out the pointer fields to catch programming errors */
760  res->attDescs = NULL;
761  res->tuples = NULL;
762  res->paramDescs = NULL;
763  res->errFields = NULL;
764  res->events = NULL;
765  res->nEvents = 0;
766  /* res->curBlock was zeroed out earlier */
767 
768  /* Free the PGresult structure itself */
769  free(res);
770 }
771 
772 /*
773  * Handy subroutine to deallocate any partially constructed async result.
774  *
775  * Any "next" result gets cleared too.
776  */
777 void
779 {
780  if (conn->result)
781  PQclear(conn->result);
782  conn->result = NULL;
783  conn->error_result = false;
784  if (conn->next_result)
786  conn->next_result = NULL;
787 }
788 
789 /*
790  * pqSaveErrorResult -
791  * remember that we have an error condition
792  *
793  * In much of libpq, reporting an error just requires appending text to
794  * conn->errorMessage and returning a failure code to one's caller.
795  * Where returning a failure code is impractical, instead call this
796  * function to remember that an error needs to be reported.
797  *
798  * (It might seem that appending text to conn->errorMessage should be
799  * sufficient, but we can't rely on that working under out-of-memory
800  * conditions. The OOM hazard is also why we don't try to make a new
801  * PGresult right here.)
802  */
803 void
805 {
806  /* Drop any pending result ... */
808  /* ... and set flag to remember to make an error result later */
809  conn->error_result = true;
810 }
811 
812 /*
813  * pqSaveWriteError -
814  * report a write failure
815  *
816  * As above, after appending conn->write_err_msg to whatever other error we
817  * have. This is used when we've detected a write failure and have exhausted
818  * our chances of reporting something else instead.
819  */
820 static void
822 {
823  /*
824  * If write_err_msg is null because of previous strdup failure, do what we
825  * can. (It's likely our machinations here will get OOM failures as well,
826  * but might as well try.)
827  */
828  if (conn->write_err_msg)
829  {
831  /* Avoid possibly appending the same message twice */
832  conn->write_err_msg[0] = '\0';
833  }
834  else
836  libpq_gettext("write to server failed\n"));
837 
839 }
840 
841 /*
842  * pqPrepareAsyncResult -
843  * prepare the current async result object for return to the caller
844  *
845  * If there is not already an async result object, build an error object
846  * using whatever is in conn->errorMessage. In any case, clear the async
847  * result storage, and update our notion of how much error text has been
848  * returned to the application.
849  */
850 PGresult *
852 {
853  PGresult *res;
854 
855  res = conn->result;
856  if (res)
857  {
858  /*
859  * If the pre-existing result is an ERROR (presumably something
860  * received from the server), assume that it represents whatever is in
861  * conn->errorMessage, and advance errorReported.
862  */
865  }
866  else
867  {
868  /*
869  * We get here after internal-to-libpq errors. We should probably
870  * always have error_result = true, but if we don't, gin up some error
871  * text.
872  */
873  if (!conn->error_result)
875  libpq_gettext("no error text available\n"));
876 
877  /* Paranoia: be sure errorReported offset is sane */
878  if (conn->errorReported < 0 ||
880  conn->errorReported = 0;
881 
882  /*
883  * Make a PGresult struct for the error. We temporarily lie about the
884  * result status, so that PQmakeEmptyPGresult doesn't uselessly copy
885  * all of conn->errorMessage.
886  */
888  if (res)
889  {
890  /*
891  * Report whatever new error text we have, and advance
892  * errorReported.
893  */
897  }
898  else
899  {
900  /*
901  * Ouch, not enough memory for a PGresult. Fortunately, we have a
902  * card up our sleeve: we can use the static OOM_result. Casting
903  * away const here is a bit ugly, but it seems best to declare
904  * OOM_result as const, in hopes it will be allocated in read-only
905  * storage.
906  */
908 
909  /*
910  * Don't advance errorReported. Perhaps we'll be able to report
911  * the text later.
912  */
913  }
914  }
915 
916  /*
917  * Replace conn->result with next_result, if any. In the normal case
918  * there isn't a next result and we're just dropping ownership of the
919  * current result. In single-row mode this restores the situation to what
920  * it was before we created the current single-row result.
921  */
923  conn->error_result = false; /* next_result is never an error */
924  conn->next_result = NULL;
925 
926  return res;
927 }
928 
929 /*
930  * pqInternalNotice - produce an internally-generated notice message
931  *
932  * A format string and optional arguments can be passed. Note that we do
933  * libpq_gettext() here, so callers need not.
934  *
935  * The supplied text is taken as primary message (ie., it should not include
936  * a trailing newline, and should not be more than one line).
937  */
938 void
939 pqInternalNotice(const PGNoticeHooks *hooks, const char *fmt,...)
940 {
941  char msgBuf[1024];
942  va_list args;
943  PGresult *res;
944 
945  if (hooks->noticeRec == NULL)
946  return; /* nobody home to receive notice? */
947 
948  /* Format the message */
949  va_start(args, fmt);
950  vsnprintf(msgBuf, sizeof(msgBuf), libpq_gettext(fmt), args);
951  va_end(args);
952  msgBuf[sizeof(msgBuf) - 1] = '\0'; /* make real sure it's terminated */
953 
954  /* Make a PGresult to pass to the notice receiver */
956  if (!res)
957  return;
958  res->noticeHooks = *hooks;
959 
960  /*
961  * Set up fields of notice.
962  */
966  /* XXX should provide a SQLSTATE too? */
967 
968  /*
969  * Result text is always just the primary message + newline. If we can't
970  * allocate it, substitute "out of memory", as in pqSetResultError.
971  */
972  res->errMsg = (char *) pqResultAlloc(res, strlen(msgBuf) + 2, false);
973  if (res->errMsg)
974  sprintf(res->errMsg, "%s\n", msgBuf);
975  else
976  res->errMsg = libpq_gettext("out of memory\n");
977 
978  /*
979  * Pass to receiver, then free it.
980  */
982  PQclear(res);
983 }
984 
985 /*
986  * pqAddTuple
987  * add a row pointer to the PGresult structure, growing it if necessary
988  * Returns true if OK, false if an error prevented adding the row
989  *
990  * On error, *errmsgp can be set to an error string to be returned.
991  * If it is left NULL, the error is presumed to be "out of memory".
992  */
993 static bool
994 pqAddTuple(PGresult *res, PGresAttValue *tup, const char **errmsgp)
995 {
996  if (res->ntups >= res->tupArrSize)
997  {
998  /*
999  * Try to grow the array.
1000  *
1001  * We can use realloc because shallow copying of the structure is
1002  * okay. Note that the first time through, res->tuples is NULL. While
1003  * ANSI says that realloc() should act like malloc() in that case,
1004  * some old C libraries (like SunOS 4.1.x) coredump instead. On
1005  * failure realloc is supposed to return NULL without damaging the
1006  * existing allocation. Note that the positions beyond res->ntups are
1007  * garbage, not necessarily NULL.
1008  */
1009  int newSize;
1010  PGresAttValue **newTuples;
1011 
1012  /*
1013  * Since we use integers for row numbers, we can't support more than
1014  * INT_MAX rows. Make sure we allow that many, though.
1015  */
1016  if (res->tupArrSize <= INT_MAX / 2)
1017  newSize = (res->tupArrSize > 0) ? res->tupArrSize * 2 : 128;
1018  else if (res->tupArrSize < INT_MAX)
1019  newSize = INT_MAX;
1020  else
1021  {
1022  *errmsgp = libpq_gettext("PGresult cannot support more than INT_MAX tuples");
1023  return false;
1024  }
1025 
1026  /*
1027  * Also, on 32-bit platforms we could, in theory, overflow size_t even
1028  * before newSize gets to INT_MAX. (In practice we'd doubtless hit
1029  * OOM long before that, but let's check.)
1030  */
1031 #if INT_MAX >= (SIZE_MAX / 2)
1032  if (newSize > SIZE_MAX / sizeof(PGresAttValue *))
1033  {
1034  *errmsgp = libpq_gettext("size_t overflow");
1035  return false;
1036  }
1037 #endif
1038 
1039  if (res->tuples == NULL)
1040  newTuples = (PGresAttValue **)
1041  malloc(newSize * sizeof(PGresAttValue *));
1042  else
1043  newTuples = (PGresAttValue **)
1044  realloc(res->tuples, newSize * sizeof(PGresAttValue *));
1045  if (!newTuples)
1046  return false; /* malloc or realloc failed */
1047  res->memorySize +=
1048  (newSize - res->tupArrSize) * sizeof(PGresAttValue *);
1049  res->tupArrSize = newSize;
1050  res->tuples = newTuples;
1051  }
1052  res->tuples[res->ntups] = tup;
1053  res->ntups++;
1054  return true;
1055 }
1056 
1057 /*
1058  * pqSaveMessageField - save one field of an error or notice message
1059  */
1060 void
1061 pqSaveMessageField(PGresult *res, char code, const char *value)
1062 {
1063  PGMessageField *pfield;
1064 
1065  pfield = (PGMessageField *)
1067  offsetof(PGMessageField, contents) +
1068  strlen(value) + 1,
1069  true);
1070  if (!pfield)
1071  return; /* out of memory? */
1072  pfield->code = code;
1073  strcpy(pfield->contents, value);
1074  pfield->next = res->errFields;
1075  res->errFields = pfield;
1076 }
1077 
1078 /*
1079  * pqSaveParameterStatus - remember parameter status sent by backend
1080  */
1081 void
1082 pqSaveParameterStatus(PGconn *conn, const char *name, const char *value)
1083 {
1084  pgParameterStatus *pstatus;
1085  pgParameterStatus *prev;
1086 
1087  /*
1088  * Forget any old information about the parameter
1089  */
1090  for (pstatus = conn->pstatus, prev = NULL;
1091  pstatus != NULL;
1092  prev = pstatus, pstatus = pstatus->next)
1093  {
1094  if (strcmp(pstatus->name, name) == 0)
1095  {
1096  if (prev)
1097  prev->next = pstatus->next;
1098  else
1099  conn->pstatus = pstatus->next;
1100  free(pstatus); /* frees name and value strings too */
1101  break;
1102  }
1103  }
1104 
1105  /*
1106  * Store new info as a single malloc block
1107  */
1108  pstatus = (pgParameterStatus *) malloc(sizeof(pgParameterStatus) +
1109  strlen(name) + strlen(value) + 2);
1110  if (pstatus)
1111  {
1112  char *ptr;
1113 
1114  ptr = ((char *) pstatus) + sizeof(pgParameterStatus);
1115  pstatus->name = ptr;
1116  strcpy(ptr, name);
1117  ptr += strlen(name) + 1;
1118  pstatus->value = ptr;
1119  strcpy(ptr, value);
1120  pstatus->next = conn->pstatus;
1121  conn->pstatus = pstatus;
1122  }
1123 
1124  /*
1125  * Save values of settings that are of interest to libpq in fields of the
1126  * PGconn object. We keep client_encoding and standard_conforming_strings
1127  * in static variables as well, so that PQescapeString and PQescapeBytea
1128  * can behave somewhat sanely (at least in single-connection-using
1129  * programs).
1130  */
1131  if (strcmp(name, "client_encoding") == 0)
1132  {
1134  /* if we don't recognize the encoding name, fall back to SQL_ASCII */
1135  if (conn->client_encoding < 0)
1138  }
1139  else if (strcmp(name, "standard_conforming_strings") == 0)
1140  {
1141  conn->std_strings = (strcmp(value, "on") == 0);
1143  }
1144  else if (strcmp(name, "server_version") == 0)
1145  {
1146  /* We convert the server version to numeric form. */
1147  int cnt;
1148  int vmaj,
1149  vmin,
1150  vrev;
1151 
1152  cnt = sscanf(value, "%d.%d.%d", &vmaj, &vmin, &vrev);
1153 
1154  if (cnt == 3)
1155  {
1156  /* old style, e.g. 9.6.1 */
1157  conn->sversion = (100 * vmaj + vmin) * 100 + vrev;
1158  }
1159  else if (cnt == 2)
1160  {
1161  if (vmaj >= 10)
1162  {
1163  /* new style, e.g. 10.1 */
1164  conn->sversion = 100 * 100 * vmaj + vmin;
1165  }
1166  else
1167  {
1168  /* old style without minor version, e.g. 9.6devel */
1169  conn->sversion = (100 * vmaj + vmin) * 100;
1170  }
1171  }
1172  else if (cnt == 1)
1173  {
1174  /* new style without minor version, e.g. 10devel */
1175  conn->sversion = 100 * 100 * vmaj;
1176  }
1177  else
1178  conn->sversion = 0; /* unknown */
1179  }
1180  else if (strcmp(name, "default_transaction_read_only") == 0)
1181  {
1183  (strcmp(value, "on") == 0) ? PG_BOOL_YES : PG_BOOL_NO;
1184  }
1185  else if (strcmp(name, "in_hot_standby") == 0)
1186  {
1187  conn->in_hot_standby =
1188  (strcmp(value, "on") == 0) ? PG_BOOL_YES : PG_BOOL_NO;
1189  }
1190 }
1191 
1192 
1193 /*
1194  * pqRowProcessor
1195  * Add the received row to the current async result (conn->result).
1196  * Returns 1 if OK, 0 if error occurred.
1197  *
1198  * On error, *errmsgp can be set to an error string to be returned.
1199  * (Such a string should already be translated via libpq_gettext().)
1200  * If it is left NULL, the error is presumed to be "out of memory".
1201  *
1202  * In single-row mode, we create a new result holding just the current row,
1203  * stashing the previous result in conn->next_result so that it becomes
1204  * active again after pqPrepareAsyncResult(). This allows the result metadata
1205  * (column descriptions) to be carried forward to each result row.
1206  */
1207 int
1208 pqRowProcessor(PGconn *conn, const char **errmsgp)
1209 {
1210  PGresult *res = conn->result;
1211  int nfields = res->numAttributes;
1212  const PGdataValue *columns = conn->rowBuf;
1213  PGresAttValue *tup;
1214  int i;
1215 
1216  /*
1217  * In single-row mode, make a new PGresult that will hold just this one
1218  * row; the original conn->result is left unchanged so that it can be used
1219  * again as the template for future rows.
1220  */
1221  if (conn->singleRowMode)
1222  {
1223  /* Copy everything that should be in the result at this point */
1224  res = PQcopyResult(res,
1227  if (!res)
1228  return 0;
1229  }
1230 
1231  /*
1232  * Basically we just allocate space in the PGresult for each field and
1233  * copy the data over.
1234  *
1235  * Note: on malloc failure, we return 0 leaving *errmsgp still NULL, which
1236  * caller will take to mean "out of memory". This is preferable to trying
1237  * to set up such a message here, because evidently there's not enough
1238  * memory for gettext() to do anything.
1239  */
1240  tup = (PGresAttValue *)
1241  pqResultAlloc(res, nfields * sizeof(PGresAttValue), true);
1242  if (tup == NULL)
1243  goto fail;
1244 
1245  for (i = 0; i < nfields; i++)
1246  {
1247  int clen = columns[i].len;
1248 
1249  if (clen < 0)
1250  {
1251  /* null field */
1252  tup[i].len = NULL_LEN;
1253  tup[i].value = res->null_field;
1254  }
1255  else
1256  {
1257  bool isbinary = (res->attDescs[i].format != 0);
1258  char *val;
1259 
1260  val = (char *) pqResultAlloc(res, clen + 1, isbinary);
1261  if (val == NULL)
1262  goto fail;
1263 
1264  /* copy and zero-terminate the data (even if it's binary) */
1265  memcpy(val, columns[i].value, clen);
1266  val[clen] = '\0';
1267 
1268  tup[i].len = clen;
1269  tup[i].value = val;
1270  }
1271  }
1272 
1273  /* And add the tuple to the PGresult's tuple array */
1274  if (!pqAddTuple(res, tup, errmsgp))
1275  goto fail;
1276 
1277  /*
1278  * Success. In single-row mode, make the result available to the client
1279  * immediately.
1280  */
1281  if (conn->singleRowMode)
1282  {
1283  /* Change result status to special single-row value */
1285  /* Stash old result for re-use later */
1287  conn->result = res;
1288  /* And mark the result ready to return */
1290  }
1291 
1292  return 1;
1293 
1294 fail:
1295  /* release locally allocated PGresult, if we made one */
1296  if (res != conn->result)
1297  PQclear(res);
1298  return 0;
1299 }
1300 
1301 
1302 /*
1303  * pqAllocCmdQueueEntry
1304  * Get a command queue entry for caller to fill.
1305  *
1306  * If the recycle queue has a free element, that is returned; if not, a
1307  * fresh one is allocated. Caller is responsible for adding it to the
1308  * command queue (pqAppendCmdQueueEntry) once the struct is filled in, or
1309  * releasing the memory (pqRecycleCmdQueueEntry) if an error occurs.
1310  *
1311  * If allocation fails, sets the error message and returns NULL.
1312  */
1313 static PGcmdQueueEntry *
1315 {
1316  PGcmdQueueEntry *entry;
1317 
1318  if (conn->cmd_queue_recycle == NULL)
1319  {
1320  entry = (PGcmdQueueEntry *) malloc(sizeof(PGcmdQueueEntry));
1321  if (entry == NULL)
1322  {
1324  libpq_gettext("out of memory\n"));
1325  return NULL;
1326  }
1327  }
1328  else
1329  {
1330  entry = conn->cmd_queue_recycle;
1331  conn->cmd_queue_recycle = entry->next;
1332  }
1333  entry->next = NULL;
1334  entry->query = NULL;
1335 
1336  return entry;
1337 }
1338 
1339 /*
1340  * pqAppendCmdQueueEntry
1341  * Append a caller-allocated entry to the command queue, and update
1342  * conn->asyncStatus to account for it.
1343  *
1344  * The query itself must already have been put in the output buffer by the
1345  * caller.
1346  */
1347 static void
1349 {
1350  Assert(entry->next == NULL);
1351 
1352  if (conn->cmd_queue_head == NULL)
1353  conn->cmd_queue_head = entry;
1354  else
1355  conn->cmd_queue_tail->next = entry;
1356 
1357  conn->cmd_queue_tail = entry;
1358 
1359  switch (conn->pipelineStatus)
1360  {
1361  case PQ_PIPELINE_OFF:
1362  case PQ_PIPELINE_ON:
1363 
1364  /*
1365  * When not in pipeline aborted state, if there's a result ready
1366  * to be consumed, let it be so (that is, don't change away from
1367  * READY or READY_MORE); otherwise set us busy to wait for
1368  * something to arrive from the server.
1369  */
1370  if (conn->asyncStatus == PGASYNC_IDLE)
1372  break;
1373 
1374  case PQ_PIPELINE_ABORTED:
1375 
1376  /*
1377  * In aborted pipeline state, we don't expect anything from the
1378  * server (since we don't send any queries that are queued).
1379  * Therefore, if IDLE then do what PQgetResult would do to let
1380  * itself consume commands from the queue; if we're in any other
1381  * state, we don't have to do anything.
1382  */
1383  if (conn->asyncStatus == PGASYNC_IDLE)
1385  break;
1386  }
1387 }
1388 
1389 /*
1390  * pqRecycleCmdQueueEntry
1391  * Push a command queue entry onto the freelist.
1392  */
1393 static void
1395 {
1396  if (entry == NULL)
1397  return;
1398 
1399  /* recyclable entries should not have a follow-on command */
1400  Assert(entry->next == NULL);
1401 
1402  if (entry->query)
1403  {
1404  free(entry->query);
1405  entry->query = NULL;
1406  }
1407 
1408  entry->next = conn->cmd_queue_recycle;
1409  conn->cmd_queue_recycle = entry;
1410 }
1411 
1412 
1413 /*
1414  * PQsendQuery
1415  * Submit a query, but don't wait for it to finish
1416  *
1417  * Returns: 1 if successfully submitted
1418  * 0 if error (conn->errorMessage is set)
1419  *
1420  * PQsendQueryContinue is a non-exported version that behaves identically
1421  * except that it doesn't reset conn->errorMessage.
1422  */
1423 int
1424 PQsendQuery(PGconn *conn, const char *query)
1425 {
1426  return PQsendQueryInternal(conn, query, true);
1427 }
1428 
1429 int
1430 PQsendQueryContinue(PGconn *conn, const char *query)
1431 {
1432  return PQsendQueryInternal(conn, query, false);
1433 }
1434 
1435 static int
1436 PQsendQueryInternal(PGconn *conn, const char *query, bool newQuery)
1437 {
1438  PGcmdQueueEntry *entry = NULL;
1439 
1440  if (!PQsendQueryStart(conn, newQuery))
1441  return 0;
1442 
1443  /* check the argument */
1444  if (!query)
1445  {
1447  libpq_gettext("command string is a null pointer\n"));
1448  return 0;
1449  }
1450 
1451  entry = pqAllocCmdQueueEntry(conn);
1452  if (entry == NULL)
1453  return 0; /* error msg already set */
1454 
1455  /* Send the query message(s) */
1457  {
1458  /* construct the outgoing Query message */
1459  if (pqPutMsgStart('Q', conn) < 0 ||
1460  pqPuts(query, conn) < 0 ||
1461  pqPutMsgEnd(conn) < 0)
1462  {
1463  /* error message should be set up already */
1464  pqRecycleCmdQueueEntry(conn, entry);
1465  return 0;
1466  }
1467 
1468  /* remember we are using simple query protocol */
1469  entry->queryclass = PGQUERY_SIMPLE;
1470  /* and remember the query text too, if possible */
1471  entry->query = strdup(query);
1472  }
1473  else
1474  {
1475  /*
1476  * In pipeline mode we cannot use the simple protocol, so we send
1477  * Parse, Bind, Describe Portal, Execute, Close Portal (with the
1478  * unnamed portal).
1479  */
1480  if (pqPutMsgStart('P', conn) < 0 ||
1481  pqPuts("", conn) < 0 ||
1482  pqPuts(query, conn) < 0 ||
1483  pqPutInt(0, 2, conn) < 0 ||
1484  pqPutMsgEnd(conn) < 0)
1485  goto sendFailed;
1486  if (pqPutMsgStart('B', conn) < 0 ||
1487  pqPuts("", conn) < 0 ||
1488  pqPuts("", conn) < 0 ||
1489  pqPutInt(0, 2, conn) < 0 ||
1490  pqPutInt(0, 2, conn) < 0 ||
1491  pqPutInt(0, 2, conn) < 0 ||
1492  pqPutMsgEnd(conn) < 0)
1493  goto sendFailed;
1494  if (pqPutMsgStart('D', conn) < 0 ||
1495  pqPutc('P', conn) < 0 ||
1496  pqPuts("", conn) < 0 ||
1497  pqPutMsgEnd(conn) < 0)
1498  goto sendFailed;
1499  if (pqPutMsgStart('E', conn) < 0 ||
1500  pqPuts("", conn) < 0 ||
1501  pqPutInt(0, 4, conn) < 0 ||
1502  pqPutMsgEnd(conn) < 0)
1503  goto sendFailed;
1504  if (pqPutMsgStart('C', conn) < 0 ||
1505  pqPutc('P', conn) < 0 ||
1506  pqPuts("", conn) < 0 ||
1507  pqPutMsgEnd(conn) < 0)
1508  goto sendFailed;
1509 
1510  entry->queryclass = PGQUERY_EXTENDED;
1511  entry->query = strdup(query);
1512  }
1513 
1514  /*
1515  * Give the data a push. In nonblock mode, don't complain if we're unable
1516  * to send it all; PQgetResult() will do any additional flushing needed.
1517  */
1518  if (pqPipelineFlush(conn) < 0)
1519  goto sendFailed;
1520 
1521  /* OK, it's launched! */
1522  pqAppendCmdQueueEntry(conn, entry);
1523  return 1;
1524 
1525 sendFailed:
1526  pqRecycleCmdQueueEntry(conn, entry);
1527  /* error message should be set up already */
1528  return 0;
1529 }
1530 
1531 /*
1532  * PQsendQueryParams
1533  * Like PQsendQuery, but use extended query protocol so we can pass parameters
1534  */
1535 int
1537  const char *command,
1538  int nParams,
1539  const Oid *paramTypes,
1540  const char *const *paramValues,
1541  const int *paramLengths,
1542  const int *paramFormats,
1543  int resultFormat)
1544 {
1545  if (!PQsendQueryStart(conn, true))
1546  return 0;
1547 
1548  /* check the arguments */
1549  if (!command)
1550  {
1552  libpq_gettext("command string is a null pointer\n"));
1553  return 0;
1554  }
1555  if (nParams < 0 || nParams > PQ_QUERY_PARAM_MAX_LIMIT)
1556  {
1558  libpq_gettext("number of parameters must be between 0 and %d\n"),
1560  return 0;
1561  }
1562 
1563  return PQsendQueryGuts(conn,
1564  command,
1565  "", /* use unnamed statement */
1566  nParams,
1567  paramTypes,
1568  paramValues,
1569  paramLengths,
1570  paramFormats,
1571  resultFormat);
1572 }
1573 
1574 /*
1575  * PQsendPrepare
1576  * Submit a Parse message, but don't wait for it to finish
1577  *
1578  * Returns: 1 if successfully submitted
1579  * 0 if error (conn->errorMessage is set)
1580  */
1581 int
1583  const char *stmtName, const char *query,
1584  int nParams, const Oid *paramTypes)
1585 {
1586  PGcmdQueueEntry *entry = NULL;
1587 
1588  if (!PQsendQueryStart(conn, true))
1589  return 0;
1590 
1591  /* check the arguments */
1592  if (!stmtName)
1593  {
1595  libpq_gettext("statement name is a null pointer\n"));
1596  return 0;
1597  }
1598  if (!query)
1599  {
1601  libpq_gettext("command string is a null pointer\n"));
1602  return 0;
1603  }
1604  if (nParams < 0 || nParams > PQ_QUERY_PARAM_MAX_LIMIT)
1605  {
1607  libpq_gettext("number of parameters must be between 0 and %d\n"),
1609  return 0;
1610  }
1611 
1612  entry = pqAllocCmdQueueEntry(conn);
1613  if (entry == NULL)
1614  return 0; /* error msg already set */
1615 
1616  /* construct the Parse message */
1617  if (pqPutMsgStart('P', conn) < 0 ||
1618  pqPuts(stmtName, conn) < 0 ||
1619  pqPuts(query, conn) < 0)
1620  goto sendFailed;
1621 
1622  if (nParams > 0 && paramTypes)
1623  {
1624  int i;
1625 
1626  if (pqPutInt(nParams, 2, conn) < 0)
1627  goto sendFailed;
1628  for (i = 0; i < nParams; i++)
1629  {
1630  if (pqPutInt(paramTypes[i], 4, conn) < 0)
1631  goto sendFailed;
1632  }
1633  }
1634  else
1635  {
1636  if (pqPutInt(0, 2, conn) < 0)
1637  goto sendFailed;
1638  }
1639  if (pqPutMsgEnd(conn) < 0)
1640  goto sendFailed;
1641 
1642  /* Add a Sync, unless in pipeline mode. */
1644  {
1645  if (pqPutMsgStart('S', conn) < 0 ||
1646  pqPutMsgEnd(conn) < 0)
1647  goto sendFailed;
1648  }
1649 
1650  /* remember we are doing just a Parse */
1651  entry->queryclass = PGQUERY_PREPARE;
1652 
1653  /* and remember the query text too, if possible */
1654  /* if insufficient memory, query just winds up NULL */
1655  entry->query = strdup(query);
1656 
1657  /*
1658  * Give the data a push (in pipeline mode, only if we're past the size
1659  * threshold). In nonblock mode, don't complain if we're unable to send
1660  * it all; PQgetResult() will do any additional flushing needed.
1661  */
1662  if (pqPipelineFlush(conn) < 0)
1663  goto sendFailed;
1664 
1665  /* OK, it's launched! */
1666  pqAppendCmdQueueEntry(conn, entry);
1667 
1668  return 1;
1669 
1670 sendFailed:
1671  pqRecycleCmdQueueEntry(conn, entry);
1672  /* error message should be set up already */
1673  return 0;
1674 }
1675 
1676 /*
1677  * PQsendQueryPrepared
1678  * Like PQsendQuery, but execute a previously prepared statement,
1679  * using extended query protocol so we can pass parameters
1680  */
1681 int
1683  const char *stmtName,
1684  int nParams,
1685  const char *const *paramValues,
1686  const int *paramLengths,
1687  const int *paramFormats,
1688  int resultFormat)
1689 {
1690  if (!PQsendQueryStart(conn, true))
1691  return 0;
1692 
1693  /* check the arguments */
1694  if (!stmtName)
1695  {
1697  libpq_gettext("statement name is a null pointer\n"));
1698  return 0;
1699  }
1700  if (nParams < 0 || nParams > PQ_QUERY_PARAM_MAX_LIMIT)
1701  {
1703  libpq_gettext("number of parameters must be between 0 and %d\n"),
1705  return 0;
1706  }
1707 
1708  return PQsendQueryGuts(conn,
1709  NULL, /* no command to parse */
1710  stmtName,
1711  nParams,
1712  NULL, /* no param types */
1713  paramValues,
1714  paramLengths,
1715  paramFormats,
1716  resultFormat);
1717 }
1718 
1719 /*
1720  * PQsendQueryStart
1721  * Common startup code for PQsendQuery and sibling routines
1722  */
1723 static bool
1724 PQsendQueryStart(PGconn *conn, bool newQuery)
1725 {
1726  if (!conn)
1727  return false;
1728 
1729  /*
1730  * If this is the beginning of a query cycle, reset the error state.
1731  * However, in pipeline mode with something already queued, the error
1732  * buffer belongs to that command and we shouldn't clear it.
1733  */
1734  if (newQuery && conn->cmd_queue_head == NULL)
1736 
1737  /* Don't try to send if we know there's no live connection. */
1738  if (conn->status != CONNECTION_OK)
1739  {
1741  libpq_gettext("no connection to the server\n"));
1742  return false;
1743  }
1744 
1745  /* Can't send while already busy, either, unless enqueuing for later */
1746  if (conn->asyncStatus != PGASYNC_IDLE &&
1748  {
1750  libpq_gettext("another command is already in progress\n"));
1751  return false;
1752  }
1753 
1755  {
1756  /*
1757  * When enqueuing commands we don't change much of the connection
1758  * state since it's already in use for the current command. The
1759  * connection state will get updated when pqPipelineProcessQueue()
1760  * advances to start processing the queued message.
1761  *
1762  * Just make sure we can safely enqueue given the current connection
1763  * state. We can enqueue behind another queue item, or behind a
1764  * non-queue command (one that sends its own sync), but we can't
1765  * enqueue if the connection is in a copy state.
1766  */
1767  switch (conn->asyncStatus)
1768  {
1769  case PGASYNC_IDLE:
1770  case PGASYNC_READY:
1771  case PGASYNC_READY_MORE:
1772  case PGASYNC_BUSY:
1773  /* ok to queue */
1774  break;
1775  case PGASYNC_COPY_IN:
1776  case PGASYNC_COPY_OUT:
1777  case PGASYNC_COPY_BOTH:
1779  libpq_gettext("cannot queue commands during COPY\n"));
1780  return false;
1781  }
1782  }
1783  else
1784  {
1785  /*
1786  * This command's results will come in immediately. Initialize async
1787  * result-accumulation state
1788  */
1790 
1791  /* reset single-row processing mode */
1792  conn->singleRowMode = false;
1793  }
1794 
1795  /* ready to send command message */
1796  return true;
1797 }
1798 
1799 /*
1800  * PQsendQueryGuts
1801  * Common code for sending a query with extended query protocol
1802  * PQsendQueryStart should be done already
1803  *
1804  * command may be NULL to indicate we use an already-prepared statement
1805  */
1806 static int
1808  const char *command,
1809  const char *stmtName,
1810  int nParams,
1811  const Oid *paramTypes,
1812  const char *const *paramValues,
1813  const int *paramLengths,
1814  const int *paramFormats,
1815  int resultFormat)
1816 {
1817  int i;
1818  PGcmdQueueEntry *entry;
1819 
1820  entry = pqAllocCmdQueueEntry(conn);
1821  if (entry == NULL)
1822  return 0; /* error msg already set */
1823 
1824  /*
1825  * We will send Parse (if needed), Bind, Describe Portal, Execute, Sync
1826  * (if not in pipeline mode), using specified statement name and the
1827  * unnamed portal.
1828  */
1829 
1830  if (command)
1831  {
1832  /* construct the Parse message */
1833  if (pqPutMsgStart('P', conn) < 0 ||
1834  pqPuts(stmtName, conn) < 0 ||
1835  pqPuts(command, conn) < 0)
1836  goto sendFailed;
1837  if (nParams > 0 && paramTypes)
1838  {
1839  if (pqPutInt(nParams, 2, conn) < 0)
1840  goto sendFailed;
1841  for (i = 0; i < nParams; i++)
1842  {
1843  if (pqPutInt(paramTypes[i], 4, conn) < 0)
1844  goto sendFailed;
1845  }
1846  }
1847  else
1848  {
1849  if (pqPutInt(0, 2, conn) < 0)
1850  goto sendFailed;
1851  }
1852  if (pqPutMsgEnd(conn) < 0)
1853  goto sendFailed;
1854  }
1855 
1856  /* Construct the Bind message */
1857  if (pqPutMsgStart('B', conn) < 0 ||
1858  pqPuts("", conn) < 0 ||
1859  pqPuts(stmtName, conn) < 0)
1860  goto sendFailed;
1861 
1862  /* Send parameter formats */
1863  if (nParams > 0 && paramFormats)
1864  {
1865  if (pqPutInt(nParams, 2, conn) < 0)
1866  goto sendFailed;
1867  for (i = 0; i < nParams; i++)
1868  {
1869  if (pqPutInt(paramFormats[i], 2, conn) < 0)
1870  goto sendFailed;
1871  }
1872  }
1873  else
1874  {
1875  if (pqPutInt(0, 2, conn) < 0)
1876  goto sendFailed;
1877  }
1878 
1879  if (pqPutInt(nParams, 2, conn) < 0)
1880  goto sendFailed;
1881 
1882  /* Send parameters */
1883  for (i = 0; i < nParams; i++)
1884  {
1885  if (paramValues && paramValues[i])
1886  {
1887  int nbytes;
1888 
1889  if (paramFormats && paramFormats[i] != 0)
1890  {
1891  /* binary parameter */
1892  if (paramLengths)
1893  nbytes = paramLengths[i];
1894  else
1895  {
1897  libpq_gettext("length must be given for binary parameter\n"));
1898  goto sendFailed;
1899  }
1900  }
1901  else
1902  {
1903  /* text parameter, do not use paramLengths */
1904  nbytes = strlen(paramValues[i]);
1905  }
1906  if (pqPutInt(nbytes, 4, conn) < 0 ||
1907  pqPutnchar(paramValues[i], nbytes, conn) < 0)
1908  goto sendFailed;
1909  }
1910  else
1911  {
1912  /* take the param as NULL */
1913  if (pqPutInt(-1, 4, conn) < 0)
1914  goto sendFailed;
1915  }
1916  }
1917  if (pqPutInt(1, 2, conn) < 0 ||
1918  pqPutInt(resultFormat, 2, conn))
1919  goto sendFailed;
1920  if (pqPutMsgEnd(conn) < 0)
1921  goto sendFailed;
1922 
1923  /* construct the Describe Portal message */
1924  if (pqPutMsgStart('D', conn) < 0 ||
1925  pqPutc('P', conn) < 0 ||
1926  pqPuts("", conn) < 0 ||
1927  pqPutMsgEnd(conn) < 0)
1928  goto sendFailed;
1929 
1930  /* construct the Execute message */
1931  if (pqPutMsgStart('E', conn) < 0 ||
1932  pqPuts("", conn) < 0 ||
1933  pqPutInt(0, 4, conn) < 0 ||
1934  pqPutMsgEnd(conn) < 0)
1935  goto sendFailed;
1936 
1937  /* construct the Sync message if not in pipeline mode */
1939  {
1940  if (pqPutMsgStart('S', conn) < 0 ||
1941  pqPutMsgEnd(conn) < 0)
1942  goto sendFailed;
1943  }
1944 
1945  /* remember we are using extended query protocol */
1946  entry->queryclass = PGQUERY_EXTENDED;
1947 
1948  /* and remember the query text too, if possible */
1949  /* if insufficient memory, query just winds up NULL */
1950  if (command)
1951  entry->query = strdup(command);
1952 
1953  /*
1954  * Give the data a push (in pipeline mode, only if we're past the size
1955  * threshold). In nonblock mode, don't complain if we're unable to send
1956  * it all; PQgetResult() will do any additional flushing needed.
1957  */
1958  if (pqPipelineFlush(conn) < 0)
1959  goto sendFailed;
1960 
1961  /* OK, it's launched! */
1962  pqAppendCmdQueueEntry(conn, entry);
1963 
1964  return 1;
1965 
1966 sendFailed:
1967  pqRecycleCmdQueueEntry(conn, entry);
1968  /* error message should be set up already */
1969  return 0;
1970 }
1971 
1972 /*
1973  * Select row-by-row processing mode
1974  */
1975 int
1977 {
1978  /*
1979  * Only allow setting the flag when we have launched a query and not yet
1980  * received any results.
1981  */
1982  if (!conn)
1983  return 0;
1984  if (conn->asyncStatus != PGASYNC_BUSY)
1985  return 0;
1986  if (!conn->cmd_queue_head ||
1989  return 0;
1991  return 0;
1992 
1993  /* OK, set flag */
1994  conn->singleRowMode = true;
1995  return 1;
1996 }
1997 
1998 /*
1999  * Consume any available input from the backend
2000  * 0 return: some kind of trouble
2001  * 1 return: no problem
2002  */
2003 int
2005 {
2006  if (!conn)
2007  return 0;
2008 
2009  /*
2010  * for non-blocking connections try to flush the send-queue, otherwise we
2011  * may never get a response for something that may not have already been
2012  * sent because it's in our write buffer!
2013  */
2014  if (pqIsnonblocking(conn))
2015  {
2016  if (pqFlush(conn) < 0)
2017  return 0;
2018  }
2019 
2020  /*
2021  * Load more data, if available. We do this no matter what state we are
2022  * in, since we are probably getting called because the application wants
2023  * to get rid of a read-select condition. Note that we will NOT block
2024  * waiting for more input.
2025  */
2026  if (pqReadData(conn) < 0)
2027  return 0;
2028 
2029  /* Parsing of the data waits till later. */
2030  return 1;
2031 }
2032 
2033 
2034 /*
2035  * parseInput: if appropriate, parse input data from backend
2036  * until input is exhausted or a stopping state is reached.
2037  * Note that this function will NOT attempt to read more data from the backend.
2038  */
2039 static void
2041 {
2043 }
2044 
2045 /*
2046  * PQisBusy
2047  * Return true if PQgetResult would block waiting for input.
2048  */
2049 
2050 int
2052 {
2053  if (!conn)
2054  return false;
2055 
2056  /* Parse any available data, if our state permits. */
2057  parseInput(conn);
2058 
2059  /*
2060  * PQgetResult will return immediately in all states except BUSY. Also,
2061  * if we've detected read EOF and dropped the connection, we can expect
2062  * that PQgetResult will fail immediately. Note that we do *not* check
2063  * conn->write_failed here --- once that's become set, we know we have
2064  * trouble, but we need to keep trying to read until we have a complete
2065  * server message or detect read EOF.
2066  */
2068 }
2069 
2070 /*
2071  * PQgetResult
2072  * Get the next PGresult produced by a query. Returns NULL if no
2073  * query work remains or an error has occurred (e.g. out of
2074  * memory).
2075  *
2076  * In pipeline mode, once all the result of a query have been returned,
2077  * PQgetResult returns NULL to let the user know that the next
2078  * query is being processed. At the end of the pipeline, returns a
2079  * result with PQresultStatus(result) == PGRES_PIPELINE_SYNC.
2080  */
2081 PGresult *
2083 {
2084  PGresult *res;
2085 
2086  if (!conn)
2087  return NULL;
2088 
2089  /* Parse any available data, if our state permits. */
2090  parseInput(conn);
2091 
2092  /* If not ready to return something, block until we are. */
2093  while (conn->asyncStatus == PGASYNC_BUSY)
2094  {
2095  int flushResult;
2096 
2097  /*
2098  * If data remains unsent, send it. Else we might be waiting for the
2099  * result of a command the backend hasn't even got yet.
2100  */
2101  while ((flushResult = pqFlush(conn)) > 0)
2102  {
2103  if (pqWait(false, true, conn))
2104  {
2105  flushResult = -1;
2106  break;
2107  }
2108  }
2109 
2110  /*
2111  * Wait for some more data, and load it. (Note: if the connection has
2112  * been lost, pqWait should return immediately because the socket
2113  * should be read-ready, either with the last server data or with an
2114  * EOF indication. We expect therefore that this won't result in any
2115  * undue delay in reporting a previous write failure.)
2116  */
2117  if (flushResult ||
2118  pqWait(true, false, conn) ||
2119  pqReadData(conn) < 0)
2120  {
2121  /* Report the error saved by pqWait or pqReadData */
2124  return pqPrepareAsyncResult(conn);
2125  }
2126 
2127  /* Parse it. */
2128  parseInput(conn);
2129 
2130  /*
2131  * If we had a write error, but nothing above obtained a query result
2132  * or detected a read error, report the write error.
2133  */
2135  {
2138  return pqPrepareAsyncResult(conn);
2139  }
2140  }
2141 
2142  /* Return the appropriate thing. */
2143  switch (conn->asyncStatus)
2144  {
2145  case PGASYNC_IDLE:
2146  res = NULL; /* query is complete */
2148  {
2149  /*
2150  * We're about to return the NULL that terminates the round of
2151  * results from the current query; prepare to send the results
2152  * of the next query when we're called next.
2153  */
2155  }
2156  break;
2157  case PGASYNC_READY:
2158 
2159  /*
2160  * For any query type other than simple query protocol, we advance
2161  * the command queue here. This is because for simple query
2162  * protocol we can get the READY state multiple times before the
2163  * command is actually complete, since the command string can
2164  * contain many queries. In simple query protocol, the queue
2165  * advance is done by fe-protocol3 when it receives ReadyForQuery.
2166  */
2167  if (conn->cmd_queue_head &&
2172  {
2173  /*
2174  * We're about to send the results of the current query. Set
2175  * us idle now, and ...
2176  */
2178 
2179  /*
2180  * ... in cases when we're sending a pipeline-sync result,
2181  * move queue processing forwards immediately, so that next
2182  * time we're called, we're prepared to return the next result
2183  * received from the server. In all other cases, leave the
2184  * queue state change for next time, so that a terminating
2185  * NULL result is sent.
2186  *
2187  * (In other words: we don't return a NULL after a pipeline
2188  * sync.)
2189  */
2192  }
2193  else
2194  {
2195  /* Set the state back to BUSY, allowing parsing to proceed. */
2197  }
2198  break;
2199  case PGASYNC_READY_MORE:
2201  /* Set the state back to BUSY, allowing parsing to proceed. */
2203  break;
2204  case PGASYNC_COPY_IN:
2206  break;
2207  case PGASYNC_COPY_OUT:
2209  break;
2210  case PGASYNC_COPY_BOTH:
2212  break;
2213  default:
2215  libpq_gettext("unexpected asyncStatus: %d\n"),
2216  (int) conn->asyncStatus);
2218  conn->asyncStatus = PGASYNC_IDLE; /* try to restore valid state */
2220  break;
2221  }
2222 
2223  /* Time to fire PGEVT_RESULTCREATE events, if there are any */
2224  if (res && res->nEvents > 0)
2226 
2227  return res;
2228 }
2229 
2230 /*
2231  * getCopyResult
2232  * Helper for PQgetResult: generate result for COPY-in-progress cases
2233  */
2234 static PGresult *
2236 {
2237  /*
2238  * If the server connection has been lost, don't pretend everything is
2239  * hunky-dory; instead return a PGRES_FATAL_ERROR result, and reset the
2240  * asyncStatus to idle (corresponding to what we'd do if we'd detected I/O
2241  * error in the earlier steps in PQgetResult). The text returned in the
2242  * result is whatever is in conn->errorMessage; we hope that was filled
2243  * with something relevant when the lost connection was detected.
2244  */
2245  if (conn->status != CONNECTION_OK)
2246  {
2249  return pqPrepareAsyncResult(conn);
2250  }
2251 
2252  /* If we have an async result for the COPY, return that */
2253  if (conn->result && conn->result->resultStatus == copytype)
2254  return pqPrepareAsyncResult(conn);
2255 
2256  /* Otherwise, invent a suitable PGresult */
2257  return PQmakeEmptyPGresult(conn, copytype);
2258 }
2259 
2260 
2261 /*
2262  * PQexec
2263  * send a query to the backend and package up the result in a PGresult
2264  *
2265  * If the query was not even sent, return NULL; conn->errorMessage is set to
2266  * a relevant message.
2267  * If the query was sent, a new PGresult is returned (which could indicate
2268  * either success or failure).
2269  * The user is responsible for freeing the PGresult via PQclear()
2270  * when done with it.
2271  */
2272 PGresult *
2273 PQexec(PGconn *conn, const char *query)
2274 {
2275  if (!PQexecStart(conn))
2276  return NULL;
2277  if (!PQsendQuery(conn, query))
2278  return NULL;
2279  return PQexecFinish(conn);
2280 }
2281 
2282 /*
2283  * PQexecParams
2284  * Like PQexec, but use extended query protocol so we can pass parameters
2285  */
2286 PGresult *
2288  const char *command,
2289  int nParams,
2290  const Oid *paramTypes,
2291  const char *const *paramValues,
2292  const int *paramLengths,
2293  const int *paramFormats,
2294  int resultFormat)
2295 {
2296  if (!PQexecStart(conn))
2297  return NULL;
2298  if (!PQsendQueryParams(conn, command,
2299  nParams, paramTypes, paramValues, paramLengths,
2300  paramFormats, resultFormat))
2301  return NULL;
2302  return PQexecFinish(conn);
2303 }
2304 
2305 /*
2306  * PQprepare
2307  * Creates a prepared statement by issuing a Parse message.
2308  *
2309  * If the query was not even sent, return NULL; conn->errorMessage is set to
2310  * a relevant message.
2311  * If the query was sent, a new PGresult is returned (which could indicate
2312  * either success or failure).
2313  * The user is responsible for freeing the PGresult via PQclear()
2314  * when done with it.
2315  */
2316 PGresult *
2318  const char *stmtName, const char *query,
2319  int nParams, const Oid *paramTypes)
2320 {
2321  if (!PQexecStart(conn))
2322  return NULL;
2323  if (!PQsendPrepare(conn, stmtName, query, nParams, paramTypes))
2324  return NULL;
2325  return PQexecFinish(conn);
2326 }
2327 
2328 /*
2329  * PQexecPrepared
2330  * Like PQexec, but execute a previously prepared statement,
2331  * using extended query protocol so we can pass parameters
2332  */
2333 PGresult *
2335  const char *stmtName,
2336  int nParams,
2337  const char *const *paramValues,
2338  const int *paramLengths,
2339  const int *paramFormats,
2340  int resultFormat)
2341 {
2342  if (!PQexecStart(conn))
2343  return NULL;
2344  if (!PQsendQueryPrepared(conn, stmtName,
2345  nParams, paramValues, paramLengths,
2346  paramFormats, resultFormat))
2347  return NULL;
2348  return PQexecFinish(conn);
2349 }
2350 
2351 /*
2352  * Common code for PQexec and sibling routines: prepare to send command
2353  */
2354 static bool
2356 {
2357  PGresult *result;
2358 
2359  if (!conn)
2360  return false;
2361 
2362  /*
2363  * Since this is the beginning of a query cycle, reset the error state.
2364  * However, in pipeline mode with something already queued, the error
2365  * buffer belongs to that command and we shouldn't clear it.
2366  */
2367  if (conn->cmd_queue_head == NULL)
2369 
2371  {
2373  libpq_gettext("synchronous command execution functions are not allowed in pipeline mode\n"));
2374  return false;
2375  }
2376 
2377  /*
2378  * Silently discard any prior query result that application didn't eat.
2379  * This is probably poor design, but it's here for backward compatibility.
2380  */
2381  while ((result = PQgetResult(conn)) != NULL)
2382  {
2383  ExecStatusType resultStatus = result->resultStatus;
2384 
2385  PQclear(result); /* only need its status */
2386  if (resultStatus == PGRES_COPY_IN)
2387  {
2388  /* get out of a COPY IN state */
2389  if (PQputCopyEnd(conn,
2390  libpq_gettext("COPY terminated by new PQexec")) < 0)
2391  return false;
2392  /* keep waiting to swallow the copy's failure message */
2393  }
2394  else if (resultStatus == PGRES_COPY_OUT)
2395  {
2396  /*
2397  * Get out of a COPY OUT state: we just switch back to BUSY and
2398  * allow the remaining COPY data to be dropped on the floor.
2399  */
2401  /* keep waiting to swallow the copy's completion message */
2402  }
2403  else if (resultStatus == PGRES_COPY_BOTH)
2404  {
2405  /* We don't allow PQexec during COPY BOTH */
2407  libpq_gettext("PQexec not allowed during COPY BOTH\n"));
2408  return false;
2409  }
2410  /* check for loss of connection, too */
2411  if (conn->status == CONNECTION_BAD)
2412  return false;
2413  }
2414 
2415  /* OK to send a command */
2416  return true;
2417 }
2418 
2419 /*
2420  * Common code for PQexec and sibling routines: wait for command result
2421  */
2422 static PGresult *
2424 {
2425  PGresult *result;
2426  PGresult *lastResult;
2427 
2428  /*
2429  * For backwards compatibility, return the last result if there are more
2430  * than one. (We used to have logic here to concatenate successive error
2431  * messages, but now that happens automatically, since conn->errorMessage
2432  * will continue to accumulate errors throughout this loop.)
2433  *
2434  * We have to stop if we see copy in/out/both, however. We will resume
2435  * parsing after application performs the data transfer.
2436  *
2437  * Also stop if the connection is lost (else we'll loop infinitely).
2438  */
2439  lastResult = NULL;
2440  while ((result = PQgetResult(conn)) != NULL)
2441  {
2442  if (lastResult)
2443  PQclear(lastResult);
2444  lastResult = result;
2445  if (result->resultStatus == PGRES_COPY_IN ||
2446  result->resultStatus == PGRES_COPY_OUT ||
2447  result->resultStatus == PGRES_COPY_BOTH ||
2449  break;
2450  }
2451 
2452  return lastResult;
2453 }
2454 
2455 /*
2456  * PQdescribePrepared
2457  * Obtain information about a previously prepared statement
2458  *
2459  * If the query was not even sent, return NULL; conn->errorMessage is set to
2460  * a relevant message.
2461  * If the query was sent, a new PGresult is returned (which could indicate
2462  * either success or failure). On success, the PGresult contains status
2463  * PGRES_COMMAND_OK, and its parameter and column-heading fields describe
2464  * the statement's inputs and outputs respectively.
2465  * The user is responsible for freeing the PGresult via PQclear()
2466  * when done with it.
2467  */
2468 PGresult *
2469 PQdescribePrepared(PGconn *conn, const char *stmt)
2470 {
2471  if (!PQexecStart(conn))
2472  return NULL;
2473  if (!PQsendDescribe(conn, 'S', stmt))
2474  return NULL;
2475  return PQexecFinish(conn);
2476 }
2477 
2478 /*
2479  * PQdescribePortal
2480  * Obtain information about a previously created portal
2481  *
2482  * This is much like PQdescribePrepared, except that no parameter info is
2483  * returned. Note that at the moment, libpq doesn't really expose portals
2484  * to the client; but this can be used with a portal created by a SQL
2485  * DECLARE CURSOR command.
2486  */
2487 PGresult *
2488 PQdescribePortal(PGconn *conn, const char *portal)
2489 {
2490  if (!PQexecStart(conn))
2491  return NULL;
2492  if (!PQsendDescribe(conn, 'P', portal))
2493  return NULL;
2494  return PQexecFinish(conn);
2495 }
2496 
2497 /*
2498  * PQsendDescribePrepared
2499  * Submit a Describe Statement command, but don't wait for it to finish
2500  *
2501  * Returns: 1 if successfully submitted
2502  * 0 if error (conn->errorMessage is set)
2503  */
2504 int
2506 {
2507  return PQsendDescribe(conn, 'S', stmt);
2508 }
2509 
2510 /*
2511  * PQsendDescribePortal
2512  * Submit a Describe Portal command, but don't wait for it to finish
2513  *
2514  * Returns: 1 if successfully submitted
2515  * 0 if error (conn->errorMessage is set)
2516  */
2517 int
2518 PQsendDescribePortal(PGconn *conn, const char *portal)
2519 {
2520  return PQsendDescribe(conn, 'P', portal);
2521 }
2522 
2523 /*
2524  * PQsendDescribe
2525  * Common code to send a Describe command
2526  *
2527  * Available options for desc_type are
2528  * 'S' to describe a prepared statement; or
2529  * 'P' to describe a portal.
2530  * Returns 1 on success and 0 on failure.
2531  */
2532 static int
2533 PQsendDescribe(PGconn *conn, char desc_type, const char *desc_target)
2534 {
2535  PGcmdQueueEntry *entry = NULL;
2536 
2537  /* Treat null desc_target as empty string */
2538  if (!desc_target)
2539  desc_target = "";
2540 
2541  if (!PQsendQueryStart(conn, true))
2542  return 0;
2543 
2544  entry = pqAllocCmdQueueEntry(conn);
2545  if (entry == NULL)
2546  return 0; /* error msg already set */
2547 
2548  /* construct the Describe message */
2549  if (pqPutMsgStart('D', conn) < 0 ||
2550  pqPutc(desc_type, conn) < 0 ||
2551  pqPuts(desc_target, conn) < 0 ||
2552  pqPutMsgEnd(conn) < 0)
2553  goto sendFailed;
2554 
2555  /* construct the Sync message */
2557  {
2558  if (pqPutMsgStart('S', conn) < 0 ||
2559  pqPutMsgEnd(conn) < 0)
2560  goto sendFailed;
2561  }
2562 
2563  /* remember we are doing a Describe */
2564  entry->queryclass = PGQUERY_DESCRIBE;
2565 
2566  /*
2567  * Give the data a push (in pipeline mode, only if we're past the size
2568  * threshold). In nonblock mode, don't complain if we're unable to send
2569  * it all; PQgetResult() will do any additional flushing needed.
2570  */
2571  if (pqPipelineFlush(conn) < 0)
2572  goto sendFailed;
2573 
2574  /* OK, it's launched! */
2575  pqAppendCmdQueueEntry(conn, entry);
2576 
2577  return 1;
2578 
2579 sendFailed:
2580  pqRecycleCmdQueueEntry(conn, entry);
2581  /* error message should be set up already */
2582  return 0;
2583 }
2584 
2585 /*
2586  * PQnotifies
2587  * returns a PGnotify* structure of the latest async notification
2588  * that has not yet been handled
2589  *
2590  * returns NULL, if there is currently
2591  * no unhandled async notification from the backend
2592  *
2593  * the CALLER is responsible for FREE'ing the structure returned
2594  *
2595  * Note that this function does not read any new data from the socket;
2596  * so usually, caller should call PQconsumeInput() first.
2597  */
2598 PGnotify *
2600 {
2601  PGnotify *event;
2602 
2603  if (!conn)
2604  return NULL;
2605 
2606  /* Parse any available data to see if we can extract NOTIFY messages. */
2607  parseInput(conn);
2608 
2609  event = conn->notifyHead;
2610  if (event)
2611  {
2612  conn->notifyHead = event->next;
2613  if (!conn->notifyHead)
2614  conn->notifyTail = NULL;
2615  event->next = NULL; /* don't let app see the internal state */
2616  }
2617  return event;
2618 }
2619 
2620 /*
2621  * PQputCopyData - send some data to the backend during COPY IN or COPY BOTH
2622  *
2623  * Returns 1 if successful, 0 if data could not be sent (only possible
2624  * in nonblock mode), or -1 if an error occurs.
2625  */
2626 int
2627 PQputCopyData(PGconn *conn, const char *buffer, int nbytes)
2628 {
2629  if (!conn)
2630  return -1;
2631  if (conn->asyncStatus != PGASYNC_COPY_IN &&
2633  {
2635  libpq_gettext("no COPY in progress\n"));
2636  return -1;
2637  }
2638 
2639  /*
2640  * Process any NOTICE or NOTIFY messages that might be pending in the
2641  * input buffer. Since the server might generate many notices during the
2642  * COPY, we want to clean those out reasonably promptly to prevent
2643  * indefinite expansion of the input buffer. (Note: the actual read of
2644  * input data into the input buffer happens down inside pqSendSome, but
2645  * it's not authorized to get rid of the data again.)
2646  */
2647  parseInput(conn);
2648 
2649  if (nbytes > 0)
2650  {
2651  /*
2652  * Try to flush any previously sent data in preference to growing the
2653  * output buffer. If we can't enlarge the buffer enough to hold the
2654  * data, return 0 in the nonblock case, else hard error. (For
2655  * simplicity, always assume 5 bytes of overhead.)
2656  */
2657  if ((conn->outBufSize - conn->outCount - 5) < nbytes)
2658  {
2659  if (pqFlush(conn) < 0)
2660  return -1;
2661  if (pqCheckOutBufferSpace(conn->outCount + 5 + (size_t) nbytes,
2662  conn))
2663  return pqIsnonblocking(conn) ? 0 : -1;
2664  }
2665  /* Send the data (too simple to delegate to fe-protocol files) */
2666  if (pqPutMsgStart('d', conn) < 0 ||
2667  pqPutnchar(buffer, nbytes, conn) < 0 ||
2668  pqPutMsgEnd(conn) < 0)
2669  return -1;
2670  }
2671  return 1;
2672 }
2673 
2674 /*
2675  * PQputCopyEnd - send EOF indication to the backend during COPY IN
2676  *
2677  * After calling this, use PQgetResult() to check command completion status.
2678  *
2679  * Returns 1 if successful, 0 if data could not be sent (only possible
2680  * in nonblock mode), or -1 if an error occurs.
2681  */
2682 int
2683 PQputCopyEnd(PGconn *conn, const char *errormsg)
2684 {
2685  if (!conn)
2686  return -1;
2687  if (conn->asyncStatus != PGASYNC_COPY_IN &&
2689  {
2691  libpq_gettext("no COPY in progress\n"));
2692  return -1;
2693  }
2694 
2695  /*
2696  * Send the COPY END indicator. This is simple enough that we don't
2697  * bother delegating it to the fe-protocol files.
2698  */
2699  if (errormsg)
2700  {
2701  /* Send COPY FAIL */
2702  if (pqPutMsgStart('f', conn) < 0 ||
2703  pqPuts(errormsg, conn) < 0 ||
2704  pqPutMsgEnd(conn) < 0)
2705  return -1;
2706  }
2707  else
2708  {
2709  /* Send COPY DONE */
2710  if (pqPutMsgStart('c', conn) < 0 ||
2711  pqPutMsgEnd(conn) < 0)
2712  return -1;
2713  }
2714 
2715  /*
2716  * If we sent the COPY command in extended-query mode, we must issue a
2717  * Sync as well.
2718  */
2719  if (conn->cmd_queue_head &&
2721  {
2722  if (pqPutMsgStart('S', conn) < 0 ||
2723  pqPutMsgEnd(conn) < 0)
2724  return -1;
2725  }
2726 
2727  /* Return to active duty */
2730  else
2732 
2733  /* Try to flush data */
2734  if (pqFlush(conn) < 0)
2735  return -1;
2736 
2737  return 1;
2738 }
2739 
2740 /*
2741  * PQgetCopyData - read a row of data from the backend during COPY OUT
2742  * or COPY BOTH
2743  *
2744  * If successful, sets *buffer to point to a malloc'd row of data, and
2745  * returns row length (always > 0) as result.
2746  * Returns 0 if no row available yet (only possible if async is true),
2747  * -1 if end of copy (consult PQgetResult), or -2 if error (consult
2748  * PQerrorMessage).
2749  */
2750 int
2751 PQgetCopyData(PGconn *conn, char **buffer, int async)
2752 {
2753  *buffer = NULL; /* for all failure cases */
2754  if (!conn)
2755  return -2;
2756  if (conn->asyncStatus != PGASYNC_COPY_OUT &&
2758  {
2760  libpq_gettext("no COPY in progress\n"));
2761  return -2;
2762  }
2763  return pqGetCopyData3(conn, buffer, async);
2764 }
2765 
2766 /*
2767  * PQgetline - gets a newline-terminated string from the backend.
2768  *
2769  * Chiefly here so that applications can use "COPY <rel> to stdout"
2770  * and read the output string. Returns a null-terminated string in s.
2771  *
2772  * XXX this routine is now deprecated, because it can't handle binary data.
2773  * If called during a COPY BINARY we return EOF.
2774  *
2775  * PQgetline reads up to maxlen-1 characters (like fgets(3)) but strips
2776  * the terminating \n (like gets(3)).
2777  *
2778  * CAUTION: the caller is responsible for detecting the end-of-copy signal
2779  * (a line containing just "\.") when using this routine.
2780  *
2781  * RETURNS:
2782  * EOF if error (eg, invalid arguments are given)
2783  * 0 if EOL is reached (i.e., \n has been read)
2784  * (this is required for backward-compatibility -- this
2785  * routine used to always return EOF or 0, assuming that
2786  * the line ended within maxlen bytes.)
2787  * 1 in other cases (i.e., the buffer was filled before \n is reached)
2788  */
2789 int
2790 PQgetline(PGconn *conn, char *s, int maxlen)
2791 {
2792  if (!s || maxlen <= 0)
2793  return EOF;
2794  *s = '\0';
2795  /* maxlen must be at least 3 to hold the \. terminator! */
2796  if (maxlen < 3)
2797  return EOF;
2798 
2799  if (!conn)
2800  return EOF;
2801 
2802  return pqGetline3(conn, s, maxlen);
2803 }
2804 
2805 /*
2806  * PQgetlineAsync - gets a COPY data row without blocking.
2807  *
2808  * This routine is for applications that want to do "COPY <rel> to stdout"
2809  * asynchronously, that is without blocking. Having issued the COPY command
2810  * and gotten a PGRES_COPY_OUT response, the app should call PQconsumeInput
2811  * and this routine until the end-of-data signal is detected. Unlike
2812  * PQgetline, this routine takes responsibility for detecting end-of-data.
2813  *
2814  * On each call, PQgetlineAsync will return data if a complete data row
2815  * is available in libpq's input buffer. Otherwise, no data is returned
2816  * until the rest of the row arrives.
2817  *
2818  * If -1 is returned, the end-of-data signal has been recognized (and removed
2819  * from libpq's input buffer). The caller *must* next call PQendcopy and
2820  * then return to normal processing.
2821  *
2822  * RETURNS:
2823  * -1 if the end-of-copy-data marker has been recognized
2824  * 0 if no data is available
2825  * >0 the number of bytes returned.
2826  *
2827  * The data returned will not extend beyond a data-row boundary. If possible
2828  * a whole row will be returned at one time. But if the buffer offered by
2829  * the caller is too small to hold a row sent by the backend, then a partial
2830  * data row will be returned. In text mode this can be detected by testing
2831  * whether the last returned byte is '\n' or not.
2832  *
2833  * The returned data is *not* null-terminated.
2834  */
2835 
2836 int
2837 PQgetlineAsync(PGconn *conn, char *buffer, int bufsize)
2838 {
2839  if (!conn)
2840  return -1;
2841 
2842  return pqGetlineAsync3(conn, buffer, bufsize);
2843 }
2844 
2845 /*
2846  * PQputline -- sends a string to the backend during COPY IN.
2847  * Returns 0 if OK, EOF if not.
2848  *
2849  * This is deprecated primarily because the return convention doesn't allow
2850  * caller to tell the difference between a hard error and a nonblock-mode
2851  * send failure.
2852  */
2853 int
2854 PQputline(PGconn *conn, const char *s)
2855 {
2856  return PQputnbytes(conn, s, strlen(s));
2857 }
2858 
2859 /*
2860  * PQputnbytes -- like PQputline, but buffer need not be null-terminated.
2861  * Returns 0 if OK, EOF if not.
2862  */
2863 int
2864 PQputnbytes(PGconn *conn, const char *buffer, int nbytes)
2865 {
2866  if (PQputCopyData(conn, buffer, nbytes) > 0)
2867  return 0;
2868  else
2869  return EOF;
2870 }
2871 
2872 /*
2873  * PQendcopy
2874  * After completing the data transfer portion of a copy in/out,
2875  * the application must call this routine to finish the command protocol.
2876  *
2877  * This is deprecated; it's cleaner to use PQgetResult to get the transfer
2878  * status.
2879  *
2880  * RETURNS:
2881  * 0 on success
2882  * 1 on failure
2883  */
2884 int
2886 {
2887  if (!conn)
2888  return 0;
2889 
2890  return pqEndcopy3(conn);
2891 }
2892 
2893 
2894 /* ----------------
2895  * PQfn - Send a function call to the POSTGRES backend.
2896  *
2897  * conn : backend connection
2898  * fnid : OID of function to be called
2899  * result_buf : pointer to result buffer
2900  * result_len : actual length of result is returned here
2901  * result_is_int : If the result is an integer, this must be 1,
2902  * otherwise this should be 0
2903  * args : pointer to an array of function arguments
2904  * (each has length, if integer, and value/pointer)
2905  * nargs : # of arguments in args array.
2906  *
2907  * RETURNS
2908  * PGresult with status = PGRES_COMMAND_OK if successful.
2909  * *result_len is > 0 if there is a return value, 0 if not.
2910  * PGresult with status = PGRES_FATAL_ERROR if backend returns an error.
2911  * NULL on communications failure. conn->errorMessage will be set.
2912  * ----------------
2913  */
2914 
2915 PGresult *
2917  int fnid,
2918  int *result_buf,
2919  int *result_len,
2920  int result_is_int,
2921  const PQArgBlock *args,
2922  int nargs)
2923 {
2924  *result_len = 0;
2925 
2926  if (!conn)
2927  return NULL;
2928 
2929  /*
2930  * Since this is the beginning of a query cycle, reset the error state.
2931  * However, in pipeline mode with something already queued, the error
2932  * buffer belongs to that command and we shouldn't clear it.
2933  */
2934  if (conn->cmd_queue_head == NULL)
2936 
2938  {
2940  libpq_gettext("PQfn not allowed in pipeline mode\n"));
2941  return NULL;
2942  }
2943 
2946  {
2948  libpq_gettext("connection in wrong state\n"));
2949  return NULL;
2950  }
2951 
2952  return pqFunctionCall3(conn, fnid,
2953  result_buf, result_len,
2954  result_is_int,
2955  args, nargs);
2956 }
2957 
2958 /* ====== Pipeline mode support ======== */
2959 
2960 /*
2961  * PQenterPipelineMode
2962  * Put an idle connection in pipeline mode.
2963  *
2964  * Returns 1 on success. On failure, errorMessage is set and 0 is returned.
2965  *
2966  * Commands submitted after this can be pipelined on the connection;
2967  * there's no requirement to wait for one to finish before the next is
2968  * dispatched.
2969  *
2970  * Queuing of a new query or syncing during COPY is not allowed.
2971  *
2972  * A set of commands is terminated by a PQpipelineSync. Multiple sync
2973  * points can be established while in pipeline mode. Pipeline mode can
2974  * be exited by calling PQexitPipelineMode() once all results are processed.
2975  *
2976  * This doesn't actually send anything on the wire, it just puts libpq
2977  * into a state where it can pipeline work.
2978  */
2979 int
2981 {
2982  if (!conn)
2983  return 0;
2984 
2985  /* succeed with no action if already in pipeline mode */
2987  return 1;
2988 
2989  if (conn->asyncStatus != PGASYNC_IDLE)
2990  {
2992  libpq_gettext("cannot enter pipeline mode, connection not idle\n"));
2993  return 0;
2994  }
2995 
2997 
2998  return 1;
2999 }
3000 
3001 /*
3002  * PQexitPipelineMode
3003  * End pipeline mode and return to normal command mode.
3004  *
3005  * Returns 1 in success (pipeline mode successfully ended, or not in pipeline
3006  * mode).
3007  *
3008  * Returns 0 if in pipeline mode and cannot be ended yet. Error message will
3009  * be set.
3010  */
3011 int
3013 {
3014  if (!conn)
3015  return 0;
3016 
3018  return 1;
3019 
3020  switch (conn->asyncStatus)
3021  {
3022  case PGASYNC_READY:
3023  case PGASYNC_READY_MORE:
3024  /* there are some uncollected results */
3026  libpq_gettext("cannot exit pipeline mode with uncollected results\n"));
3027  return 0;
3028 
3029  case PGASYNC_BUSY:
3031  libpq_gettext("cannot exit pipeline mode while busy\n"));
3032  return 0;
3033 
3034  default:
3035  /* OK */
3036  break;
3037  }
3038 
3039  /* still work to process */
3040  if (conn->cmd_queue_head != NULL)
3041  {
3043  libpq_gettext("cannot exit pipeline mode with uncollected results\n"));
3044  return 0;
3045  }
3046 
3049 
3050  /* Flush any pending data in out buffer */
3051  if (pqFlush(conn) < 0)
3052  return 0; /* error message is setup already */
3053  return 1;
3054 }
3055 
3056 /*
3057  * pqCommandQueueAdvance
3058  * Remove one query from the command queue, when we receive
3059  * all results from the server that pertain to it.
3060  */
3061 void
3063 {
3064  PGcmdQueueEntry *prevquery;
3065 
3066  if (conn->cmd_queue_head == NULL)
3067  return;
3068 
3069  /* delink from queue */
3070  prevquery = conn->cmd_queue_head;
3072 
3073  /* and make it recyclable */
3074  prevquery->next = NULL;
3075  pqRecycleCmdQueueEntry(conn, prevquery);
3076 }
3077 
3078 /*
3079  * pqPipelineProcessQueue: subroutine for PQgetResult
3080  * In pipeline mode, start processing the results of the next query in the queue.
3081  */
3082 static void
3084 {
3085  switch (conn->asyncStatus)
3086  {
3087  case PGASYNC_COPY_IN:
3088  case PGASYNC_COPY_OUT:
3089  case PGASYNC_COPY_BOTH:
3090  case PGASYNC_READY:
3091  case PGASYNC_READY_MORE:
3092  case PGASYNC_BUSY:
3093  /* client still has to process current query or results */
3094  return;
3095  case PGASYNC_IDLE:
3096  /* next query please */
3097  break;
3098  }
3099 
3100  /* Nothing to do if not in pipeline mode, or queue is empty */
3102  conn->cmd_queue_head == NULL)
3103  return;
3104 
3105  /*
3106  * Reset the error state. This and the next couple of steps correspond to
3107  * what PQsendQueryStart didn't do for this query.
3108  */
3110 
3111  /* Initialize async result-accumulation state */
3113 
3114  /*
3115  * Reset single-row processing mode. (Client has to set it up for each
3116  * query, if desired.)
3117  */
3118  conn->singleRowMode = false;
3119 
3122  {
3123  /*
3124  * In an aborted pipeline we don't get anything from the server for
3125  * each result; we're just discarding commands from the queue until we
3126  * get to the next sync from the server.
3127  *
3128  * The PGRES_PIPELINE_ABORTED results tell the client that its queries
3129  * got aborted.
3130  */
3132  if (!conn->result)
3133  {
3135  libpq_gettext("out of memory\n"));
3137  return;
3138  }
3140  }
3141  else
3142  {
3143  /* allow parsing to continue */
3145  }
3146 }
3147 
3148 /*
3149  * PQpipelineSync
3150  * Send a Sync message as part of a pipeline, and flush to server
3151  *
3152  * It's legal to start submitting more commands in the pipeline immediately,
3153  * without waiting for the results of the current pipeline. There's no need to
3154  * end pipeline mode and start it again.
3155  *
3156  * If a command in a pipeline fails, every subsequent command up to and including
3157  * the result to the Sync message sent by PQpipelineSync gets set to
3158  * PGRES_PIPELINE_ABORTED state. If the whole pipeline is processed without
3159  * error, a PGresult with PGRES_PIPELINE_SYNC is produced.
3160  *
3161  * Queries can already have been sent before PQpipelineSync is called, but
3162  * PQpipelineSync need to be called before retrieving command results.
3163  *
3164  * The connection will remain in pipeline mode and unavailable for new
3165  * synchronous command execution functions until all results from the pipeline
3166  * are processed by the client.
3167  */
3168 int
3170 {
3171  PGcmdQueueEntry *entry;
3172 
3173  if (!conn)
3174  return 0;
3175 
3177  {
3179  libpq_gettext("cannot send pipeline when not in pipeline mode\n"));
3180  return 0;
3181  }
3182 
3183  switch (conn->asyncStatus)
3184  {
3185  case PGASYNC_COPY_IN:
3186  case PGASYNC_COPY_OUT:
3187  case PGASYNC_COPY_BOTH:
3188  /* should be unreachable */
3190  "internal error: cannot send pipeline while in COPY\n");
3191  return 0;
3192  case PGASYNC_READY:
3193  case PGASYNC_READY_MORE:
3194  case PGASYNC_BUSY:
3195  case PGASYNC_IDLE:
3196  /* OK to send sync */
3197  break;
3198  }
3199 
3200  entry = pqAllocCmdQueueEntry(conn);
3201  if (entry == NULL)
3202  return 0; /* error msg already set */
3203 
3204  entry->queryclass = PGQUERY_SYNC;
3205  entry->query = NULL;
3206 
3207  /* construct the Sync message */
3208  if (pqPutMsgStart('S', conn) < 0 ||
3209  pqPutMsgEnd(conn) < 0)
3210  goto sendFailed;
3211 
3212  /*
3213  * Give the data a push. In nonblock mode, don't complain if we're unable
3214  * to send it all; PQgetResult() will do any additional flushing needed.
3215  */
3216  if (PQflush(conn) < 0)
3217  goto sendFailed;
3218 
3219  /* OK, it's launched! */
3220  pqAppendCmdQueueEntry(conn, entry);
3221 
3222  return 1;
3223 
3224 sendFailed:
3225  pqRecycleCmdQueueEntry(conn, entry);
3226  /* error message should be set up already */
3227  return 0;
3228 }
3229 
3230 /*
3231  * PQsendFlushRequest
3232  * Send request for server to flush its buffer. Useful in pipeline
3233  * mode when a sync point is not desired.
3234  */
3235 int
3237 {
3238  if (!conn)
3239  return 0;
3240 
3241  /* Don't try to send if we know there's no live connection. */
3242  if (conn->status != CONNECTION_OK)
3243  {
3245  libpq_gettext("no connection to the server\n"));
3246  return 0;
3247  }
3248 
3249  /* Can't send while already busy, either, unless enqueuing for later */
3250  if (conn->asyncStatus != PGASYNC_IDLE &&
3252  {
3254  libpq_gettext("another command is already in progress\n"));
3255  return 0;
3256  }
3257 
3258  if (pqPutMsgStart('H', conn) < 0 ||
3259  pqPutMsgEnd(conn) < 0)
3260  {
3261  return 0;
3262  }
3263 
3264  return 1;
3265 }
3266 
3267 /* ====== accessor funcs for PGresult ======== */
3268 
3271 {
3272  if (!res)
3273  return PGRES_FATAL_ERROR;
3274  return res->resultStatus;
3275 }
3276 
3277 char *
3279 {
3280  if ((unsigned int) status >= lengthof(pgresStatus))
3281  return libpq_gettext("invalid ExecStatusType code");
3282  return pgresStatus[status];
3283 }
3284 
3285 char *
3287 {
3288  if (!res || !res->errMsg)
3289  return "";
3290  return res->errMsg;
3291 }
3292 
3293 char *
3295  PGVerbosity verbosity,
3296  PGContextVisibility show_context)
3297 {
3298  PQExpBufferData workBuf;
3299 
3300  /*
3301  * Because the caller is expected to free the result string, we must
3302  * strdup any constant result. We use plain strdup and document that
3303  * callers should expect NULL if out-of-memory.
3304  */
3305  if (!res ||
3308  return strdup(libpq_gettext("PGresult is not an error result\n"));
3309 
3310  initPQExpBuffer(&workBuf);
3311 
3312  pqBuildErrorMessage3(&workBuf, res, verbosity, show_context);
3313 
3314  /* If insufficient memory to format the message, fail cleanly */
3315  if (PQExpBufferDataBroken(workBuf))
3316  {
3317  termPQExpBuffer(&workBuf);
3318  return strdup(libpq_gettext("out of memory\n"));
3319  }
3320 
3321  return workBuf.data;
3322 }
3323 
3324 char *
3325 PQresultErrorField(const PGresult *res, int fieldcode)
3326 {
3327  PGMessageField *pfield;
3328 
3329  if (!res)
3330  return NULL;
3331  for (pfield = res->errFields; pfield != NULL; pfield = pfield->next)
3332  {
3333  if (pfield->code == fieldcode)
3334  return pfield->contents;
3335  }
3336  return NULL;
3337 }
3338 
3339 int
3341 {
3342  if (!res)
3343  return 0;
3344  return res->ntups;
3345 }
3346 
3347 int
3349 {
3350  if (!res)
3351  return 0;
3352  return res->numAttributes;
3353 }
3354 
3355 int
3357 {
3358  if (!res)
3359  return 0;
3360  return res->binary;
3361 }
3362 
3363 /*
3364  * Helper routines to range-check field numbers and tuple numbers.
3365  * Return true if OK, false if not
3366  */
3367 
3368 static int
3369 check_field_number(const PGresult *res, int field_num)
3370 {
3371  if (!res)
3372  return false; /* no way to display error message... */
3373  if (field_num < 0 || field_num >= res->numAttributes)
3374  {
3376  "column number %d is out of range 0..%d",
3377  field_num, res->numAttributes - 1);
3378  return false;
3379  }
3380  return true;
3381 }
3382 
3383 static int
3385  int tup_num, int field_num)
3386 {
3387  if (!res)
3388  return false; /* no way to display error message... */
3389  if (tup_num < 0 || tup_num >= res->ntups)
3390  {
3392  "row number %d is out of range 0..%d",
3393  tup_num, res->ntups - 1);
3394  return false;
3395  }
3396  if (field_num < 0 || field_num >= res->numAttributes)
3397  {
3399  "column number %d is out of range 0..%d",
3400  field_num, res->numAttributes - 1);
3401  return false;
3402  }
3403  return true;
3404 }
3405 
3406 static int
3407 check_param_number(const PGresult *res, int param_num)
3408 {
3409  if (!res)
3410  return false; /* no way to display error message... */
3411  if (param_num < 0 || param_num >= res->numParameters)
3412  {
3414  "parameter number %d is out of range 0..%d",
3415  param_num, res->numParameters - 1);
3416  return false;
3417  }
3418 
3419  return true;
3420 }
3421 
3422 /*
3423  * returns NULL if the field_num is invalid
3424  */
3425 char *
3426 PQfname(const PGresult *res, int field_num)
3427 {
3428  if (!check_field_number(res, field_num))
3429  return NULL;
3430  if (res->attDescs)
3431  return res->attDescs[field_num].name;
3432  else
3433  return NULL;
3434 }
3435 
3436 /*
3437  * PQfnumber: find column number given column name
3438  *
3439  * The column name is parsed as if it were in a SQL statement, including
3440  * case-folding and double-quote processing. But note a possible gotcha:
3441  * downcasing in the frontend might follow different locale rules than
3442  * downcasing in the backend...
3443  *
3444  * Returns -1 if no match. In the present backend it is also possible
3445  * to have multiple matches, in which case the first one is found.
3446  */
3447 int
3448 PQfnumber(const PGresult *res, const char *field_name)
3449 {
3450  char *field_case;
3451  bool in_quotes;
3452  bool all_lower = true;
3453  const char *iptr;
3454  char *optr;
3455  int i;
3456 
3457  if (!res)
3458  return -1;
3459 
3460  /*
3461  * Note: it is correct to reject a zero-length input string; the proper
3462  * input to match a zero-length field name would be "".
3463  */
3464  if (field_name == NULL ||
3465  field_name[0] == '\0' ||
3466  res->attDescs == NULL)
3467  return -1;
3468 
3469  /*
3470  * Check if we can avoid the strdup() and related work because the
3471  * passed-in string wouldn't be changed before we do the check anyway.
3472  */
3473  for (iptr = field_name; *iptr; iptr++)
3474  {
3475  char c = *iptr;
3476 
3477  if (c == '"' || c != pg_tolower((unsigned char) c))
3478  {
3479  all_lower = false;
3480  break;
3481  }
3482  }
3483 
3484  if (all_lower)
3485  for (i = 0; i < res->numAttributes; i++)
3486  if (strcmp(field_name, res->attDescs[i].name) == 0)
3487  return i;
3488 
3489  /* Fall through to the normal check if that didn't work out. */
3490 
3491  /*
3492  * Note: this code will not reject partially quoted strings, eg
3493  * foo"BAR"foo will become fooBARfoo when it probably ought to be an error
3494  * condition.
3495  */
3496  field_case = strdup(field_name);
3497  if (field_case == NULL)
3498  return -1; /* grotty */
3499 
3500  in_quotes = false;
3501  optr = field_case;
3502  for (iptr = field_case; *iptr; iptr++)
3503  {
3504  char c = *iptr;
3505 
3506  if (in_quotes)
3507  {
3508  if (c == '"')
3509  {
3510  if (iptr[1] == '"')
3511  {
3512  /* doubled quotes become a single quote */
3513  *optr++ = '"';
3514  iptr++;
3515  }
3516  else
3517  in_quotes = false;
3518  }
3519  else
3520  *optr++ = c;
3521  }
3522  else if (c == '"')
3523  in_quotes = true;
3524  else
3525  {
3526  c = pg_tolower((unsigned char) c);
3527  *optr++ = c;
3528  }
3529  }
3530  *optr = '\0';
3531 
3532  for (i = 0; i < res->numAttributes; i++)
3533  {
3534  if (strcmp(field_case, res->attDescs[i].name) == 0)
3535  {
3536  free(field_case);
3537  return i;
3538  }
3539  }
3540  free(field_case);
3541  return -1;
3542 }
3543 
3544 Oid
3545 PQftable(const PGresult *res, int field_num)
3546 {
3547  if (!check_field_number(res, field_num))
3548  return InvalidOid;
3549  if (res->attDescs)
3550  return res->attDescs[field_num].tableid;
3551  else
3552  return InvalidOid;
3553 }
3554 
3555 int
3556 PQftablecol(const PGresult *res, int field_num)
3557 {
3558  if (!check_field_number(res, field_num))
3559  return 0;
3560  if (res->attDescs)
3561  return res->attDescs[field_num].columnid;
3562  else
3563  return 0;
3564 }
3565 
3566 int
3567 PQfformat(const PGresult *res, int field_num)
3568 {
3569  if (!check_field_number(res, field_num))
3570  return 0;
3571  if (res->attDescs)
3572  return res->attDescs[field_num].format;
3573  else
3574  return 0;
3575 }
3576 
3577 Oid
3578 PQftype(const PGresult *res, int field_num)
3579 {
3580  if (!check_field_number(res, field_num))
3581  return InvalidOid;
3582  if (res->attDescs)
3583  return res->attDescs[field_num].typid;
3584  else
3585  return InvalidOid;
3586 }
3587 
3588 int
3589 PQfsize(const PGresult *res, int field_num)
3590 {
3591  if (!check_field_number(res, field_num))
3592  return 0;
3593  if (res->attDescs)
3594  return res->attDescs[field_num].typlen;
3595  else
3596  return 0;
3597 }
3598 
3599 int
3600 PQfmod(const PGresult *res, int field_num)
3601 {
3602  if (!check_field_number(res, field_num))
3603  return 0;
3604  if (res->attDescs)
3605  return res->attDescs[field_num].atttypmod;
3606  else
3607  return 0;
3608 }
3609 
3610 char *
3612 {
3613  if (!res)
3614  return NULL;
3615  return res->cmdStatus;
3616 }
3617 
3618 /*
3619  * PQoidStatus -
3620  * if the last command was an INSERT, return the oid string
3621  * if not, return ""
3622  */
3623 char *
3625 {
3626  /*
3627  * This must be enough to hold the result. Don't laugh, this is better
3628  * than what this function used to do.
3629  */
3630  static char buf[24];
3631 
3632  size_t len;
3633 
3634  if (!res || strncmp(res->cmdStatus, "INSERT ", 7) != 0)
3635  return "";
3636 
3637  len = strspn(res->cmdStatus + 7, "0123456789");
3638  if (len > sizeof(buf) - 1)
3639  len = sizeof(buf) - 1;
3640  memcpy(buf, res->cmdStatus + 7, len);
3641  buf[len] = '\0';
3642 
3643  return buf;
3644 }
3645 
3646 /*
3647  * PQoidValue -
3648  * a perhaps preferable form of the above which just returns
3649  * an Oid type
3650  */
3651 Oid
3653 {
3654  char *endptr = NULL;
3655  unsigned long result;
3656 
3657  if (!res ||
3658  strncmp(res->cmdStatus, "INSERT ", 7) != 0 ||
3659  res->cmdStatus[7] < '0' ||
3660  res->cmdStatus[7] > '9')
3661  return InvalidOid;
3662 
3663  result = strtoul(res->cmdStatus + 7, &endptr, 10);
3664 
3665  if (!endptr || (*endptr != ' ' && *endptr != '\0'))
3666  return InvalidOid;
3667  else
3668  return (Oid) result;
3669 }
3670 
3671 
3672 /*
3673  * PQcmdTuples -
3674  * If the last command was INSERT/UPDATE/DELETE/MERGE/MOVE/FETCH/COPY,
3675  * return a string containing the number of inserted/affected tuples.
3676  * If not, return "".
3677  *
3678  * XXX: this should probably return an int
3679  */
3680 char *
3682 {
3683  char *p,
3684  *c;
3685 
3686  if (!res)
3687  return "";
3688 
3689  if (strncmp(res->cmdStatus, "INSERT ", 7) == 0)
3690  {
3691  p = res->cmdStatus + 7;
3692  /* INSERT: skip oid and space */
3693  while (*p && *p != ' ')
3694  p++;
3695  if (*p == 0)
3696  goto interpret_error; /* no space? */
3697  p++;
3698  }
3699  else if (strncmp(res->cmdStatus, "SELECT ", 7) == 0 ||
3700  strncmp(res->cmdStatus, "DELETE ", 7) == 0 ||
3701  strncmp(res->cmdStatus, "UPDATE ", 7) == 0)
3702  p = res->cmdStatus + 7;
3703  else if (strncmp(res->cmdStatus, "FETCH ", 6) == 0 ||
3704  strncmp(res->cmdStatus, "MERGE ", 6) == 0)
3705  p = res->cmdStatus + 6;
3706  else if (strncmp(res->cmdStatus, "MOVE ", 5) == 0 ||
3707  strncmp(res->cmdStatus, "COPY ", 5) == 0)
3708  p = res->cmdStatus + 5;
3709  else
3710  return "";
3711 
3712  /* check that we have an integer (at least one digit, nothing else) */
3713  for (c = p; *c; c++)
3714  {
3715  if (!isdigit((unsigned char) *c))
3716  goto interpret_error;
3717  }
3718  if (c == p)
3719  goto interpret_error;
3720 
3721  return p;
3722 
3723 interpret_error:
3725  "could not interpret result from server: %s",
3726  res->cmdStatus);
3727  return "";
3728 }
3729 
3730 /*
3731  * PQgetvalue:
3732  * return the value of field 'field_num' of row 'tup_num'
3733  */
3734 char *
3735 PQgetvalue(const PGresult *res, int tup_num, int field_num)
3736 {
3737  if (!check_tuple_field_number(res, tup_num, field_num))
3738  return NULL;
3739  return res->tuples[tup_num][field_num].value;
3740 }
3741 
3742 /* PQgetlength:
3743  * returns the actual length of a field value in bytes.
3744  */
3745 int
3746 PQgetlength(const PGresult *res, int tup_num, int field_num)
3747 {
3748  if (!check_tuple_field_number(res, tup_num, field_num))
3749  return 0;
3750  if (res->tuples[tup_num][field_num].len != NULL_LEN)
3751  return res->tuples[tup_num][field_num].len;
3752  else
3753  return 0;
3754 }
3755 
3756 /* PQgetisnull:
3757  * returns the null status of a field value.
3758  */
3759 int
3760 PQgetisnull(const PGresult *res, int tup_num, int field_num)
3761 {
3762  if (!check_tuple_field_number(res, tup_num, field_num))
3763  return 1; /* pretend it is null */
3764  if (res->tuples[tup_num][field_num].len == NULL_LEN)
3765  return 1;
3766  else
3767  return 0;
3768 }
3769 
3770 /* PQnparams:
3771  * returns the number of input parameters of a prepared statement.
3772  */
3773 int
3775 {
3776  if (!res)
3777  return 0;
3778  return res->numParameters;
3779 }
3780 
3781 /* PQparamtype:
3782  * returns type Oid of the specified statement parameter.
3783  */
3784 Oid
3785 PQparamtype(const PGresult *res, int param_num)
3786 {
3787  if (!check_param_number(res, param_num))
3788  return InvalidOid;
3789  if (res->paramDescs)
3790  return res->paramDescs[param_num].typid;
3791  else
3792  return InvalidOid;
3793 }
3794 
3795 
3796 /* PQsetnonblocking:
3797  * sets the PGconn's database connection non-blocking if the arg is true
3798  * or makes it blocking if the arg is false, this will not protect
3799  * you from PQexec(), you'll only be safe when using the non-blocking API.
3800  * Needs to be called only on a connected database connection.
3801  */
3802 int
3804 {
3805  bool barg;
3806 
3807  if (!conn || conn->status == CONNECTION_BAD)
3808  return -1;
3809 
3810  barg = (arg ? true : false);
3811 
3812  /* early out if the socket is already in the state requested */
3813  if (barg == conn->nonblocking)
3814  return 0;
3815 
3816  /*
3817  * to guarantee constancy for flushing/query/result-polling behavior we
3818  * need to flush the send queue at this point in order to guarantee proper
3819  * behavior. this is ok because either they are making a transition _from_
3820  * or _to_ blocking mode, either way we can block them.
3821  *
3822  * Clear error state in case pqFlush adds to it, unless we're actively
3823  * pipelining, in which case it seems best not to.
3824  */
3825  if (conn->cmd_queue_head == NULL)
3827 
3828  /* if we are going from blocking to non-blocking flush here */
3829  if (pqFlush(conn))
3830  return -1;
3831 
3832  conn->nonblocking = barg;
3833 
3834  return 0;
3835 }
3836 
3837 /*
3838  * return the blocking status of the database connection
3839  * true == nonblocking, false == blocking
3840  */
3841 int
3843 {
3844  return pqIsnonblocking(conn);
3845 }
3846 
3847 /* libpq is thread-safe? */
3848 int
3850 {
3851 #ifdef ENABLE_THREAD_SAFETY
3852  return true;
3853 #else
3854  return false;
3855 #endif
3856 }
3857 
3858 
3859 /* try to force data out, really only useful for non-blocking users */
3860 int
3862 {
3863  return pqFlush(conn);
3864 }
3865 
3866 /*
3867  * pqPipelineFlush
3868  *
3869  * In pipeline mode, data will be flushed only when the out buffer reaches the
3870  * threshold value. In non-pipeline mode, it behaves as stock pqFlush.
3871  *
3872  * Returns 0 on success.
3873  */
3874 static int
3876 {
3877  if ((conn->pipelineStatus != PQ_PIPELINE_ON) ||
3879  return pqFlush(conn);
3880  return 0;
3881 }
3882 
3883 
3884 /*
3885  * PQfreemem - safely frees memory allocated
3886  *
3887  * Needed mostly by Win32, unless multithreaded DLL (/MD in VC6)
3888  * Used for freeing memory from PQescapeBytea()/PQunescapeBytea()
3889  */
3890 void
3891 PQfreemem(void *ptr)
3892 {
3893  free(ptr);
3894 }
3895 
3896 /*
3897  * PQfreeNotify - free's the memory associated with a PGnotify
3898  *
3899  * This function is here only for binary backward compatibility.
3900  * New code should use PQfreemem(). A macro will automatically map
3901  * calls to PQfreemem. It should be removed in the future. bjm 2003-03-24
3902  */
3903 
3904 #undef PQfreeNotify
3905 void PQfreeNotify(PGnotify *notify);
3906 
3907 void
3909 {
3910  PQfreemem(notify);
3911 }
3912 
3913 
3914 /*
3915  * Escaping arbitrary strings to get valid SQL literal strings.
3916  *
3917  * Replaces "'" with "''", and if not std_strings, replaces "\" with "\\".
3918  *
3919  * length is the length of the source string. (Note: if a terminating NUL
3920  * is encountered sooner, PQescapeString stops short of "length"; the behavior
3921  * is thus rather like strncpy.)
3922  *
3923  * For safety the buffer at "to" must be at least 2*length + 1 bytes long.
3924  * A terminating NUL character is added to the output string, whether the
3925  * input is NUL-terminated or not.
3926  *
3927  * Returns the actual length of the output (not counting the terminating NUL).
3928  */
3929 static size_t
3931  char *to, const char *from, size_t length,
3932  int *error,
3933  int encoding, bool std_strings)
3934 {
3935  const char *source = from;
3936  char *target = to;
3937  size_t remaining = length;
3938 
3939  if (error)
3940  *error = 0;
3941 
3942  while (remaining > 0 && *source != '\0')
3943  {
3944  char c = *source;
3945  int len;
3946  int i;
3947 
3948  /* Fast path for plain ASCII */
3949  if (!IS_HIGHBIT_SET(c))
3950  {
3951  /* Apply quoting if needed */
3952  if (SQL_STR_DOUBLE(c, !std_strings))
3953  *target++ = c;
3954  /* Copy the character */
3955  *target++ = c;
3956  source++;
3957  remaining--;
3958  continue;
3959  }
3960 
3961  /* Slow path for possible multibyte characters */
3963 
3964  /* Copy the character */
3965  for (i = 0; i < len; i++)
3966  {
3967  if (remaining == 0 || *source == '\0')
3968  break;
3969  *target++ = *source++;
3970  remaining--;
3971  }
3972 
3973  /*
3974  * If we hit premature end of string (ie, incomplete multibyte
3975  * character), try to pad out to the correct length with spaces. We
3976  * may not be able to pad completely, but we will always be able to
3977  * insert at least one pad space (since we'd not have quoted a
3978  * multibyte character). This should be enough to make a string that
3979  * the server will error out on.
3980  */
3981  if (i < len)
3982  {
3983  if (error)
3984  *error = 1;
3985  if (conn)
3987  libpq_gettext("incomplete multibyte character\n"));
3988  for (; i < len; i++)
3989  {
3990  if (((size_t) (target - to)) / 2 >= length)
3991  break;
3992  *target++ = ' ';
3993  }
3994  break;
3995  }
3996  }
3997 
3998  /* Write the terminating NUL character. */
3999  *target = '\0';
4000 
4001  return target - to;
4002 }
4003 
4004 size_t
4006  char *to, const char *from, size_t length,
4007  int *error)
4008 {
4009  if (!conn)
4010  {
4011  /* force empty-string result */
4012  *to = '\0';
4013  if (error)
4014  *error = 1;
4015  return 0;
4016  }
4017 
4018  if (conn->cmd_queue_head == NULL)
4020 
4021  return PQescapeStringInternal(conn, to, from, length, error,
4023  conn->std_strings);
4024 }
4025 
4026 size_t
4027 PQescapeString(char *to, const char *from, size_t length)
4028 {
4029  return PQescapeStringInternal(NULL, to, from, length, NULL,
4032 }
4033 
4034 
4035 /*
4036  * Escape arbitrary strings. If as_ident is true, we escape the result
4037  * as an identifier; if false, as a literal. The result is returned in
4038  * a newly allocated buffer. If we fail due to an encoding violation or out
4039  * of memory condition, we return NULL, storing an error message into conn.
4040  */
4041 static char *
4042 PQescapeInternal(PGconn *conn, const char *str, size_t len, bool as_ident)
4043 {
4044  const char *s;
4045  char *result;
4046  char *rp;
4047  int num_quotes = 0; /* single or double, depending on as_ident */
4048  int num_backslashes = 0;
4049  int input_len;
4050  int result_size;
4051  char quote_char = as_ident ? '"' : '\'';
4052 
4053  /* We must have a connection, else fail immediately. */
4054  if (!conn)
4055  return NULL;
4056 
4057  if (conn->cmd_queue_head == NULL)
4059 
4060  /* Scan the string for characters that must be escaped. */
4061  for (s = str; (s - str) < len && *s != '\0'; ++s)
4062  {
4063  if (*s == quote_char)
4064  ++num_quotes;
4065  else if (*s == '\\')
4066  ++num_backslashes;
4067  else if (IS_HIGHBIT_SET(*s))
4068  {
4069  int charlen;
4070 
4071  /* Slow path for possible multibyte characters */
4072  charlen = pg_encoding_mblen(conn->client_encoding, s);
4073 
4074  /* Multibyte character overruns allowable length. */
4075  if ((s - str) + charlen > len || memchr(s, 0, charlen) != NULL)
4076  {
4078  libpq_gettext("incomplete multibyte character\n"));
4079  return NULL;
4080  }
4081 
4082  /* Adjust s, bearing in mind that for loop will increment it. */
4083  s += charlen - 1;
4084  }
4085  }
4086 
4087  /* Allocate output buffer. */
4088  input_len = s - str;
4089  result_size = input_len + num_quotes + 3; /* two quotes, plus a NUL */
4090  if (!as_ident && num_backslashes > 0)
4091  result_size += num_backslashes + 2;
4092  result = rp = (char *) malloc(result_size);
4093  if (rp == NULL)
4094  {
4096  libpq_gettext("out of memory\n"));
4097  return NULL;
4098  }
4099 
4100  /*
4101  * If we are escaping a literal that contains backslashes, we use the
4102  * escape string syntax so that the result is correct under either value
4103  * of standard_conforming_strings. We also emit a leading space in this
4104  * case, to guard against the possibility that the result might be
4105  * interpolated immediately following an identifier.
4106  */
4107  if (!as_ident && num_backslashes > 0)
4108  {
4109  *rp++ = ' ';
4110  *rp++ = 'E';
4111  }
4112 
4113  /* Opening quote. */
4114  *rp++ = quote_char;
4115 
4116  /*
4117  * Use fast path if possible.
4118  *
4119  * We've already verified that the input string is well-formed in the
4120  * current encoding. If it contains no quotes and, in the case of
4121  * literal-escaping, no backslashes, then we can just copy it directly to
4122  * the output buffer, adding the necessary quotes.
4123  *
4124  * If not, we must rescan the input and process each character
4125  * individually.
4126  */
4127  if (num_quotes == 0 && (num_backslashes == 0 || as_ident))
4128  {
4129  memcpy(rp, str, input_len);
4130  rp += input_len;
4131  }
4132  else
4133  {
4134  for (s = str; s - str < input_len; ++s)
4135  {
4136  if (*s == quote_char || (!as_ident && *s == '\\'))
4137  {
4138  *rp++ = *s;
4139  *rp++ = *s;
4140  }
4141  else if (!IS_HIGHBIT_SET(*s))
4142  *rp++ = *s;
4143  else
4144  {
4146 
4147  while (1)
4148  {
4149  *rp++ = *s;
4150  if (--i == 0)
4151  break;
4152  ++s; /* for loop will provide the final increment */
4153  }
4154  }
4155  }
4156  }
4157 
4158  /* Closing quote and terminating NUL. */
4159  *rp++ = quote_char;
4160  *rp = '\0';
4161 
4162  return result;
4163 }
4164 
4165 char *
4166 PQescapeLiteral(PGconn *conn, const char *str, size_t len)
4167 {
4168  return PQescapeInternal(conn, str, len, false);
4169 }
4170 
4171 char *
4172 PQescapeIdentifier(PGconn *conn, const char *str, size_t len)
4173 {
4174  return PQescapeInternal(conn, str, len, true);
4175 }
4176 
4177 /* HEX encoding support for bytea */
4178 static const char hextbl[] = "0123456789abcdef";
4179 
4180 static const int8 hexlookup[128] = {
4181  -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
4182  -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
4183  -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
4184  0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1, -1, -1, -1, -1, -1,
4185  -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1,
4186  -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
4187  -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1,
4188  -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
4189 };
4190 
4191 static inline char
4192 get_hex(char c)
4193 {
4194  int res = -1;
4195 
4196  if (c > 0 && c < 127)
4197  res = hexlookup[(unsigned char) c];
4198 
4199  return (char) res;
4200 }
4201 
4202 
4203 /*
4204  * PQescapeBytea - converts from binary string to the
4205  * minimal encoding necessary to include the string in an SQL
4206  * INSERT statement with a bytea type column as the target.
4207  *
4208  * We can use either hex or escape (traditional) encoding.
4209  * In escape mode, the following transformations are applied:
4210  * '\0' == ASCII 0 == \000
4211  * '\'' == ASCII 39 == ''
4212  * '\\' == ASCII 92 == \\
4213  * anything < 0x20, or > 0x7e ---> \ooo
4214  * (where ooo is an octal expression)
4215  *
4216  * If not std_strings, all backslashes sent to the output are doubled.
4217  */
4218 static unsigned char *
4220  const unsigned char *from, size_t from_length,
4221  size_t *to_length, bool std_strings, bool use_hex)
4222 {
4223  const unsigned char *vp;
4224  unsigned char *rp;
4225  unsigned char *result;
4226  size_t i;
4227  size_t len;
4228  size_t bslash_len = (std_strings ? 1 : 2);
4229 
4230  /*
4231  * empty string has 1 char ('\0')
4232  */
4233  len = 1;
4234 
4235  if (use_hex)
4236  {
4237  len += bslash_len + 1 + 2 * from_length;
4238  }
4239  else
4240  {
4241  vp = from;
4242  for (i = from_length; i > 0; i--, vp++)
4243  {
4244  if (*vp < 0x20 || *vp > 0x7e)
4245  len += bslash_len + 3;
4246  else if (*vp == '\'')
4247  len += 2;
4248  else if (*vp == '\\')
4249  len += bslash_len + bslash_len;
4250  else
4251  len++;
4252  }
4253  }
4254 
4255  *to_length = len;
4256  rp = result = (unsigned char *) malloc(len);
4257  if (rp == NULL)
4258  {
4259  if (conn)
4261  libpq_gettext("out of memory\n"));
4262  return NULL;
4263  }
4264 
4265  if (use_hex)
4266  {
4267  if (!std_strings)
4268  *rp++ = '\\';
4269  *rp++ = '\\';
4270  *rp++ = 'x';
4271  }
4272 
4273  vp = from;
4274  for (i = from_length; i > 0; i--, vp++)
4275  {
4276  unsigned char c = *vp;
4277 
4278  if (use_hex)
4279  {
4280  *rp++ = hextbl[(c >> 4) & 0xF];
4281  *rp++ = hextbl[c & 0xF];
4282  }
4283  else if (c < 0x20 || c > 0x7e)
4284  {
4285  if (!std_strings)
4286  *rp++ = '\\';
4287  *rp++ = '\\';
4288  *rp++ = (c >> 6) + '0';
4289  *rp++ = ((c >> 3) & 07) + '0';
4290  *rp++ = (c & 07) + '0';
4291  }
4292  else if (c == '\'')
4293  {
4294  *rp++ = '\'';
4295  *rp++ = '\'';
4296  }
4297  else if (c == '\\')
4298  {
4299  if (!std_strings)
4300  {
4301  *rp++ = '\\';
4302  *rp++ = '\\';
4303  }
4304  *rp++ = '\\';
4305  *rp++ = '\\';
4306  }
4307  else
4308  *rp++ = c;
4309  }
4310  *rp = '\0';
4311 
4312  return result;
4313 }
4314 
4315 unsigned char *
4317  const unsigned char *from, size_t from_length,
4318  size_t *to_length)
4319 {
4320  if (!conn)
4321  return NULL;
4322 
4323  if (conn->cmd_queue_head == NULL)
4325 
4326  return PQescapeByteaInternal(conn, from, from_length, to_length,
4327  conn->std_strings,
4328  (conn->sversion >= 90000));
4329 }
4330 
4331 unsigned char *
4332 PQescapeBytea(const unsigned char *from, size_t from_length, size_t *to_length)
4333 {
4334  return PQescapeByteaInternal(NULL, from, from_length, to_length,
4336  false /* can't use hex */ );
4337 }
4338 
4339 
4340 #define ISFIRSTOCTDIGIT(CH) ((CH) >= '0' && (CH) <= '3')
4341 #define ISOCTDIGIT(CH) ((CH) >= '0' && (CH) <= '7')
4342 #define OCTVAL(CH) ((CH) - '0')
4343 
4344 /*
4345  * PQunescapeBytea - converts the null terminated string representation
4346  * of a bytea, strtext, into binary, filling a buffer. It returns a
4347  * pointer to the buffer (or NULL on error), and the size of the
4348  * buffer in retbuflen. The pointer may subsequently be used as an
4349  * argument to the function PQfreemem.
4350  *
4351  * The following transformations are made:
4352  * \\ == ASCII 92 == \
4353  * \ooo == a byte whose value = ooo (ooo is an octal number)
4354  * \x == x (x is any character not matched by the above transformations)
4355  */
4356 unsigned char *
4357 PQunescapeBytea(const unsigned char *strtext, size_t *retbuflen)
4358 {
4359  size_t strtextlen,
4360  buflen;
4361  unsigned char *buffer,
4362  *tmpbuf;
4363  size_t i,
4364  j;
4365 
4366  if (strtext == NULL)
4367  return NULL;
4368 
4369  strtextlen = strlen((const char *) strtext);
4370 
4371  if (strtext[0] == '\\' && strtext[1] == 'x')
4372  {
4373  const unsigned char *s;
4374  unsigned char *p;
4375 
4376  buflen = (strtextlen - 2) / 2;
4377  /* Avoid unportable malloc(0) */
4378  buffer = (unsigned char *) malloc(buflen > 0 ? buflen : 1);
4379  if (buffer == NULL)
4380  return NULL;
4381 
4382  s = strtext + 2;
4383  p = buffer;
4384  while (*s)
4385  {
4386  char v1,
4387  v2;
4388 
4389  /*
4390  * Bad input is silently ignored. Note that this includes
4391  * whitespace between hex pairs, which is allowed by byteain.
4392  */
4393  v1 = get_hex(*s++);
4394  if (!*s || v1 == (char) -1)
4395  continue;
4396  v2 = get_hex(*s++);
4397  if (v2 != (char) -1)
4398  *p++ = (v1 << 4) | v2;
4399  }
4400 
4401  buflen = p - buffer;
4402  }
4403  else
4404  {
4405  /*
4406  * Length of input is max length of output, but add one to avoid
4407  * unportable malloc(0) if input is zero-length.
4408  */
4409  buffer = (unsigned char *) malloc(strtextlen + 1);
4410  if (buffer == NULL)
4411  return NULL;
4412 
4413  for (i = j = 0; i < strtextlen;)
4414  {
4415  switch (strtext[i])
4416  {
4417  case '\\':
4418  i++;
4419  if (strtext[i] == '\\')
4420  buffer[j++] = strtext[i++];
4421  else
4422  {
4423  if ((ISFIRSTOCTDIGIT(strtext[i])) &&
4424  (ISOCTDIGIT(strtext[i + 1])) &&
4425  (ISOCTDIGIT(strtext[i + 2])))
4426  {
4427  int byte;
4428 
4429  byte = OCTVAL(strtext[i++]);
4430  byte = (byte << 3) + OCTVAL(strtext[i++]);
4431  byte = (byte << 3) + OCTVAL(strtext[i++]);
4432  buffer[j++] = byte;
4433  }
4434  }
4435 
4436  /*
4437  * Note: if we see '\' followed by something that isn't a
4438  * recognized escape sequence, we loop around having done
4439  * nothing except advance i. Therefore the something will
4440  * be emitted as ordinary data on the next cycle. Corner
4441  * case: '\' at end of string will just be discarded.
4442  */
4443  break;
4444 
4445  default:
4446  buffer[j++] = strtext[i++];
4447  break;
4448  }
4449  }
4450  buflen = j; /* buflen is the length of the dequoted data */
4451  }
4452 
4453  /* Shrink the buffer to be no larger than necessary */
4454  /* +1 avoids unportable behavior when buflen==0 */
4455  tmpbuf = realloc(buffer, buflen + 1);
4456 
4457  /* It would only be a very brain-dead realloc that could fail, but... */
4458  if (!tmpbuf)
4459  {
4460  free(buffer);
4461  return NULL;
4462  }
4463 
4464  *retbuflen = buflen;
4465  return tmpbuf;
4466 }
#define unconstify(underlying_type, expr)
Definition: c.h:1240
signed char int8
Definition: c.h:427
#define offsetof(type, field)
Definition: c.h:727
#define IS_HIGHBIT_SET(ch)
Definition: c.h:1153
#define SQL_STR_DOUBLE(ch, escape_backslash)
Definition: c.h:1161
#define lengthof(array)
Definition: c.h:734
int errmsg(const char *fmt,...)
Definition: elog.c:904
int pg_char_to_encoding(const char *name)
Definition: encnames.c:550
const char * name
Definition: encode.c:561
static char * PQescapeInternal(PGconn *conn, const char *str, size_t len, bool as_ident)
Definition: fe-exec.c:4042
static int PQsendQueryInternal(PGconn *conn, const char *query, bool newQuery)
Definition: fe-exec.c:1436
unsigned char * PQescapeBytea(const unsigned char *from, size_t from_length, size_t *to_length)
Definition: fe-exec.c:4332
PGresult * PQfn(PGconn *conn, int fnid, int *result_buf, int *result_len, int result_is_int, const PQArgBlock *args, int nargs)
Definition: fe-exec.c:2916
int PQsendQueryParams(PGconn *conn, const char *command, int nParams, const Oid *paramTypes, const char *const *paramValues, const int *paramLengths, const int *paramFormats, int resultFormat)
Definition: fe-exec.c:1536
int PQsendQueryContinue(PGconn *conn, const char *query)
Definition: fe-exec.c:1430
int PQgetlength(const PGresult *res, int tup_num, int field_num)
Definition: fe-exec.c:3746
int PQsetSingleRowMode(PGconn *conn)
Definition: fe-exec.c:1976
static char get_hex(char c)
Definition: fe-exec.c:4192
int PQbinaryTuples(const PGresult *res)
Definition: fe-exec.c:3356
int PQflush(PGconn *conn)
Definition: fe-exec.c:3861
void PQfreemem(void *ptr)
Definition: fe-exec.c:3891
PGnotify * PQnotifies(PGconn *conn)
Definition: fe-exec.c:2599
PGresult * PQprepare(PGconn *conn, const char *stmtName, const char *query, int nParams, const Oid *paramTypes)
Definition: fe-exec.c:2317
unsigned char * PQunescapeBytea(const unsigned char *strtext, size_t *retbuflen)
Definition: fe-exec.c:4357
static size_t PQescapeStringInternal(PGconn *conn, char *to, const char *from, size_t length, int *error, int encoding, bool std_strings)
Definition: fe-exec.c:3930
Oid PQftype(const PGresult *res, int field_num)
Definition: fe-exec.c:3578
int PQexitPipelineMode(PGconn *conn)
Definition: fe-exec.c:3012
int PQsetResultAttrs(PGresult *res, int numAttributes, PGresAttDesc *attDescs)
Definition: fe-exec.c:246
#define ISOCTDIGIT(CH)
Definition: fe-exec.c:4341
void pqSaveMessageField(PGresult *res, char code, const char *value)
Definition: fe-exec.c:1061
char * PQescapeIdentifier(PGconn *conn, const char *str, size_t len)
Definition: fe-exec.c:4172
static unsigned char * PQescapeByteaInternal(PGconn *conn, const unsigned char *from, size_t from_length, size_t *to_length, bool std_strings, bool use_hex)
Definition: fe-exec.c:4219
static int check_tuple_field_number(const PGresult *res, int tup_num, int field_num)
Definition: fe-exec.c:3384
static void pqSaveWriteError(PGconn *conn)
Definition: fe-exec.c:821
int PQenterPipelineMode(PGconn *conn)
Definition: fe-exec.c:2980
void pqSetResultError(PGresult *res, PQExpBuffer errorMessage, int offset)
Definition: fe-exec.c:689
size_t PQescapeStringConn(PGconn *conn, char *to, const char *from, size_t length, int *error)
Definition: fe-exec.c:4005
void pqSaveErrorResult(PGconn *conn)
Definition: fe-exec.c:804
char *const pgresStatus[]
Definition: fe-exec.c:32
int PQputline(PGconn *conn, const char *s)
Definition: fe-exec.c:2854
#define OCTVAL(CH)
Definition: fe-exec.c:4342
char * pqResultStrdup(PGresult *res, const char *str)
Definition: fe-exec.c:672
#define PGRESULT_DATA_BLOCKSIZE
Definition: fe-exec.c:140
PGresult * PQexecParams(PGconn *conn, const char *command, int nParams, const Oid *paramTypes, const char *const *paramValues, const int *paramLengths, const int *paramFormats, int resultFormat)
Definition: fe-exec.c:2287
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:3270
Oid PQparamtype(const PGresult *res, int param_num)
Definition: fe-exec.c:3785
static int check_param_number(const PGresult *res, int param_num)
Definition: fe-exec.c:3407
int pqRowProcessor(PGconn *conn, const char **errmsgp)
Definition: fe-exec.c:1208
PGresult * PQdescribePrepared(PGconn *conn, const char *stmt)
Definition: fe-exec.c:2469
int PQnparams(const PGresult *res)
Definition: fe-exec.c:3774
void PQclear(PGresult *res)
Definition: fe-exec.c:718
char * PQcmdTuples(PGresult *res)
Definition: fe-exec.c:3681
char * PQresultErrorMessage(const PGresult *res)
Definition: fe-exec.c:3286
static PGresult * PQexecFinish(PGconn *conn)
Definition: fe-exec.c:2423
int PQfformat(const PGresult *res, int field_num)
Definition: fe-exec.c:3567
static void pqAppendCmdQueueEntry(PGconn *conn, PGcmdQueueEntry *entry)
Definition: fe-exec.c:1348
static int PQsendQueryGuts(PGconn *conn, const char *command, const char *stmtName, int nParams, const Oid *paramTypes, const char *const *paramValues, const int *paramLengths, const int *paramFormats, int resultFormat)
Definition: fe-exec.c:1807
int PQendcopy(PGconn *conn)
Definition: fe-exec.c:2885
static int pqPipelineFlush(PGconn *conn)
Definition: fe-exec.c:3875
int PQputCopyEnd(PGconn *conn, const char *errormsg)
Definition: fe-exec.c:2683
int PQntuples(const PGresult *res)
Definition: fe-exec.c:3340
int PQputnbytes(PGconn *conn, const char *buffer, int nbytes)
Definition: fe-exec.c:2864
int PQgetlineAsync(PGconn *conn, char *buffer, int bufsize)
Definition: fe-exec.c:2837
static const PGresult OOM_result
Definition: fe-exec.c:48
#define PGRESULT_BLOCK_OVERHEAD
Definition: fe-exec.c:142
int PQputCopyData(PGconn *conn, const char *buffer, int nbytes)
Definition: fe-exec.c:2627
PGresult * PQexecPrepared(PGconn *conn, const char *stmtName, int nParams, const char *const *paramValues, const int *paramLengths, const int *paramFormats, int resultFormat)
Definition: fe-exec.c:2334
static PGcmdQueueEntry * pqAllocCmdQueueEntry(PGconn *conn)
Definition: fe-exec.c:1314
static PGresult * getCopyResult(PGconn *conn, ExecStatusType copytype)
Definition: fe-exec.c:2235
static PGEvent * dupEvents(PGEvent *events, int count, size_t *memSize)
Definition: fe-exec.c:405
int PQisthreadsafe(void)
Definition: fe-exec.c:3849
char * PQfname(const PGresult *res, int field_num)
Definition: fe-exec.c:3426
static bool static_std_strings
Definition: fe-exec.c:59
char * PQescapeLiteral(PGconn *conn, const char *str, size_t len)
Definition: fe-exec.c:4166
void pqInternalNotice(const PGNoticeHooks *hooks, const char *fmt,...)
Definition: fe-exec.c:939
PGresult * PQdescribePortal(PGconn *conn, const char *portal)
Definition: fe-exec.c:2488
int PQsendDescribePrepared(PGconn *conn, const char *stmt)
Definition: fe-exec.c:2505
PGresult * PQmakeEmptyPGresult(PGconn *conn, ExecStatusType status)
Definition: fe-exec.c:157
PGresult * PQexec(PGconn *conn, const char *query)
Definition: fe-exec.c:2273
unsigned char * PQescapeByteaConn(PGconn *conn, const unsigned char *from, size_t from_length, size_t *to_length)
Definition: fe-exec.c:4316
static const char hextbl[]
Definition: fe-exec.c:4178
static bool PQexecStart(PGconn *conn)
Definition: fe-exec.c:2355
size_t PQescapeString(char *to, const char *from, size_t length)
Definition: fe-exec.c:4027
int PQconsumeInput(PGconn *conn)
Definition: fe-exec.c:2004
#define ISFIRSTOCTDIGIT(CH)
Definition: fe-exec.c:4340
static void parseInput(PGconn *conn)
Definition: fe-exec.c:2040
char * PQgetvalue(const PGresult *res, int tup_num, int field_num)
Definition: fe-exec.c:3735
Oid PQftable(const PGresult *res, int field_num)
Definition: fe-exec.c:3545
int PQfnumber(const PGresult *res, const char *field_name)
Definition: fe-exec.c:3448
char * PQcmdStatus(PGresult *res)
Definition: fe-exec.c:3611
void pqSaveParameterStatus(PGconn *conn, const char *name, const char *value)
Definition: fe-exec.c:1082
int PQsetnonblocking(PGconn *conn, int arg)
Definition: fe-exec.c:3803
static int PQsendDescribe(PGconn *conn, char desc_type, const char *desc_target)
Definition: fe-exec.c:2533
int PQsendPrepare(PGconn *conn, const char *stmtName, const char *query, int nParams, const Oid *paramTypes)
Definition: fe-exec.c:1582
#define PGRESULT_SEP_ALLOC_THRESHOLD
Definition: fe-exec.c:143
int PQfmod(const PGresult *res, int field_num)
Definition: fe-exec.c:3600
void pqClearAsyncResult(PGconn *conn)
Definition: fe-exec.c:778
int PQgetisnull(const PGresult *res, int tup_num, int field_num)
Definition: fe-exec.c:3760
int PQftablecol(const PGresult *res, int field_num)
Definition: fe-exec.c:3556
static int static_client_encoding
Definition: fe-exec.c:58
int PQsetvalue(PGresult *res, int tup_num, int field_num, char *value, int len)
Definition: fe-exec.c:449
int PQsendQuery(PGconn *conn, const char *query)
Definition: fe-exec.c:1424
int PQpipelineSync(PGconn *conn)
Definition: fe-exec.c:3169
char * PQresStatus(ExecStatusType status)
Definition: fe-exec.c:3278
int PQsendDescribePortal(PGconn *conn, const char *portal)
Definition: fe-exec.c:2518
size_t PQresultMemorySize(const PGresult *res)
Definition: fe-exec.c:660
int PQisBusy(PGconn *conn)
Definition: fe-exec.c:2051
int PQsendQueryPrepared(PGconn *conn, const char *stmtName, int nParams, const char *const *paramValues, const int *paramLengths, const int *paramFormats, int resultFormat)
Definition: fe-exec.c:1682
static void pqPipelineProcessQueue(PGconn *conn)
Definition: fe-exec.c:3083
int PQsendFlushRequest(PGconn *conn)
Definition: fe-exec.c:3236
void * pqResultAlloc(PGresult *res, size_t nBytes, bool isBinary)
Definition: fe-exec.c:560
char * PQoidStatus(const PGresult *res)
Definition: fe-exec.c:3624
char * PQresultErrorField(const PGresult *res, int fieldcode)
Definition: fe-exec.c:3325
int PQisnonblocking(const PGconn *conn)
Definition: fe-exec.c:3842
PGresult * PQcopyResult(const PGresult *src, int flags)
Definition: fe-exec.c:315
void * PQresultAlloc(PGresult *res, size_t nBytes)
Definition: fe-exec.c:540
Oid PQoidValue(const PGresult *res)
Definition: fe-exec.c:3652
static bool pqAddTuple(PGresult *res, PGresAttValue *tup, const char **errmsgp)
Definition: fe-exec.c:994
char * PQresultVerboseErrorMessage(const PGresult *res, PGVerbosity verbosity, PGContextVisibility show_context)
Definition: fe-exec.c:3294
#define PGRESULT_ALIGN_BOUNDARY
Definition: fe-exec.c:141
int PQnfields(const PGresult *res)
Definition: fe-exec.c:3348
static int check_field_number(const PGresult *res, int field_num)
Definition: fe-exec.c:3369
PGresult * PQgetResult(PGconn *conn)
Definition: fe-exec.c:2082
PGresult * pqPrepareAsyncResult(PGconn *conn)
Definition: fe-exec.c:851
int PQfsize(const PGresult *res, int field_num)
Definition: fe-exec.c:3589
static bool PQsendQueryStart(PGconn *conn, bool newQuery)
Definition: fe-exec.c:1724
int PQgetline(PGconn *conn, char *s, int maxlen)
Definition: fe-exec.c:2790
static const int8 hexlookup[128]
Definition: fe-exec.c:4180
int PQgetCopyData(PGconn *conn, char **buffer, int async)
Definition: fe-exec.c:2751
static void pqRecycleCmdQueueEntry(PGconn *conn, PGcmdQueueEntry *entry)
Definition: fe-exec.c:1394
void PQfreeNotify(PGnotify *notify)
Definition: fe-exec.c:3908
void pqCommandQueueAdvance(PGconn *conn)
Definition: fe-exec.c:3062
int pqPutc(char c, PGconn *conn)
Definition: fe-misc.c:95
int pqReadData(PGconn *conn)
Definition: fe-misc.c:568
int pqPutInt(int value, size_t bytes, PGconn *conn)
Definition: fe-misc.c:256
int pqCheckOutBufferSpace(size_t bytes_needed, PGconn *conn)
Definition: fe-misc.c:290
int pqFlush(PGconn *conn)
Definition: fe-misc.c:958
int pqPutMsgStart(char msg_type, PGconn *conn)
Definition: fe-misc.c:461
int pqWait(int forRead, int forWrite, PGconn *conn)
Definition: fe-misc.c:983
int pqPutnchar(const char *s, size_t len, PGconn *conn)
Definition: fe-misc.c:205
int pqPuts(const char *s, PGconn *conn)
Definition: fe-misc.c:155
int pqPutMsgEnd(PGconn *conn)
Definition: fe-misc.c:520
void pqBuildErrorMessage3(PQExpBuffer msg, const PGresult *res, PGVerbosity verbosity, PGContextVisibility show_context)
void pqParseInput3(PGconn *conn)
Definition: fe-protocol3.c:63
int pqEndcopy3(PGconn *conn)
PGresult * pqFunctionCall3(PGconn *conn, Oid fnid, int *result_buf, int *actual_result_len, int result_is_int, const PQArgBlock *args, int nargs)
int pqGetlineAsync3(PGconn *conn, char *buffer, int bufsize)
int pqGetCopyData3(PGconn *conn, char **buffer, int async)
int pqGetline3(PGconn *conn, char *s, int maxlen)
#define realloc(a, b)
Definition: header.h:60
#define free(a)
Definition: header.h:65
#define malloc(a)
Definition: header.h:50
static struct @151 value
long val
Definition: informix.c:664
int remaining
Definition: informix.c:667
return true
Definition: isn.c:126
int j
Definition: isn.c:74
int i
Definition: isn.c:73
int PQfireResultCreateEvents(PGconn *conn, PGresult *res)
Definition: libpq-events.c:185
@ PGEVT_RESULTDESTROY
Definition: libpq-events.h:34
@ PGEVT_RESULTCOPY
Definition: libpq-events.h:33
@ CONNECTION_BAD
Definition: libpq-fe.h:61
@ CONNECTION_OK
Definition: libpq-fe.h:60
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_SINGLE_TUPLE
Definition: libpq-fe.h:110
@ 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_PIPELINE_ABORTED
Definition: libpq-fe.h:112
@ PGRES_NONFATAL_ERROR
Definition: libpq-fe.h:107
@ PGRES_TUPLES_OK
Definition: libpq-fe.h:100
PGContextVisibility
Definition: libpq-fe.h:134
#define PG_COPYRES_TUPLES
Definition: libpq-fe.h:46
@ PQ_PIPELINE_OFF
Definition: libpq-fe.h:158
@ PQ_PIPELINE_ABORTED
Definition: libpq-fe.h:160
@ PQ_PIPELINE_ON
Definition: libpq-fe.h:159
#define PG_COPYRES_ATTRS
Definition: libpq-fe.h:45
struct pg_result PGresult
Definition: libpq-fe.h:173
PGVerbosity
Definition: libpq-fe.h:126
#define PG_COPYRES_EVENTS
Definition: libpq-fe.h:47
#define PG_COPYRES_NOTICEHOOKS
Definition: libpq-fe.h:48
#define PQ_QUERY_PARAM_MAX_LIMIT
Definition: libpq-fe.h:443
struct PGEvent PGEvent
@ PGASYNC_COPY_OUT
Definition: libpq-int.h:227
@ PGASYNC_READY_MORE
Definition: libpq-int.h:223
@ PGASYNC_READY
Definition: libpq-int.h:221
@ PGASYNC_COPY_BOTH
Definition: libpq-int.h:228
@ PGASYNC_IDLE
Definition: libpq-int.h:219
@ PGASYNC_COPY_IN
Definition: libpq-int.h:226
@ PGASYNC_BUSY
Definition: libpq-int.h:220
#define libpq_gettext(x)
Definition: libpq-int.h:878
@ PGQUERY_SIMPLE
Definition: libpq-int.h:310
@ PGQUERY_SYNC
Definition: libpq-int.h:314
@ PGQUERY_EXTENDED
Definition: libpq-int.h:311
@ PGQUERY_DESCRIBE
Definition: libpq-int.h:313
@ PGQUERY_PREPARE
Definition: libpq-int.h:312
#define NULL_LEN
Definition: libpq-int.h:134
struct pgParameterStatus pgParameterStatus
#define pqClearConnErrorState(conn)
Definition: libpq-int.h:851
union pgresult_data PGresult_data
Definition: libpq-int.h:102
@ PG_BOOL_YES
Definition: libpq-int.h:247
@ PG_BOOL_NO
Definition: libpq-int.h:248
#define pqIsnonblocking(conn)
Definition: libpq-int.h:867
#define OUTBUFFER_THRESHOLD
Definition: libpq-int.h:872
#define pgHavePendingResult(conn)
Definition: libpq-int.h:860
va_end(args)
Assert(fmt[strlen(fmt) - 1] !='\n')
static void const char * fmt
va_start(args, fmt)
void * arg
const void size_t len
int32 encoding
Definition: pg_database.h:41
static void static void status(const char *fmt,...) pg_attribute_printf(1
Definition: pg_regress.c:229
static rewind_source * source
Definition: pg_rewind.c:81
static char * buf
Definition: pg_test_fsync.c:67
@ PG_SQL_ASCII
Definition: pg_wchar.h:224
#define vsnprintf
Definition: port.h:224
#define sprintf
Definition: port.h:227
unsigned char pg_tolower(unsigned char ch)
Definition: pgstrcasecmp.c:122
#define PGINVALID_SOCKET
Definition: port.h:31
#define InvalidOid
Definition: postgres_ext.h:36
unsigned int Oid
Definition: postgres_ext.h:31
#define PG_DIAG_SEVERITY_NONLOCALIZED
Definition: postgres_ext.h:56
#define PG_DIAG_MESSAGE_PRIMARY
Definition: postgres_ext.h:58
#define PG_DIAG_SEVERITY
Definition: postgres_ext.h:55
void initPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:92
void appendPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:267
void appendPQExpBufferStr(PQExpBuffer str, const char *data)
Definition: pqexpbuffer.c:369
void termPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:131
#define PQExpBufferBroken(str)
Definition: pqexpbuffer.h:59
#define PQExpBufferDataBroken(buf)
Definition: pqexpbuffer.h:67
char * c
static void error(void)
Definition: sql-dyntest.c:147
PGconn * conn
Definition: streamutil.c:54
const PGresult * src
Definition: libpq-events.h:60
PGresult * dest
Definition: libpq-events.h:61
void * passThrough
Definition: libpq-int.h:163
char * name
Definition: libpq-int.h:162
void * data
Definition: libpq-int.h:164
PGEventProc proc
Definition: libpq-int.h:161
bool resultInitialized
Definition: libpq-int.h:165
void * noticeProcArg
Definition: libpq-int.h:156
PQnoticeReceiver noticeRec
Definition: libpq-int.h:153
PQnoticeProcessor noticeProc
Definition: libpq-int.h:155
void * noticeRecArg
Definition: libpq-int.h:154
PGQueryClass queryclass
Definition: libpq-int.h:322
struct PGcmdQueueEntry * next
Definition: libpq-int.h:324
struct pgMessageField * next
Definition: libpq-int.h:145
char contents[FLEXIBLE_ARRAY_MEMBER]
Definition: libpq-int.h:147
struct pgNotify * next
Definition: libpq-fe.h:193
struct pgParameterStatus * next
Definition: libpq-int.h:261
char * write_err_msg
Definition: libpq-int.h:455
PGnotify * notifyHead
Definition: libpq-int.h:421
PGdataValue * rowBuf
Definition: libpq-int.h:496
bool singleRowMode
Definition: libpq-int.h:418
pgsocket sock
Definition: libpq-int.h:444
PGresult * next_result
Definition: libpq-int.h:510
bool std_strings
Definition: libpq-int.h:471
int errorReported
Definition: libpq-int.h:586
bool write_failed
Definition: libpq-int.h:454
PGTernaryBool in_hot_standby
Definition: libpq-int.h:473
PGcmdQueueEntry * cmd_queue_recycle
Definition: libpq-int.h:441
PGcmdQueueEntry * cmd_queue_tail
Definition: libpq-int.h:435
PGnotify * notifyTail
Definition: libpq-int.h:422
bool nonblocking
Definition: libpq-int.h:415
int client_encoding
Definition: libpq-int.h:470
int sversion
Definition: libpq-int.h:449
PGTernaryBool default_transaction_read_only
Definition: libpq-int.h:472
pgParameterStatus * pstatus
Definition: libpq-int.h:469
PGresult * result
Definition: libpq-int.h:508
PQExpBufferData errorMessage
Definition: libpq-int.h:585
int nEvents
Definition: libpq-int.h:406
bool error_result
Definition: libpq-int.h:509
PGAsyncStatusType asyncStatus
Definition: libpq-int.h:411
PGpipelineStatus pipelineStatus
Definition: libpq-int.h:417
int outBufSize
Definition: libpq-int.h:487
PGNoticeHooks noticeHooks
Definition: libpq-int.h:402
PGcmdQueueEntry * cmd_queue_head
Definition: libpq-int.h:434
int outCount
Definition: libpq-int.h:488
PGEvent * events
Definition: libpq-int.h:405
ConnStatusType status
Definition: libpq-int.h:410
size_t memorySize
Definition: libpq-int.h:213
int ntups
Definition: libpq-int.h:170
int curOffset
Definition: libpq-int.h:210
int binary
Definition: libpq-int.h:180
PGNoticeHooks noticeHooks
Definition: libpq-int.h:187
char null_field[1]
Definition: libpq-int.h:202
char * errMsg
Definition: libpq-int.h:197
int nEvents
Definition: libpq-int.h:189
PGresAttValue ** tuples
Definition: libpq-int.h:173
int numParameters
Definition: libpq-int.h:176
int spaceLeft
Definition: libpq-int.h:211
PGresAttDesc * attDescs
Definition: libpq-int.h:172
int numAttributes
Definition: libpq-int.h:171
char cmdStatus[CMDSTATUS_LEN]
Definition: libpq-int.h:179
PGMessageField * errFields
Definition: libpq-int.h:198
PGresParamDesc * paramDescs
Definition: libpq-int.h:177
PGEvent * events
Definition: libpq-int.h:188
PGresult_data * curBlock
Definition: libpq-int.h:209
int tupArrSize
Definition: libpq-int.h:175
ExecStatusType resultStatus
Definition: libpq-int.h:178
char * errQuery
Definition: libpq-int.h:199
int client_encoding
Definition: libpq-int.h:190
char * name
Definition: libpq-fe.h:263
int columnid
Definition: libpq-fe.h:265
int atttypmod
Definition: libpq-fe.h:269
char * value
Definition: libpq-int.h:139
PGresult_data * next
Definition: libpq-int.h:106
char space[1]
Definition: libpq-int.h:107
static StringInfoData tmpbuf
Definition: walsender.c:160
int pg_encoding_mblen(int encoding, const char *mbstr)
Definition: wchar.c:2129