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