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