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