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 PQsendTypedCommand(PGconn *conn, char command, char type,
81  const char *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  else if (strcmp(name, "scram_iterations") == 0)
1185  {
1187  }
1188 }
1189 
1190 
1191 /*
1192  * pqRowProcessor
1193  * Add the received row to the current async result (conn->result).
1194  * Returns 1 if OK, 0 if error occurred.
1195  *
1196  * On error, *errmsgp can be set to an error string to be returned.
1197  * (Such a string should already be translated via libpq_gettext().)
1198  * If it is left NULL, the error is presumed to be "out of memory".
1199  *
1200  * In single-row mode, we create a new result holding just the current row,
1201  * stashing the previous result in conn->next_result so that it becomes
1202  * active again after pqPrepareAsyncResult(). This allows the result metadata
1203  * (column descriptions) to be carried forward to each result row.
1204  */
1205 int
1206 pqRowProcessor(PGconn *conn, const char **errmsgp)
1207 {
1208  PGresult *res = conn->result;
1209  int nfields = res->numAttributes;
1210  const PGdataValue *columns = conn->rowBuf;
1211  PGresAttValue *tup;
1212  int i;
1213 
1214  /*
1215  * In single-row mode, make a new PGresult that will hold just this one
1216  * row; the original conn->result is left unchanged so that it can be used
1217  * again as the template for future rows.
1218  */
1219  if (conn->singleRowMode)
1220  {
1221  /* Copy everything that should be in the result at this point */
1222  res = PQcopyResult(res,
1225  if (!res)
1226  return 0;
1227  }
1228 
1229  /*
1230  * Basically we just allocate space in the PGresult for each field and
1231  * copy the data over.
1232  *
1233  * Note: on malloc failure, we return 0 leaving *errmsgp still NULL, which
1234  * caller will take to mean "out of memory". This is preferable to trying
1235  * to set up such a message here, because evidently there's not enough
1236  * memory for gettext() to do anything.
1237  */
1238  tup = (PGresAttValue *)
1239  pqResultAlloc(res, nfields * sizeof(PGresAttValue), true);
1240  if (tup == NULL)
1241  goto fail;
1242 
1243  for (i = 0; i < nfields; i++)
1244  {
1245  int clen = columns[i].len;
1246 
1247  if (clen < 0)
1248  {
1249  /* null field */
1250  tup[i].len = NULL_LEN;
1251  tup[i].value = res->null_field;
1252  }
1253  else
1254  {
1255  bool isbinary = (res->attDescs[i].format != 0);
1256  char *val;
1257 
1258  val = (char *) pqResultAlloc(res, clen + 1, isbinary);
1259  if (val == NULL)
1260  goto fail;
1261 
1262  /* copy and zero-terminate the data (even if it's binary) */
1263  memcpy(val, columns[i].value, clen);
1264  val[clen] = '\0';
1265 
1266  tup[i].len = clen;
1267  tup[i].value = val;
1268  }
1269  }
1270 
1271  /* And add the tuple to the PGresult's tuple array */
1272  if (!pqAddTuple(res, tup, errmsgp))
1273  goto fail;
1274 
1275  /*
1276  * Success. In single-row mode, make the result available to the client
1277  * immediately.
1278  */
1279  if (conn->singleRowMode)
1280  {
1281  /* Change result status to special single-row value */
1283  /* Stash old result for re-use later */
1285  conn->result = res;
1286  /* And mark the result ready to return */
1288  }
1289 
1290  return 1;
1291 
1292 fail:
1293  /* release locally allocated PGresult, if we made one */
1294  if (res != conn->result)
1295  PQclear(res);
1296  return 0;
1297 }
1298 
1299 
1300 /*
1301  * pqAllocCmdQueueEntry
1302  * Get a command queue entry for caller to fill.
1303  *
1304  * If the recycle queue has a free element, that is returned; if not, a
1305  * fresh one is allocated. Caller is responsible for adding it to the
1306  * command queue (pqAppendCmdQueueEntry) once the struct is filled in, or
1307  * releasing the memory (pqRecycleCmdQueueEntry) if an error occurs.
1308  *
1309  * If allocation fails, sets the error message and returns NULL.
1310  */
1311 static PGcmdQueueEntry *
1313 {
1314  PGcmdQueueEntry *entry;
1315 
1316  if (conn->cmd_queue_recycle == NULL)
1317  {
1318  entry = (PGcmdQueueEntry *) malloc(sizeof(PGcmdQueueEntry));
1319  if (entry == NULL)
1320  {
1321  libpq_append_conn_error(conn, "out of memory");
1322  return NULL;
1323  }
1324  }
1325  else
1326  {
1327  entry = conn->cmd_queue_recycle;
1328  conn->cmd_queue_recycle = entry->next;
1329  }
1330  entry->next = NULL;
1331  entry->query = NULL;
1332 
1333  return entry;
1334 }
1335 
1336 /*
1337  * pqAppendCmdQueueEntry
1338  * Append a caller-allocated entry to the command queue, and update
1339  * conn->asyncStatus to account for it.
1340  *
1341  * The query itself must already have been put in the output buffer by the
1342  * caller.
1343  */
1344 static void
1346 {
1347  Assert(entry->next == NULL);
1348 
1349  if (conn->cmd_queue_head == NULL)
1350  conn->cmd_queue_head = entry;
1351  else
1352  conn->cmd_queue_tail->next = entry;
1353 
1354  conn->cmd_queue_tail = entry;
1355 
1356  switch (conn->pipelineStatus)
1357  {
1358  case PQ_PIPELINE_OFF:
1359  case PQ_PIPELINE_ON:
1360 
1361  /*
1362  * When not in pipeline aborted state, if there's a result ready
1363  * to be consumed, let it be so (that is, don't change away from
1364  * READY or READY_MORE); otherwise set us busy to wait for
1365  * something to arrive from the server.
1366  */
1367  if (conn->asyncStatus == PGASYNC_IDLE)
1369  break;
1370 
1371  case PQ_PIPELINE_ABORTED:
1372 
1373  /*
1374  * In aborted pipeline state, we don't expect anything from the
1375  * server (since we don't send any queries that are queued).
1376  * Therefore, if IDLE then do what PQgetResult would do to let
1377  * itself consume commands from the queue; if we're in any other
1378  * state, we don't have to do anything.
1379  */
1380  if (conn->asyncStatus == PGASYNC_IDLE ||
1383  break;
1384  }
1385 }
1386 
1387 /*
1388  * pqRecycleCmdQueueEntry
1389  * Push a command queue entry onto the freelist.
1390  */
1391 static void
1393 {
1394  if (entry == NULL)
1395  return;
1396 
1397  /* recyclable entries should not have a follow-on command */
1398  Assert(entry->next == NULL);
1399 
1400  if (entry->query)
1401  {
1402  free(entry->query);
1403  entry->query = NULL;
1404  }
1405 
1406  entry->next = conn->cmd_queue_recycle;
1407  conn->cmd_queue_recycle = entry;
1408 }
1409 
1410 
1411 /*
1412  * PQsendQuery
1413  * Submit a query, but don't wait for it to finish
1414  *
1415  * Returns: 1 if successfully submitted
1416  * 0 if error (conn->errorMessage is set)
1417  *
1418  * PQsendQueryContinue is a non-exported version that behaves identically
1419  * except that it doesn't reset conn->errorMessage.
1420  */
1421 int
1422 PQsendQuery(PGconn *conn, const char *query)
1423 {
1424  return PQsendQueryInternal(conn, query, true);
1425 }
1426 
1427 int
1428 PQsendQueryContinue(PGconn *conn, const char *query)
1429 {
1430  return PQsendQueryInternal(conn, query, false);
1431 }
1432 
1433 static int
1434 PQsendQueryInternal(PGconn *conn, const char *query, bool newQuery)
1435 {
1436  PGcmdQueueEntry *entry = NULL;
1437 
1438  if (!PQsendQueryStart(conn, newQuery))
1439  return 0;
1440 
1441  /* check the argument */
1442  if (!query)
1443  {
1444  libpq_append_conn_error(conn, "command string is a null pointer");
1445  return 0;
1446  }
1447 
1449  {
1450  libpq_append_conn_error(conn, "%s not allowed in pipeline mode",
1451  "PQsendQuery");
1452  return 0;
1453  }
1454 
1455  entry = pqAllocCmdQueueEntry(conn);
1456  if (entry == NULL)
1457  return 0; /* error msg already set */
1458 
1459  /* Send the query message(s) */
1460  /* construct the outgoing Query message */
1461  if (pqPutMsgStart(PqMsg_Query, conn) < 0 ||
1462  pqPuts(query, conn) < 0 ||
1463  pqPutMsgEnd(conn) < 0)
1464  {
1465  /* error message should be set up already */
1466  pqRecycleCmdQueueEntry(conn, entry);
1467  return 0;
1468  }
1469 
1470  /* remember we are using simple query protocol */
1471  entry->queryclass = PGQUERY_SIMPLE;
1472  /* and remember the query text too, if possible */
1473  entry->query = strdup(query);
1474 
1475  /*
1476  * Give the data a push. In nonblock mode, don't complain if we're unable
1477  * to send it all; PQgetResult() will do any additional flushing needed.
1478  */
1479  if (pqFlush(conn) < 0)
1480  goto sendFailed;
1481 
1482  /* OK, it's launched! */
1483  pqAppendCmdQueueEntry(conn, entry);
1484 
1485  return 1;
1486 
1487 sendFailed:
1488  pqRecycleCmdQueueEntry(conn, entry);
1489  /* error message should be set up already */
1490  return 0;
1491 }
1492 
1493 /*
1494  * PQsendQueryParams
1495  * Like PQsendQuery, but use extended query protocol so we can pass parameters
1496  */
1497 int
1499  const char *command,
1500  int nParams,
1501  const Oid *paramTypes,
1502  const char *const *paramValues,
1503  const int *paramLengths,
1504  const int *paramFormats,
1505  int resultFormat)
1506 {
1507  if (!PQsendQueryStart(conn, true))
1508  return 0;
1509 
1510  /* check the arguments */
1511  if (!command)
1512  {
1513  libpq_append_conn_error(conn, "command string is a null pointer");
1514  return 0;
1515  }
1516  if (nParams < 0 || nParams > PQ_QUERY_PARAM_MAX_LIMIT)
1517  {
1518  libpq_append_conn_error(conn, "number of parameters must be between 0 and %d",
1520  return 0;
1521  }
1522 
1523  return PQsendQueryGuts(conn,
1524  command,
1525  "", /* use unnamed statement */
1526  nParams,
1527  paramTypes,
1528  paramValues,
1529  paramLengths,
1530  paramFormats,
1531  resultFormat);
1532 }
1533 
1534 /*
1535  * PQsendPrepare
1536  * Submit a Parse message, but don't wait for it to finish
1537  *
1538  * Returns: 1 if successfully submitted
1539  * 0 if error (conn->errorMessage is set)
1540  */
1541 int
1543  const char *stmtName, const char *query,
1544  int nParams, const Oid *paramTypes)
1545 {
1546  PGcmdQueueEntry *entry = NULL;
1547 
1548  if (!PQsendQueryStart(conn, true))
1549  return 0;
1550 
1551  /* check the arguments */
1552  if (!stmtName)
1553  {
1554  libpq_append_conn_error(conn, "statement name is a null pointer");
1555  return 0;
1556  }
1557  if (!query)
1558  {
1559  libpq_append_conn_error(conn, "command string is a null pointer");
1560  return 0;
1561  }
1562  if (nParams < 0 || nParams > PQ_QUERY_PARAM_MAX_LIMIT)
1563  {
1564  libpq_append_conn_error(conn, "number of parameters must be between 0 and %d",
1566  return 0;
1567  }
1568 
1569  entry = pqAllocCmdQueueEntry(conn);
1570  if (entry == NULL)
1571  return 0; /* error msg already set */
1572 
1573  /* construct the Parse message */
1574  if (pqPutMsgStart(PqMsg_Parse, conn) < 0 ||
1575  pqPuts(stmtName, conn) < 0 ||
1576  pqPuts(query, conn) < 0)
1577  goto sendFailed;
1578 
1579  if (nParams > 0 && paramTypes)
1580  {
1581  int i;
1582 
1583  if (pqPutInt(nParams, 2, conn) < 0)
1584  goto sendFailed;
1585  for (i = 0; i < nParams; i++)
1586  {
1587  if (pqPutInt(paramTypes[i], 4, conn) < 0)
1588  goto sendFailed;
1589  }
1590  }
1591  else
1592  {
1593  if (pqPutInt(0, 2, conn) < 0)
1594  goto sendFailed;
1595  }
1596  if (pqPutMsgEnd(conn) < 0)
1597  goto sendFailed;
1598 
1599  /* Add a Sync, unless in pipeline mode. */
1601  {
1602  if (pqPutMsgStart(PqMsg_Sync, conn) < 0 ||
1603  pqPutMsgEnd(conn) < 0)
1604  goto sendFailed;
1605  }
1606 
1607  /* remember we are doing just a Parse */
1608  entry->queryclass = PGQUERY_PREPARE;
1609 
1610  /* and remember the query text too, if possible */
1611  /* if insufficient memory, query just winds up NULL */
1612  entry->query = strdup(query);
1613 
1614  /*
1615  * Give the data a push (in pipeline mode, only if we're past the size
1616  * threshold). In nonblock mode, don't complain if we're unable to send
1617  * it all; PQgetResult() will do any additional flushing needed.
1618  */
1619  if (pqPipelineFlush(conn) < 0)
1620  goto sendFailed;
1621 
1622  /* OK, it's launched! */
1623  pqAppendCmdQueueEntry(conn, entry);
1624 
1625  return 1;
1626 
1627 sendFailed:
1628  pqRecycleCmdQueueEntry(conn, entry);
1629  /* error message should be set up already */
1630  return 0;
1631 }
1632 
1633 /*
1634  * PQsendQueryPrepared
1635  * Like PQsendQuery, but execute a previously prepared statement,
1636  * using extended query protocol so we can pass parameters
1637  */
1638 int
1640  const char *stmtName,
1641  int nParams,
1642  const char *const *paramValues,
1643  const int *paramLengths,
1644  const int *paramFormats,
1645  int resultFormat)
1646 {
1647  if (!PQsendQueryStart(conn, true))
1648  return 0;
1649 
1650  /* check the arguments */
1651  if (!stmtName)
1652  {
1653  libpq_append_conn_error(conn, "statement name is a null pointer");
1654  return 0;
1655  }
1656  if (nParams < 0 || nParams > PQ_QUERY_PARAM_MAX_LIMIT)
1657  {
1658  libpq_append_conn_error(conn, "number of parameters must be between 0 and %d",
1660  return 0;
1661  }
1662 
1663  return PQsendQueryGuts(conn,
1664  NULL, /* no command to parse */
1665  stmtName,
1666  nParams,
1667  NULL, /* no param types */
1668  paramValues,
1669  paramLengths,
1670  paramFormats,
1671  resultFormat);
1672 }
1673 
1674 /*
1675  * PQsendQueryStart
1676  * Common startup code for PQsendQuery and sibling routines
1677  */
1678 static bool
1679 PQsendQueryStart(PGconn *conn, bool newQuery)
1680 {
1681  if (!conn)
1682  return false;
1683 
1684  /*
1685  * If this is the beginning of a query cycle, reset the error state.
1686  * However, in pipeline mode with something already queued, the error
1687  * buffer belongs to that command and we shouldn't clear it.
1688  */
1689  if (newQuery && conn->cmd_queue_head == NULL)
1691 
1692  /* Don't try to send if we know there's no live connection. */
1693  if (conn->status != CONNECTION_OK)
1694  {
1695  libpq_append_conn_error(conn, "no connection to the server");
1696  return false;
1697  }
1698 
1699  /* Can't send while already busy, either, unless enqueuing for later */
1700  if (conn->asyncStatus != PGASYNC_IDLE &&
1702  {
1703  libpq_append_conn_error(conn, "another command is already in progress");
1704  return false;
1705  }
1706 
1708  {
1709  /*
1710  * When enqueuing commands we don't change much of the connection
1711  * state since it's already in use for the current command. The
1712  * connection state will get updated when pqPipelineProcessQueue()
1713  * advances to start processing the queued message.
1714  *
1715  * Just make sure we can safely enqueue given the current connection
1716  * state. We can enqueue behind another queue item, or behind a
1717  * non-queue command (one that sends its own sync), but we can't
1718  * enqueue if the connection is in a copy state.
1719  */
1720  switch (conn->asyncStatus)
1721  {
1722  case PGASYNC_IDLE:
1723  case PGASYNC_PIPELINE_IDLE:
1724  case PGASYNC_READY:
1725  case PGASYNC_READY_MORE:
1726  case PGASYNC_BUSY:
1727  /* ok to queue */
1728  break;
1729 
1730  case PGASYNC_COPY_IN:
1731  case PGASYNC_COPY_OUT:
1732  case PGASYNC_COPY_BOTH:
1733  libpq_append_conn_error(conn, "cannot queue commands during COPY");
1734  return false;
1735  }
1736  }
1737  else
1738  {
1739  /*
1740  * This command's results will come in immediately. Initialize async
1741  * result-accumulation state
1742  */
1744 
1745  /* reset single-row processing mode */
1746  conn->singleRowMode = false;
1747  }
1748 
1749  /* ready to send command message */
1750  return true;
1751 }
1752 
1753 /*
1754  * PQsendQueryGuts
1755  * Common code for sending a query with extended query protocol
1756  * PQsendQueryStart should be done already
1757  *
1758  * command may be NULL to indicate we use an already-prepared statement
1759  */
1760 static int
1762  const char *command,
1763  const char *stmtName,
1764  int nParams,
1765  const Oid *paramTypes,
1766  const char *const *paramValues,
1767  const int *paramLengths,
1768  const int *paramFormats,
1769  int resultFormat)
1770 {
1771  int i;
1772  PGcmdQueueEntry *entry;
1773 
1774  entry = pqAllocCmdQueueEntry(conn);
1775  if (entry == NULL)
1776  return 0; /* error msg already set */
1777 
1778  /*
1779  * We will send Parse (if needed), Bind, Describe Portal, Execute, Sync
1780  * (if not in pipeline mode), using specified statement name and the
1781  * unnamed portal.
1782  */
1783 
1784  if (command)
1785  {
1786  /* construct the Parse message */
1787  if (pqPutMsgStart(PqMsg_Parse, conn) < 0 ||
1788  pqPuts(stmtName, conn) < 0 ||
1789  pqPuts(command, conn) < 0)
1790  goto sendFailed;
1791  if (nParams > 0 && paramTypes)
1792  {
1793  if (pqPutInt(nParams, 2, conn) < 0)
1794  goto sendFailed;
1795  for (i = 0; i < nParams; i++)
1796  {
1797  if (pqPutInt(paramTypes[i], 4, conn) < 0)
1798  goto sendFailed;
1799  }
1800  }
1801  else
1802  {
1803  if (pqPutInt(0, 2, conn) < 0)
1804  goto sendFailed;
1805  }
1806  if (pqPutMsgEnd(conn) < 0)
1807  goto sendFailed;
1808  }
1809 
1810  /* Construct the Bind message */
1811  if (pqPutMsgStart(PqMsg_Bind, conn) < 0 ||
1812  pqPuts("", conn) < 0 ||
1813  pqPuts(stmtName, conn) < 0)
1814  goto sendFailed;
1815 
1816  /* Send parameter formats */
1817  if (nParams > 0 && paramFormats)
1818  {
1819  if (pqPutInt(nParams, 2, conn) < 0)
1820  goto sendFailed;
1821  for (i = 0; i < nParams; i++)
1822  {
1823  if (pqPutInt(paramFormats[i], 2, conn) < 0)
1824  goto sendFailed;
1825  }
1826  }
1827  else
1828  {
1829  if (pqPutInt(0, 2, conn) < 0)
1830  goto sendFailed;
1831  }
1832 
1833  if (pqPutInt(nParams, 2, conn) < 0)
1834  goto sendFailed;
1835 
1836  /* Send parameters */
1837  for (i = 0; i < nParams; i++)
1838  {
1839  if (paramValues && paramValues[i])
1840  {
1841  int nbytes;
1842 
1843  if (paramFormats && paramFormats[i] != 0)
1844  {
1845  /* binary parameter */
1846  if (paramLengths)
1847  nbytes = paramLengths[i];
1848  else
1849  {
1850  libpq_append_conn_error(conn, "length must be given for binary parameter");
1851  goto sendFailed;
1852  }
1853  }
1854  else
1855  {
1856  /* text parameter, do not use paramLengths */
1857  nbytes = strlen(paramValues[i]);
1858  }
1859  if (pqPutInt(nbytes, 4, conn) < 0 ||
1860  pqPutnchar(paramValues[i], nbytes, conn) < 0)
1861  goto sendFailed;
1862  }
1863  else
1864  {
1865  /* take the param as NULL */
1866  if (pqPutInt(-1, 4, conn) < 0)
1867  goto sendFailed;
1868  }
1869  }
1870  if (pqPutInt(1, 2, conn) < 0 ||
1871  pqPutInt(resultFormat, 2, conn))
1872  goto sendFailed;
1873  if (pqPutMsgEnd(conn) < 0)
1874  goto sendFailed;
1875 
1876  /* construct the Describe Portal message */
1877  if (pqPutMsgStart(PqMsg_Describe, conn) < 0 ||
1878  pqPutc('P', conn) < 0 ||
1879  pqPuts("", conn) < 0 ||
1880  pqPutMsgEnd(conn) < 0)
1881  goto sendFailed;
1882 
1883  /* construct the Execute message */
1884  if (pqPutMsgStart(PqMsg_Execute, conn) < 0 ||
1885  pqPuts("", conn) < 0 ||
1886  pqPutInt(0, 4, conn) < 0 ||
1887  pqPutMsgEnd(conn) < 0)
1888  goto sendFailed;
1889 
1890  /* construct the Sync message if not in pipeline mode */
1892  {
1893  if (pqPutMsgStart(PqMsg_Sync, conn) < 0 ||
1894  pqPutMsgEnd(conn) < 0)
1895  goto sendFailed;
1896  }
1897 
1898  /* remember we are using extended query protocol */
1899  entry->queryclass = PGQUERY_EXTENDED;
1900 
1901  /* and remember the query text too, if possible */
1902  /* if insufficient memory, query just winds up NULL */
1903  if (command)
1904  entry->query = strdup(command);
1905 
1906  /*
1907  * Give the data a push (in pipeline mode, only if we're past the size
1908  * threshold). In nonblock mode, don't complain if we're unable to send
1909  * it all; PQgetResult() will do any additional flushing needed.
1910  */
1911  if (pqPipelineFlush(conn) < 0)
1912  goto sendFailed;
1913 
1914  /* OK, it's launched! */
1915  pqAppendCmdQueueEntry(conn, entry);
1916 
1917  return 1;
1918 
1919 sendFailed:
1920  pqRecycleCmdQueueEntry(conn, entry);
1921  /* error message should be set up already */
1922  return 0;
1923 }
1924 
1925 /*
1926  * Select row-by-row processing mode
1927  */
1928 int
1930 {
1931  /*
1932  * Only allow setting the flag when we have launched a query and not yet
1933  * received any results.
1934  */
1935  if (!conn)
1936  return 0;
1937  if (conn->asyncStatus != PGASYNC_BUSY)
1938  return 0;
1939  if (!conn->cmd_queue_head ||
1942  return 0;
1944  return 0;
1945 
1946  /* OK, set flag */
1947  conn->singleRowMode = true;
1948  return 1;
1949 }
1950 
1951 /*
1952  * Consume any available input from the backend
1953  * 0 return: some kind of trouble
1954  * 1 return: no problem
1955  */
1956 int
1958 {
1959  if (!conn)
1960  return 0;
1961 
1962  /*
1963  * for non-blocking connections try to flush the send-queue, otherwise we
1964  * may never get a response for something that may not have already been
1965  * sent because it's in our write buffer!
1966  */
1967  if (pqIsnonblocking(conn))
1968  {
1969  if (pqFlush(conn) < 0)
1970  return 0;
1971  }
1972 
1973  /*
1974  * Load more data, if available. We do this no matter what state we are
1975  * in, since we are probably getting called because the application wants
1976  * to get rid of a read-select condition. Note that we will NOT block
1977  * waiting for more input.
1978  */
1979  if (pqReadData(conn) < 0)
1980  return 0;
1981 
1982  /* Parsing of the data waits till later. */
1983  return 1;
1984 }
1985 
1986 
1987 /*
1988  * parseInput: if appropriate, parse input data from backend
1989  * until input is exhausted or a stopping state is reached.
1990  * Note that this function will NOT attempt to read more data from the backend.
1991  */
1992 static void
1994 {
1996 }
1997 
1998 /*
1999  * PQisBusy
2000  * Return true if PQgetResult would block waiting for input.
2001  */
2002 
2003 int
2005 {
2006  if (!conn)
2007  return false;
2008 
2009  /* Parse any available data, if our state permits. */
2010  parseInput(conn);
2011 
2012  /*
2013  * PQgetResult will return immediately in all states except BUSY. Also,
2014  * if we've detected read EOF and dropped the connection, we can expect
2015  * that PQgetResult will fail immediately. Note that we do *not* check
2016  * conn->write_failed here --- once that's become set, we know we have
2017  * trouble, but we need to keep trying to read until we have a complete
2018  * server message or detect read EOF.
2019  */
2021 }
2022 
2023 /*
2024  * PQgetResult
2025  * Get the next PGresult produced by a query. Returns NULL if no
2026  * query work remains or an error has occurred (e.g. out of
2027  * memory).
2028  *
2029  * In pipeline mode, once all the result of a query have been returned,
2030  * PQgetResult returns NULL to let the user know that the next
2031  * query is being processed. At the end of the pipeline, returns a
2032  * result with PQresultStatus(result) == PGRES_PIPELINE_SYNC.
2033  */
2034 PGresult *
2036 {
2037  PGresult *res;
2038 
2039  if (!conn)
2040  return NULL;
2041 
2042  /* Parse any available data, if our state permits. */
2043  parseInput(conn);
2044 
2045  /* If not ready to return something, block until we are. */
2046  while (conn->asyncStatus == PGASYNC_BUSY)
2047  {
2048  int flushResult;
2049 
2050  /*
2051  * If data remains unsent, send it. Else we might be waiting for the
2052  * result of a command the backend hasn't even got yet.
2053  */
2054  while ((flushResult = pqFlush(conn)) > 0)
2055  {
2056  if (pqWait(false, true, conn))
2057  {
2058  flushResult = -1;
2059  break;
2060  }
2061  }
2062 
2063  /*
2064  * Wait for some more data, and load it. (Note: if the connection has
2065  * been lost, pqWait should return immediately because the socket
2066  * should be read-ready, either with the last server data or with an
2067  * EOF indication. We expect therefore that this won't result in any
2068  * undue delay in reporting a previous write failure.)
2069  */
2070  if (flushResult ||
2071  pqWait(true, false, conn) ||
2072  pqReadData(conn) < 0)
2073  {
2074  /* Report the error saved by pqWait or pqReadData */
2077  return pqPrepareAsyncResult(conn);
2078  }
2079 
2080  /* Parse it. */
2081  parseInput(conn);
2082 
2083  /*
2084  * If we had a write error, but nothing above obtained a query result
2085  * or detected a read error, report the write error.
2086  */
2088  {
2091  return pqPrepareAsyncResult(conn);
2092  }
2093  }
2094 
2095  /* Return the appropriate thing. */
2096  switch (conn->asyncStatus)
2097  {
2098  case PGASYNC_IDLE:
2099  res = NULL; /* query is complete */
2100  break;
2101  case PGASYNC_PIPELINE_IDLE:
2103 
2104  /*
2105  * We're about to return the NULL that terminates the round of
2106  * results from the current query; prepare to send the results of
2107  * the next query, if any, when we're called next. If there's no
2108  * next element in the command queue, this gets us in IDLE state.
2109  */
2111  res = NULL; /* query is complete */
2112  break;
2113 
2114  case PGASYNC_READY:
2116 
2117  /* Advance the queue as appropriate */
2118  pqCommandQueueAdvance(conn, false,
2120 
2122  {
2123  /*
2124  * We're about to send the results of the current query. Set
2125  * us idle now, and ...
2126  */
2128 
2129  /*
2130  * ... in cases when we're sending a pipeline-sync result,
2131  * move queue processing forwards immediately, so that next
2132  * time we're called, we're prepared to return the next result
2133  * received from the server. In all other cases, leave the
2134  * queue state change for next time, so that a terminating
2135  * NULL result is sent.
2136  *
2137  * (In other words: we don't return a NULL after a pipeline
2138  * sync.)
2139  */
2142  }
2143  else
2144  {
2145  /* Set the state back to BUSY, allowing parsing to proceed. */
2147  }
2148  break;
2149  case PGASYNC_READY_MORE:
2151  /* Set the state back to BUSY, allowing parsing to proceed. */
2153  break;
2154  case PGASYNC_COPY_IN:
2156  break;
2157  case PGASYNC_COPY_OUT:
2159  break;
2160  case PGASYNC_COPY_BOTH:
2162  break;
2163  default:
2164  libpq_append_conn_error(conn, "unexpected asyncStatus: %d", (int) conn->asyncStatus);
2166  conn->asyncStatus = PGASYNC_IDLE; /* try to restore valid state */
2168  break;
2169  }
2170 
2171  /* Time to fire PGEVT_RESULTCREATE events, if there are any */
2172  if (res && res->nEvents > 0)
2174 
2175  return res;
2176 }
2177 
2178 /*
2179  * getCopyResult
2180  * Helper for PQgetResult: generate result for COPY-in-progress cases
2181  */
2182 static PGresult *
2184 {
2185  /*
2186  * If the server connection has been lost, don't pretend everything is
2187  * hunky-dory; instead return a PGRES_FATAL_ERROR result, and reset the
2188  * asyncStatus to idle (corresponding to what we'd do if we'd detected I/O
2189  * error in the earlier steps in PQgetResult). The text returned in the
2190  * result is whatever is in conn->errorMessage; we hope that was filled
2191  * with something relevant when the lost connection was detected.
2192  */
2193  if (conn->status != CONNECTION_OK)
2194  {
2197  return pqPrepareAsyncResult(conn);
2198  }
2199 
2200  /* If we have an async result for the COPY, return that */
2201  if (conn->result && conn->result->resultStatus == copytype)
2202  return pqPrepareAsyncResult(conn);
2203 
2204  /* Otherwise, invent a suitable PGresult */
2205  return PQmakeEmptyPGresult(conn, copytype);
2206 }
2207 
2208 
2209 /*
2210  * PQexec
2211  * send a query to the backend and package up the result in a PGresult
2212  *
2213  * If the query was not even sent, return NULL; conn->errorMessage is set to
2214  * a relevant message.
2215  * If the query was sent, a new PGresult is returned (which could indicate
2216  * either success or failure).
2217  * The user is responsible for freeing the PGresult via PQclear()
2218  * when done with it.
2219  */
2220 PGresult *
2221 PQexec(PGconn *conn, const char *query)
2222 {
2223  if (!PQexecStart(conn))
2224  return NULL;
2225  if (!PQsendQuery(conn, query))
2226  return NULL;
2227  return PQexecFinish(conn);
2228 }
2229 
2230 /*
2231  * PQexecParams
2232  * Like PQexec, but use extended query protocol so we can pass parameters
2233  */
2234 PGresult *
2236  const char *command,
2237  int nParams,
2238  const Oid *paramTypes,
2239  const char *const *paramValues,
2240  const int *paramLengths,
2241  const int *paramFormats,
2242  int resultFormat)
2243 {
2244  if (!PQexecStart(conn))
2245  return NULL;
2246  if (!PQsendQueryParams(conn, command,
2247  nParams, paramTypes, paramValues, paramLengths,
2248  paramFormats, resultFormat))
2249  return NULL;
2250  return PQexecFinish(conn);
2251 }
2252 
2253 /*
2254  * PQprepare
2255  * Creates a prepared statement by issuing a Parse message.
2256  *
2257  * If the query was not even sent, return NULL; conn->errorMessage is set to
2258  * a relevant message.
2259  * If the query was sent, a new PGresult is returned (which could indicate
2260  * either success or failure).
2261  * The user is responsible for freeing the PGresult via PQclear()
2262  * when done with it.
2263  */
2264 PGresult *
2266  const char *stmtName, const char *query,
2267  int nParams, const Oid *paramTypes)
2268 {
2269  if (!PQexecStart(conn))
2270  return NULL;
2271  if (!PQsendPrepare(conn, stmtName, query, nParams, paramTypes))
2272  return NULL;
2273  return PQexecFinish(conn);
2274 }
2275 
2276 /*
2277  * PQexecPrepared
2278  * Like PQexec, but execute a previously prepared statement,
2279  * using extended query protocol so we can pass parameters
2280  */
2281 PGresult *
2283  const char *stmtName,
2284  int nParams,
2285  const char *const *paramValues,
2286  const int *paramLengths,
2287  const int *paramFormats,
2288  int resultFormat)
2289 {
2290  if (!PQexecStart(conn))
2291  return NULL;
2292  if (!PQsendQueryPrepared(conn, stmtName,
2293  nParams, paramValues, paramLengths,
2294  paramFormats, resultFormat))
2295  return NULL;
2296  return PQexecFinish(conn);
2297 }
2298 
2299 /*
2300  * Common code for PQexec and sibling routines: prepare to send command
2301  */
2302 static bool
2304 {
2305  PGresult *result;
2306 
2307  if (!conn)
2308  return false;
2309 
2310  /*
2311  * Since this is the beginning of a query cycle, reset the error state.
2312  * However, in pipeline mode with something already queued, the error
2313  * buffer belongs to that command and we shouldn't clear it.
2314  */
2315  if (conn->cmd_queue_head == NULL)
2317 
2319  {
2320  libpq_append_conn_error(conn, "synchronous command execution functions are not allowed in pipeline mode");
2321  return false;
2322  }
2323 
2324  /*
2325  * Silently discard any prior query result that application didn't eat.
2326  * This is probably poor design, but it's here for backward compatibility.
2327  */
2328  while ((result = PQgetResult(conn)) != NULL)
2329  {
2330  ExecStatusType resultStatus = result->resultStatus;
2331 
2332  PQclear(result); /* only need its status */
2333  if (resultStatus == PGRES_COPY_IN)
2334  {
2335  /* get out of a COPY IN state */
2336  if (PQputCopyEnd(conn,
2337  libpq_gettext("COPY terminated by new PQexec")) < 0)
2338  return false;
2339  /* keep waiting to swallow the copy's failure message */
2340  }
2341  else if (resultStatus == PGRES_COPY_OUT)
2342  {
2343  /*
2344  * Get out of a COPY OUT state: we just switch back to BUSY and
2345  * allow the remaining COPY data to be dropped on the floor.
2346  */
2348  /* keep waiting to swallow the copy's completion message */
2349  }
2350  else if (resultStatus == PGRES_COPY_BOTH)
2351  {
2352  /* We don't allow PQexec during COPY BOTH */
2353  libpq_append_conn_error(conn, "PQexec not allowed during COPY BOTH");
2354  return false;
2355  }
2356  /* check for loss of connection, too */
2357  if (conn->status == CONNECTION_BAD)
2358  return false;
2359  }
2360 
2361  /* OK to send a command */
2362  return true;
2363 }
2364 
2365 /*
2366  * Common code for PQexec and sibling routines: wait for command result
2367  */
2368 static PGresult *
2370 {
2371  PGresult *result;
2372  PGresult *lastResult;
2373 
2374  /*
2375  * For backwards compatibility, return the last result if there are more
2376  * than one. (We used to have logic here to concatenate successive error
2377  * messages, but now that happens automatically, since conn->errorMessage
2378  * will continue to accumulate errors throughout this loop.)
2379  *
2380  * We have to stop if we see copy in/out/both, however. We will resume
2381  * parsing after application performs the data transfer.
2382  *
2383  * Also stop if the connection is lost (else we'll loop infinitely).
2384  */
2385  lastResult = NULL;
2386  while ((result = PQgetResult(conn)) != NULL)
2387  {
2388  PQclear(lastResult);
2389  lastResult = result;
2390  if (result->resultStatus == PGRES_COPY_IN ||
2391  result->resultStatus == PGRES_COPY_OUT ||
2392  result->resultStatus == PGRES_COPY_BOTH ||
2394  break;
2395  }
2396 
2397  return lastResult;
2398 }
2399 
2400 /*
2401  * PQdescribePrepared
2402  * Obtain information about a previously prepared statement
2403  *
2404  * If the query was not even sent, return NULL; conn->errorMessage is set to
2405  * a relevant message.
2406  * If the query was sent, a new PGresult is returned (which could indicate
2407  * either success or failure). On success, the PGresult contains status
2408  * PGRES_COMMAND_OK, and its parameter and column-heading fields describe
2409  * the statement's inputs and outputs respectively.
2410  * The user is responsible for freeing the PGresult via PQclear()
2411  * when done with it.
2412  */
2413 PGresult *
2415 {
2416  if (!PQexecStart(conn))
2417  return NULL;
2419  return NULL;
2420  return PQexecFinish(conn);
2421 }
2422 
2423 /*
2424  * PQdescribePortal
2425  * Obtain information about a previously created portal
2426  *
2427  * This is much like PQdescribePrepared, except that no parameter info is
2428  * returned. Note that at the moment, libpq doesn't really expose portals
2429  * to the client; but this can be used with a portal created by a SQL
2430  * DECLARE CURSOR command.
2431  */
2432 PGresult *
2433 PQdescribePortal(PGconn *conn, const char *portal)
2434 {
2435  if (!PQexecStart(conn))
2436  return NULL;
2437  if (!PQsendTypedCommand(conn, PqMsg_Describe, 'P', portal))
2438  return NULL;
2439  return PQexecFinish(conn);
2440 }
2441 
2442 /*
2443  * PQsendDescribePrepared
2444  * Submit a Describe Statement command, but don't wait for it to finish
2445  *
2446  * Returns: 1 if successfully submitted
2447  * 0 if error (conn->errorMessage is set)
2448  */
2449 int
2451 {
2452  return PQsendTypedCommand(conn, PqMsg_Describe, 'S', stmt);
2453 }
2454 
2455 /*
2456  * PQsendDescribePortal
2457  * Submit a Describe Portal command, but don't wait for it to finish
2458  *
2459  * Returns: 1 if successfully submitted
2460  * 0 if error (conn->errorMessage is set)
2461  */
2462 int
2463 PQsendDescribePortal(PGconn *conn, const char *portal)
2464 {
2465  return PQsendTypedCommand(conn, PqMsg_Describe, 'P', portal);
2466 }
2467 
2468 /*
2469  * PQclosePrepared
2470  * Close a previously prepared statement
2471  *
2472  * If the query was not even sent, return NULL; conn->errorMessage is set to
2473  * a relevant message.
2474  * If the query was sent, a new PGresult is returned (which could indicate
2475  * either success or failure). On success, the PGresult contains status
2476  * PGRES_COMMAND_OK. The user is responsible for freeing the PGresult via
2477  * PQclear() when done with it.
2478  */
2479 PGresult *
2481 {
2482  if (!PQexecStart(conn))
2483  return NULL;
2484  if (!PQsendTypedCommand(conn, PqMsg_Close, 'S', stmt))
2485  return NULL;
2486  return PQexecFinish(conn);
2487 }
2488 
2489 /*
2490  * PQclosePortal
2491  * Close a previously created portal
2492  *
2493  * This is exactly like PQclosePrepared, but for portals. Note that at the
2494  * moment, libpq doesn't really expose portals to the client; but this can be
2495  * used with a portal created by a SQL DECLARE CURSOR command.
2496  */
2497 PGresult *
2498 PQclosePortal(PGconn *conn, const char *portal)
2499 {
2500  if (!PQexecStart(conn))
2501  return NULL;
2502  if (!PQsendTypedCommand(conn, PqMsg_Close, 'P', portal))
2503  return NULL;
2504  return PQexecFinish(conn);
2505 }
2506 
2507 /*
2508  * PQsendClosePrepared
2509  * Submit a Close Statement command, but don't wait for it to finish
2510  *
2511  * Returns: 1 if successfully submitted
2512  * 0 if error (conn->errorMessage is set)
2513  */
2514 int
2516 {
2517  return PQsendTypedCommand(conn, PqMsg_Close, 'S', stmt);
2518 }
2519 
2520 /*
2521  * PQsendClosePortal
2522  * Submit a Close Portal command, but don't wait for it to finish
2523  *
2524  * Returns: 1 if successfully submitted
2525  * 0 if error (conn->errorMessage is set)
2526  */
2527 int
2528 PQsendClosePortal(PGconn *conn, const char *portal)
2529 {
2530  return PQsendTypedCommand(conn, PqMsg_Close, 'P', portal);
2531 }
2532 
2533 /*
2534  * PQsendTypedCommand
2535  * Common code to send a Describe or Close command
2536  *
2537  * Available options for "command" are
2538  * PqMsg_Close for Close; or
2539  * PqMsg_Describe for Describe.
2540  *
2541  * Available options for "type" are
2542  * 'S' to run a command on a prepared statement; or
2543  * 'P' to run a command on a portal.
2544  *
2545  * Returns 1 on success and 0 on failure.
2546  */
2547 static int
2548 PQsendTypedCommand(PGconn *conn, char command, char type, const char *target)
2549 {
2550  PGcmdQueueEntry *entry = NULL;
2551 
2552  /* Treat null target as empty string */
2553  if (!target)
2554  target = "";
2555 
2556  if (!PQsendQueryStart(conn, true))
2557  return 0;
2558 
2559  entry = pqAllocCmdQueueEntry(conn);
2560  if (entry == NULL)
2561  return 0; /* error msg already set */
2562 
2563  /* construct the Close message */
2564  if (pqPutMsgStart(command, conn) < 0 ||
2565  pqPutc(type, conn) < 0 ||
2566  pqPuts(target, conn) < 0 ||
2567  pqPutMsgEnd(conn) < 0)
2568  goto sendFailed;
2569 
2570  /* construct the Sync message */
2572  {
2573  if (pqPutMsgStart(PqMsg_Sync, conn) < 0 ||
2574  pqPutMsgEnd(conn) < 0)
2575  goto sendFailed;
2576  }
2577 
2578  /* remember if we are doing a Close or a Describe */
2579  if (command == PqMsg_Close)
2580  {
2581  entry->queryclass = PGQUERY_CLOSE;
2582  }
2583  else if (command == PqMsg_Describe)
2584  {
2585  entry->queryclass = PGQUERY_DESCRIBE;
2586  }
2587  else
2588  {
2589  libpq_append_conn_error(conn, "unknown command type provided");
2590  goto sendFailed;
2591  }
2592 
2593  /*
2594  * Give the data a push (in pipeline mode, only if we're past the size
2595  * threshold). In nonblock mode, don't complain if we're unable to send
2596  * it all; PQgetResult() will do any additional flushing needed.
2597  */
2598  if (pqPipelineFlush(conn) < 0)
2599  goto sendFailed;
2600 
2601  /* OK, it's launched! */
2602  pqAppendCmdQueueEntry(conn, entry);
2603 
2604  return 1;
2605 
2606 sendFailed:
2607  pqRecycleCmdQueueEntry(conn, entry);
2608  /* error message should be set up already */
2609  return 0;
2610 }
2611 
2612 /*
2613  * PQnotifies
2614  * returns a PGnotify* structure of the latest async notification
2615  * that has not yet been handled
2616  *
2617  * returns NULL, if there is currently
2618  * no unhandled async notification from the backend
2619  *
2620  * the CALLER is responsible for FREE'ing the structure returned
2621  *
2622  * Note that this function does not read any new data from the socket;
2623  * so usually, caller should call PQconsumeInput() first.
2624  */
2625 PGnotify *
2627 {
2628  PGnotify *event;
2629 
2630  if (!conn)
2631  return NULL;
2632 
2633  /* Parse any available data to see if we can extract NOTIFY messages. */
2634  parseInput(conn);
2635 
2636  event = conn->notifyHead;
2637  if (event)
2638  {
2639  conn->notifyHead = event->next;
2640  if (!conn->notifyHead)
2641  conn->notifyTail = NULL;
2642  event->next = NULL; /* don't let app see the internal state */
2643  }
2644  return event;
2645 }
2646 
2647 /*
2648  * PQputCopyData - send some data to the backend during COPY IN or COPY BOTH
2649  *
2650  * Returns 1 if successful, 0 if data could not be sent (only possible
2651  * in nonblock mode), or -1 if an error occurs.
2652  */
2653 int
2654 PQputCopyData(PGconn *conn, const char *buffer, int nbytes)
2655 {
2656  if (!conn)
2657  return -1;
2658  if (conn->asyncStatus != PGASYNC_COPY_IN &&
2660  {
2661  libpq_append_conn_error(conn, "no COPY in progress");
2662  return -1;
2663  }
2664 
2665  /*
2666  * Process any NOTICE or NOTIFY messages that might be pending in the
2667  * input buffer. Since the server might generate many notices during the
2668  * COPY, we want to clean those out reasonably promptly to prevent
2669  * indefinite expansion of the input buffer. (Note: the actual read of
2670  * input data into the input buffer happens down inside pqSendSome, but
2671  * it's not authorized to get rid of the data again.)
2672  */
2673  parseInput(conn);
2674 
2675  if (nbytes > 0)
2676  {
2677  /*
2678  * Try to flush any previously sent data in preference to growing the
2679  * output buffer. If we can't enlarge the buffer enough to hold the
2680  * data, return 0 in the nonblock case, else hard error. (For
2681  * simplicity, always assume 5 bytes of overhead.)
2682  */
2683  if ((conn->outBufSize - conn->outCount - 5) < nbytes)
2684  {
2685  if (pqFlush(conn) < 0)
2686  return -1;
2687  if (pqCheckOutBufferSpace(conn->outCount + 5 + (size_t) nbytes,
2688  conn))
2689  return pqIsnonblocking(conn) ? 0 : -1;
2690  }
2691  /* Send the data (too simple to delegate to fe-protocol files) */
2692  if (pqPutMsgStart(PqMsg_CopyData, conn) < 0 ||
2693  pqPutnchar(buffer, nbytes, conn) < 0 ||
2694  pqPutMsgEnd(conn) < 0)
2695  return -1;
2696  }
2697  return 1;
2698 }
2699 
2700 /*
2701  * PQputCopyEnd - send EOF indication to the backend during COPY IN
2702  *
2703  * After calling this, use PQgetResult() to check command completion status.
2704  *
2705  * Returns 1 if successful, or -1 if an error occurs.
2706  */
2707 int
2708 PQputCopyEnd(PGconn *conn, const char *errormsg)
2709 {
2710  if (!conn)
2711  return -1;
2712  if (conn->asyncStatus != PGASYNC_COPY_IN &&
2714  {
2715  libpq_append_conn_error(conn, "no COPY in progress");
2716  return -1;
2717  }
2718 
2719  /*
2720  * Send the COPY END indicator. This is simple enough that we don't
2721  * bother delegating it to the fe-protocol files.
2722  */
2723  if (errormsg)
2724  {
2725  /* Send COPY FAIL */
2726  if (pqPutMsgStart(PqMsg_CopyFail, conn) < 0 ||
2727  pqPuts(errormsg, conn) < 0 ||
2728  pqPutMsgEnd(conn) < 0)
2729  return -1;
2730  }
2731  else
2732  {
2733  /* Send COPY DONE */
2734  if (pqPutMsgStart(PqMsg_CopyDone, conn) < 0 ||
2735  pqPutMsgEnd(conn) < 0)
2736  return -1;
2737  }
2738 
2739  /*
2740  * If we sent the COPY command in extended-query mode, we must issue a
2741  * Sync as well.
2742  */
2743  if (conn->cmd_queue_head &&
2745  {
2746  if (pqPutMsgStart(PqMsg_Sync, conn) < 0 ||
2747  pqPutMsgEnd(conn) < 0)
2748  return -1;
2749  }
2750 
2751  /* Return to active duty */
2754  else
2756 
2757  /* Try to flush data */
2758  if (pqFlush(conn) < 0)
2759  return -1;
2760 
2761  return 1;
2762 }
2763 
2764 /*
2765  * PQgetCopyData - read a row of data from the backend during COPY OUT
2766  * or COPY BOTH
2767  *
2768  * If successful, sets *buffer to point to a malloc'd row of data, and
2769  * returns row length (always > 0) as result.
2770  * Returns 0 if no row available yet (only possible if async is true),
2771  * -1 if end of copy (consult PQgetResult), or -2 if error (consult
2772  * PQerrorMessage).
2773  */
2774 int
2775 PQgetCopyData(PGconn *conn, char **buffer, int async)
2776 {
2777  *buffer = NULL; /* for all failure cases */
2778  if (!conn)
2779  return -2;
2780  if (conn->asyncStatus != PGASYNC_COPY_OUT &&
2782  {
2783  libpq_append_conn_error(conn, "no COPY in progress");
2784  return -2;
2785  }
2786  return pqGetCopyData3(conn, buffer, async);
2787 }
2788 
2789 /*
2790  * PQgetline - gets a newline-terminated string from the backend.
2791  *
2792  * Chiefly here so that applications can use "COPY <rel> to stdout"
2793  * and read the output string. Returns a null-terminated string in `buffer`.
2794  *
2795  * XXX this routine is now deprecated, because it can't handle binary data.
2796  * If called during a COPY BINARY we return EOF.
2797  *
2798  * PQgetline reads up to `length`-1 characters (like fgets(3)) but strips
2799  * the terminating \n (like gets(3)).
2800  *
2801  * CAUTION: the caller is responsible for detecting the end-of-copy signal
2802  * (a line containing just "\.") when using this routine.
2803  *
2804  * RETURNS:
2805  * EOF if error (eg, invalid arguments are given)
2806  * 0 if EOL is reached (i.e., \n has been read)
2807  * (this is required for backward-compatibility -- this
2808  * routine used to always return EOF or 0, assuming that
2809  * the line ended within `length` bytes.)
2810  * 1 in other cases (i.e., the buffer was filled before \n is reached)
2811  */
2812 int
2813 PQgetline(PGconn *conn, char *buffer, int length)
2814 {
2815  if (!buffer || length <= 0)
2816  return EOF;
2817  *buffer = '\0';
2818  /* length must be at least 3 to hold the \. terminator! */
2819  if (length < 3)
2820  return EOF;
2821 
2822  if (!conn)
2823  return EOF;
2824 
2825  return pqGetline3(conn, buffer, length);
2826 }
2827 
2828 /*
2829  * PQgetlineAsync - gets a COPY data row without blocking.
2830  *
2831  * This routine is for applications that want to do "COPY <rel> to stdout"
2832  * asynchronously, that is without blocking. Having issued the COPY command
2833  * and gotten a PGRES_COPY_OUT response, the app should call PQconsumeInput
2834  * and this routine until the end-of-data signal is detected. Unlike
2835  * PQgetline, this routine takes responsibility for detecting end-of-data.
2836  *
2837  * On each call, PQgetlineAsync will return data if a complete data row
2838  * is available in libpq's input buffer. Otherwise, no data is returned
2839  * until the rest of the row arrives.
2840  *
2841  * If -1 is returned, the end-of-data signal has been recognized (and removed
2842  * from libpq's input buffer). The caller *must* next call PQendcopy and
2843  * then return to normal processing.
2844  *
2845  * RETURNS:
2846  * -1 if the end-of-copy-data marker has been recognized
2847  * 0 if no data is available
2848  * >0 the number of bytes returned.
2849  *
2850  * The data returned will not extend beyond a data-row boundary. If possible
2851  * a whole row will be returned at one time. But if the buffer offered by
2852  * the caller is too small to hold a row sent by the backend, then a partial
2853  * data row will be returned. In text mode this can be detected by testing
2854  * whether the last returned byte is '\n' or not.
2855  *
2856  * The returned data is *not* null-terminated.
2857  */
2858 
2859 int
2860 PQgetlineAsync(PGconn *conn, char *buffer, int bufsize)
2861 {
2862  if (!conn)
2863  return -1;
2864 
2865  return pqGetlineAsync3(conn, buffer, bufsize);
2866 }
2867 
2868 /*
2869  * PQputline -- sends a string to the backend during COPY IN.
2870  * Returns 0 if OK, EOF if not.
2871  *
2872  * This is deprecated primarily because the return convention doesn't allow
2873  * caller to tell the difference between a hard error and a nonblock-mode
2874  * send failure.
2875  */
2876 int
2877 PQputline(PGconn *conn, const char *string)
2878 {
2879  return PQputnbytes(conn, string, strlen(string));
2880 }
2881 
2882 /*
2883  * PQputnbytes -- like PQputline, but buffer need not be null-terminated.
2884  * Returns 0 if OK, EOF if not.
2885  */
2886 int
2887 PQputnbytes(PGconn *conn, const char *buffer, int nbytes)
2888 {
2889  if (PQputCopyData(conn, buffer, nbytes) > 0)
2890  return 0;
2891  else
2892  return EOF;
2893 }
2894 
2895 /*
2896  * PQendcopy
2897  * After completing the data transfer portion of a copy in/out,
2898  * the application must call this routine to finish the command protocol.
2899  *
2900  * This is deprecated; it's cleaner to use PQgetResult to get the transfer
2901  * status.
2902  *
2903  * RETURNS:
2904  * 0 on success
2905  * 1 on failure
2906  */
2907 int
2909 {
2910  if (!conn)
2911  return 0;
2912 
2913  return pqEndcopy3(conn);
2914 }
2915 
2916 
2917 /* ----------------
2918  * PQfn - Send a function call to the POSTGRES backend.
2919  *
2920  * conn : backend connection
2921  * fnid : OID of function to be called
2922  * result_buf : pointer to result buffer
2923  * result_len : actual length of result is returned here
2924  * result_is_int : If the result is an integer, this must be 1,
2925  * otherwise this should be 0
2926  * args : pointer to an array of function arguments
2927  * (each has length, if integer, and value/pointer)
2928  * nargs : # of arguments in args array.
2929  *
2930  * RETURNS
2931  * PGresult with status = PGRES_COMMAND_OK if successful.
2932  * *result_len is > 0 if there is a return value, 0 if not.
2933  * PGresult with status = PGRES_FATAL_ERROR if backend returns an error.
2934  * NULL on communications failure. conn->errorMessage will be set.
2935  * ----------------
2936  */
2937 
2938 PGresult *
2940  int fnid,
2941  int *result_buf,
2942  int *result_len,
2943  int result_is_int,
2944  const PQArgBlock *args,
2945  int nargs)
2946 {
2947  *result_len = 0;
2948 
2949  if (!conn)
2950  return NULL;
2951 
2952  /*
2953  * Since this is the beginning of a query cycle, reset the error state.
2954  * However, in pipeline mode with something already queued, the error
2955  * buffer belongs to that command and we shouldn't clear it.
2956  */
2957  if (conn->cmd_queue_head == NULL)
2959 
2961  {
2962  libpq_append_conn_error(conn, "%s not allowed in pipeline mode", "PQfn");
2963  return NULL;
2964  }
2965 
2968  {
2969  libpq_append_conn_error(conn, "connection in wrong state");
2970  return NULL;
2971  }
2972 
2973  return pqFunctionCall3(conn, fnid,
2974  result_buf, result_len,
2975  result_is_int,
2976  args, nargs);
2977 }
2978 
2979 /* ====== Pipeline mode support ======== */
2980 
2981 /*
2982  * PQenterPipelineMode
2983  * Put an idle connection in pipeline mode.
2984  *
2985  * Returns 1 on success. On failure, errorMessage is set and 0 is returned.
2986  *
2987  * Commands submitted after this can be pipelined on the connection;
2988  * there's no requirement to wait for one to finish before the next is
2989  * dispatched.
2990  *
2991  * Queuing of a new query or syncing during COPY is not allowed.
2992  *
2993  * A set of commands is terminated by a PQpipelineSync. Multiple sync
2994  * points can be established while in pipeline mode. Pipeline mode can
2995  * be exited by calling PQexitPipelineMode() once all results are processed.
2996  *
2997  * This doesn't actually send anything on the wire, it just puts libpq
2998  * into a state where it can pipeline work.
2999  */
3000 int
3002 {
3003  if (!conn)
3004  return 0;
3005 
3006  /* succeed with no action if already in pipeline mode */
3008  return 1;
3009 
3010  if (conn->asyncStatus != PGASYNC_IDLE)
3011  {
3012  libpq_append_conn_error(conn, "cannot enter pipeline mode, connection not idle");
3013  return 0;
3014  }
3015 
3017 
3018  return 1;
3019 }
3020 
3021 /*
3022  * PQexitPipelineMode
3023  * End pipeline mode and return to normal command mode.
3024  *
3025  * Returns 1 in success (pipeline mode successfully ended, or not in pipeline
3026  * mode).
3027  *
3028  * Returns 0 if in pipeline mode and cannot be ended yet. Error message will
3029  * be set.
3030  */
3031 int
3033 {
3034  if (!conn)
3035  return 0;
3036 
3038  (conn->asyncStatus == PGASYNC_IDLE ||
3040  conn->cmd_queue_head == NULL)
3041  return 1;
3042 
3043  switch (conn->asyncStatus)
3044  {
3045  case PGASYNC_READY:
3046  case PGASYNC_READY_MORE:
3047  /* there are some uncollected results */
3048  libpq_append_conn_error(conn, "cannot exit pipeline mode with uncollected results");
3049  return 0;
3050 
3051  case PGASYNC_BUSY:
3052  libpq_append_conn_error(conn, "cannot exit pipeline mode while busy");
3053  return 0;
3054 
3055  case PGASYNC_IDLE:
3056  case PGASYNC_PIPELINE_IDLE:
3057  /* OK */
3058  break;
3059 
3060  case PGASYNC_COPY_IN:
3061  case PGASYNC_COPY_OUT:
3062  case PGASYNC_COPY_BOTH:
3063  libpq_append_conn_error(conn, "cannot exit pipeline mode while in COPY");
3064  }
3065 
3066  /* still work to process */
3067  if (conn->cmd_queue_head != NULL)
3068  {
3069  libpq_append_conn_error(conn, "cannot exit pipeline mode with uncollected results");
3070  return 0;
3071  }
3072 
3075 
3076  /* Flush any pending data in out buffer */
3077  if (pqFlush(conn) < 0)
3078  return 0; /* error message is setup already */
3079  return 1;
3080 }
3081 
3082 /*
3083  * pqCommandQueueAdvance
3084  * Remove one query from the command queue, if appropriate.
3085  *
3086  * If we have received all results corresponding to the head element
3087  * in the command queue, remove it.
3088  *
3089  * In simple query protocol we must not advance the command queue until the
3090  * ReadyForQuery message has been received. This is because in simple mode a
3091  * command can have multiple queries, and we must process result for all of
3092  * them before moving on to the next command.
3093  *
3094  * Another consideration is synchronization during error processing in
3095  * extended query protocol: we refuse to advance the queue past a SYNC queue
3096  * element, unless the result we've received is also a SYNC. In particular
3097  * this protects us from advancing when an error is received at an
3098  * inappropriate moment.
3099  */
3100 void
3101 pqCommandQueueAdvance(PGconn *conn, bool isReadyForQuery, bool gotSync)
3102 {
3103  PGcmdQueueEntry *prevquery;
3104 
3105  if (conn->cmd_queue_head == NULL)
3106  return;
3107 
3108  /*
3109  * If processing a query of simple query protocol, we only advance the
3110  * queue when we receive the ReadyForQuery message for it.
3111  */
3112  if (conn->cmd_queue_head->queryclass == PGQUERY_SIMPLE && !isReadyForQuery)
3113  return;
3114 
3115  /*
3116  * If we're waiting for a SYNC, don't advance the queue until we get one.
3117  */
3118  if (conn->cmd_queue_head->queryclass == PGQUERY_SYNC && !gotSync)
3119  return;
3120 
3121  /* delink element from queue */
3122  prevquery = conn->cmd_queue_head;
3124 
3125  /* If the queue is now empty, reset the tail too */
3126  if (conn->cmd_queue_head == NULL)
3127  conn->cmd_queue_tail = NULL;
3128 
3129  /* and make the queue element recyclable */
3130  prevquery->next = NULL;
3131  pqRecycleCmdQueueEntry(conn, prevquery);
3132 }
3133 
3134 /*
3135  * pqPipelineProcessQueue: subroutine for PQgetResult
3136  * In pipeline mode, start processing the results of the next query in the queue.
3137  */
3138 static void
3140 {
3141  switch (conn->asyncStatus)
3142  {
3143  case PGASYNC_COPY_IN:
3144  case PGASYNC_COPY_OUT:
3145  case PGASYNC_COPY_BOTH:
3146  case PGASYNC_READY:
3147  case PGASYNC_READY_MORE:
3148  case PGASYNC_BUSY:
3149  /* client still has to process current query or results */
3150  return;
3151 
3152  case PGASYNC_IDLE:
3153 
3154  /*
3155  * If we're in IDLE mode and there's some command in the queue,
3156  * get us into PIPELINE_IDLE mode and process normally. Otherwise
3157  * there's nothing for us to do.
3158  */
3159  if (conn->cmd_queue_head != NULL)
3160  {
3162  break;
3163  }
3164  return;
3165 
3166  case PGASYNC_PIPELINE_IDLE:
3168  /* next query please */
3169  break;
3170  }
3171 
3172  /*
3173  * Reset single-row processing mode. (Client has to set it up for each
3174  * query, if desired.)
3175  */
3176  conn->singleRowMode = false;
3177 
3178  /*
3179  * If there are no further commands to process in the queue, get us in
3180  * "real idle" mode now.
3181  */
3182  if (conn->cmd_queue_head == NULL)
3183  {
3185  return;
3186  }
3187 
3188  /*
3189  * Reset the error state. This and the next couple of steps correspond to
3190  * what PQsendQueryStart didn't do for this query.
3191  */
3193 
3194  /* Initialize async result-accumulation state */
3196 
3199  {
3200  /*
3201  * In an aborted pipeline we don't get anything from the server for
3202  * each result; we're just discarding commands from the queue until we
3203  * get to the next sync from the server.
3204  *
3205  * The PGRES_PIPELINE_ABORTED results tell the client that its queries
3206  * got aborted.
3207  */
3209  if (!conn->result)
3210  {
3211  libpq_append_conn_error(conn, "out of memory");
3213  return;
3214  }
3216  }
3217  else
3218  {
3219  /* allow parsing to continue */
3221  }
3222 }
3223 
3224 /*
3225  * PQpipelineSync
3226  * Send a Sync message as part of a pipeline, and flush to server
3227  *
3228  * It's legal to start submitting more commands in the pipeline immediately,
3229  * without waiting for the results of the current pipeline. There's no need to
3230  * end pipeline mode and start it again.
3231  *
3232  * If a command in a pipeline fails, every subsequent command up to and including
3233  * the result to the Sync message sent by PQpipelineSync gets set to
3234  * PGRES_PIPELINE_ABORTED state. If the whole pipeline is processed without
3235  * error, a PGresult with PGRES_PIPELINE_SYNC is produced.
3236  *
3237  * Queries can already have been sent before PQpipelineSync is called, but
3238  * PQpipelineSync need to be called before retrieving command results.
3239  *
3240  * The connection will remain in pipeline mode and unavailable for new
3241  * synchronous command execution functions until all results from the pipeline
3242  * are processed by the client.
3243  */
3244 int
3246 {
3247  PGcmdQueueEntry *entry;
3248 
3249  if (!conn)
3250  return 0;
3251 
3253  {
3254  libpq_append_conn_error(conn, "cannot send pipeline when not in pipeline mode");
3255  return 0;
3256  }
3257 
3258  switch (conn->asyncStatus)
3259  {
3260  case PGASYNC_COPY_IN:
3261  case PGASYNC_COPY_OUT:
3262  case PGASYNC_COPY_BOTH:
3263  /* should be unreachable */
3265  "internal error: cannot send pipeline while in COPY\n");
3266  return 0;
3267  case PGASYNC_READY:
3268  case PGASYNC_READY_MORE:
3269  case PGASYNC_BUSY:
3270  case PGASYNC_IDLE:
3271  case PGASYNC_PIPELINE_IDLE:
3272  /* OK to send sync */
3273  break;
3274  }
3275 
3276  entry = pqAllocCmdQueueEntry(conn);
3277  if (entry == NULL)
3278  return 0; /* error msg already set */
3279 
3280  entry->queryclass = PGQUERY_SYNC;
3281  entry->query = NULL;
3282 
3283  /* construct the Sync message */
3284  if (pqPutMsgStart(PqMsg_Sync, conn) < 0 ||
3285  pqPutMsgEnd(conn) < 0)
3286  goto sendFailed;
3287 
3288  /*
3289  * Give the data a push. In nonblock mode, don't complain if we're unable
3290  * to send it all; PQgetResult() will do any additional flushing needed.
3291  */
3292  if (PQflush(conn) < 0)
3293  goto sendFailed;
3294 
3295  /* OK, it's launched! */
3296  pqAppendCmdQueueEntry(conn, entry);
3297 
3298  return 1;
3299 
3300 sendFailed:
3301  pqRecycleCmdQueueEntry(conn, entry);
3302  /* error message should be set up already */
3303  return 0;
3304 }
3305 
3306 /*
3307  * PQsendFlushRequest
3308  * Send request for server to flush its buffer. Useful in pipeline
3309  * mode when a sync point is not desired.
3310  */
3311 int
3313 {
3314  if (!conn)
3315  return 0;
3316 
3317  /* Don't try to send if we know there's no live connection. */
3318  if (conn->status != CONNECTION_OK)
3319  {
3320  libpq_append_conn_error(conn, "no connection to the server");
3321  return 0;
3322  }
3323 
3324  /* Can't send while already busy, either, unless enqueuing for later */
3325  if (conn->asyncStatus != PGASYNC_IDLE &&
3327  {
3328  libpq_append_conn_error(conn, "another command is already in progress");
3329  return 0;
3330  }
3331 
3332  if (pqPutMsgStart(PqMsg_Flush, conn) < 0 ||
3333  pqPutMsgEnd(conn) < 0)
3334  {
3335  return 0;
3336  }
3337 
3338  /*
3339  * Give the data a push (in pipeline mode, only if we're past the size
3340  * threshold). In nonblock mode, don't complain if we're unable to send
3341  * it all; PQgetResult() will do any additional flushing needed.
3342  */
3343  if (pqPipelineFlush(conn) < 0)
3344  return 0;
3345 
3346  return 1;
3347 }
3348 
3349 /* ====== accessor funcs for PGresult ======== */
3350 
3353 {
3354  if (!res)
3355  return PGRES_FATAL_ERROR;
3356  return res->resultStatus;
3357 }
3358 
3359 char *
3361 {
3362  if ((unsigned int) status >= lengthof(pgresStatus))
3363  return libpq_gettext("invalid ExecStatusType code");
3364  return pgresStatus[status];
3365 }
3366 
3367 char *
3369 {
3370  if (!res || !res->errMsg)
3371  return "";
3372  return res->errMsg;
3373 }
3374 
3375 char *
3377  PGVerbosity verbosity,
3378  PGContextVisibility show_context)
3379 {
3380  PQExpBufferData workBuf;
3381 
3382  /*
3383  * Because the caller is expected to free the result string, we must
3384  * strdup any constant result. We use plain strdup and document that
3385  * callers should expect NULL if out-of-memory.
3386  */
3387  if (!res ||
3390  return strdup(libpq_gettext("PGresult is not an error result\n"));
3391 
3392  initPQExpBuffer(&workBuf);
3393 
3394  pqBuildErrorMessage3(&workBuf, res, verbosity, show_context);
3395 
3396  /* If insufficient memory to format the message, fail cleanly */
3397  if (PQExpBufferDataBroken(workBuf))
3398  {
3399  termPQExpBuffer(&workBuf);
3400  return strdup(libpq_gettext("out of memory\n"));
3401  }
3402 
3403  return workBuf.data;
3404 }
3405 
3406 char *
3407 PQresultErrorField(const PGresult *res, int fieldcode)
3408 {
3409  PGMessageField *pfield;
3410 
3411  if (!res)
3412  return NULL;
3413  for (pfield = res->errFields; pfield != NULL; pfield = pfield->next)
3414  {
3415  if (pfield->code == fieldcode)
3416  return pfield->contents;
3417  }
3418  return NULL;
3419 }
3420 
3421 int
3423 {
3424  if (!res)
3425  return 0;
3426  return res->ntups;
3427 }
3428 
3429 int
3431 {
3432  if (!res)
3433  return 0;
3434  return res->numAttributes;
3435 }
3436 
3437 int
3439 {
3440  if (!res)
3441  return 0;
3442  return res->binary;
3443 }
3444 
3445 /*
3446  * Helper routines to range-check field numbers and tuple numbers.
3447  * Return true if OK, false if not
3448  */
3449 
3450 static int
3451 check_field_number(const PGresult *res, int field_num)
3452 {
3453  if (!res)
3454  return false; /* no way to display error message... */
3455  if (field_num < 0 || field_num >= res->numAttributes)
3456  {
3458  "column number %d is out of range 0..%d",
3459  field_num, res->numAttributes - 1);
3460  return false;
3461  }
3462  return true;
3463 }
3464 
3465 static int
3467  int tup_num, int field_num)
3468 {
3469  if (!res)
3470  return false; /* no way to display error message... */
3471  if (tup_num < 0 || tup_num >= res->ntups)
3472  {
3474  "row number %d is out of range 0..%d",
3475  tup_num, res->ntups - 1);
3476  return false;
3477  }
3478  if (field_num < 0 || field_num >= res->numAttributes)
3479  {
3481  "column number %d is out of range 0..%d",
3482  field_num, res->numAttributes - 1);
3483  return false;
3484  }
3485  return true;
3486 }
3487 
3488 static int
3489 check_param_number(const PGresult *res, int param_num)
3490 {
3491  if (!res)
3492  return false; /* no way to display error message... */
3493  if (param_num < 0 || param_num >= res->numParameters)
3494  {
3496  "parameter number %d is out of range 0..%d",
3497  param_num, res->numParameters - 1);
3498  return false;
3499  }
3500 
3501  return true;
3502 }
3503 
3504 /*
3505  * returns NULL if the field_num is invalid
3506  */
3507 char *
3508 PQfname(const PGresult *res, int field_num)
3509 {
3510  if (!check_field_number(res, field_num))
3511  return NULL;
3512  if (res->attDescs)
3513  return res->attDescs[field_num].name;
3514  else
3515  return NULL;
3516 }
3517 
3518 /*
3519  * PQfnumber: find column number given column name
3520  *
3521  * The column name is parsed as if it were in a SQL statement, including
3522  * case-folding and double-quote processing. But note a possible gotcha:
3523  * downcasing in the frontend might follow different locale rules than
3524  * downcasing in the backend...
3525  *
3526  * Returns -1 if no match. In the present backend it is also possible
3527  * to have multiple matches, in which case the first one is found.
3528  */
3529 int
3530 PQfnumber(const PGresult *res, const char *field_name)
3531 {
3532  char *field_case;
3533  bool in_quotes;
3534  bool all_lower = true;
3535  const char *iptr;
3536  char *optr;
3537  int i;
3538 
3539  if (!res)
3540  return -1;
3541 
3542  /*
3543  * Note: it is correct to reject a zero-length input string; the proper
3544  * input to match a zero-length field name would be "".
3545  */
3546  if (field_name == NULL ||
3547  field_name[0] == '\0' ||
3548  res->attDescs == NULL)
3549  return -1;
3550 
3551  /*
3552  * Check if we can avoid the strdup() and related work because the
3553  * passed-in string wouldn't be changed before we do the check anyway.
3554  */
3555  for (iptr = field_name; *iptr; iptr++)
3556  {
3557  char c = *iptr;
3558 
3559  if (c == '"' || c != pg_tolower((unsigned char) c))
3560  {
3561  all_lower = false;
3562  break;
3563  }
3564  }
3565 
3566  if (all_lower)
3567  for (i = 0; i < res->numAttributes; i++)
3568  if (strcmp(field_name, res->attDescs[i].name) == 0)
3569  return i;
3570 
3571  /* Fall through to the normal check if that didn't work out. */
3572 
3573  /*
3574  * Note: this code will not reject partially quoted strings, eg
3575  * foo"BAR"foo will become fooBARfoo when it probably ought to be an error
3576  * condition.
3577  */
3578  field_case = strdup(field_name);
3579  if (field_case == NULL)
3580  return -1; /* grotty */
3581 
3582  in_quotes = false;
3583  optr = field_case;
3584  for (iptr = field_case; *iptr; iptr++)
3585  {
3586  char c = *iptr;
3587 
3588  if (in_quotes)
3589  {
3590  if (c == '"')
3591  {
3592  if (iptr[1] == '"')
3593  {
3594  /* doubled quotes become a single quote */
3595  *optr++ = '"';
3596  iptr++;
3597  }
3598  else
3599  in_quotes = false;
3600  }
3601  else
3602  *optr++ = c;
3603  }
3604  else if (c == '"')
3605  in_quotes = true;
3606  else
3607  {
3608  c = pg_tolower((unsigned char) c);
3609  *optr++ = c;
3610  }
3611  }
3612  *optr = '\0';
3613 
3614  for (i = 0; i < res->numAttributes; i++)
3615  {
3616  if (strcmp(field_case, res->attDescs[i].name) == 0)
3617  {
3618  free(field_case);
3619  return i;
3620  }
3621  }
3622  free(field_case);
3623  return -1;
3624 }
3625 
3626 Oid
3627 PQftable(const PGresult *res, int field_num)
3628 {
3629  if (!check_field_number(res, field_num))
3630  return InvalidOid;
3631  if (res->attDescs)
3632  return res->attDescs[field_num].tableid;
3633  else
3634  return InvalidOid;
3635 }
3636 
3637 int
3638 PQftablecol(const PGresult *res, int field_num)
3639 {
3640  if (!check_field_number(res, field_num))
3641  return 0;
3642  if (res->attDescs)
3643  return res->attDescs[field_num].columnid;
3644  else
3645  return 0;
3646 }
3647 
3648 int
3649 PQfformat(const PGresult *res, int field_num)
3650 {
3651  if (!check_field_number(res, field_num))
3652  return 0;
3653  if (res->attDescs)
3654  return res->attDescs[field_num].format;
3655  else
3656  return 0;
3657 }
3658 
3659 Oid
3660 PQftype(const PGresult *res, int field_num)
3661 {
3662  if (!check_field_number(res, field_num))
3663  return InvalidOid;
3664  if (res->attDescs)
3665  return res->attDescs[field_num].typid;
3666  else
3667  return InvalidOid;
3668 }
3669 
3670 int
3671 PQfsize(const PGresult *res, int field_num)
3672 {
3673  if (!check_field_number(res, field_num))
3674  return 0;
3675  if (res->attDescs)
3676  return res->attDescs[field_num].typlen;
3677  else
3678  return 0;
3679 }
3680 
3681 int
3682 PQfmod(const PGresult *res, int field_num)
3683 {
3684  if (!check_field_number(res, field_num))
3685  return 0;
3686  if (res->attDescs)
3687  return res->attDescs[field_num].atttypmod;
3688  else
3689  return 0;
3690 }
3691 
3692 char *
3694 {
3695  if (!res)
3696  return NULL;
3697  return res->cmdStatus;
3698 }
3699 
3700 /*
3701  * PQoidStatus -
3702  * if the last command was an INSERT, return the oid string
3703  * if not, return ""
3704  */
3705 char *
3707 {
3708  /*
3709  * This must be enough to hold the result. Don't laugh, this is better
3710  * than what this function used to do.
3711  */
3712  static char buf[24];
3713 
3714  size_t len;
3715 
3716  if (!res || strncmp(res->cmdStatus, "INSERT ", 7) != 0)
3717  return "";
3718 
3719  len = strspn(res->cmdStatus + 7, "0123456789");
3720  if (len > sizeof(buf) - 1)
3721  len = sizeof(buf) - 1;
3722  memcpy(buf, res->cmdStatus + 7, len);
3723  buf[len] = '\0';
3724 
3725  return buf;
3726 }
3727 
3728 /*
3729  * PQoidValue -
3730  * a perhaps preferable form of the above which just returns
3731  * an Oid type
3732  */
3733 Oid
3735 {
3736  char *endptr = NULL;
3737  unsigned long result;
3738 
3739  if (!res ||
3740  strncmp(res->cmdStatus, "INSERT ", 7) != 0 ||
3741  res->cmdStatus[7] < '0' ||
3742  res->cmdStatus[7] > '9')
3743  return InvalidOid;
3744 
3745  result = strtoul(res->cmdStatus + 7, &endptr, 10);
3746 
3747  if (!endptr || (*endptr != ' ' && *endptr != '\0'))
3748  return InvalidOid;
3749  else
3750  return (Oid) result;
3751 }
3752 
3753 
3754 /*
3755  * PQcmdTuples -
3756  * If the last command was INSERT/UPDATE/DELETE/MERGE/MOVE/FETCH/COPY,
3757  * return a string containing the number of inserted/affected tuples.
3758  * If not, return "".
3759  *
3760  * XXX: this should probably return an int
3761  */
3762 char *
3764 {
3765  char *p,
3766  *c;
3767 
3768  if (!res)
3769  return "";
3770 
3771  if (strncmp(res->cmdStatus, "INSERT ", 7) == 0)
3772  {
3773  p = res->cmdStatus + 7;
3774  /* INSERT: skip oid and space */
3775  while (*p && *p != ' ')
3776  p++;
3777  if (*p == 0)
3778  goto interpret_error; /* no space? */
3779  p++;
3780  }
3781  else if (strncmp(res->cmdStatus, "SELECT ", 7) == 0 ||
3782  strncmp(res->cmdStatus, "DELETE ", 7) == 0 ||
3783  strncmp(res->cmdStatus, "UPDATE ", 7) == 0)
3784  p = res->cmdStatus + 7;
3785  else if (strncmp(res->cmdStatus, "FETCH ", 6) == 0 ||
3786  strncmp(res->cmdStatus, "MERGE ", 6) == 0)
3787  p = res->cmdStatus + 6;
3788  else if (strncmp(res->cmdStatus, "MOVE ", 5) == 0 ||
3789  strncmp(res->cmdStatus, "COPY ", 5) == 0)
3790  p = res->cmdStatus + 5;
3791  else
3792  return "";
3793 
3794  /* check that we have an integer (at least one digit, nothing else) */
3795  for (c = p; *c; c++)
3796  {
3797  if (!isdigit((unsigned char) *c))
3798  goto interpret_error;
3799  }
3800  if (c == p)
3801  goto interpret_error;
3802 
3803  return p;
3804 
3805 interpret_error:
3807  "could not interpret result from server: %s",
3808  res->cmdStatus);
3809  return "";
3810 }
3811 
3812 /*
3813  * PQgetvalue:
3814  * return the value of field 'field_num' of row 'tup_num'
3815  */
3816 char *
3817 PQgetvalue(const PGresult *res, int tup_num, int field_num)
3818 {
3819  if (!check_tuple_field_number(res, tup_num, field_num))
3820  return NULL;
3821  return res->tuples[tup_num][field_num].value;
3822 }
3823 
3824 /* PQgetlength:
3825  * returns the actual length of a field value in bytes.
3826  */
3827 int
3828 PQgetlength(const PGresult *res, int tup_num, int field_num)
3829 {
3830  if (!check_tuple_field_number(res, tup_num, field_num))
3831  return 0;
3832  if (res->tuples[tup_num][field_num].len != NULL_LEN)
3833  return res->tuples[tup_num][field_num].len;
3834  else
3835  return 0;
3836 }
3837 
3838 /* PQgetisnull:
3839  * returns the null status of a field value.
3840  */
3841 int
3842 PQgetisnull(const PGresult *res, int tup_num, int field_num)
3843 {
3844  if (!check_tuple_field_number(res, tup_num, field_num))
3845  return 1; /* pretend it is null */
3846  if (res->tuples[tup_num][field_num].len == NULL_LEN)
3847  return 1;
3848  else
3849  return 0;
3850 }
3851 
3852 /* PQnparams:
3853  * returns the number of input parameters of a prepared statement.
3854  */
3855 int
3857 {
3858  if (!res)
3859  return 0;
3860  return res->numParameters;
3861 }
3862 
3863 /* PQparamtype:
3864  * returns type Oid of the specified statement parameter.
3865  */
3866 Oid
3867 PQparamtype(const PGresult *res, int param_num)
3868 {
3869  if (!check_param_number(res, param_num))
3870  return InvalidOid;
3871  if (res->paramDescs)
3872  return res->paramDescs[param_num].typid;
3873  else
3874  return InvalidOid;
3875 }
3876 
3877 
3878 /* PQsetnonblocking:
3879  * sets the PGconn's database connection non-blocking if the arg is true
3880  * or makes it blocking if the arg is false, this will not protect
3881  * you from PQexec(), you'll only be safe when using the non-blocking API.
3882  * Needs to be called only on a connected database connection.
3883  */
3884 int
3886 {
3887  bool barg;
3888 
3889  if (!conn || conn->status == CONNECTION_BAD)
3890  return -1;
3891 
3892  barg = (arg ? true : false);
3893 
3894  /* early out if the socket is already in the state requested */
3895  if (barg == conn->nonblocking)
3896  return 0;
3897 
3898  /*
3899  * to guarantee constancy for flushing/query/result-polling behavior we
3900  * need to flush the send queue at this point in order to guarantee proper
3901  * behavior. this is ok because either they are making a transition _from_
3902  * or _to_ blocking mode, either way we can block them.
3903  *
3904  * Clear error state in case pqFlush adds to it, unless we're actively
3905  * pipelining, in which case it seems best not to.
3906  */
3907  if (conn->cmd_queue_head == NULL)
3909 
3910  /* if we are going from blocking to non-blocking flush here */
3911  if (pqFlush(conn))
3912  return -1;
3913 
3914  conn->nonblocking = barg;
3915 
3916  return 0;
3917 }
3918 
3919 /*
3920  * return the blocking status of the database connection
3921  * true == nonblocking, false == blocking
3922  */
3923 int
3925 {
3926  if (!conn || conn->status == CONNECTION_BAD)
3927  return false;
3928  return pqIsnonblocking(conn);
3929 }
3930 
3931 /* libpq is thread-safe? */
3932 int
3934 {
3935  return true;
3936 }
3937 
3938 
3939 /* try to force data out, really only useful for non-blocking users */
3940 int
3942 {
3943  if (!conn || conn->status == CONNECTION_BAD)
3944  return -1;
3945  return pqFlush(conn);
3946 }
3947 
3948 /*
3949  * pqPipelineFlush
3950  *
3951  * In pipeline mode, data will be flushed only when the out buffer reaches the
3952  * threshold value. In non-pipeline mode, it behaves as stock pqFlush.
3953  *
3954  * Returns 0 on success.
3955  */
3956 static int
3958 {
3959  if ((conn->pipelineStatus != PQ_PIPELINE_ON) ||
3961  return pqFlush(conn);
3962  return 0;
3963 }
3964 
3965 
3966 /*
3967  * PQfreemem - safely frees memory allocated
3968  *
3969  * Needed mostly by Win32, unless multithreaded DLL (/MD in VC6)
3970  * Used for freeing memory from PQescapeBytea()/PQunescapeBytea()
3971  */
3972 void
3973 PQfreemem(void *ptr)
3974 {
3975  free(ptr);
3976 }
3977 
3978 /*
3979  * PQfreeNotify - free's the memory associated with a PGnotify
3980  *
3981  * This function is here only for binary backward compatibility.
3982  * New code should use PQfreemem(). A macro will automatically map
3983  * calls to PQfreemem. It should be removed in the future. bjm 2003-03-24
3984  */
3985 
3986 #undef PQfreeNotify
3987 void PQfreeNotify(PGnotify *notify);
3988 
3989 void
3991 {
3992  PQfreemem(notify);
3993 }
3994 
3995 
3996 /*
3997  * Escaping arbitrary strings to get valid SQL literal strings.
3998  *
3999  * Replaces "'" with "''", and if not std_strings, replaces "\" with "\\".
4000  *
4001  * length is the length of the source string. (Note: if a terminating NUL
4002  * is encountered sooner, PQescapeString stops short of "length"; the behavior
4003  * is thus rather like strncpy.)
4004  *
4005  * For safety the buffer at "to" must be at least 2*length + 1 bytes long.
4006  * A terminating NUL character is added to the output string, whether the
4007  * input is NUL-terminated or not.
4008  *
4009  * Returns the actual length of the output (not counting the terminating NUL).
4010  */
4011 static size_t
4013  char *to, const char *from, size_t length,
4014  int *error,
4015  int encoding, bool std_strings)
4016 {
4017  const char *source = from;
4018  char *target = to;
4019  size_t remaining = length;
4020 
4021  if (error)
4022  *error = 0;
4023 
4024  while (remaining > 0 && *source != '\0')
4025  {
4026  char c = *source;
4027  int len;
4028  int i;
4029 
4030  /* Fast path for plain ASCII */
4031  if (!IS_HIGHBIT_SET(c))
4032  {
4033  /* Apply quoting if needed */
4034  if (SQL_STR_DOUBLE(c, !std_strings))
4035  *target++ = c;
4036  /* Copy the character */
4037  *target++ = c;
4038  source++;
4039  remaining--;
4040  continue;
4041  }
4042 
4043  /* Slow path for possible multibyte characters */
4045 
4046  /* Copy the character */
4047  for (i = 0; i < len; i++)
4048  {
4049  if (remaining == 0 || *source == '\0')
4050  break;
4051  *target++ = *source++;
4052  remaining--;
4053  }
4054 
4055  /*
4056  * If we hit premature end of string (ie, incomplete multibyte
4057  * character), try to pad out to the correct length with spaces. We
4058  * may not be able to pad completely, but we will always be able to
4059  * insert at least one pad space (since we'd not have quoted a
4060  * multibyte character). This should be enough to make a string that
4061  * the server will error out on.
4062  */
4063  if (i < len)
4064  {
4065  if (error)
4066  *error = 1;
4067  if (conn)
4068  libpq_append_conn_error(conn, "incomplete multibyte character");
4069  for (; i < len; i++)
4070  {
4071  if (((size_t) (target - to)) / 2 >= length)
4072  break;
4073  *target++ = ' ';
4074  }
4075  break;
4076  }
4077  }
4078 
4079  /* Write the terminating NUL character. */
4080  *target = '\0';
4081 
4082  return target - to;
4083 }
4084 
4085 size_t
4087  char *to, const char *from, size_t length,
4088  int *error)
4089 {
4090  if (!conn)
4091  {
4092  /* force empty-string result */
4093  *to = '\0';
4094  if (error)
4095  *error = 1;
4096  return 0;
4097  }
4098 
4099  if (conn->cmd_queue_head == NULL)
4101 
4102  return PQescapeStringInternal(conn, to, from, length, error,
4104  conn->std_strings);
4105 }
4106 
4107 size_t
4108 PQescapeString(char *to, const char *from, size_t length)
4109 {
4110  return PQescapeStringInternal(NULL, to, from, length, NULL,
4113 }
4114 
4115 
4116 /*
4117  * Escape arbitrary strings. If as_ident is true, we escape the result
4118  * as an identifier; if false, as a literal. The result is returned in
4119  * a newly allocated buffer. If we fail due to an encoding violation or out
4120  * of memory condition, we return NULL, storing an error message into conn.
4121  */
4122 static char *
4123 PQescapeInternal(PGconn *conn, const char *str, size_t len, bool as_ident)
4124 {
4125  const char *s;
4126  char *result;
4127  char *rp;
4128  int num_quotes = 0; /* single or double, depending on as_ident */
4129  int num_backslashes = 0;
4130  int input_len;
4131  int result_size;
4132  char quote_char = as_ident ? '"' : '\'';
4133 
4134  /* We must have a connection, else fail immediately. */
4135  if (!conn)
4136  return NULL;
4137 
4138  if (conn->cmd_queue_head == NULL)
4140 
4141  /* Scan the string for characters that must be escaped. */
4142  for (s = str; (s - str) < len && *s != '\0'; ++s)
4143  {
4144  if (*s == quote_char)
4145  ++num_quotes;
4146  else if (*s == '\\')
4147  ++num_backslashes;
4148  else if (IS_HIGHBIT_SET(*s))
4149  {
4150  int charlen;
4151 
4152  /* Slow path for possible multibyte characters */
4153  charlen = pg_encoding_mblen(conn->client_encoding, s);
4154 
4155  /* Multibyte character overruns allowable length. */
4156  if ((s - str) + charlen > len || memchr(s, 0, charlen) != NULL)
4157  {
4158  libpq_append_conn_error(conn, "incomplete multibyte character");
4159  return NULL;
4160  }
4161 
4162  /* Adjust s, bearing in mind that for loop will increment it. */
4163  s += charlen - 1;
4164  }
4165  }
4166 
4167  /* Allocate output buffer. */
4168  input_len = s - str;
4169  result_size = input_len + num_quotes + 3; /* two quotes, plus a NUL */
4170  if (!as_ident && num_backslashes > 0)
4171  result_size += num_backslashes + 2;
4172  result = rp = (char *) malloc(result_size);
4173  if (rp == NULL)
4174  {
4175  libpq_append_conn_error(conn, "out of memory");
4176  return NULL;
4177  }
4178 
4179  /*
4180  * If we are escaping a literal that contains backslashes, we use the
4181  * escape string syntax so that the result is correct under either value
4182  * of standard_conforming_strings. We also emit a leading space in this
4183  * case, to guard against the possibility that the result might be
4184  * interpolated immediately following an identifier.
4185  */
4186  if (!as_ident && num_backslashes > 0)
4187  {
4188  *rp++ = ' ';
4189  *rp++ = 'E';
4190  }
4191 
4192  /* Opening quote. */
4193  *rp++ = quote_char;
4194 
4195  /*
4196  * Use fast path if possible.
4197  *
4198  * We've already verified that the input string is well-formed in the
4199  * current encoding. If it contains no quotes and, in the case of
4200  * literal-escaping, no backslashes, then we can just copy it directly to
4201  * the output buffer, adding the necessary quotes.
4202  *
4203  * If not, we must rescan the input and process each character
4204  * individually.
4205  */
4206  if (num_quotes == 0 && (num_backslashes == 0 || as_ident))
4207  {
4208  memcpy(rp, str, input_len);
4209  rp += input_len;
4210  }
4211  else
4212  {
4213  for (s = str; s - str < input_len; ++s)
4214  {
4215  if (*s == quote_char || (!as_ident && *s == '\\'))
4216  {
4217  *rp++ = *s;
4218  *rp++ = *s;
4219  }
4220  else if (!IS_HIGHBIT_SET(*s))
4221  *rp++ = *s;
4222  else
4223  {
4225 
4226  while (1)
4227  {
4228  *rp++ = *s;
4229  if (--i == 0)
4230  break;
4231  ++s; /* for loop will provide the final increment */
4232  }
4233  }
4234  }
4235  }
4236 
4237  /* Closing quote and terminating NUL. */
4238  *rp++ = quote_char;
4239  *rp = '\0';
4240 
4241  return result;
4242 }
4243 
4244 char *
4245 PQescapeLiteral(PGconn *conn, const char *str, size_t len)
4246 {
4247  return PQescapeInternal(conn, str, len, false);
4248 }
4249 
4250 char *
4251 PQescapeIdentifier(PGconn *conn, const char *str, size_t len)
4252 {
4253  return PQescapeInternal(conn, str, len, true);
4254 }
4255 
4256 /* HEX encoding support for bytea */
4257 static const char hextbl[] = "0123456789abcdef";
4258 
4259 static const int8 hexlookup[128] = {
4260  -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
4261  -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
4262  -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
4263  0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1, -1, -1, -1, -1, -1,
4264  -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1,
4265  -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
4266  -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1,
4267  -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
4268 };
4269 
4270 static inline char
4271 get_hex(char c)
4272 {
4273  int res = -1;
4274 
4275  if (c > 0 && c < 127)
4276  res = hexlookup[(unsigned char) c];
4277 
4278  return (char) res;
4279 }
4280 
4281 
4282 /*
4283  * PQescapeBytea - converts from binary string to the
4284  * minimal encoding necessary to include the string in an SQL
4285  * INSERT statement with a bytea type column as the target.
4286  *
4287  * We can use either hex or escape (traditional) encoding.
4288  * In escape mode, the following transformations are applied:
4289  * '\0' == ASCII 0 == \000
4290  * '\'' == ASCII 39 == ''
4291  * '\\' == ASCII 92 == \\
4292  * anything < 0x20, or > 0x7e ---> \ooo
4293  * (where ooo is an octal expression)
4294  *
4295  * If not std_strings, all backslashes sent to the output are doubled.
4296  */
4297 static unsigned char *
4299  const unsigned char *from, size_t from_length,
4300  size_t *to_length, bool std_strings, bool use_hex)
4301 {
4302  const unsigned char *vp;
4303  unsigned char *rp;
4304  unsigned char *result;
4305  size_t i;
4306  size_t len;
4307  size_t bslash_len = (std_strings ? 1 : 2);
4308 
4309  /*
4310  * empty string has 1 char ('\0')
4311  */
4312  len = 1;
4313 
4314  if (use_hex)
4315  {
4316  len += bslash_len + 1 + 2 * from_length;
4317  }
4318  else
4319  {
4320  vp = from;
4321  for (i = from_length; i > 0; i--, vp++)
4322  {
4323  if (*vp < 0x20 || *vp > 0x7e)
4324  len += bslash_len + 3;
4325  else if (*vp == '\'')
4326  len += 2;
4327  else if (*vp == '\\')
4328  len += bslash_len + bslash_len;
4329  else
4330  len++;
4331  }
4332  }
4333 
4334  *to_length = len;
4335  rp = result = (unsigned char *) malloc(len);
4336  if (rp == NULL)
4337  {
4338  if (conn)
4339  libpq_append_conn_error(conn, "out of memory");
4340  return NULL;
4341  }
4342 
4343  if (use_hex)
4344  {
4345  if (!std_strings)
4346  *rp++ = '\\';
4347  *rp++ = '\\';
4348  *rp++ = 'x';
4349  }
4350 
4351  vp = from;
4352  for (i = from_length; i > 0; i--, vp++)
4353  {
4354  unsigned char c = *vp;
4355 
4356  if (use_hex)
4357  {
4358  *rp++ = hextbl[(c >> 4) & 0xF];
4359  *rp++ = hextbl[c & 0xF];
4360  }
4361  else if (c < 0x20 || c > 0x7e)
4362  {
4363  if (!std_strings)
4364  *rp++ = '\\';
4365  *rp++ = '\\';
4366  *rp++ = (c >> 6) + '0';
4367  *rp++ = ((c >> 3) & 07) + '0';
4368  *rp++ = (c & 07) + '0';
4369  }
4370  else if (c == '\'')
4371  {
4372  *rp++ = '\'';
4373  *rp++ = '\'';
4374  }
4375  else if (c == '\\')
4376  {
4377  if (!std_strings)
4378  {
4379  *rp++ = '\\';
4380  *rp++ = '\\';
4381  }
4382  *rp++ = '\\';
4383  *rp++ = '\\';
4384  }
4385  else
4386  *rp++ = c;
4387  }
4388  *rp = '\0';
4389 
4390  return result;
4391 }
4392 
4393 unsigned char *
4395  const unsigned char *from, size_t from_length,
4396  size_t *to_length)
4397 {
4398  if (!conn)
4399  return NULL;
4400 
4401  if (conn->cmd_queue_head == NULL)
4403 
4404  return PQescapeByteaInternal(conn, from, from_length, to_length,
4405  conn->std_strings,
4406  (conn->sversion >= 90000));
4407 }
4408 
4409 unsigned char *
4410 PQescapeBytea(const unsigned char *from, size_t from_length, size_t *to_length)
4411 {
4412  return PQescapeByteaInternal(NULL, from, from_length, to_length,
4414  false /* can't use hex */ );
4415 }
4416 
4417 
4418 #define ISFIRSTOCTDIGIT(CH) ((CH) >= '0' && (CH) <= '3')
4419 #define ISOCTDIGIT(CH) ((CH) >= '0' && (CH) <= '7')
4420 #define OCTVAL(CH) ((CH) - '0')
4421 
4422 /*
4423  * PQunescapeBytea - converts the null terminated string representation
4424  * of a bytea, strtext, into binary, filling a buffer. It returns a
4425  * pointer to the buffer (or NULL on error), and the size of the
4426  * buffer in retbuflen. The pointer may subsequently be used as an
4427  * argument to the function PQfreemem.
4428  *
4429  * The following transformations are made:
4430  * \\ == ASCII 92 == \
4431  * \ooo == a byte whose value = ooo (ooo is an octal number)
4432  * \x == x (x is any character not matched by the above transformations)
4433  */
4434 unsigned char *
4435 PQunescapeBytea(const unsigned char *strtext, size_t *retbuflen)
4436 {
4437  size_t strtextlen,
4438  buflen;
4439  unsigned char *buffer,
4440  *tmpbuf;
4441  size_t i,
4442  j;
4443 
4444  if (strtext == NULL)
4445  return NULL;
4446 
4447  strtextlen = strlen((const char *) strtext);
4448 
4449  if (strtext[0] == '\\' && strtext[1] == 'x')
4450  {
4451  const unsigned char *s;
4452  unsigned char *p;
4453 
4454  buflen = (strtextlen - 2) / 2;
4455  /* Avoid unportable malloc(0) */
4456  buffer = (unsigned char *) malloc(buflen > 0 ? buflen : 1);
4457  if (buffer == NULL)
4458  return NULL;
4459 
4460  s = strtext + 2;
4461  p = buffer;
4462  while (*s)
4463  {
4464  char v1,
4465  v2;
4466 
4467  /*
4468  * Bad input is silently ignored. Note that this includes
4469  * whitespace between hex pairs, which is allowed by byteain.
4470  */
4471  v1 = get_hex(*s++);
4472  if (!*s || v1 == (char) -1)
4473  continue;
4474  v2 = get_hex(*s++);
4475  if (v2 != (char) -1)
4476  *p++ = (v1 << 4) | v2;
4477  }
4478 
4479  buflen = p - buffer;
4480  }
4481  else
4482  {
4483  /*
4484  * Length of input is max length of output, but add one to avoid
4485  * unportable malloc(0) if input is zero-length.
4486  */
4487  buffer = (unsigned char *) malloc(strtextlen + 1);
4488  if (buffer == NULL)
4489  return NULL;
4490 
4491  for (i = j = 0; i < strtextlen;)
4492  {
4493  switch (strtext[i])
4494  {
4495  case '\\':
4496  i++;
4497  if (strtext[i] == '\\')
4498  buffer[j++] = strtext[i++];
4499  else
4500  {
4501  if ((ISFIRSTOCTDIGIT(strtext[i])) &&
4502  (ISOCTDIGIT(strtext[i + 1])) &&
4503  (ISOCTDIGIT(strtext[i + 2])))
4504  {
4505  int byte;
4506 
4507  byte = OCTVAL(strtext[i++]);
4508  byte = (byte << 3) + OCTVAL(strtext[i++]);
4509  byte = (byte << 3) + OCTVAL(strtext[i++]);
4510  buffer[j++] = byte;
4511  }
4512  }
4513 
4514  /*
4515  * Note: if we see '\' followed by something that isn't a
4516  * recognized escape sequence, we loop around having done
4517  * nothing except advance i. Therefore the something will
4518  * be emitted as ordinary data on the next cycle. Corner
4519  * case: '\' at end of string will just be discarded.
4520  */
4521  break;
4522 
4523  default:
4524  buffer[j++] = strtext[i++];
4525  break;
4526  }
4527  }
4528  buflen = j; /* buflen is the length of the dequoted data */
4529  }
4530 
4531  /* Shrink the buffer to be no larger than necessary */
4532  /* +1 avoids unportable behavior when buflen==0 */
4533  tmpbuf = realloc(buffer, buflen + 1);
4534 
4535  /* It would only be a very brain-dead realloc that could fail, but... */
4536  if (!tmpbuf)
4537  {
4538  free(buffer);
4539  return NULL;
4540  }
4541 
4542  *retbuflen = buflen;
4543  return tmpbuf;
4544 }
#define unconstify(underlying_type, expr)
Definition: c.h:1255
signed char int8
Definition: c.h:481
#define IS_HIGHBIT_SET(ch)
Definition: c.h:1168
#define SQL_STR_DOUBLE(ch, escape_backslash)
Definition: c.h:1176
#define lengthof(array)
Definition: c.h:777
int errmsg(const char *fmt,...)
Definition: elog.c:1069
static char * PQescapeInternal(PGconn *conn, const char *str, size_t len, bool as_ident)
Definition: fe-exec.c:4123
static int PQsendQueryInternal(PGconn *conn, const char *query, bool newQuery)
Definition: fe-exec.c:1434
unsigned char * PQescapeBytea(const unsigned char *from, size_t from_length, size_t *to_length)
Definition: fe-exec.c:4410
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:2939
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:1498
int PQsendQueryContinue(PGconn *conn, const char *query)
Definition: fe-exec.c:1428
int PQgetlength(const PGresult *res, int tup_num, int field_num)
Definition: fe-exec.c:3828
int PQsetSingleRowMode(PGconn *conn)
Definition: fe-exec.c:1929
static char get_hex(char c)
Definition: fe-exec.c:4271
int PQbinaryTuples(const PGresult *res)
Definition: fe-exec.c:3438
int PQflush(PGconn *conn)
Definition: fe-exec.c:3941
void PQfreemem(void *ptr)
Definition: fe-exec.c:3973
PGnotify * PQnotifies(PGconn *conn)
Definition: fe-exec.c:2626
PGresult * PQprepare(PGconn *conn, const char *stmtName, const char *query, int nParams, const Oid *paramTypes)
Definition: fe-exec.c:2265
int PQgetline(PGconn *conn, char *buffer, int length)
Definition: fe-exec.c:2813
unsigned char * PQunescapeBytea(const unsigned char *strtext, size_t *retbuflen)
Definition: fe-exec.c:4435
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:4012
Oid PQftype(const PGresult *res, int field_num)
Definition: fe-exec.c:3660
int PQexitPipelineMode(PGconn *conn)
Definition: fe-exec.c:3032
int PQsendClosePortal(PGconn *conn, const char *portal)
Definition: fe-exec.c:2528
int PQsetResultAttrs(PGresult *res, int numAttributes, PGresAttDesc *attDescs)
Definition: fe-exec.c:246
#define ISOCTDIGIT(CH)
Definition: fe-exec.c:4419
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:4251
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:4298
static int check_tuple_field_number(const PGresult *res, int tup_num, int field_num)
Definition: fe-exec.c:3466
static void pqSaveWriteError(PGconn *conn)
Definition: fe-exec.c:817
int PQenterPipelineMode(PGconn *conn)
Definition: fe-exec.c:3001
void pqCommandQueueAdvance(PGconn *conn, bool isReadyForQuery, bool gotSync)
Definition: fe-exec.c:3101
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:4086
void pqSaveErrorResult(PGconn *conn)
Definition: fe-exec.c:800
char *const pgresStatus[]
Definition: fe-exec.c:32
#define OCTVAL(CH)
Definition: fe-exec.c:4420
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:2235
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:3352
Oid PQparamtype(const PGresult *res, int param_num)
Definition: fe-exec.c:3867
static int check_param_number(const PGresult *res, int param_num)
Definition: fe-exec.c:3489
int pqRowProcessor(PGconn *conn, const char **errmsgp)
Definition: fe-exec.c:1206
PGresult * PQdescribePrepared(PGconn *conn, const char *stmt)
Definition: fe-exec.c:2414
int PQnparams(const PGresult *res)
Definition: fe-exec.c:3856
void PQclear(PGresult *res)
Definition: fe-exec.c:718
int PQsendClosePrepared(PGconn *conn, const char *stmt)
Definition: fe-exec.c:2515
char * PQcmdTuples(PGresult *res)
Definition: fe-exec.c:3763
char * PQresultErrorMessage(const PGresult *res)
Definition: fe-exec.c:3368
static PGresult * PQexecFinish(PGconn *conn)
Definition: fe-exec.c:2369
int PQfformat(const PGresult *res, int field_num)
Definition: fe-exec.c:3649
static void pqAppendCmdQueueEntry(PGconn *conn, PGcmdQueueEntry *entry)
Definition: fe-exec.c:1345
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:1761
PGresult * PQclosePortal(PGconn *conn, const char *portal)
Definition: fe-exec.c:2498
int PQendcopy(PGconn *conn)
Definition: fe-exec.c:2908
static int pqPipelineFlush(PGconn *conn)
Definition: fe-exec.c:3957
int PQputCopyEnd(PGconn *conn, const char *errormsg)
Definition: fe-exec.c:2708
static int PQsendTypedCommand(PGconn *conn, char command, char type, const char *target)
Definition: fe-exec.c:2548
int PQntuples(const PGresult *res)
Definition: fe-exec.c:3422
int PQputnbytes(PGconn *conn, const char *buffer, int nbytes)
Definition: fe-exec.c:2887
int PQputline(PGconn *conn, const char *string)
Definition: fe-exec.c:2877
int PQgetlineAsync(PGconn *conn, char *buffer, int bufsize)
Definition: fe-exec.c:2860
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:2654
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:2282
static PGcmdQueueEntry * pqAllocCmdQueueEntry(PGconn *conn)
Definition: fe-exec.c:1312
static PGresult * getCopyResult(PGconn *conn, ExecStatusType copytype)
Definition: fe-exec.c:2183
static PGEvent * dupEvents(PGEvent *events, int count, size_t *memSize)
Definition: fe-exec.c:405
int PQisthreadsafe(void)
Definition: fe-exec.c:3933
char * PQfname(const PGresult *res, int field_num)
Definition: fe-exec.c:3508
static bool static_std_strings
Definition: fe-exec.c:59
char * PQescapeLiteral(PGconn *conn, const char *str, size_t len)
Definition: fe-exec.c:4245
void pqInternalNotice(const PGNoticeHooks *hooks, const char *fmt,...)
Definition: fe-exec.c:933
PGresult * PQdescribePortal(PGconn *conn, const char *portal)
Definition: fe-exec.c:2433
int PQsendDescribePrepared(PGconn *conn, const char *stmt)
Definition: fe-exec.c:2450
PGresult * PQmakeEmptyPGresult(PGconn *conn, ExecStatusType status)
Definition: fe-exec.c:157
PGresult * PQexec(PGconn *conn, const char *query)
Definition: fe-exec.c:2221
unsigned char * PQescapeByteaConn(PGconn *conn, const unsigned char *from, size_t from_length, size_t *to_length)
Definition: fe-exec.c:4394
static const char hextbl[]
Definition: fe-exec.c:4257
static bool PQexecStart(PGconn *conn)
Definition: fe-exec.c:2303
size_t PQescapeString(char *to, const char *from, size_t length)
Definition: fe-exec.c:4108
int PQconsumeInput(PGconn *conn)
Definition: fe-exec.c:1957
#define ISFIRSTOCTDIGIT(CH)
Definition: fe-exec.c:4418
static void parseInput(PGconn *conn)
Definition: fe-exec.c:1993
char * PQgetvalue(const PGresult *res, int tup_num, int field_num)
Definition: fe-exec.c:3817
Oid PQftable(const PGresult *res, int field_num)
Definition: fe-exec.c:3627
int PQfnumber(const PGresult *res, const char *field_name)
Definition: fe-exec.c:3530
char * PQcmdStatus(PGresult *res)
Definition: fe-exec.c:3693
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:3885
int PQsendPrepare(PGconn *conn, const char *stmtName, const char *query, int nParams, const Oid *paramTypes)
Definition: fe-exec.c:1542
#define PGRESULT_SEP_ALLOC_THRESHOLD
Definition: fe-exec.c:143
int PQfmod(const PGresult *res, int field_num)
Definition: fe-exec.c:3682
void pqClearAsyncResult(PGconn *conn)
Definition: fe-exec.c:776
int PQgetisnull(const PGresult *res, int tup_num, int field_num)
Definition: fe-exec.c:3842
int PQftablecol(const PGresult *res, int field_num)
Definition: fe-exec.c:3638
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:1422
int PQpipelineSync(PGconn *conn)
Definition: fe-exec.c:3245
char * PQresStatus(ExecStatusType status)
Definition: fe-exec.c:3360
int PQsendDescribePortal(PGconn *conn, const char *portal)
Definition: fe-exec.c:2463
PGresult * PQclosePrepared(PGconn *conn, const char *stmt)
Definition: fe-exec.c:2480
size_t PQresultMemorySize(const PGresult *res)
Definition: fe-exec.c:660
int PQisBusy(PGconn *conn)
Definition: fe-exec.c:2004
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:1639
static void pqPipelineProcessQueue(PGconn *conn)
Definition: fe-exec.c:3139
int PQsendFlushRequest(PGconn *conn)
Definition: fe-exec.c:3312
void * pqResultAlloc(PGresult *res, size_t nBytes, bool isBinary)
Definition: fe-exec.c:560
char * PQoidStatus(const PGresult *res)
Definition: fe-exec.c:3706
char * PQresultErrorField(const PGresult *res, int fieldcode)
Definition: fe-exec.c:3407
int PQisnonblocking(const PGconn *conn)
Definition: fe-exec.c:3924
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:3734
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:3376
#define PGRESULT_ALIGN_BOUNDARY
Definition: fe-exec.c:141
int PQnfields(const PGresult *res)
Definition: fe-exec.c:3430
static int check_field_number(const PGresult *res, int field_num)
Definition: fe-exec.c:3451
PGresult * PQgetResult(PGconn *conn)
Definition: fe-exec.c:2035
PGresult * pqPrepareAsyncResult(PGconn *conn)
Definition: fe-exec.c:846
int PQfsize(const PGresult *res, int field_num)
Definition: fe-exec.c:3671
static bool PQsendQueryStart(PGconn *conn, bool newQuery)
Definition: fe-exec.c:1679
static const int8 hexlookup[128]
Definition: fe-exec.c:4259
int PQgetCopyData(PGconn *conn, char **buffer, int async)
Definition: fe-exec.c:2775
static void pqRecycleCmdQueueEntry(PGconn *conn, PGcmdQueueEntry *entry)
Definition: fe-exec.c:1392
void PQfreeNotify(PGnotify *notify)
Definition: fe-exec.c:3990
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)
void pqParseInput3(PGconn *conn)
Definition: fe-protocol3.c:66
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
long val
Definition: informix.c:664
int remaining
Definition: informix.c:667
static struct @148 value
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:444
struct PGEvent PGEvent
@ PGASYNC_COPY_OUT
Definition: libpq-int.h:229
@ PGASYNC_READY_MORE
Definition: libpq-int.h:225
@ PGASYNC_READY
Definition: libpq-int.h:223
@ PGASYNC_COPY_BOTH
Definition: libpq-int.h:230
@ PGASYNC_IDLE
Definition: libpq-int.h:221
@ PGASYNC_COPY_IN
Definition: libpq-int.h:228
@ PGASYNC_BUSY
Definition: libpq-int.h:222
@ PGASYNC_PIPELINE_IDLE
Definition: libpq-int.h:231
#define libpq_gettext(x)
Definition: libpq-int.h:901
@ PGQUERY_SIMPLE
Definition: libpq-int.h:320
@ PGQUERY_SYNC
Definition: libpq-int.h:324
@ PGQUERY_EXTENDED
Definition: libpq-int.h:321
@ PGQUERY_DESCRIBE
Definition: libpq-int.h:323
@ PGQUERY_CLOSE
Definition: libpq-int.h:325
@ PGQUERY_PREPARE
Definition: libpq-int.h:322
#define NULL_LEN
Definition: libpq-int.h:136
struct pgParameterStatus pgParameterStatus
#define pqClearConnErrorState(conn)
Definition: libpq-int.h:874
union pgresult_data PGresult_data
Definition: libpq-int.h:104
@ PG_BOOL_YES
Definition: libpq-int.h:257
@ PG_BOOL_NO
Definition: libpq-int.h:258
#define pqIsnonblocking(conn)
Definition: libpq-int.h:890
#define OUTBUFFER_THRESHOLD
Definition: libpq-int.h:895
#define pgHavePendingResult(conn)
Definition: libpq-int.h:883
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 rewind_source * source
Definition: pg_rewind.c:89
static char * buf
Definition: pg_test_fsync.c:73
@ PG_SQL_ASCII
Definition: pg_wchar.h:229
#define pg_char_to_encoding
Definition: pg_wchar.h:562
#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
#define PqMsg_CopyDone
Definition: protocol.h:64
#define PqMsg_CopyData
Definition: protocol.h:65
#define PqMsg_Describe
Definition: protocol.h:21
#define PqMsg_Parse
Definition: protocol.h:25
#define PqMsg_Bind
Definition: protocol.h:19
#define PqMsg_Sync
Definition: protocol.h:27
#define PqMsg_CopyFail
Definition: protocol.h:29
#define PqMsg_Flush
Definition: protocol.h:24
#define PqMsg_Query
Definition: protocol.h:26
#define PqMsg_Execute
Definition: protocol.h:22
#define PqMsg_Close
Definition: protocol.h:20
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:165
char * name
Definition: libpq-int.h:164
void * data
Definition: libpq-int.h:166
PGEventProc proc
Definition: libpq-int.h:163
bool resultInitialized
Definition: libpq-int.h:167
void * noticeProcArg
Definition: libpq-int.h:158
PQnoticeReceiver noticeRec
Definition: libpq-int.h:155
PQnoticeProcessor noticeProc
Definition: libpq-int.h:157
void * noticeRecArg
Definition: libpq-int.h:156
PGQueryClass queryclass
Definition: libpq-int.h:333
struct PGcmdQueueEntry * next
Definition: libpq-int.h:335
struct pgMessageField * next
Definition: libpq-int.h:147
char contents[FLEXIBLE_ARRAY_MEMBER]
Definition: libpq-int.h:149
struct pgNotify * next
Definition: libpq-fe.h:193
struct pgParameterStatus * next
Definition: libpq-int.h:271
char * write_err_msg
Definition: libpq-int.h:471
PGnotify * notifyHead
Definition: libpq-int.h:436
PGdataValue * rowBuf
Definition: libpq-int.h:525
bool singleRowMode
Definition: libpq-int.h:433
pgsocket sock
Definition: libpq-int.h:459
PGresult * next_result
Definition: libpq-int.h:539
bool std_strings
Definition: libpq-int.h:498
int errorReported
Definition: libpq-int.h:618
bool write_failed
Definition: libpq-int.h:470
PGTernaryBool in_hot_standby
Definition: libpq-int.h:500
PGcmdQueueEntry * cmd_queue_recycle
Definition: libpq-int.h:456
PGcmdQueueEntry * cmd_queue_tail
Definition: libpq-int.h:450
PGnotify * notifyTail
Definition: libpq-int.h:437
bool nonblocking
Definition: libpq-int.h:430
int client_encoding
Definition: libpq-int.h:497
int sversion
Definition: libpq-int.h:464
PGTernaryBool default_transaction_read_only
Definition: libpq-int.h:499
pgParameterStatus * pstatus
Definition: libpq-int.h:496
PGresult * result
Definition: libpq-int.h:537
PQExpBufferData errorMessage
Definition: libpq-int.h:617
int nEvents
Definition: libpq-int.h:421
bool error_result
Definition: libpq-int.h:538
PGAsyncStatusType asyncStatus
Definition: libpq-int.h:426
int scram_sha_256_iterations
Definition: libpq-int.h:544
PGpipelineStatus pipelineStatus
Definition: libpq-int.h:432
int outBufSize
Definition: libpq-int.h:516
PGNoticeHooks noticeHooks
Definition: libpq-int.h:417
PGcmdQueueEntry * cmd_queue_head
Definition: libpq-int.h:449
int outCount
Definition: libpq-int.h:517
PGEvent * events
Definition: libpq-int.h:420
ConnStatusType status
Definition: libpq-int.h:425
size_t memorySize
Definition: libpq-int.h:215
int ntups
Definition: libpq-int.h:172
int curOffset
Definition: libpq-int.h:212
int binary
Definition: libpq-int.h:182
PGNoticeHooks noticeHooks
Definition: libpq-int.h:189
char null_field[1]
Definition: libpq-int.h:204
char * errMsg
Definition: libpq-int.h:199
int nEvents
Definition: libpq-int.h:191
PGresAttValue ** tuples
Definition: libpq-int.h:175
int numParameters
Definition: libpq-int.h:178
int spaceLeft
Definition: libpq-int.h:213
PGresAttDesc * attDescs
Definition: libpq-int.h:174
int numAttributes
Definition: libpq-int.h:173
char cmdStatus[CMDSTATUS_LEN]
Definition: libpq-int.h:181
PGMessageField * errFields
Definition: libpq-int.h:200
PGresParamDesc * paramDescs
Definition: libpq-int.h:179
PGEvent * events
Definition: libpq-int.h:190
PGresult_data * curBlock
Definition: libpq-int.h:211
int tupArrSize
Definition: libpq-int.h:177
ExecStatusType resultStatus
Definition: libpq-int.h:180
char * errQuery
Definition: libpq-int.h:201
int client_encoding
Definition: libpq-int.h:192
char * name
Definition: libpq-fe.h:263
int columnid
Definition: libpq-fe.h:265
int atttypmod
Definition: libpq-fe.h:269
char * value
Definition: libpq-int.h:141
PGresult_data * next
Definition: libpq-int.h:108
char space[1]
Definition: libpq-int.h:109
const char * type
const char * name
static StringInfoData tmpbuf
Definition: walsender.c:160
int pg_encoding_mblen(int encoding, const char *mbstr)
Definition: wchar.c:2130