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