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