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