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