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