PostgreSQL Source Code  git master
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros
libpq-fe.h File Reference
#include <stdio.h>
#include "postgres_ext.h"
Include dependency graph for libpq-fe.h:
This graph shows which files directly or indirectly include this file:

Go to the source code of this file.

Data Structures

struct  pgNotify
 
struct  _PQprintOpt
 
struct  _PQconninfoOption
 
struct  PQArgBlock
 
struct  pgresAttDesc
 

Macros

#define PG_COPYRES_ATTRS   0x01
 
#define PG_COPYRES_TUPLES   0x02 /* Implies PG_COPYRES_ATTRS */
 
#define PG_COPYRES_EVENTS   0x04
 
#define PG_COPYRES_NOTICEHOOKS   0x08
 
#define PQsetdb(M_PGHOST, M_PGPORT, M_PGOPT, M_PGTTY, M_DBNAME)   PQsetdbLogin(M_PGHOST, M_PGPORT, M_PGOPT, M_PGTTY, M_DBNAME, NULL, NULL)
 
#define PQfreeNotify(ptr)   PQfreemem(ptr)
 
#define PQnoPasswordSupplied   "fe_sendauth: no password supplied\n"
 

Typedefs

typedef struct pg_conn PGconn
 
typedef struct pg_result PGresult
 
typedef struct pg_cancel PGcancel
 
typedef struct pgNotify PGnotify
 
typedef void(* PQnoticeReceiver )(void *arg, const PGresult *res)
 
typedef void(* PQnoticeProcessor )(void *arg, const char *message)
 
typedef char pqbool
 
typedef struct _PQprintOpt PQprintOpt
 
typedef struct _PQconninfoOption PQconninfoOption
 
typedef struct pgresAttDesc PGresAttDesc
 
typedef void(* pgthreadlock_t )(int acquire)
 

Enumerations

enum  ConnStatusType {
  CONNECTION_OK, CONNECTION_BAD, CONNECTION_STARTED, CONNECTION_MADE,
  CONNECTION_AWAITING_RESPONSE, CONNECTION_AUTH_OK, CONNECTION_SETENV, CONNECTION_SSL_STARTUP,
  CONNECTION_NEEDED, CONNECTION_CHECK_WRITABLE, CONNECTION_CONSUME
}
 
enum  PostgresPollingStatusType {
  PGRES_POLLING_FAILED = 0, PGRES_POLLING_READING, PGRES_POLLING_WRITING, PGRES_POLLING_OK,
  PGRES_POLLING_ACTIVE
}
 
enum  ExecStatusType {
  PGRES_EMPTY_QUERY = 0, PGRES_COMMAND_OK, PGRES_TUPLES_OK, PGRES_COPY_OUT,
  PGRES_COPY_IN, PGRES_BAD_RESPONSE, PGRES_NONFATAL_ERROR, PGRES_FATAL_ERROR,
  PGRES_COPY_BOTH, PGRES_SINGLE_TUPLE
}
 
enum  PGTransactionStatusType {
  PQTRANS_IDLE, PQTRANS_ACTIVE, PQTRANS_INTRANS, PQTRANS_INERROR,
  PQTRANS_UNKNOWN
}
 
enum  PGVerbosity { PQERRORS_TERSE, PQERRORS_DEFAULT, PQERRORS_VERBOSE }
 
enum  PGContextVisibility { PQSHOW_CONTEXT_NEVER, PQSHOW_CONTEXT_ERRORS, PQSHOW_CONTEXT_ALWAYS }
 
enum  PGPing { PQPING_OK, PQPING_REJECT, PQPING_NO_RESPONSE, PQPING_NO_ATTEMPT }
 

Functions

PGconnPQconnectStart (const char *conninfo)
 
PGconnPQconnectStartParams (const char *const *keywords, const char *const *values, int expand_dbname)
 
PostgresPollingStatusType PQconnectPoll (PGconn *conn)
 
PGconnPQconnectdb (const char *conninfo)
 
PGconnPQconnectdbParams (const char *const *keywords, const char *const *values, int expand_dbname)
 
PGconnPQsetdbLogin (const char *pghost, const char *pgport, const char *pgoptions, const char *pgtty, const char *dbName, const char *login, const char *pwd)
 
void PQfinish (PGconn *conn)
 
PQconninfoOptionPQconndefaults (void)
 
PQconninfoOptionPQconninfoParse (const char *conninfo, char **errmsg)
 
PQconninfoOptionPQconninfo (PGconn *conn)
 
void PQconninfoFree (PQconninfoOption *connOptions)
 
int PQresetStart (PGconn *conn)
 
PostgresPollingStatusType PQresetPoll (PGconn *conn)
 
void PQreset (PGconn *conn)
 
PGcancelPQgetCancel (PGconn *conn)
 
void PQfreeCancel (PGcancel *cancel)
 
int PQcancel (PGcancel *cancel, char *errbuf, int errbufsize)
 
int PQrequestCancel (PGconn *conn)
 
char * PQdb (const PGconn *conn)
 
char * PQuser (const PGconn *conn)
 
char * PQpass (const PGconn *conn)
 
char * PQhost (const PGconn *conn)
 
char * PQport (const PGconn *conn)
 
char * PQtty (const PGconn *conn)
 
char * PQoptions (const PGconn *conn)
 
ConnStatusType PQstatus (const PGconn *conn)
 
PGTransactionStatusType PQtransactionStatus (const PGconn *conn)
 
const char * PQparameterStatus (const PGconn *conn, const char *paramName)
 
int PQprotocolVersion (const PGconn *conn)
 
int PQserverVersion (const PGconn *conn)
 
char * PQerrorMessage (const PGconn *conn)
 
int PQsocket (const PGconn *conn)
 
int PQbackendPID (const PGconn *conn)
 
int PQconnectionNeedsPassword (const PGconn *conn)
 
int PQconnectionUsedPassword (const PGconn *conn)
 
int PQclientEncoding (const PGconn *conn)
 
int PQsetClientEncoding (PGconn *conn, const char *encoding)
 
int PQsslInUse (PGconn *conn)
 
void * PQsslStruct (PGconn *conn, const char *struct_name)
 
const char * PQsslAttribute (PGconn *conn, const char *attribute_name)
 
const char *const * PQsslAttributeNames (PGconn *conn)
 
void * PQgetssl (PGconn *conn)
 
void PQinitSSL (int do_init)
 
void PQinitOpenSSL (int do_ssl, int do_crypto)
 
PGVerbosity PQsetErrorVerbosity (PGconn *conn, PGVerbosity verbosity)
 
PGContextVisibility PQsetErrorContextVisibility (PGconn *conn, PGContextVisibility show_context)
 
void PQtrace (PGconn *conn, FILE *debug_port)
 
void PQuntrace (PGconn *conn)
 
PQnoticeReceiver PQsetNoticeReceiver (PGconn *conn, PQnoticeReceiver proc, void *arg)
 
PQnoticeProcessor PQsetNoticeProcessor (PGconn *conn, PQnoticeProcessor proc, void *arg)
 
pgthreadlock_t PQregisterThreadLock (pgthreadlock_t newhandler)
 
PGresultPQexec (PGconn *conn, const char *query)
 
PGresultPQexecParams (PGconn *conn, const char *command, int nParams, const Oid *paramTypes, const char *const *paramValues, const int *paramLengths, const int *paramFormats, int resultFormat)
 
PGresultPQprepare (PGconn *conn, const char *stmtName, const char *query, int nParams, const Oid *paramTypes)
 
PGresultPQexecPrepared (PGconn *conn, const char *stmtName, int nParams, const char *const *paramValues, const int *paramLengths, const int *paramFormats, int resultFormat)
 
int PQsendQuery (PGconn *conn, const char *query)
 
int PQsendQueryParams (PGconn *conn, const char *command, int nParams, const Oid *paramTypes, const char *const *paramValues, const int *paramLengths, const int *paramFormats, int resultFormat)
 
int PQsendPrepare (PGconn *conn, const char *stmtName, const char *query, int nParams, const Oid *paramTypes)
 
int PQsendQueryPrepared (PGconn *conn, const char *stmtName, int nParams, const char *const *paramValues, const int *paramLengths, const int *paramFormats, int resultFormat)
 
int PQsetSingleRowMode (PGconn *conn)
 
PGresultPQgetResult (PGconn *conn)
 
int PQisBusy (PGconn *conn)
 
int PQconsumeInput (PGconn *conn)
 
PGnotifyPQnotifies (PGconn *conn)
 
int PQputCopyData (PGconn *conn, const char *buffer, int nbytes)
 
int PQputCopyEnd (PGconn *conn, const char *errormsg)
 
int PQgetCopyData (PGconn *conn, char **buffer, int async)
 
int PQgetline (PGconn *conn, char *string, int length)
 
int PQputline (PGconn *conn, const char *string)
 
int PQgetlineAsync (PGconn *conn, char *buffer, int bufsize)
 
int PQputnbytes (PGconn *conn, const char *buffer, int nbytes)
 
int PQendcopy (PGconn *conn)
 
int PQsetnonblocking (PGconn *conn, int arg)
 
int PQisnonblocking (const PGconn *conn)
 
int PQisthreadsafe (void)
 
PGPing PQping (const char *conninfo)
 
PGPing PQpingParams (const char *const *keywords, const char *const *values, int expand_dbname)
 
int PQflush (PGconn *conn)
 
PGresultPQfn (PGconn *conn, int fnid, int *result_buf, int *result_len, int result_is_int, const PQArgBlock *args, int nargs)
 
ExecStatusType PQresultStatus (const PGresult *res)
 
char * PQresStatus (ExecStatusType status)
 
char * PQresultErrorMessage (const PGresult *res)
 
char * PQresultVerboseErrorMessage (const PGresult *res, PGVerbosity verbosity, PGContextVisibility show_context)
 
char * PQresultErrorField (const PGresult *res, int fieldcode)
 
int PQntuples (const PGresult *res)
 
int PQnfields (const PGresult *res)
 
int PQbinaryTuples (const PGresult *res)
 
char * PQfname (const PGresult *res, int field_num)
 
int PQfnumber (const PGresult *res, const char *field_name)
 
Oid PQftable (const PGresult *res, int field_num)
 
int PQftablecol (const PGresult *res, int field_num)
 
int PQfformat (const PGresult *res, int field_num)
 
Oid PQftype (const PGresult *res, int field_num)
 
int PQfsize (const PGresult *res, int field_num)
 
int PQfmod (const PGresult *res, int field_num)
 
char * PQcmdStatus (PGresult *res)
 
char * PQoidStatus (const PGresult *res)
 
Oid PQoidValue (const PGresult *res)
 
char * PQcmdTuples (PGresult *res)
 
char * PQgetvalue (const PGresult *res, int tup_num, int field_num)
 
int PQgetlength (const PGresult *res, int tup_num, int field_num)
 
int PQgetisnull (const PGresult *res, int tup_num, int field_num)
 
int PQnparams (const PGresult *res)
 
Oid PQparamtype (const PGresult *res, int param_num)
 
PGresultPQdescribePrepared (PGconn *conn, const char *stmt)
 
PGresultPQdescribePortal (PGconn *conn, const char *portal)
 
int PQsendDescribePrepared (PGconn *conn, const char *stmt)
 
int PQsendDescribePortal (PGconn *conn, const char *portal)
 
void PQclear (PGresult *res)
 
void PQfreemem (void *ptr)
 
PGresultPQmakeEmptyPGresult (PGconn *conn, ExecStatusType status)
 
PGresultPQcopyResult (const PGresult *src, int flags)
 
int PQsetResultAttrs (PGresult *res, int numAttributes, PGresAttDesc *attDescs)
 
void * PQresultAlloc (PGresult *res, size_t nBytes)
 
int PQsetvalue (PGresult *res, int tup_num, int field_num, char *value, int len)
 
size_t PQescapeStringConn (PGconn *conn, char *to, const char *from, size_t length, int *error)
 
char * PQescapeLiteral (PGconn *conn, const char *str, size_t len)
 
char * PQescapeIdentifier (PGconn *conn, const char *str, size_t len)
 
unsigned char * PQescapeByteaConn (PGconn *conn, const unsigned char *from, size_t from_length, size_t *to_length)
 
unsigned char * PQunescapeBytea (const unsigned char *strtext, size_t *retbuflen)
 
size_t PQescapeString (char *to, const char *from, size_t length)
 
unsigned char * PQescapeBytea (const unsigned char *from, size_t from_length, size_t *to_length)
 
void PQprint (FILE *fout, const PGresult *res, const PQprintOpt *ps)
 
void PQdisplayTuples (const PGresult *res, FILE *fp, int fillAlign, const char *fieldSep, int printHeader, int quiet)
 
void PQprintTuples (const PGresult *res, FILE *fout, int printAttName, int terseOutput, int width)
 
int lo_open (PGconn *conn, Oid lobjId, int mode)
 
int lo_close (PGconn *conn, int fd)
 
int lo_read (PGconn *conn, int fd, char *buf, size_t len)
 
int lo_write (PGconn *conn, int fd, const char *buf, size_t len)
 
int lo_lseek (PGconn *conn, int fd, int offset, int whence)
 
pg_int64 lo_lseek64 (PGconn *conn, int fd, pg_int64 offset, int whence)
 
Oid lo_creat (PGconn *conn, int mode)
 
Oid lo_create (PGconn *conn, Oid lobjId)
 
int lo_tell (PGconn *conn, int fd)
 
pg_int64 lo_tell64 (PGconn *conn, int fd)
 
int lo_truncate (PGconn *conn, int fd, size_t len)
 
int lo_truncate64 (PGconn *conn, int fd, pg_int64 len)
 
int lo_unlink (PGconn *conn, Oid lobjId)
 
Oid lo_import (PGconn *conn, const char *filename)
 
Oid lo_import_with_oid (PGconn *conn, const char *filename, Oid lobjId)
 
int lo_export (PGconn *conn, Oid lobjId, const char *filename)
 
int PQlibVersion (void)
 
int PQmblen (const char *s, int encoding)
 
int PQdsplen (const char *s, int encoding)
 
int PQenv2encoding (void)
 
char * PQencryptPassword (const char *passwd, const char *user)
 
int pg_char_to_encoding (const char *name)
 
const char * pg_encoding_to_char (int encoding)
 
int pg_valid_server_encoding_id (int encoding)
 

Macro Definition Documentation

#define PG_COPYRES_ATTRS   0x01

Definition at line 34 of file libpq-fe.h.

Referenced by PQcopyResult(), and pqRowProcessor().

#define PG_COPYRES_EVENTS   0x04

Definition at line 36 of file libpq-fe.h.

Referenced by PQcopyResult(), and pqRowProcessor().

#define PG_COPYRES_NOTICEHOOKS   0x08

Definition at line 37 of file libpq-fe.h.

Referenced by PQcopyResult(), and pqRowProcessor().

#define PG_COPYRES_TUPLES   0x02 /* Implies PG_COPYRES_ATTRS */

Definition at line 35 of file libpq-fe.h.

Referenced by PQcopyResult().

#define PQfreeNotify (   ptr)    PQfreemem(ptr)

Definition at line 508 of file libpq-fe.h.

#define PQnoPasswordSupplied   "fe_sendauth: no password supplied\n"

Definition at line 512 of file libpq-fe.h.

Referenced by pg_fe_sendauth(), and pg_SASL_init().

#define PQsetdb (   M_PGHOST,
  M_PGPORT,
  M_PGOPT,
  M_PGTTY,
  M_DBNAME 
)    PQsetdbLogin(M_PGHOST, M_PGPORT, M_PGOPT, M_PGTTY, M_DBNAME, NULL, NULL)

Definition at line 269 of file libpq-fe.h.

Referenced by main().

Typedef Documentation

Definition at line 153 of file libpq-fe.h.

Definition at line 140 of file libpq-fe.h.

Definition at line 147 of file libpq-fe.h.

typedef void(* pgthreadlock_t)(int acquire)

Definition at line 374 of file libpq-fe.h.

Definition at line 175 of file libpq-fe.h.

typedef void(* PQnoticeProcessor)(void *arg, const char *message)

Definition at line 172 of file libpq-fe.h.

typedef void(* PQnoticeReceiver)(void *arg, const PGresult *res)

Definition at line 171 of file libpq-fe.h.

Enumeration Type Documentation

Enumerator
CONNECTION_OK 
CONNECTION_BAD 
CONNECTION_STARTED 
CONNECTION_MADE 
CONNECTION_AWAITING_RESPONSE 
CONNECTION_AUTH_OK 
CONNECTION_SETENV 
CONNECTION_SSL_STARTUP 
CONNECTION_NEEDED 
CONNECTION_CHECK_WRITABLE 
CONNECTION_CONSUME 

Definition at line 47 of file libpq-fe.h.

48 {
51  /* Non-blocking mode only below here */
52 
53  /*
54  * The existence of these should never be relied upon - they should only
55  * be used for user feedback or similar purposes.
56  */
57  CONNECTION_STARTED, /* Waiting for connection to be made. */
58  CONNECTION_MADE, /* Connection OK; waiting to send. */
59  CONNECTION_AWAITING_RESPONSE, /* Waiting for a response from the
60  * postmaster. */
61  CONNECTION_AUTH_OK, /* Received authentication; waiting for
62  * backend startup. */
63  CONNECTION_SETENV, /* Negotiating environment. */
64  CONNECTION_SSL_STARTUP, /* Negotiating SSL. */
65  CONNECTION_NEEDED, /* Internal state: connect() needed */
66  CONNECTION_CHECK_WRITABLE, /* Check if we could make a writable
67  * connection. */
68  CONNECTION_CONSUME /* Wait for any pending message and
69  * consume them. */
ConnStatusType
Definition: libpq-fe.h:47
Enumerator
PGRES_EMPTY_QUERY 
PGRES_COMMAND_OK 
PGRES_TUPLES_OK 
PGRES_COPY_OUT 
PGRES_COPY_IN 
PGRES_BAD_RESPONSE 
PGRES_NONFATAL_ERROR 
PGRES_FATAL_ERROR 
PGRES_COPY_BOTH 
PGRES_SINGLE_TUPLE 

Definition at line 82 of file libpq-fe.h.

83 {
84  PGRES_EMPTY_QUERY = 0, /* empty query string was executed */
85  PGRES_COMMAND_OK, /* a query command that doesn't return
86  * anything was executed properly by the
87  * backend */
88  PGRES_TUPLES_OK, /* a query command that returns tuples was
89  * executed properly by the backend, PGresult
90  * contains the result tuples */
91  PGRES_COPY_OUT, /* Copy Out data transfer in progress */
92  PGRES_COPY_IN, /* Copy In data transfer in progress */
93  PGRES_BAD_RESPONSE, /* an unexpected response was recv'd from the
94  * backend */
95  PGRES_NONFATAL_ERROR, /* notice or warning message */
96  PGRES_FATAL_ERROR, /* query failed */
97  PGRES_COPY_BOTH, /* Copy In/Out data transfer in progress */
98  PGRES_SINGLE_TUPLE /* single tuple from larger resultset */
ExecStatusType
Definition: libpq-fe.h:82
Enumerator
PQSHOW_CONTEXT_NEVER 
PQSHOW_CONTEXT_ERRORS 
PQSHOW_CONTEXT_ALWAYS 

Definition at line 117 of file libpq-fe.h.

118 {
119  PQSHOW_CONTEXT_NEVER, /* never show CONTEXT field */
120  PQSHOW_CONTEXT_ERRORS, /* show CONTEXT for errors only (default) */
121  PQSHOW_CONTEXT_ALWAYS /* always show CONTEXT field */
PGContextVisibility
Definition: libpq-fe.h:117
enum PGPing
Enumerator
PQPING_OK 
PQPING_REJECT 
PQPING_NO_RESPONSE 
PQPING_NO_ATTEMPT 

Definition at line 129 of file libpq-fe.h.

130 {
131  PQPING_OK, /* server is accepting connections */
132  PQPING_REJECT, /* server is alive but rejecting connections */
133  PQPING_NO_RESPONSE, /* could not establish connection */
134  PQPING_NO_ATTEMPT /* connection not attempted (bad params) */
135 } PGPing;
PGPing
Definition: libpq-fe.h:129
Enumerator
PQTRANS_IDLE 
PQTRANS_ACTIVE 
PQTRANS_INTRANS 
PQTRANS_INERROR 
PQTRANS_UNKNOWN 

Definition at line 101 of file libpq-fe.h.

102 {
103  PQTRANS_IDLE, /* connection idle */
104  PQTRANS_ACTIVE, /* command in progress */
105  PQTRANS_INTRANS, /* idle, within transaction block */
106  PQTRANS_INERROR, /* idle, within failed transaction */
107  PQTRANS_UNKNOWN /* cannot determine status */
PGTransactionStatusType
Definition: libpq-fe.h:101
Enumerator
PQERRORS_TERSE 
PQERRORS_DEFAULT 
PQERRORS_VERBOSE 

Definition at line 110 of file libpq-fe.h.

111 {
112  PQERRORS_TERSE, /* single-line error messages */
113  PQERRORS_DEFAULT, /* recommended style */
114  PQERRORS_VERBOSE /* all the facts, ma'am */
115 } PGVerbosity;
PGVerbosity
Definition: libpq-fe.h:110
Enumerator
PGRES_POLLING_FAILED 
PGRES_POLLING_READING 
PGRES_POLLING_WRITING 
PGRES_POLLING_OK 
PGRES_POLLING_ACTIVE 

Definition at line 72 of file libpq-fe.h.

73 {
75  PGRES_POLLING_READING, /* These two indicate that one may */
76  PGRES_POLLING_WRITING, /* use select before polling again. */
78  PGRES_POLLING_ACTIVE /* unused; keep for awhile for backwards
79  * compatibility */
PostgresPollingStatusType
Definition: libpq-fe.h:72

Function Documentation

int lo_close ( PGconn conn,
int  fd 
)

Definition at line 100 of file fe-lobj.c.

References fd(), pgLobjfuncs::fn_lo_close, PQArgBlock::integer, PQArgBlock::isint, PQArgBlock::len, lo_initialize(), pg_conn::lobjfuncs, NULL, PGRES_COMMAND_OK, PQclear(), PQfn(), PQresultStatus(), and PQArgBlock::u.

Referenced by dumpBlobs(), EndRestoreBlob(), exportFile(), importFile(), lo_export(), lo_import_internal(), my_truncate(), overwrite(), and pickout().

101 {
102  PQArgBlock argv[1];
103  PGresult *res;
104  int retval;
105  int result_len;
106 
107  if (conn == NULL || conn->lobjfuncs == NULL)
108  {
109  if (lo_initialize(conn) < 0)
110  return -1;
111  }
112 
113  argv[0].isint = 1;
114  argv[0].len = 4;
115  argv[0].u.integer = fd;
116  res = PQfn(conn, conn->lobjfuncs->fn_lo_close,
117  &retval, &result_len, 1, argv, 1);
118  if (PQresultStatus(res) == PGRES_COMMAND_OK)
119  {
120  PQclear(res);
121  return retval;
122  }
123  else
124  {
125  PQclear(res);
126  return -1;
127  }
128 }
union PQArgBlock::@139 u
PGresult * PQfn(PGconn *conn, int fnid, int *result_buf, int *result_len, int result_is_int, const PQArgBlock *args, int nargs)
Definition: fe-exec.c:2556
static int fd(const char *x, int i)
Definition: preproc-init.c:105
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:2596
void PQclear(PGresult *res)
Definition: fe-exec.c:650
#define NULL
Definition: c.h:229
Oid fn_lo_close
Definition: libpq-int.h:268
int isint
Definition: libpq-fe.h:223
PGlobjfuncs * lobjfuncs
Definition: libpq-int.h:427
int integer
Definition: libpq-fe.h:227
static int lo_initialize(PGconn *conn)
Definition: fe-lobj.c:877
Oid lo_creat ( PGconn conn,
int  mode 
)

Definition at line 466 of file fe-lobj.c.

References pgLobjfuncs::fn_lo_creat, PQArgBlock::integer, InvalidOid, PQArgBlock::isint, PQArgBlock::len, lo_initialize(), pg_conn::lobjfuncs, NULL, PGRES_COMMAND_OK, PQclear(), PQfn(), PQresultStatus(), and PQArgBlock::u.

Referenced by importFile(), and lo_import_internal().

467 {
468  PQArgBlock argv[1];
469  PGresult *res;
470  int retval;
471  int result_len;
472 
473  if (conn == NULL || conn->lobjfuncs == NULL)
474  {
475  if (lo_initialize(conn) < 0)
476  return InvalidOid;
477  }
478 
479  argv[0].isint = 1;
480  argv[0].len = 4;
481  argv[0].u.integer = mode;
482  res = PQfn(conn, conn->lobjfuncs->fn_lo_creat,
483  &retval, &result_len, 1, argv, 1);
484  if (PQresultStatus(res) == PGRES_COMMAND_OK)
485  {
486  PQclear(res);
487  return (Oid) retval;
488  }
489  else
490  {
491  PQclear(res);
492  return InvalidOid;
493  }
494 }
union PQArgBlock::@139 u
unsigned int Oid
Definition: postgres_ext.h:31
PGresult * PQfn(PGconn *conn, int fnid, int *result_buf, int *result_len, int result_is_int, const PQArgBlock *args, int nargs)
Definition: fe-exec.c:2556
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:2596
#define InvalidOid
Definition: postgres_ext.h:36
void PQclear(PGresult *res)
Definition: fe-exec.c:650
#define NULL
Definition: c.h:229
Oid fn_lo_creat
Definition: libpq-int.h:269
int isint
Definition: libpq-fe.h:223
PGlobjfuncs * lobjfuncs
Definition: libpq-int.h:427
int integer
Definition: libpq-fe.h:227
static int lo_initialize(PGconn *conn)
Definition: fe-lobj.c:877
Oid lo_create ( PGconn conn,
Oid  lobjId 
)

Definition at line 505 of file fe-lobj.c.

References pg_conn::errorMessage, pgLobjfuncs::fn_lo_create, PQArgBlock::integer, InvalidOid, PQArgBlock::isint, PQArgBlock::len, libpq_gettext, lo_initialize(), pg_conn::lobjfuncs, NULL, PGRES_COMMAND_OK, PQclear(), PQfn(), PQresultStatus(), printfPQExpBuffer(), and PQArgBlock::u.

Referenced by lo_import_internal(), and StartRestoreBlob().

506 {
507  PQArgBlock argv[1];
508  PGresult *res;
509  int retval;
510  int result_len;
511 
512  if (conn == NULL || conn->lobjfuncs == NULL)
513  {
514  if (lo_initialize(conn) < 0)
515  return InvalidOid;
516  }
517 
518  /* Must check this on-the-fly because it's not there pre-8.1 */
519  if (conn->lobjfuncs->fn_lo_create == 0)
520  {
522  libpq_gettext("cannot determine OID of function lo_create\n"));
523  return InvalidOid;
524  }
525 
526  argv[0].isint = 1;
527  argv[0].len = 4;
528  argv[0].u.integer = lobjId;
529  res = PQfn(conn, conn->lobjfuncs->fn_lo_create,
530  &retval, &result_len, 1, argv, 1);
531  if (PQresultStatus(res) == PGRES_COMMAND_OK)
532  {
533  PQclear(res);
534  return (Oid) retval;
535  }
536  else
537  {
538  PQclear(res);
539  return InvalidOid;
540  }
541 }
union PQArgBlock::@139 u
void printfPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:234
Oid fn_lo_create
Definition: libpq-int.h:270
unsigned int Oid
Definition: postgres_ext.h:31
PGresult * PQfn(PGconn *conn, int fnid, int *result_buf, int *result_len, int result_is_int, const PQArgBlock *args, int nargs)
Definition: fe-exec.c:2556
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:2596
PQExpBufferData errorMessage
Definition: libpq-int.h:492
#define InvalidOid
Definition: postgres_ext.h:36
void PQclear(PGresult *res)
Definition: fe-exec.c:650
#define NULL
Definition: c.h:229
int isint
Definition: libpq-fe.h:223
PGlobjfuncs * lobjfuncs
Definition: libpq-int.h:427
#define libpq_gettext(x)
Definition: libpq-int.h:683
int integer
Definition: libpq-fe.h:227
static int lo_initialize(PGconn *conn)
Definition: fe-lobj.c:877
int lo_export ( PGconn conn,
Oid  lobjId,
const char *  filename 
)

Definition at line 785 of file fe-lobj.c.

References buf, close, pg_conn::errorMessage, fd(), INV_READ, libpq_gettext, LO_BUFSIZE, lo_close(), lo_open(), lo_read(), PG_BINARY, pqStrerror(), printfPQExpBuffer(), result, and write.

Referenced by do_lo_export(), and main().

786 {
787  int result = 1;
788  int fd;
789  int nbytes,
790  tmp;
791  char buf[LO_BUFSIZE];
792  int lobj;
793  char sebuf[256];
794 
795  /*
796  * open the large object.
797  */
798  lobj = lo_open(conn, lobjId, INV_READ);
799  if (lobj == -1)
800  {
801  /* we assume lo_open() already set a suitable error message */
802  return -1;
803  }
804 
805  /*
806  * create the file to be written to
807  */
808  fd = open(filename, O_CREAT | O_WRONLY | O_TRUNC | PG_BINARY, 0666);
809  if (fd < 0)
810  {
811  /* We must do lo_close before setting the errorMessage */
812  int save_errno = errno;
813 
814  (void) lo_close(conn, lobj);
816  libpq_gettext("could not open file \"%s\": %s\n"),
817  filename,
818  pqStrerror(save_errno, sebuf, sizeof(sebuf)));
819  return -1;
820  }
821 
822  /*
823  * read in from the large object and write to the file
824  */
825  while ((nbytes = lo_read(conn, lobj, buf, LO_BUFSIZE)) > 0)
826  {
827  tmp = write(fd, buf, nbytes);
828  if (tmp != nbytes)
829  {
830  /* We must do lo_close before setting the errorMessage */
831  int save_errno = errno;
832 
833  (void) lo_close(conn, lobj);
834  (void) close(fd);
836  libpq_gettext("could not write to file \"%s\": %s\n"),
837  filename,
838  pqStrerror(save_errno, sebuf, sizeof(sebuf)));
839  return -1;
840  }
841  }
842 
843  /*
844  * If lo_read() failed, we are now in an aborted transaction so there's no
845  * need for lo_close(); furthermore, if we tried it we'd overwrite the
846  * useful error result with a useless one. So skip lo_close() if we got a
847  * failure result.
848  */
849  if (nbytes < 0 ||
850  lo_close(conn, lobj) != 0)
851  {
852  /* assume lo_read() or lo_close() left a suitable error message */
853  result = -1;
854  }
855 
856  /* if we already failed, don't overwrite that msg with a close error */
857  if (close(fd) && result >= 0)
858  {
860  libpq_gettext("could not write to file \"%s\": %s\n"),
861  filename, pqStrerror(errno, sebuf, sizeof(sebuf)));
862  result = -1;
863  }
864 
865  return result;
866 }
void printfPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:234
#define write(a, b, c)
Definition: win32.h:14
char * pqStrerror(int errnum, char *strerrbuf, size_t buflen)
Definition: thread.c:61
return result
Definition: formatting.c:1618
static int fd(const char *x, int i)
Definition: preproc-init.c:105
#define PG_BINARY
Definition: c.h:1038
#define INV_READ
Definition: libpq-fs.h:22
int lo_close(PGconn *conn, int fd)
Definition: fe-lobj.c:100
static char * buf
Definition: pg_test_fsync.c:66
int lo_open(PGconn *conn, Oid lobjId, int mode)
Definition: fe-lobj.c:58
PQExpBufferData errorMessage
Definition: libpq-int.h:492
#define LO_BUFSIZE
Definition: fe-lobj.c:43
static char * filename
Definition: pg_dumpall.c:87
int lo_read(PGconn *conn, int fd, char *buf, size_t len)
Definition: fe-lobj.c:259
#define close(a)
Definition: win32.h:12
#define libpq_gettext(x)
Definition: libpq-int.h:683
Oid lo_import ( PGconn conn,
const char *  filename 
)

Definition at line 669 of file fe-lobj.c.

References InvalidOid, and lo_import_internal().

Referenced by do_lo_import(), and main().

670 {
671  return lo_import_internal(conn, filename, InvalidOid);
672 }
static Oid lo_import_internal(PGconn *conn, const char *filename, Oid oid)
Definition: fe-lobj.c:690
#define InvalidOid
Definition: postgres_ext.h:36
static char * filename
Definition: pg_dumpall.c:87
Oid lo_import_with_oid ( PGconn conn,
const char *  filename,
Oid  lobjId 
)

Definition at line 684 of file fe-lobj.c.

References lo_import_internal().

685 {
686  return lo_import_internal(conn, filename, lobjId);
687 }
static Oid lo_import_internal(PGconn *conn, const char *filename, Oid oid)
Definition: fe-lobj.c:690
static char * filename
Definition: pg_dumpall.c:87
int lo_lseek ( PGconn conn,
int  fd,
int  offset,
int  whence 
)

Definition at line 366 of file fe-lobj.c.

References fd(), pgLobjfuncs::fn_lo_lseek, PQArgBlock::integer, PQArgBlock::isint, PQArgBlock::len, lo_initialize(), pg_conn::lobjfuncs, NULL, PGRES_COMMAND_OK, PQclear(), PQfn(), PQresultStatus(), and PQArgBlock::u.

Referenced by overwrite(), and pickout().

367 {
368  PQArgBlock argv[3];
369  PGresult *res;
370  int retval;
371  int result_len;
372 
373  if (conn == NULL || conn->lobjfuncs == NULL)
374  {
375  if (lo_initialize(conn) < 0)
376  return -1;
377  }
378 
379  argv[0].isint = 1;
380  argv[0].len = 4;
381  argv[0].u.integer = fd;
382 
383  argv[1].isint = 1;
384  argv[1].len = 4;
385  argv[1].u.integer = offset;
386 
387  argv[2].isint = 1;
388  argv[2].len = 4;
389  argv[2].u.integer = whence;
390 
391  res = PQfn(conn, conn->lobjfuncs->fn_lo_lseek,
392  &retval, &result_len, 1, argv, 3);
393  if (PQresultStatus(res) == PGRES_COMMAND_OK)
394  {
395  PQclear(res);
396  return retval;
397  }
398  else
399  {
400  PQclear(res);
401  return -1;
402  }
403 }
union PQArgBlock::@139 u
Oid fn_lo_lseek
Definition: libpq-int.h:272
PGresult * PQfn(PGconn *conn, int fnid, int *result_buf, int *result_len, int result_is_int, const PQArgBlock *args, int nargs)
Definition: fe-exec.c:2556
static int fd(const char *x, int i)
Definition: preproc-init.c:105
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:2596
void PQclear(PGresult *res)
Definition: fe-exec.c:650
#define NULL
Definition: c.h:229
int isint
Definition: libpq-fe.h:223
PGlobjfuncs * lobjfuncs
Definition: libpq-int.h:427
int integer
Definition: libpq-fe.h:227
static int lo_initialize(PGconn *conn)
Definition: fe-lobj.c:877
pg_int64 lo_lseek64 ( PGconn conn,
int  fd,
pg_int64  offset,
int  whence 
)

Definition at line 410 of file fe-lobj.c.

References pg_conn::errorMessage, fd(), pgLobjfuncs::fn_lo_lseek64, PQArgBlock::integer, PQArgBlock::isint, PQArgBlock::len, libpq_gettext, lo_hton64(), lo_initialize(), lo_ntoh64(), pg_conn::lobjfuncs, NULL, PGRES_COMMAND_OK, PQclear(), PQfn(), PQresultStatus(), printfPQExpBuffer(), PQArgBlock::ptr, and PQArgBlock::u.

Referenced by overwrite(), and pickout().

411 {
412  PQArgBlock argv[3];
413  PGresult *res;
414  pg_int64 retval;
415  int result_len;
416 
417  if (conn == NULL || conn->lobjfuncs == NULL)
418  {
419  if (lo_initialize(conn) < 0)
420  return -1;
421  }
422 
423  if (conn->lobjfuncs->fn_lo_lseek64 == 0)
424  {
426  libpq_gettext("cannot determine OID of function lo_lseek64\n"));
427  return -1;
428  }
429 
430  argv[0].isint = 1;
431  argv[0].len = 4;
432  argv[0].u.integer = fd;
433 
434  offset = lo_hton64(offset);
435  argv[1].isint = 0;
436  argv[1].len = 8;
437  argv[1].u.ptr = (int *) &offset;
438 
439  argv[2].isint = 1;
440  argv[2].len = 4;
441  argv[2].u.integer = whence;
442 
443  res = PQfn(conn, conn->lobjfuncs->fn_lo_lseek64,
444  (void *) &retval, &result_len, 0, argv, 3);
445  if (PQresultStatus(res) == PGRES_COMMAND_OK && result_len == 8)
446  {
447  PQclear(res);
448  return lo_ntoh64(retval);
449  }
450  else
451  {
452  PQclear(res);
453  return -1;
454  }
455 }
union PQArgBlock::@139 u
void printfPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:234
PGresult * PQfn(PGconn *conn, int fnid, int *result_buf, int *result_len, int result_is_int, const PQArgBlock *args, int nargs)
Definition: fe-exec.c:2556
static int fd(const char *x, int i)
Definition: preproc-init.c:105
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:2596
PG_INT64_TYPE pg_int64
Definition: postgres_ext.h:47
static pg_int64 lo_hton64(pg_int64 host64)
Definition: fe-lobj.c:1062
PQExpBufferData errorMessage
Definition: libpq-int.h:492
void PQclear(PGresult *res)
Definition: fe-exec.c:650
#define NULL
Definition: c.h:229
Oid fn_lo_lseek64
Definition: libpq-int.h:273
int isint
Definition: libpq-fe.h:223
PGlobjfuncs * lobjfuncs
Definition: libpq-int.h:427
int * ptr
Definition: libpq-fe.h:226
#define libpq_gettext(x)
Definition: libpq-int.h:683
int integer
Definition: libpq-fe.h:227
static pg_int64 lo_ntoh64(pg_int64 net64)
Definition: fe-lobj.c:1087
static int lo_initialize(PGconn *conn)
Definition: fe-lobj.c:877
int lo_open ( PGconn conn,
Oid  lobjId,
int  mode 
)

Definition at line 58 of file fe-lobj.c.

References fd(), pgLobjfuncs::fn_lo_open, PQArgBlock::integer, PQArgBlock::isint, PQArgBlock::len, lo_initialize(), pg_conn::lobjfuncs, NULL, PGRES_COMMAND_OK, PQclear(), PQfn(), PQresultStatus(), and PQArgBlock::u.

Referenced by dumpBlobs(), exportFile(), importFile(), lo_export(), lo_import_internal(), my_truncate(), overwrite(), pickout(), and StartRestoreBlob().

59 {
60  int fd;
61  int result_len;
62  PQArgBlock argv[2];
63  PGresult *res;
64 
65  if (conn == NULL || conn->lobjfuncs == NULL)
66  {
67  if (lo_initialize(conn) < 0)
68  return -1;
69  }
70 
71  argv[0].isint = 1;
72  argv[0].len = 4;
73  argv[0].u.integer = lobjId;
74 
75  argv[1].isint = 1;
76  argv[1].len = 4;
77  argv[1].u.integer = mode;
78 
79  res = PQfn(conn, conn->lobjfuncs->fn_lo_open, &fd, &result_len, 1, argv, 2);
80  if (PQresultStatus(res) == PGRES_COMMAND_OK)
81  {
82  PQclear(res);
83  return fd;
84  }
85  else
86  {
87  PQclear(res);
88  return -1;
89  }
90 }
union PQArgBlock::@139 u
PGresult * PQfn(PGconn *conn, int fnid, int *result_buf, int *result_len, int result_is_int, const PQArgBlock *args, int nargs)
Definition: fe-exec.c:2556
static int fd(const char *x, int i)
Definition: preproc-init.c:105
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:2596
Oid fn_lo_open
Definition: libpq-int.h:267
void PQclear(PGresult *res)
Definition: fe-exec.c:650
#define NULL
Definition: c.h:229
int isint
Definition: libpq-fe.h:223
PGlobjfuncs * lobjfuncs
Definition: libpq-int.h:427
int integer
Definition: libpq-fe.h:227
static int lo_initialize(PGconn *conn)
Definition: fe-lobj.c:877
int lo_read ( PGconn conn,
int  fd,
char *  buf,
size_t  len 
)

Definition at line 259 of file fe-lobj.c.

References pg_conn::errorMessage, fd(), pgLobjfuncs::fn_lo_read, PQArgBlock::integer, PQArgBlock::isint, PQArgBlock::len, libpq_gettext, lo_initialize(), pg_conn::lobjfuncs, NULL, PGRES_COMMAND_OK, PQclear(), PQfn(), PQresultStatus(), printfPQExpBuffer(), and PQArgBlock::u.

Referenced by lo_export().

260 {
261  PQArgBlock argv[2];
262  PGresult *res;
263  int result_len;
264 
265  if (conn == NULL || conn->lobjfuncs == NULL)
266  {
267  if (lo_initialize(conn) < 0)
268  return -1;
269  }
270 
271  /*
272  * Long ago, somebody thought it'd be a good idea to declare this function
273  * as taking size_t ... but the underlying backend function only accepts a
274  * signed int32 length. So throw error if the given value overflows
275  * int32.
276  */
277  if (len > (size_t) INT_MAX)
278  {
280  libpq_gettext("argument of lo_read exceeds integer range\n"));
281  return -1;
282  }
283 
284  argv[0].isint = 1;
285  argv[0].len = 4;
286  argv[0].u.integer = fd;
287 
288  argv[1].isint = 1;
289  argv[1].len = 4;
290  argv[1].u.integer = (int) len;
291 
292  res = PQfn(conn, conn->lobjfuncs->fn_lo_read,
293  (void *) buf, &result_len, 0, argv, 2);
294  if (PQresultStatus(res) == PGRES_COMMAND_OK)
295  {
296  PQclear(res);
297  return result_len;
298  }
299  else
300  {
301  PQclear(res);
302  return -1;
303  }
304 }
union PQArgBlock::@139 u
void printfPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:234
PGresult * PQfn(PGconn *conn, int fnid, int *result_buf, int *result_len, int result_is_int, const PQArgBlock *args, int nargs)
Definition: fe-exec.c:2556
static int fd(const char *x, int i)
Definition: preproc-init.c:105
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:2596
Oid fn_lo_read
Definition: libpq-int.h:278
static char * buf
Definition: pg_test_fsync.c:66
PQExpBufferData errorMessage
Definition: libpq-int.h:492
void PQclear(PGresult *res)
Definition: fe-exec.c:650
#define NULL
Definition: c.h:229
int isint
Definition: libpq-fe.h:223
PGlobjfuncs * lobjfuncs
Definition: libpq-int.h:427
#define libpq_gettext(x)
Definition: libpq-int.h:683
int integer
Definition: libpq-fe.h:227
static int lo_initialize(PGconn *conn)
Definition: fe-lobj.c:877
int lo_tell ( PGconn conn,
int  fd 
)

Definition at line 549 of file fe-lobj.c.

References fd(), pgLobjfuncs::fn_lo_tell, PQArgBlock::integer, PQArgBlock::isint, PQArgBlock::len, lo_initialize(), pg_conn::lobjfuncs, NULL, PGRES_COMMAND_OK, PQclear(), PQfn(), PQresultStatus(), and PQArgBlock::u.

550 {
551  int retval;
552  PQArgBlock argv[1];
553  PGresult *res;
554  int result_len;
555 
556  if (conn == NULL || conn->lobjfuncs == NULL)
557  {
558  if (lo_initialize(conn) < 0)
559  return -1;
560  }
561 
562  argv[0].isint = 1;
563  argv[0].len = 4;
564  argv[0].u.integer = fd;
565 
566  res = PQfn(conn, conn->lobjfuncs->fn_lo_tell,
567  &retval, &result_len, 1, argv, 1);
568  if (PQresultStatus(res) == PGRES_COMMAND_OK)
569  {
570  PQclear(res);
571  return retval;
572  }
573  else
574  {
575  PQclear(res);
576  return -1;
577  }
578 }
union PQArgBlock::@139 u
PGresult * PQfn(PGconn *conn, int fnid, int *result_buf, int *result_len, int result_is_int, const PQArgBlock *args, int nargs)
Definition: fe-exec.c:2556
static int fd(const char *x, int i)
Definition: preproc-init.c:105
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:2596
Oid fn_lo_tell
Definition: libpq-int.h:274
void PQclear(PGresult *res)
Definition: fe-exec.c:650
#define NULL
Definition: c.h:229
int isint
Definition: libpq-fe.h:223
PGlobjfuncs * lobjfuncs
Definition: libpq-int.h:427
int integer
Definition: libpq-fe.h:227
static int lo_initialize(PGconn *conn)
Definition: fe-lobj.c:877
pg_int64 lo_tell64 ( PGconn conn,
int  fd 
)

Definition at line 585 of file fe-lobj.c.

References pg_conn::errorMessage, fd(), pgLobjfuncs::fn_lo_tell64, PQArgBlock::integer, PQArgBlock::isint, PQArgBlock::len, libpq_gettext, lo_initialize(), lo_ntoh64(), pg_conn::lobjfuncs, NULL, PGRES_COMMAND_OK, PQclear(), PQfn(), PQresultStatus(), printfPQExpBuffer(), and PQArgBlock::u.

Referenced by pickout().

586 {
587  pg_int64 retval;
588  PQArgBlock argv[1];
589  PGresult *res;
590  int result_len;
591 
592  if (conn == NULL || conn->lobjfuncs == NULL)
593  {
594  if (lo_initialize(conn) < 0)
595  return -1;
596  }
597 
598  if (conn->lobjfuncs->fn_lo_tell64 == 0)
599  {
601  libpq_gettext("cannot determine OID of function lo_tell64\n"));
602  return -1;
603  }
604 
605  argv[0].isint = 1;
606  argv[0].len = 4;
607  argv[0].u.integer = fd;
608 
609  res = PQfn(conn, conn->lobjfuncs->fn_lo_tell64,
610  (void *) &retval, &result_len, 0, argv, 1);
611  if (PQresultStatus(res) == PGRES_COMMAND_OK && result_len == 8)
612  {
613  PQclear(res);
614  return lo_ntoh64(retval);
615  }
616  else
617  {
618  PQclear(res);
619  return -1;
620  }
621 }
union PQArgBlock::@139 u
void printfPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:234
PGresult * PQfn(PGconn *conn, int fnid, int *result_buf, int *result_len, int result_is_int, const PQArgBlock *args, int nargs)
Definition: fe-exec.c:2556
static int fd(const char *x, int i)
Definition: preproc-init.c:105
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:2596
PG_INT64_TYPE pg_int64
Definition: postgres_ext.h:47
Oid fn_lo_tell64
Definition: libpq-int.h:275
PQExpBufferData errorMessage
Definition: libpq-int.h:492
void PQclear(PGresult *res)
Definition: fe-exec.c:650
#define NULL
Definition: c.h:229
int isint
Definition: libpq-fe.h:223
PGlobjfuncs * lobjfuncs
Definition: libpq-int.h:427
#define libpq_gettext(x)
Definition: libpq-int.h:683
int integer
Definition: libpq-fe.h:227
static pg_int64 lo_ntoh64(pg_int64 net64)
Definition: fe-lobj.c:1087
static int lo_initialize(PGconn *conn)
Definition: fe-lobj.c:877
int lo_truncate ( PGconn conn,
int  fd,
size_t  len 
)

Definition at line 138 of file fe-lobj.c.

References pg_conn::errorMessage, fd(), pgLobjfuncs::fn_lo_truncate, PQArgBlock::integer, PQArgBlock::isint, PQArgBlock::len, libpq_gettext, lo_initialize(), pg_conn::lobjfuncs, NULL, PGRES_COMMAND_OK, PQclear(), PQfn(), PQresultStatus(), printfPQExpBuffer(), and PQArgBlock::u.

139 {
140  PQArgBlock argv[2];
141  PGresult *res;
142  int retval;
143  int result_len;
144 
145  if (conn == NULL || conn->lobjfuncs == NULL)
146  {
147  if (lo_initialize(conn) < 0)
148  return -1;
149  }
150 
151  /* Must check this on-the-fly because it's not there pre-8.3 */
152  if (conn->lobjfuncs->fn_lo_truncate == 0)
153  {
155  libpq_gettext("cannot determine OID of function lo_truncate\n"));
156  return -1;
157  }
158 
159  /*
160  * Long ago, somebody thought it'd be a good idea to declare this function
161  * as taking size_t ... but the underlying backend function only accepts a
162  * signed int32 length. So throw error if the given value overflows
163  * int32. (A possible alternative is to automatically redirect the call
164  * to lo_truncate64; but if the caller wanted to rely on that backend
165  * function being available, he could have called lo_truncate64 for
166  * himself.)
167  */
168  if (len > (size_t) INT_MAX)
169  {
171  libpq_gettext("argument of lo_truncate exceeds integer range\n"));
172  return -1;
173  }
174 
175  argv[0].isint = 1;
176  argv[0].len = 4;
177  argv[0].u.integer = fd;
178 
179  argv[1].isint = 1;
180  argv[1].len = 4;
181  argv[1].u.integer = (int) len;
182 
183  res = PQfn(conn, conn->lobjfuncs->fn_lo_truncate,
184  &retval, &result_len, 1, argv, 2);
185 
186  if (PQresultStatus(res) == PGRES_COMMAND_OK)
187  {
188  PQclear(res);
189  return retval;
190  }
191  else
192  {
193  PQclear(res);
194  return -1;
195  }
196 }
union PQArgBlock::@139 u
void printfPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:234
PGresult * PQfn(PGconn *conn, int fnid, int *result_buf, int *result_len, int result_is_int, const PQArgBlock *args, int nargs)
Definition: fe-exec.c:2556
static int fd(const char *x, int i)
Definition: preproc-init.c:105
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:2596
Oid fn_lo_truncate
Definition: libpq-int.h:276
PQExpBufferData errorMessage
Definition: libpq-int.h:492
void PQclear(PGresult *res)
Definition: fe-exec.c:650
#define NULL
Definition: c.h:229
int isint
Definition: libpq-fe.h:223
PGlobjfuncs * lobjfuncs
Definition: libpq-int.h:427
#define libpq_gettext(x)
Definition: libpq-int.h:683
int integer
Definition: libpq-fe.h:227
static int lo_initialize(PGconn *conn)
Definition: fe-lobj.c:877
int lo_truncate64 ( PGconn conn,
int  fd,
pg_int64  len 
)

Definition at line 206 of file fe-lobj.c.

References pg_conn::errorMessage, fd(), pgLobjfuncs::fn_lo_truncate64, PQArgBlock::integer, PQArgBlock::isint, PQArgBlock::len, libpq_gettext, lo_hton64(), lo_initialize(), pg_conn::lobjfuncs, NULL, PGRES_COMMAND_OK, PQclear(), PQfn(), PQresultStatus(), printfPQExpBuffer(), PQArgBlock::ptr, and PQArgBlock::u.

Referenced by my_truncate().

207 {
208  PQArgBlock argv[2];
209  PGresult *res;
210  int retval;
211  int result_len;
212 
213  if (conn == NULL || conn->lobjfuncs == NULL)
214  {
215  if (lo_initialize(conn) < 0)
216  return -1;
217  }
218 
219  if (conn->lobjfuncs->fn_lo_truncate64 == 0)
220  {
222  libpq_gettext("cannot determine OID of function lo_truncate64\n"));
223  return -1;
224  }
225 
226  argv[0].isint = 1;
227  argv[0].len = 4;
228  argv[0].u.integer = fd;
229 
230  len = lo_hton64(len);
231  argv[1].isint = 0;
232  argv[1].len = 8;
233  argv[1].u.ptr = (int *) &len;
234 
235  res = PQfn(conn, conn->lobjfuncs->fn_lo_truncate64,
236  &retval, &result_len, 1, argv, 2);
237 
238  if (PQresultStatus(res) == PGRES_COMMAND_OK)
239  {
240  PQclear(res);
241  return retval;
242  }
243  else
244  {
245  PQclear(res);
246  return -1;
247  }
248 }
union PQArgBlock::@139 u
void printfPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:234
PGresult * PQfn(PGconn *conn, int fnid, int *result_buf, int *result_len, int result_is_int, const PQArgBlock *args, int nargs)
Definition: fe-exec.c:2556
static int fd(const char *x, int i)
Definition: preproc-init.c:105
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:2596
static pg_int64 lo_hton64(pg_int64 host64)
Definition: fe-lobj.c:1062
Oid fn_lo_truncate64
Definition: libpq-int.h:277
PQExpBufferData errorMessage
Definition: libpq-int.h:492
void PQclear(PGresult *res)
Definition: fe-exec.c:650
#define NULL
Definition: c.h:229
int isint
Definition: libpq-fe.h:223
PGlobjfuncs * lobjfuncs
Definition: libpq-int.h:427
int * ptr
Definition: libpq-fe.h:226
#define libpq_gettext(x)
Definition: libpq-int.h:683
int integer
Definition: libpq-fe.h:227
static int lo_initialize(PGconn *conn)
Definition: fe-lobj.c:877
int lo_unlink ( PGconn conn,
Oid  lobjId 
)

Definition at line 629 of file fe-lobj.c.

References pgLobjfuncs::fn_lo_unlink, PQArgBlock::integer, PQArgBlock::isint, PQArgBlock::len, lo_initialize(), pg_conn::lobjfuncs, NULL, PGRES_COMMAND_OK, PQclear(), PQfn(), PQresultStatus(), and PQArgBlock::u.

Referenced by do_lo_unlink(), and vacuumlo().

630 {
631  PQArgBlock argv[1];
632  PGresult *res;
633  int result_len;
634  int retval;
635 
636  if (conn == NULL || conn->lobjfuncs == NULL)
637  {
638  if (lo_initialize(conn) < 0)
639  return -1;
640  }
641 
642  argv[0].isint = 1;
643  argv[0].len = 4;
644  argv[0].u.integer = lobjId;
645 
646  res = PQfn(conn, conn->lobjfuncs->fn_lo_unlink,
647  &retval, &result_len, 1, argv, 1);
648  if (PQresultStatus(res) == PGRES_COMMAND_OK)
649  {
650  PQclear(res);
651  return retval;
652  }
653  else
654  {
655  PQclear(res);
656  return -1;
657  }
658 }
union PQArgBlock::@139 u
PGresult * PQfn(PGconn *conn, int fnid, int *result_buf, int *result_len, int result_is_int, const PQArgBlock *args, int nargs)
Definition: fe-exec.c:2556
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:2596
void PQclear(PGresult *res)
Definition: fe-exec.c:650
#define NULL
Definition: c.h:229
Oid fn_lo_unlink
Definition: libpq-int.h:271
int isint
Definition: libpq-fe.h:223
PGlobjfuncs * lobjfuncs
Definition: libpq-int.h:427
int integer
Definition: libpq-fe.h:227
static int lo_initialize(PGconn *conn)
Definition: fe-lobj.c:877
int lo_write ( PGconn conn,
int  fd,
const char *  buf,
size_t  len 
)

Definition at line 313 of file fe-lobj.c.

References pg_conn::errorMessage, fd(), pgLobjfuncs::fn_lo_write, PQArgBlock::integer, PQArgBlock::isint, PQArgBlock::len, libpq_gettext, lo_initialize(), pg_conn::lobjfuncs, NULL, PGRES_COMMAND_OK, PQclear(), PQfn(), PQresultStatus(), printfPQExpBuffer(), PQArgBlock::ptr, and PQArgBlock::u.

Referenced by lo_import_internal().

314 {
315  PQArgBlock argv[2];
316  PGresult *res;
317  int result_len;
318  int retval;
319 
320  if (conn == NULL || conn->lobjfuncs == NULL)
321  {
322  if (lo_initialize(conn) < 0)
323  return -1;
324  }
325 
326  /*
327  * Long ago, somebody thought it'd be a good idea to declare this function
328  * as taking size_t ... but the underlying backend function only accepts a
329  * signed int32 length. So throw error if the given value overflows
330  * int32.
331  */
332  if (len > (size_t) INT_MAX)
333  {
335  libpq_gettext("argument of lo_write exceeds integer range\n"));
336  return -1;
337  }
338 
339  argv[0].isint = 1;
340  argv[0].len = 4;
341  argv[0].u.integer = fd;
342 
343  argv[1].isint = 0;
344  argv[1].len = (int) len;
345  argv[1].u.ptr = (int *) buf;
346 
347  res = PQfn(conn, conn->lobjfuncs->fn_lo_write,
348  &retval, &result_len, 1, argv, 2);
349  if (PQresultStatus(res) == PGRES_COMMAND_OK)
350  {
351  PQclear(res);
352  return retval;
353  }
354  else
355  {
356  PQclear(res);
357  return -1;
358  }
359 }
union PQArgBlock::@139 u
void printfPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:234
Oid fn_lo_write
Definition: libpq-int.h:279
PGresult * PQfn(PGconn *conn, int fnid, int *result_buf, int *result_len, int result_is_int, const PQArgBlock *args, int nargs)
Definition: fe-exec.c:2556
static int fd(const char *x, int i)
Definition: preproc-init.c:105
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:2596
static char * buf
Definition: pg_test_fsync.c:66
PQExpBufferData errorMessage
Definition: libpq-int.h:492
void PQclear(PGresult *res)
Definition: fe-exec.c:650
#define NULL
Definition: c.h:229
int isint
Definition: libpq-fe.h:223
PGlobjfuncs * lobjfuncs
Definition: libpq-int.h:427
int * ptr
Definition: libpq-fe.h:226
#define libpq_gettext(x)
Definition: libpq-int.h:683
int integer
Definition: libpq-fe.h:227
static int lo_initialize(PGconn *conn)
Definition: fe-lobj.c:877
int pg_char_to_encoding ( const char *  name)

Definition at line 551 of file encnames.c.

References clean_encoding_name(), ereport, errcode(), errmsg(), ERROR, lengthof, NAMEDATALEN, NULL, pg_encname_tbl, and result.

Referenced by CreateConversionCommand(), length_in_encoding(), main(), PG_char_to_encoding(), pg_convert(), pg_get_utf8_id(), pg_valid_client_encoding(), pg_valid_server_encoding(), PQenv2encoding(), pqSaveParameterStatus(), ProcessCopyOptions(), processEncodingEntry(), and to_ascii_encname().

552 {
553  unsigned int nel = lengthof(pg_encname_tbl);
554  const pg_encname *base = pg_encname_tbl,
555  *last = base + nel - 1,
556  *position;
557  int result;
558  char buff[NAMEDATALEN],
559  *key;
560 
561  if (name == NULL || *name == '\0')
562  return -1;
563 
564  if (strlen(name) >= NAMEDATALEN)
565  {
566 #ifdef FRONTEND
567  fprintf(stderr, "encoding name too long\n");
568  return -1;
569 #else
570  ereport(ERROR,
571  (errcode(ERRCODE_NAME_TOO_LONG),
572  errmsg("encoding name too long")));
573 #endif
574  }
575  key = clean_encoding_name(name, buff);
576 
577  while (last >= base)
578  {
579  position = base + ((last - base) >> 1);
580  result = key[0] - position->name[0];
581 
582  if (result == 0)
583  {
584  result = strcmp(key, position->name);
585  if (result == 0)
586  return position->encoding;
587  }
588  if (result < 0)
589  last = position - 1;
590  else
591  base = position + 1;
592  }
593  return -1;
594 }
int errcode(int sqlerrcode)
Definition: elog.c:575
return result
Definition: formatting.c:1618
#define lengthof(array)
Definition: c.h:562
#define NAMEDATALEN
#define ERROR
Definition: elog.h:43
static const pg_encname pg_encname_tbl[]
Definition: encnames.c:38
#define ereport(elevel, rest)
Definition: elog.h:122
#define NULL
Definition: c.h:229
const char * name
Definition: encode.c:521
int errmsg(const char *fmt,...)
Definition: elog.c:797
static char * clean_encoding_name(const char *key, char *newkey)
Definition: encnames.c:525
const char* pg_encoding_to_char ( int  encoding)
int pg_valid_server_encoding_id ( int  encoding)

Definition at line 515 of file encnames.c.

References PG_VALID_BE_ENCODING.

Referenced by setup_locale_encoding().

516 {
518 }
static char * encoding
Definition: initdb.c:122
#define PG_VALID_BE_ENCODING(_enc)
Definition: pg_wchar.h:293
int PQbackendPID ( const PGconn conn)

Definition at line 5960 of file fe-connect.c.

References pg_conn::be_pid, CONNECTION_OK, and pg_conn::status.

Referenced by get_prompt().

5961 {
5962  if (!conn || conn->status != CONNECTION_OK)
5963  return 0;
5964  return conn->be_pid;
5965 }
ConnStatusType status
Definition: libpq-int.h:378
int be_pid
Definition: libpq-int.h:420
int PQbinaryTuples ( const PGresult res)

Definition at line 2689 of file fe-exec.c.

References pg_result::binary.

Referenced by ProcessResult().

2690 {
2691  if (!res)
2692  return 0;
2693  return res->binary;
2694 }
int binary
Definition: libpq-int.h:179
int PQcancel ( PGcancel cancel,
char *  errbuf,
int  errbufsize 
)

Definition at line 3767 of file fe-connect.c.

References pg_cancel::be_key, pg_cancel::be_pid, FALSE, internal_cancel(), pg_cancel::raddr, and strlcpy().

Referenced by dblink_cancel_query(), DisconnectDatabase(), handle_sigint(), pgfdw_subxact_callback(), pgfdw_xact_callback(), ShutdownWorkersHard(), sigTermHandler(), and try_complete_step().

3768 {
3769  if (!cancel)
3770  {
3771  strlcpy(errbuf, "PQcancel() -- no cancel object supplied", errbufsize);
3772  return FALSE;
3773  }
3774 
3775  return internal_cancel(&cancel->raddr, cancel->be_pid, cancel->be_key,
3776  errbuf, errbufsize);
3777 }
static int internal_cancel(SockAddr *raddr, int be_pid, int be_key, char *errbuf, int errbufsize)
Definition: fe-connect.c:3663
int be_pid
Definition: libpq-int.h:505
#define FALSE
Definition: c.h:221
int be_key
Definition: libpq-int.h:506
size_t strlcpy(char *dst, const char *src, size_t siz)
Definition: strlcpy.c:45
SockAddr raddr
Definition: libpq-int.h:504
void PQclear ( PGresult res)

Definition at line 650 of file fe-exec.c.

References pg_result::attDescs, pg_result::curBlock, pg_result::errFields, pg_result::events, free, i, PGEvent::name, pg_result::nEvents, pgresult_data::next, NULL, pg_result::paramDescs, PGEvent::passThrough, PGEVT_RESULTDESTROY, PGEvent::proc, PGEventResultDestroy::result, PGEvent::resultInitialized, and pg_result::tuples.

Referenced by _check_database_version(), _doSetSessionAuth(), _doSetWithOids(), _selectOutputSchema(), _selectTablespace(), add_tablespace_footer(), BaseBackup(), binary_upgrade_set_pg_class_oids(), binary_upgrade_set_type_oids_by_rel_oid(), binary_upgrade_set_type_oids_by_type_oid(), buildMatViewRefreshDependencies(), buildShSecLabels(), check_for_isn_and_int8_passing_mismatch(), check_for_jsonb_9_4_usage(), check_for_pg_role_prefix(), check_for_prepared_transactions(), check_for_reg_data_type_usage(), check_is_install_user(), check_loadable_libraries(), check_proper_datallowconn(), ClearOrSaveResult(), close_cursor(), cluster_all_databases(), convertTSFunction(), create_cursor(), CreateReplicationSlot(), createViewAsClause(), dblink_close(), dblink_exec(), dblink_fetch(), dblink_open(), dblink_res_error(), deallocate_one(), describeAccessMethods(), describeAggregates(), describeFunctions(), describeOneTableDetails(), describeOneTSConfig(), describeOneTSParser(), describeOperators(), describePublications(), describeRoles(), describeSubscriptions(), describeTableDetails(), describeTablespaces(), describeTypes(), descriptor_free(), discard_response(), do_lo_import(), do_lo_list(), do_sql_command(), doCustom(), dropDBs(), DropReplicationSlot(), dropRoles(), dropTablespaces(), dumpAgg(), dumpBaseType(), dumpBlobs(), dumpCollation(), dumpCompositeType(), dumpCompositeTypeColComments(), dumpConversion(), dumpCreateDB(), dumpDatabase(), dumpDatabaseConfig(), dumpDatabases(), dumpDbRoleConfig(), dumpDomain(), dumpEnumType(), dumpFunc(), dumpGroups(), dumpOpclass(), dumpOpfamily(), dumpOpr(), dumpRangeType(), dumpRoleMembership(), dumpRoles(), dumpRule(), dumpSequence(), dumpSequenceData(), dumpTable(), dumpTableData_copy(), dumpTableData_insert(), dumpTableSchema(), dumpTablespaces(), dumpTSConfig(), dumpTSDictionary(), dumpUserConfig(), dumpUserMappings(), ecpg_autostart_transaction(), ecpg_check_PQresult(), ecpg_is_type_an_array(), ecpg_process_output(), ECPGdescribe(), ECPGsetcommit(), ECPGtrans(), EndDBCopyMode(), exec_command_password(), ExecQueryUsingCursor(), executeCommand(), executeMaintenanceCommand(), executeQueryOrDie(), ExecuteSqlCommand(), ExecuteSqlStatement(), executeStatement(), expand_schema_name_patterns(), expand_table_name_patterns(), fail_lo_xact(), fetch_more_data(), findLastBuiltinOid_V71(), finish_lo_xact(), get_create_object_cmd(), get_db_infos(), get_language_name(), get_loadable_libraries(), get_rel_infos(), get_remote_estimate(), get_returning_data(), get_synchronized_snapshot(), get_tablespace_paths(), getAccessMethods(), getAggregates(), getBlobs(), getCasts(), getCollations(), getConstraints(), getConversions(), getCopyStart(), getDefaultACLs(), getDependencies(), getDomainConstraints(), getEventTriggers(), getExtendedStatistics(), getExtensionMembership(), getExtensions(), getForeignDataWrappers(), getForeignServers(), getFormattedTypeName(), getFuncs(), getIndexes(), getInherits(), getNamespaces(), getOpclasses(), getOperators(), getOpfamilies(), getParamDescriptions(), getPartitions(), getPolicies(), getProcLangs(), getPublications(), getPublicationTables(), GetQueryResult(), getRowDescriptions(), getRules(), getSubscriptions(), getTableAttrs(), getTables(), getTransforms(), getTriggers(), getTSConfigurations(), getTSDictionaries(), getTSParsers(), getTSTemplates(), getTypes(), handleCopyIn(), HandleEndOfCopyStream(), init(), libpq_executeFileMap(), libpqConnect(), libpqGetFile(), libpqProcessFileList(), libpqrcv_create_slot(), libpqrcv_endstreaming(), libpqrcv_exec(), libpqrcv_identify_system(), libpqrcv_PQexec(), libpqrcv_readtimelinehistoryfile(), libpqrcv_receive(), libpqrcv_startstreaming(), listAllDbs(), listCasts(), listCollations(), listConversions(), listDbRoleSettings(), listDefaultACLs(), listDomains(), listEventTriggers(), listExtensionContents(), listExtensions(), listForeignDataWrappers(), listForeignServers(), listForeignTables(), listLanguages(), listOneExtensionContents(), listPublications(), listSchemas(), listTables(), listTSConfigs(), listTSConfigsVerbose(), listTSDictionaries(), listTSParsers(), listTSParsersVerbose(), listTSTemplates(), listUserMappings(), lo_close(), lo_creat(), lo_create(), lo_initialize(), lo_lseek(), lo_lseek64(), lo_open(), lo_read(), lo_tell(), lo_tell64(), lo_truncate(), lo_truncate64(), lo_unlink(), lo_write(), lockTableForWorker(), lookup_object_oid(), main(), materializeQueryResult(), materializeResult(), new_9_0_populate_pg_largeobject_metadata(), objectDescription(), old_9_3_check_for_line_data_type_usage(), old_9_6_check_for_unknown_data_type_usage(), permissionsList(), pg_attribute_noreturn(), pgfdw_get_result(), pgfdw_report_error(), pgfdw_subxact_callback(), pgfdw_xact_callback(), postgresAcquireSampleRowsFunc(), postgresAnalyzeForeignTable(), postgresEndDirectModify(), postgresEndForeignModify(), postgresExecForeignDelete(), postgresExecForeignInsert(), postgresExecForeignUpdate(), postgresImportForeignSchema(), postgresReScanForeignScan(), pqClearAsyncResult(), PQconnectPoll(), PQcopyResult(), pqEndcopy2(), pqEndcopy3(), PQexecFinish(), PQexecStart(), pqGetErrorNotice2(), pqGetErrorNotice3(), pqInternalNotice(), PQmakeEmptyPGresult(), pqRowProcessor(), PQsetClientEncoding(), pqSetenvPoll(), prepare_common(), prepare_foreign_modify(), processExtensionTables(), ProcessResult(), PSQLexecWatch(), receiveFileChunks(), ReceiveXlogStream(), reindex_all_databases(), run_permutation(), run_simple_query(), RunIdentifySystem(), sendCommand(), SendQuery(), set_frozenxids(), sql_exec(), start_lo_xact(), store_returning_result(), storeQueryResult(), StreamLogicalLog(), try_complete_step(), tryExecuteStatement(), vacuum_all_databases(), vacuum_one_database(), and vacuumlo().

651 {
652  PGresult_data *block;
653  int i;
654 
655  if (!res)
656  return;
657 
658  for (i = 0; i < res->nEvents; i++)
659  {
660  /* only send DESTROY to successfully-initialized event procs */
661  if (res->events[i].resultInitialized)
662  {
664 
665  evt.result = res;
666  (void) res->events[i].proc(PGEVT_RESULTDESTROY, &evt,
667  res->events[i].passThrough);
668  }
669  free(res->events[i].name);
670  }
671 
672  if (res->events)
673  free(res->events);
674 
675  /* Free all the subsidiary blocks */
676  while ((block = res->curBlock) != NULL)
677  {
678  res->curBlock = block->next;
679  free(block);
680  }
681 
682  /* Free the top-level tuple pointer array */
683  if (res->tuples)
684  free(res->tuples);
685 
686  /* zero out the pointer fields to catch programming errors */
687  res->attDescs = NULL;
688  res->tuples = NULL;
689  res->paramDescs = NULL;
690  res->errFields = NULL;
691  res->events = NULL;
692  res->nEvents = 0;
693  /* res->curBlock was zeroed out earlier */
694 
695  /* Free the PGresult structure itself */
696  free(res);
697 }
PGMessageField * errFields
Definition: libpq-int.h:197
bool resultInitialized
Definition: libpq-int.h:164
PGresult_data * next
Definition: libpq-int.h:105
int nEvents
Definition: libpq-int.h:188
PGresAttDesc * attDescs
Definition: libpq-int.h:171
PGresAttValue ** tuples
Definition: libpq-int.h:172
PGresult_data * curBlock
Definition: libpq-int.h:208
#define free(a)
Definition: header.h:65
PGresParamDesc * paramDescs
Definition: libpq-int.h:176
#define NULL
Definition: c.h:229
PGEventProc proc
Definition: libpq-int.h:160
int i
void * passThrough
Definition: libpq-int.h:162
PGEvent * events
Definition: libpq-int.h:187
char * name
Definition: libpq-int.h:161
int PQclientEncoding ( const PGconn conn)

Definition at line 5994 of file fe-connect.c.

References pg_conn::client_encoding, CONNECTION_OK, and pg_conn::status.

Referenced by appendStringLiteralConn(), dblink_connect(), dblink_get_conn(), exec_command_encoding(), main(), processSQLNamePattern(), SendQuery(), setup_connection(), and SyncVariables().

5995 {
5996  if (!conn || conn->status != CONNECTION_OK)
5997  return -1;
5998  return conn->client_encoding;
5999 }
ConnStatusType status
Definition: libpq-int.h:378
int client_encoding
Definition: libpq-int.h:423
char* PQcmdStatus ( PGresult res)

Definition at line 2944 of file fe-exec.c.

References pg_result::cmdStatus, and NULL.

Referenced by dblink_exec(), ecpg_process_output(), materializeQueryResult(), materializeResult(), PrintQueryResults(), PrintQueryStatus(), PSQLexecWatch(), and SendQuery().

2945 {
2946  if (!res)
2947  return NULL;
2948  return res->cmdStatus;
2949 }
#define NULL
Definition: c.h:229
char cmdStatus[CMDSTATUS_LEN]
Definition: libpq-int.h:178
char* PQcmdTuples ( PGresult res)

Definition at line 3014 of file fe-exec.c.

References pg_result::cmdStatus, pg_result::noticeHooks, and pqInternalNotice().

Referenced by ecpg_process_output(), execute_dml_stmt(), postgresExecForeignDelete(), postgresExecForeignInsert(), and postgresExecForeignUpdate().

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:
3057  "could not interpret result from server: %s",
3058  res->cmdStatus);
3059  return "";
3060 }
PGNoticeHooks noticeHooks
Definition: libpq-int.h:186
char * c
void pqInternalNotice(const PGNoticeHooks *hooks, const char *fmt,...)
Definition: fe-exec.c:801
char cmdStatus[CMDSTATUS_LEN]
Definition: libpq-int.h:178
PQconninfoOption* PQconndefaults ( void  )

Definition at line 1103 of file fe-connect.c.

References conninfo_add_defaults(), conninfo_init(), initPQExpBuffer(), NULL, PQconninfoFree(), PQExpBufferDataBroken, and termPQExpBuffer().

Referenced by check_pghost_envvar(), dblink_fdw_validator(), get_connect_string(), InitPgFdwOptions(), and main().

1104 {
1105  PQExpBufferData errorBuf;
1106  PQconninfoOption *connOptions;
1107 
1108  /* We don't actually report any errors here, but callees want a buffer */
1109  initPQExpBuffer(&errorBuf);
1110  if (PQExpBufferDataBroken(errorBuf))
1111  return NULL; /* out of memory already :-( */
1112 
1113  connOptions = conninfo_init(&errorBuf);
1114  if (connOptions != NULL)
1115  {
1116  /* pass NULL errorBuf to ignore errors */
1117  if (!conninfo_add_defaults(connOptions, NULL))
1118  {
1119  PQconninfoFree(connOptions);
1120  connOptions = NULL;
1121  }
1122  }
1123 
1124  termPQExpBuffer(&errorBuf);
1125  return connOptions;
1126 }
void termPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:128
static PQconninfoOption * conninfo_init(PQExpBuffer errorMessage)
Definition: fe-connect.c:4600
void PQconninfoFree(PQconninfoOption *connOptions)
Definition: fe-connect.c:5784
#define PQExpBufferDataBroken(buf)
Definition: pqexpbuffer.h:67
#define NULL
Definition: c.h:229
static bool conninfo_add_defaults(PQconninfoOption *options, PQExpBuffer errorMessage)
Definition: fe-connect.c:5036
void initPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:89
PGconn* PQconnectdb ( const char *  conninfo)

Definition at line 522 of file fe-connect.c.

References conn, connectDBComplete(), CONNECTION_BAD, PQconnectStart(), and pg_conn::status.

Referenced by dblink_connect(), dblink_get_conn(), get_db_conn(), libpqConnect(), and main().

523 {
524  PGconn *conn = PQconnectStart(conninfo);
525 
526  if (conn && conn->status != CONNECTION_BAD)
527  (void) connectDBComplete(conn);
528 
529  return conn;
530 }
PGconn * conn
Definition: streamutil.c:42
static int connectDBComplete(PGconn *conn)
Definition: fe-connect.c:1710
PGconn * PQconnectStart(const char *conninfo)
Definition: fe-connect.c:648
ConnStatusType status
Definition: libpq-int.h:378
PGconn* PQconnectdbParams ( const char *const *  keywords,
const char *const *  values,
int  expand_dbname 
)

Definition at line 466 of file fe-connect.c.

References conn, connectDBComplete(), CONNECTION_BAD, PQconnectStartParams(), and pg_conn::status.

Referenced by _connectDB(), connect_pg_server(), connectDatabase(), ConnectDatabase(), do_connect(), doConnect(), ECPGconnect(), GetConnection(), main(), sql_conn(), and vacuumlo().

469 {
470  PGconn *conn = PQconnectStartParams(keywords, values, expand_dbname);
471 
472  if (conn && conn->status != CONNECTION_BAD)
473  (void) connectDBComplete(conn);
474 
475  return conn;
476 
477 }
PGconn * conn
Definition: streamutil.c:42
static int connectDBComplete(PGconn *conn)
Definition: fe-connect.c:1710
ConnStatusType status
Definition: libpq-int.h:378
static Datum values[MAXATTR]
Definition: bootstrap.c:163
PGconn * PQconnectStartParams(const char *const *keywords, const char *const *values, int expand_dbname)
Definition: fe-connect.c:569
int PQconnectionNeedsPassword ( const PGconn conn)

Definition at line 5968 of file fe-connect.c.

References NULL, password, pg_conn::password_needed, and PQpass().

Referenced by _connectDB(), connectDatabase(), ConnectDatabase(), do_connect(), doConnect(), GetConnection(), main(), sql_conn(), and vacuumlo().

5969 {
5970  char *password;
5971 
5972  if (!conn)
5973  return false;
5974  password = PQpass(conn);
5975  if (conn->password_needed &&
5976  (password == NULL || password[0] == '\0'))
5977  return true;
5978  else
5979  return false;
5980 }
static char password[100]
Definition: streamutil.c:41
bool password_needed
Definition: libpq-int.h:408
char * PQpass(const PGconn *conn)
Definition: fe-connect.c:5818
#define NULL
Definition: c.h:229
int PQconnectionUsedPassword ( const PGconn conn)

Definition at line 5983 of file fe-connect.c.

References pg_conn::password_needed.

Referenced by _connectDB(), connect_pg_server(), ConnectDatabase(), and dblink_security_check().

5984 {
5985  if (!conn)
5986  return false;
5987  if (conn->password_needed)
5988  return true;
5989  else
5990  return false;
5991 }
bool password_needed
Definition: libpq-int.h:408
PostgresPollingStatusType PQconnectPoll ( PGconn conn)

Definition at line 1844 of file fe-connect.c.

References SockAddr::addr, pg_conn::addr_cur, pg_conn_host::addrlist, addrinfo::ai_addr, addrinfo::ai_addrlen, addrinfo::ai_family, addrinfo::ai_next, appendPQExpBuffer(), appendPQExpBufferChar(), appendPQExpBufferStr(), pg_conn::appname, pg_conn::asyncStatus, AUTH_REQ_MD5, AUTH_REQ_OK, pg_conn::auth_req_received, connect, connectFailureMessage(), CONNECTION_AUTH_OK, CONNECTION_AWAITING_RESPONSE, CONNECTION_BAD, CONNECTION_CHECK_WRITABLE, CONNECTION_CONSUME, CONNECTION_MADE, CONNECTION_NEEDED, CONNECTION_OK, CONNECTION_SETENV, CONNECTION_SSL_STARTUP, CONNECTION_STARTED, connectNoDelay(), pg_conn::connhost, PQExpBufferData::data, EINPROGRESS, EINTR, EnvironmentOptions, ERRCODE_APPNAME_UNKNOWN, pg_conn::errorMessage, EWOULDBLOCK, pg_conn::fbappname, free, getpeereid(), pg_conn_host::host, pg_conn::inCursor, pg_conn::inEnd, pg_conn::inStart, IS_AF_UNIX, pg_conn::laddr, PQExpBufferData::len, libpq_gettext, pg_conn::nconnhost, NEGOTIATE_SSL_CODE, pg_conn::next_eo, NULL, PG_DIAG_SQLSTATE, pg_fe_sendauth(), PG_PROTOCOL, PG_PROTOCOL_MAJOR, pg_set_noblock(), PGASYNC_BUSY, PGINVALID_SOCKET, pgpassfileWarning(), PGRES_FATAL_ERROR, PGRES_POLLING_FAILED, PGRES_POLLING_OK, PGRES_POLLING_READING, PGRES_POLLING_WRITING, PGRES_TUPLES_OK, pg_conn_host::port, pqBuildStartupPacket2(), pqBuildStartupPacket3(), pqCheckInBufferSpace(), PQclear(), PQconsumeInput(), pqDropConnection(), pqFlush(), pqGetc(), pqGetErrorNotice3(), pqGetInt(), pqGetpwuid(), PQgetResult(), pqGets_append(), PQgetvalue(), PQisBusy(), PQntuples(), pqPacketSend(), pqReadData(), PQresultErrorField(), PQresultStatus(), pqsecure_initialize(), pqsecure_open_client(), PQsendQuery(), pqSetenvPoll(), pqStrerror(), printfPQExpBuffer(), pg_conn::pversion, pg_conn::raddr, release_all_addrinfo(), pg_conn::requirepeer, restoreErrorMessage(), pg_result::resultStatus, SockAddr::salen, saveErrorMessage(), pg_conn::send_appname, sendTerminateConn(), pg_conn::setenv_state, SETENV_STATE_CLIENT_ENCODING_SEND, setKeepalivesCount(), setKeepalivesIdle(), setKeepalivesInterval(), pg_conn::sigpipe_flag, pg_conn::sigpipe_so, pg_conn::sock, SOCK_ERRNO, SOCK_STRERROR, socket, pg_conn::sslmode, pg_conn::status, STATUS_OK, pg_conn::target_session_attrs, termPQExpBuffer(), useKeepalives(), val, and pg_conn::whichhost.

Referenced by connectDBComplete(), connectDBStart(), libpqrcv_connect(), and PQresetPoll().

1845 {
1846  PGresult *res;
1847  char sebuf[256];
1848  int optval;
1849  PQExpBufferData savedMessage;
1850 
1851  if (conn == NULL)
1852  return PGRES_POLLING_FAILED;
1853 
1854  /* Get the new data */
1855  switch (conn->status)
1856  {
1857  /*
1858  * We really shouldn't have been polled in these two cases, but we
1859  * can handle it.
1860  */
1861  case CONNECTION_BAD:
1862  return PGRES_POLLING_FAILED;
1863  case CONNECTION_OK:
1864  return PGRES_POLLING_OK;
1865 
1866  /* These are reading states */
1868  case CONNECTION_AUTH_OK:
1869  {
1870  /* Load waiting data */
1871  int n = pqReadData(conn);
1872 
1873  if (n < 0)
1874  goto error_return;
1875  if (n == 0)
1876  return PGRES_POLLING_READING;
1877 
1878  break;
1879  }
1880 
1881  /* These are writing states, so we just proceed. */
1882  case CONNECTION_STARTED:
1883  case CONNECTION_MADE:
1884  break;
1885 
1886  /* We allow pqSetenvPoll to decide whether to proceed. */
1887  case CONNECTION_SETENV:
1888  break;
1889 
1890  /* Special cases: proceed without waiting. */
1892  case CONNECTION_NEEDED:
1894  case CONNECTION_CONSUME:
1895  break;
1896 
1897  default:
1899  libpq_gettext(
1900  "invalid connection state, "
1901  "probably indicative of memory corruption\n"
1902  ));
1903  goto error_return;
1904  }
1905 
1906 
1907 keep_going: /* We will come back to here until there is
1908  * nothing left to do. */
1909  switch (conn->status)
1910  {
1911  case CONNECTION_NEEDED:
1912  {
1913  /*
1914  * Try to initiate a connection to one of the addresses
1915  * returned by pg_getaddrinfo_all(). conn->addr_cur is the
1916  * next one to try. We fail when we run out of addresses.
1917  */
1918  for (;;)
1919  {
1920  struct addrinfo *addr_cur;
1921 
1922  /*
1923  * Advance to next possible host, if we've tried all of
1924  * the addresses for the current host.
1925  */
1926  if (conn->addr_cur == NULL)
1927  {
1928  if (++conn->whichhost >= conn->nconnhost)
1929  {
1930  conn->whichhost = 0;
1931  break;
1932  }
1933  conn->addr_cur =
1934  conn->connhost[conn->whichhost].addrlist;
1935  }
1936 
1937  /* Remember current address for possible error msg */
1938  addr_cur = conn->addr_cur;
1939  memcpy(&conn->raddr.addr, addr_cur->ai_addr,
1940  addr_cur->ai_addrlen);
1941  conn->raddr.salen = addr_cur->ai_addrlen;
1942 
1943  conn->sock = socket(addr_cur->ai_family, SOCK_STREAM, 0);
1944  if (conn->sock == PGINVALID_SOCKET)
1945  {
1946  /*
1947  * ignore socket() failure if we have more addresses
1948  * to try
1949  */
1950  if (addr_cur->ai_next != NULL ||
1951  conn->whichhost + 1 < conn->nconnhost)
1952  {
1953  conn->addr_cur = addr_cur->ai_next;
1954  continue;
1955  }
1957  libpq_gettext("could not create socket: %s\n"),
1958  SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1959  break;
1960  }
1961 
1962  /*
1963  * Select socket options: no delay of outgoing data for
1964  * TCP sockets, nonblock mode, close-on-exec. Fail if any
1965  * of this fails.
1966  */
1967  if (!IS_AF_UNIX(addr_cur->ai_family))
1968  {
1969  if (!connectNoDelay(conn))
1970  {
1971  pqDropConnection(conn, true);
1972  conn->addr_cur = addr_cur->ai_next;
1973  continue;
1974  }
1975  }
1976  if (!pg_set_noblock(conn->sock))
1977  {
1979  libpq_gettext("could not set socket to nonblocking mode: %s\n"),
1980  SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1981  pqDropConnection(conn, true);
1982  conn->addr_cur = addr_cur->ai_next;
1983  continue;
1984  }
1985 
1986 #ifdef F_SETFD
1987  if (fcntl(conn->sock, F_SETFD, FD_CLOEXEC) == -1)
1988  {
1990  libpq_gettext("could not set socket to close-on-exec mode: %s\n"),
1991  SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1992  pqDropConnection(conn, true);
1993  conn->addr_cur = addr_cur->ai_next;
1994  continue;
1995  }
1996 #endif /* F_SETFD */
1997 
1998  if (!IS_AF_UNIX(addr_cur->ai_family))
1999  {
2000 #ifndef WIN32
2001  int on = 1;
2002 #endif
2003  int usekeepalives = useKeepalives(conn);
2004  int err = 0;
2005 
2006  if (usekeepalives < 0)
2007  {
2009  libpq_gettext("keepalives parameter must be an integer\n"));
2010  err = 1;
2011  }
2012  else if (usekeepalives == 0)
2013  {
2014  /* Do nothing */
2015  }
2016 #ifndef WIN32
2017  else if (setsockopt(conn->sock,
2018  SOL_SOCKET, SO_KEEPALIVE,
2019  (char *) &on, sizeof(on)) < 0)
2020  {
2022  libpq_gettext("setsockopt(SO_KEEPALIVE) failed: %s\n"),
2023  SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
2024  err = 1;
2025  }
2026  else if (!setKeepalivesIdle(conn)
2027  || !setKeepalivesInterval(conn)
2028  || !setKeepalivesCount(conn))
2029  err = 1;
2030 #else /* WIN32 */
2031 #ifdef SIO_KEEPALIVE_VALS
2032  else if (!setKeepalivesWin32(conn))
2033  err = 1;
2034 #endif /* SIO_KEEPALIVE_VALS */
2035 #endif /* WIN32 */
2036 
2037  if (err)
2038  {
2039  pqDropConnection(conn, true);
2040  conn->addr_cur = addr_cur->ai_next;
2041  continue;
2042  }
2043  }
2044 
2045  /*----------
2046  * We have three methods of blocking SIGPIPE during
2047  * send() calls to this socket:
2048  *
2049  * - setsockopt(sock, SO_NOSIGPIPE)
2050  * - send(sock, ..., MSG_NOSIGNAL)
2051  * - setting the signal mask to SIG_IGN during send()
2052  *
2053  * The third method requires three syscalls per send,
2054  * so we prefer either of the first two, but they are
2055  * less portable. The state is tracked in the following
2056  * members of PGconn:
2057  *
2058  * conn->sigpipe_so - we have set up SO_NOSIGPIPE
2059  * conn->sigpipe_flag - we're specifying MSG_NOSIGNAL
2060  *
2061  * If we can use SO_NOSIGPIPE, then set sigpipe_so here
2062  * and we're done. Otherwise, set sigpipe_flag so that
2063  * we will try MSG_NOSIGNAL on sends. If we get an error
2064  * with MSG_NOSIGNAL, we'll clear that flag and revert to
2065  * signal masking.
2066  *----------
2067  */
2068  conn->sigpipe_so = false;
2069 #ifdef MSG_NOSIGNAL
2070  conn->sigpipe_flag = true;
2071 #else
2072  conn->sigpipe_flag = false;
2073 #endif /* MSG_NOSIGNAL */
2074 
2075 #ifdef SO_NOSIGPIPE
2076  optval = 1;
2077  if (setsockopt(conn->sock, SOL_SOCKET, SO_NOSIGPIPE,
2078  (char *) &optval, sizeof(optval)) == 0)
2079  {
2080  conn->sigpipe_so = true;
2081  conn->sigpipe_flag = false;
2082  }
2083 #endif /* SO_NOSIGPIPE */
2084 
2085  /*
2086  * Start/make connection. This should not block, since we
2087  * are in nonblock mode. If it does, well, too bad.
2088  */
2089  if (connect(conn->sock, addr_cur->ai_addr,
2090  addr_cur->ai_addrlen) < 0)
2091  {
2092  if (SOCK_ERRNO == EINPROGRESS ||
2093 #ifdef WIN32
2094  SOCK_ERRNO == EWOULDBLOCK ||
2095 #endif
2096  SOCK_ERRNO == EINTR)
2097  {
2098  /*
2099  * This is fine - we're in non-blocking mode, and
2100  * the connection is in progress. Tell caller to
2101  * wait for write-ready on socket.
2102  */
2103  conn->status = CONNECTION_STARTED;
2104  return PGRES_POLLING_WRITING;
2105  }
2106  /* otherwise, trouble */
2107  }
2108  else
2109  {
2110  /*
2111  * Hm, we're connected already --- seems the "nonblock
2112  * connection" wasn't. Advance the state machine and
2113  * go do the next stuff.
2114  */
2115  conn->status = CONNECTION_STARTED;
2116  goto keep_going;
2117  }
2118 
2119  /*
2120  * This connection failed --- set up error report, then
2121  * close socket (do it this way in case close() affects
2122  * the value of errno...). We will ignore the connect()
2123  * failure and keep going if there are more addresses.
2124  */
2126  pqDropConnection(conn, true);
2127 
2128  /*
2129  * Try the next address, if any.
2130  */
2131  conn->addr_cur = addr_cur->ai_next;
2132  } /* loop over addresses */
2133 
2134  /*
2135  * Oops, no more addresses. An appropriate error message is
2136  * already set up, so just set the right status.
2137  */
2138  goto error_return;
2139  }
2140 
2141  case CONNECTION_STARTED:
2142  {
2143  ACCEPT_TYPE_ARG3 optlen = sizeof(optval);
2144 
2145  /*
2146  * Write ready, since we've made it here, so the connection
2147  * has been made ... or has failed.
2148  */
2149 
2150  /*
2151  * Now check (using getsockopt) that there is not an error
2152  * state waiting for us on the socket.
2153  */
2154 
2155  if (getsockopt(conn->sock, SOL_SOCKET, SO_ERROR,
2156  (char *) &optval, &optlen) == -1)
2157  {
2159  libpq_gettext("could not get socket error status: %s\n"),
2160  SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
2161  goto error_return;
2162  }
2163  else if (optval != 0)
2164  {
2165  /*
2166  * When using a nonblocking connect, we will typically see
2167  * connect failures at this point, so provide a friendly
2168  * error message.
2169  */
2170  connectFailureMessage(conn, optval);
2171  pqDropConnection(conn, true);
2172 
2173  /*
2174  * If more addresses remain, keep trying, just as in the
2175  * case where connect() returned failure immediately.
2176  */
2177  if (conn->addr_cur->ai_next != NULL ||
2178  conn->whichhost + 1 < conn->nconnhost)
2179  {
2180  conn->addr_cur = conn->addr_cur->ai_next;
2181  conn->status = CONNECTION_NEEDED;
2182  goto keep_going;
2183  }
2184  goto error_return;
2185  }
2186 
2187  /* Fill in the client address */
2188  conn->laddr.salen = sizeof(conn->laddr.addr);
2189  if (getsockname(conn->sock,
2190  (struct sockaddr *) & conn->laddr.addr,
2191  &conn->laddr.salen) < 0)
2192  {
2194  libpq_gettext("could not get client address from socket: %s\n"),
2195  SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
2196  goto error_return;
2197  }
2198 
2199  /*
2200  * Make sure we can write before advancing to next step.
2201  */
2202  conn->status = CONNECTION_MADE;
2203  return PGRES_POLLING_WRITING;
2204  }
2205 
2206  case CONNECTION_MADE:
2207  {
2208  char *startpacket;
2209  int packetlen;
2210 
2211 #ifdef HAVE_UNIX_SOCKETS
2212 
2213  /*
2214  * Implement requirepeer check, if requested and it's a
2215  * Unix-domain socket.
2216  */
2217  if (conn->requirepeer && conn->requirepeer[0] &&
2218  IS_AF_UNIX(conn->raddr.addr.ss_family))
2219  {
2220  char pwdbuf[BUFSIZ];
2221  struct passwd pass_buf;
2222  struct passwd *pass;
2223  int passerr;
2224  uid_t uid;
2225  gid_t gid;
2226 
2227  errno = 0;
2228  if (getpeereid(conn->sock, &uid, &gid) != 0)
2229  {
2230  /*
2231  * Provide special error message if getpeereid is a
2232  * stub
2233  */
2234  if (errno == ENOSYS)
2236  libpq_gettext("requirepeer parameter is not supported on this platform\n"));
2237  else
2239  libpq_gettext("could not get peer credentials: %s\n"),
2240  pqStrerror(errno, sebuf, sizeof(sebuf)));
2241  goto error_return;
2242  }
2243 
2244  passerr = pqGetpwuid(uid, &pass_buf, pwdbuf, sizeof(pwdbuf), &pass);
2245  if (pass == NULL)
2246  {
2247  if (passerr != 0)
2249  libpq_gettext("could not look up local user ID %d: %s\n"),
2250  (int) uid,
2251  pqStrerror(passerr, sebuf, sizeof(sebuf)));
2252  else
2254  libpq_gettext("local user with ID %d does not exist\n"),
2255  (int) uid);
2256  goto error_return;
2257  }
2258 
2259  if (strcmp(pass->pw_name, conn->requirepeer) != 0)
2260  {
2262  libpq_gettext("requirepeer specifies \"%s\", but actual peer user name is \"%s\"\n"),
2263  conn->requirepeer, pass->pw_name);
2264  goto error_return;
2265  }
2266  }
2267 #endif /* HAVE_UNIX_SOCKETS */
2268 
2269 #ifdef USE_SSL
2270 
2271  /*
2272  * If SSL is enabled and we haven't already got it running,
2273  * request it instead of sending the startup message.
2274  */
2275  if (IS_AF_UNIX(conn->raddr.addr.ss_family))
2276  {
2277  /* Don't bother requesting SSL over a Unix socket */
2278  conn->allow_ssl_try = false;
2279  }
2280  if (conn->allow_ssl_try && !conn->wait_ssl_try &&
2281  !conn->ssl_in_use)
2282  {
2283  ProtocolVersion pv;
2284 
2285  /*
2286  * Send the SSL request packet.
2287  *
2288  * Theoretically, this could block, but it really
2289  * shouldn't since we only got here if the socket is
2290  * write-ready.
2291  */
2292  pv = htonl(NEGOTIATE_SSL_CODE);
2293  if (pqPacketSend(conn, 0, &pv, sizeof(pv)) != STATUS_OK)
2294  {
2296  libpq_gettext("could not send SSL negotiation packet: %s\n"),
2297  SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
2298  goto error_return;
2299  }
2300  /* Ok, wait for response */
2302  return PGRES_POLLING_READING;
2303  }
2304 #endif /* USE_SSL */
2305 
2306  /*
2307  * Build the startup packet.
2308  */
2309  if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
2310  startpacket = pqBuildStartupPacket3(conn, &packetlen,
2312  else
2313  startpacket = pqBuildStartupPacket2(conn, &packetlen,
2315  if (!startpacket)
2316  {
2317  /*
2318  * will not appendbuffer here, since it's likely to also
2319  * run out of memory
2320  */
2322  libpq_gettext("out of memory\n"));
2323  goto error_return;
2324  }
2325 
2326  /*
2327  * Send the startup packet.
2328  *
2329  * Theoretically, this could block, but it really shouldn't
2330  * since we only got here if the socket is write-ready.
2331  */
2332  if (pqPacketSend(conn, 0, startpacket, packetlen) != STATUS_OK)
2333  {
2335  libpq_gettext("could not send startup packet: %s\n"),
2336  SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
2337  free(startpacket);
2338  goto error_return;
2339  }
2340 
2341  free(startpacket);
2342 
2344  return PGRES_POLLING_READING;
2345  }
2346 
2347  /*
2348  * Handle SSL negotiation: wait for postmaster messages and
2349  * respond as necessary.
2350  */
2352  {
2353 #ifdef USE_SSL
2354  PostgresPollingStatusType pollres;
2355 
2356  /*
2357  * On first time through, get the postmaster's response to our
2358  * SSL negotiation packet.
2359  */
2360  if (!conn->ssl_in_use)
2361  {
2362  /*
2363  * We use pqReadData here since it has the logic to
2364  * distinguish no-data-yet from connection closure. Since
2365  * conn->ssl isn't set, a plain recv() will occur.
2366  */
2367  char SSLok;
2368  int rdresult;
2369 
2370  rdresult = pqReadData(conn);
2371  if (rdresult < 0)
2372  {
2373  /* errorMessage is already filled in */
2374  goto error_return;
2375  }
2376  if (rdresult == 0)
2377  {
2378  /* caller failed to wait for data */
2379  return PGRES_POLLING_READING;
2380  }
2381  if (pqGetc(&SSLok, conn) < 0)
2382  {
2383  /* should not happen really */
2384  return PGRES_POLLING_READING;
2385  }
2386  if (SSLok == 'S')
2387  {
2388  /* mark byte consumed */
2389  conn->inStart = conn->inCursor;
2390  /* Set up global SSL state if required */
2391  if (pqsecure_initialize(conn) != 0)
2392  goto error_return;
2393  }
2394  else if (SSLok == 'N')
2395  {
2396  /* mark byte consumed */
2397  conn->inStart = conn->inCursor;
2398  /* OK to do without SSL? */
2399  if (conn->sslmode[0] == 'r' || /* "require" */
2400  conn->sslmode[0] == 'v') /* "verify-ca" or
2401  * "verify-full" */
2402  {
2403  /* Require SSL, but server does not want it */
2405  libpq_gettext("server does not support SSL, but SSL was required\n"));
2406  goto error_return;
2407  }
2408  /* Otherwise, proceed with normal startup */
2409  conn->allow_ssl_try = false;
2410  conn->status = CONNECTION_MADE;
2411  return PGRES_POLLING_WRITING;
2412  }
2413  else if (SSLok == 'E')
2414  {
2415  /*
2416  * Server failure of some sort, such as failure to
2417  * fork a backend process. We need to process and
2418  * report the error message, which might be formatted
2419  * according to either protocol 2 or protocol 3.
2420  * Rather than duplicate the code for that, we flip
2421  * into AWAITING_RESPONSE state and let the code there
2422  * deal with it. Note we have *not* consumed the "E"
2423  * byte here.
2424  */
2426  goto keep_going;
2427  }
2428  else
2429  {
2431  libpq_gettext("received invalid response to SSL negotiation: %c\n"),
2432  SSLok);
2433  goto error_return;
2434  }
2435  }
2436 
2437  /*
2438  * Begin or continue the SSL negotiation process.
2439  */
2440  pollres = pqsecure_open_client(conn);
2441  if (pollres == PGRES_POLLING_OK)
2442  {
2443  /* SSL handshake done, ready to send startup packet */
2444  conn->status = CONNECTION_MADE;
2445  return PGRES_POLLING_WRITING;
2446  }
2447  if (pollres == PGRES_POLLING_FAILED)
2448  {
2449  /*
2450  * Failed ... if sslmode is "prefer" then do a non-SSL
2451  * retry
2452  */
2453  if (conn->sslmode[0] == 'p' /* "prefer" */
2454  && conn->allow_ssl_try /* redundant? */
2455  && !conn->wait_ssl_try) /* redundant? */
2456  {
2457  /* only retry once */
2458  conn->allow_ssl_try = false;
2459  /* Must drop the old connection */
2460  pqDropConnection(conn, true);
2461  conn->status = CONNECTION_NEEDED;
2462  goto keep_going;
2463  }
2464  }
2465  return pollres;
2466 #else /* !USE_SSL */
2467  /* can't get here */
2468  goto error_return;
2469 #endif /* USE_SSL */
2470  }
2471 
2472  /*
2473  * Handle authentication exchange: wait for postmaster messages
2474  * and respond as necessary.
2475  */
2477  {
2478  char beresp;
2479  int msgLength;
2480  int avail;
2481  AuthRequest areq;
2482  int res;
2483 
2484  /*
2485  * Scan the message from current point (note that if we find
2486  * the message is incomplete, we will return without advancing
2487  * inStart, and resume here next time).
2488  */
2489  conn->inCursor = conn->inStart;
2490 
2491  /* Read type byte */
2492  if (pqGetc(&beresp, conn))
2493  {
2494  /* We'll come back when there is more data */
2495  return PGRES_POLLING_READING;
2496  }
2497 
2498  /*
2499  * Validate message type: we expect only an authentication
2500  * request or an error here. Anything else probably means
2501  * it's not Postgres on the other end at all.
2502  */
2503  if (!(beresp == 'R' || beresp == 'E'))
2504  {
2506  libpq_gettext(
2507  "expected authentication request from "
2508  "server, but received %c\n"),
2509  beresp);
2510  goto error_return;
2511  }
2512 
2513  if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
2514  {
2515  /* Read message length word */
2516  if (pqGetInt(&msgLength, 4, conn))
2517  {
2518  /* We'll come back when there is more data */
2519  return PGRES_POLLING_READING;
2520  }
2521  }
2522  else
2523  {
2524  /* Set phony message length to disable checks below */
2525  msgLength = 8;
2526  }
2527 
2528  /*
2529  * Try to validate message length before using it.
2530  * Authentication requests can't be very large, although GSS
2531  * auth requests may not be that small. Errors can be a
2532  * little larger, but not huge. If we see a large apparent
2533  * length in an error, it means we're really talking to a
2534  * pre-3.0-protocol server; cope.
2535  */
2536  if (beresp == 'R' && (msgLength < 8 || msgLength > 2000))
2537  {
2539  libpq_gettext(
2540  "expected authentication request from "
2541  "server, but received %c\n"),
2542  beresp);
2543  goto error_return;
2544  }
2545 
2546  if (beresp == 'E' && (msgLength < 8 || msgLength > 30000))
2547  {
2548  /* Handle error from a pre-3.0 server */
2549  conn->inCursor = conn->inStart + 1; /* reread data */
2550  if (pqGets_append(&conn->errorMessage, conn))
2551  {
2552  /* We'll come back when there is more data */
2553  return PGRES_POLLING_READING;
2554  }
2555  /* OK, we read the message; mark data consumed */
2556  conn->inStart = conn->inCursor;
2557 
2558  /*
2559  * The postmaster typically won't end its message with a
2560  * newline, so add one to conform to libpq conventions.
2561  */
2562  appendPQExpBufferChar(&conn->errorMessage, '\n');
2563 
2564  /*
2565  * If we tried to open the connection in 3.0 protocol,
2566  * fall back to 2.0 protocol.
2567  */
2568  if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
2569  {
2570  conn->pversion = PG_PROTOCOL(2, 0);
2571  /* Must drop the old connection */
2572  pqDropConnection(conn, true);
2573  conn->status = CONNECTION_NEEDED;
2574  goto keep_going;
2575  }
2576 
2577  goto error_return;
2578  }
2579 
2580  /*
2581  * Can't process if message body isn't all here yet.
2582  *
2583  * (In protocol 2.0 case, we are assuming messages carry at
2584  * least 4 bytes of data.)
2585  */
2586  msgLength -= 4;
2587  avail = conn->inEnd - conn->inCursor;
2588  if (avail < msgLength)
2589  {
2590  /*
2591  * Before returning, try to enlarge the input buffer if
2592  * needed to hold the whole message; see notes in
2593  * pqParseInput3.
2594  */
2595  if (pqCheckInBufferSpace(conn->inCursor + (size_t) msgLength,
2596  conn))
2597  goto error_return;
2598  /* We'll come back when there is more data */
2599  return PGRES_POLLING_READING;
2600  }
2601 
2602  /* Handle errors. */
2603  if (beresp == 'E')
2604  {
2605  if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
2606  {
2607  if (pqGetErrorNotice3(conn, true))
2608  {
2609  /* We'll come back when there is more data */
2610  return PGRES_POLLING_READING;
2611  }
2612  }
2613  else
2614  {
2615  if (pqGets_append(&conn->errorMessage, conn))
2616  {
2617  /* We'll come back when there is more data */
2618  return PGRES_POLLING_READING;
2619  }
2620  }
2621  /* OK, we read the message; mark data consumed */
2622  conn->inStart = conn->inCursor;
2623 
2624 #ifdef USE_SSL
2625 
2626  /*
2627  * if sslmode is "allow" and we haven't tried an SSL
2628  * connection already, then retry with an SSL connection
2629  */
2630  if (conn->sslmode[0] == 'a' /* "allow" */
2631  && !conn->ssl_in_use
2632  && conn->allow_ssl_try
2633  && conn->wait_ssl_try)
2634  {
2635  /* only retry once */
2636  conn->wait_ssl_try = false;
2637  /* Must drop the old connection */
2638  pqDropConnection(conn, true);
2639  conn->status = CONNECTION_NEEDED;
2640  goto keep_going;
2641  }
2642 
2643  /*
2644  * if sslmode is "prefer" and we're in an SSL connection,
2645  * then do a non-SSL retry
2646  */
2647  if (conn->sslmode[0] == 'p' /* "prefer" */
2648  && conn->allow_ssl_try
2649  && !conn->wait_ssl_try) /* redundant? */
2650  {
2651  /* only retry once */
2652  conn->allow_ssl_try = false;
2653  /* Must drop the old connection */
2654  pqDropConnection(conn, true);
2655  conn->status = CONNECTION_NEEDED;
2656  goto keep_going;
2657  }
2658 #endif
2659 
2660  goto error_return;
2661  }
2662 
2663  /* It is an authentication request. */
2664  conn->auth_req_received = true;
2665 
2666  /* Get the type of request. */
2667  if (pqGetInt((int *) &areq, 4, conn))
2668  {
2669  /* We'll come back when there are more data */
2670  return PGRES_POLLING_READING;
2671  }
2672  msgLength -= 4;
2673 
2674  /*
2675  * Ensure the password salt is in the input buffer, if it's an
2676  * MD5 request. All the other authentication methods that
2677  * contain extra data in the authentication request are only
2678  * supported in protocol version 3, in which case we already
2679  * read the whole message above.
2680  */
2681  if (areq == AUTH_REQ_MD5 && PG_PROTOCOL_MAJOR(conn->pversion) < 3)
2682  {
2683  msgLength += 4;
2684 
2685  avail = conn->inEnd - conn->inCursor;
2686  if (avail < 4)
2687  {
2688  /*
2689  * Before returning, try to enlarge the input buffer
2690  * if needed to hold the whole message; see notes in
2691  * pqParseInput3.
2692  */
2693  if (pqCheckInBufferSpace(conn->inCursor + (size_t) 4,
2694  conn))
2695  goto error_return;
2696  /* We'll come back when there is more data */
2697  return PGRES_POLLING_READING;
2698  }
2699  }
2700 
2701  /*
2702  * Process the rest of the authentication request message, and
2703  * respond to it if necessary.
2704  *
2705  * Note that conn->pghost must be non-NULL if we are going to
2706  * avoid the Kerberos code doing a hostname look-up.
2707  */
2708  res = pg_fe_sendauth(areq, msgLength, conn);
2709  conn->errorMessage.len = strlen(conn->errorMessage.data);
2710 
2711  /* OK, we have processed the message; mark data consumed */
2712  conn->inStart = conn->inCursor;
2713 
2714  if (res != STATUS_OK)
2715  goto error_return;
2716 
2717  /*
2718  * Just make sure that any data sent by pg_fe_sendauth is
2719  * flushed out. Although this theoretically could block, it
2720  * really shouldn't since we don't send large auth responses.
2721  */
2722  if (pqFlush(conn))
2723  goto error_return;
2724 
2725  if (areq == AUTH_REQ_OK)
2726  {
2727  /* We are done with authentication exchange */
2728  conn->status = CONNECTION_AUTH_OK;
2729 
2730  /*
2731  * Set asyncStatus so that PQgetResult will think that
2732  * what comes back next is the result of a query. See
2733  * below.
2734  */
2735  conn->asyncStatus = PGASYNC_BUSY;
2736  }
2737 
2738  /* Look to see if we have more data yet. */
2739  goto keep_going;
2740  }
2741 
2742  case CONNECTION_AUTH_OK:
2743  {
2744  /*
2745  * Now we expect to hear from the backend. A ReadyForQuery
2746  * message indicates that startup is successful, but we might
2747  * also get an Error message indicating failure. (Notice
2748  * messages indicating nonfatal warnings are also allowed by
2749  * the protocol, as are ParameterStatus and BackendKeyData
2750  * messages.) Easiest way to handle this is to let
2751  * PQgetResult() read the messages. We just have to fake it
2752  * out about the state of the connection, by setting
2753  * asyncStatus = PGASYNC_BUSY (done above).
2754  */
2755 
2756  if (PQisBusy(conn))
2757  return PGRES_POLLING_READING;
2758 
2759  res = PQgetResult(conn);
2760 
2761  /*
2762  * NULL return indicating we have gone to IDLE state is
2763  * expected
2764  */
2765  if (res)
2766  {
2767  if (res->resultStatus != PGRES_FATAL_ERROR)
2769  libpq_gettext("unexpected message from server during startup\n"));
2770  else if (conn->send_appname &&
2771  (conn->appname || conn->fbappname))
2772  {
2773  /*
2774  * If we tried to send application_name, check to see
2775  * if the error is about that --- pre-9.0 servers will
2776  * reject it at this stage of the process. If so,
2777  * close the connection and retry without sending
2778  * application_name. We could possibly get a false
2779  * SQLSTATE match here and retry uselessly, but there
2780  * seems no great harm in that; we'll just get the
2781  * same error again if it's unrelated.
2782  */
2783  const char *sqlstate;
2784 
2785  sqlstate = PQresultErrorField(res, PG_DIAG_SQLSTATE);
2786  if (sqlstate &&
2787  strcmp(sqlstate, ERRCODE_APPNAME_UNKNOWN) == 0)
2788  {
2789  PQclear(res);
2790  conn->send_appname = false;
2791  /* Must drop the old connection */
2792  pqDropConnection(conn, true);
2793  conn->status = CONNECTION_NEEDED;
2794  goto keep_going;
2795  }
2796  }
2797 
2798  /*
2799  * if the resultStatus is FATAL, then conn->errorMessage
2800  * already has a copy of the error; needn't copy it back.
2801  * But add a newline if it's not there already, since
2802  * postmaster error messages may not have one.
2803  */
2804  if (conn->errorMessage.len <= 0 ||
2805  conn->errorMessage.data[conn->errorMessage.len - 1] != '\n')
2806  appendPQExpBufferChar(&conn->errorMessage, '\n');
2807  PQclear(res);
2808  goto error_return;
2809  }
2810 
2811  /* Fire up post-connection housekeeping if needed */
2812  if (PG_PROTOCOL_MAJOR(conn->pversion) < 3)
2813  {
2814  conn->status = CONNECTION_SETENV;
2816  conn->next_eo = EnvironmentOptions;
2817  return PGRES_POLLING_WRITING;
2818  }
2819 
2820  /*
2821  * If a read-write connection is required, see if we have one.
2822  */
2823  if (conn->target_session_attrs != NULL &&
2824  strcmp(conn->target_session_attrs, "read-write") == 0)
2825  {
2826  /*
2827  * We are yet to make a connection. Save all existing error
2828  * messages until we make a successful connection state.
2829  * This is important because PQsendQuery is going to reset
2830  * conn->errorMessage and we will lose error messages
2831  * related to previous hosts we have tried to connect and
2832  * failed.
2833  */
2834  if (!saveErrorMessage(conn, &savedMessage))
2835  goto error_return;
2836 
2837  conn->status = CONNECTION_OK;
2838  if (!PQsendQuery(conn,
2839  "show transaction_read_only"))
2840  {
2841  restoreErrorMessage(conn, &savedMessage);
2842  goto error_return;
2843  }
2845  restoreErrorMessage(conn, &savedMessage);
2846  return PGRES_POLLING_READING;
2847  }
2848 
2849  /* We can release the address lists now. */
2850  release_all_addrinfo(conn);
2851 
2852  /* We are open for business! */
2853  conn->status = CONNECTION_OK;
2854  return PGRES_POLLING_OK;
2855  }
2856 
2857  case CONNECTION_SETENV:
2858 
2859  /*
2860  * Do post-connection housekeeping (only needed in protocol 2.0).
2861  *
2862  * We pretend that the connection is OK for the duration of these
2863  * queries.
2864  */
2865  conn->status = CONNECTION_OK;
2866 
2867  switch (pqSetenvPoll(conn))
2868  {
2869  case PGRES_POLLING_OK: /* Success */
2870  break;
2871 
2872  case PGRES_POLLING_READING: /* Still going */
2873  conn->status = CONNECTION_SETENV;
2874  return PGRES_POLLING_READING;
2875 
2876  case PGRES_POLLING_WRITING: /* Still going */
2877  conn->status = CONNECTION_SETENV;
2878  return PGRES_POLLING_WRITING;
2879 
2880  default:
2881  goto error_return;
2882  }
2883 
2884  /*
2885  * If a read-write connection is requested check for same.
2886  */
2887  if (conn->target_session_attrs != NULL &&
2888  strcmp(conn->target_session_attrs, "read-write") == 0)
2889  {
2890  if (!saveErrorMessage(conn, &savedMessage))
2891  goto error_return;
2892 
2893  conn->status = CONNECTION_OK;
2894  if (!PQsendQuery(conn,
2895  "show transaction_read_only"))
2896  {
2897  restoreErrorMessage(conn, &savedMessage);
2898  goto error_return;
2899  }
2901  restoreErrorMessage(conn, &savedMessage);
2902  return PGRES_POLLING_READING;
2903  }
2904 
2905  /* We can release the address lists now. */
2906  release_all_addrinfo(conn);
2907 
2908  /* We are open for business! */
2909  conn->status = CONNECTION_OK;
2910  return PGRES_POLLING_OK;
2911 
2912  case CONNECTION_CONSUME:
2913  {
2914  conn->status = CONNECTION_OK;
2915  if (!PQconsumeInput(conn))
2916  goto error_return;
2917 
2918  if (PQisBusy(conn))
2919  {
2920  conn->status = CONNECTION_CONSUME;
2921  restoreErrorMessage(conn, &savedMessage);
2922  return PGRES_POLLING_READING;
2923  }
2924 
2925  /*
2926  * Call PQgetResult() again to consume NULL result.
2927  */
2928  res = PQgetResult(conn);
2929  if (res != NULL)
2930  {
2931  PQclear(res);
2932  conn->status = CONNECTION_CONSUME;
2933  goto keep_going;
2934  }
2935 
2936  /* We are open for business! */
2937  conn->status = CONNECTION_OK;
2938  return PGRES_POLLING_OK;
2939  }
2941  {
2942  if (!saveErrorMessage(conn, &savedMessage))
2943  goto error_return;
2944 
2945  conn->status = CONNECTION_OK;
2946  if (!PQconsumeInput(conn))
2947  {
2948  restoreErrorMessage(conn, &savedMessage);
2949  goto error_return;
2950  }
2951 
2952  if (PQisBusy(conn))
2953  {
2955  restoreErrorMessage(conn, &savedMessage);
2956  return PGRES_POLLING_READING;
2957  }
2958 
2959  res = PQgetResult(conn);
2960  if (res && (PQresultStatus(res) == PGRES_TUPLES_OK) &&
2961  PQntuples(res) == 1)
2962  {
2963  char *val;
2964 
2965  val = PQgetvalue(res, 0, 0);
2966  if (strncmp(val, "on", 2) == 0)
2967  {
2968  PQclear(res);
2969  restoreErrorMessage(conn, &savedMessage);
2970 
2971  /* Not writable; close connection. */
2973  libpq_gettext("could not make a writable "
2974  "connection to server "
2975  "\"%s:%s\"\n"),
2976  conn->connhost[conn->whichhost].host,
2977  conn->connhost[conn->whichhost].port);
2978  conn->status = CONNECTION_OK;
2979  sendTerminateConn(conn);
2980  pqDropConnection(conn, true);
2981 
2982  /* Skip any remaining addresses for this host. */
2983  conn->addr_cur = NULL;
2984  if (conn->whichhost + 1 < conn->nconnhost)
2985  {
2986  conn->status = CONNECTION_NEEDED;
2987  goto keep_going;
2988  }
2989 
2990  /* No more addresses to try. So we fail. */
2991  goto error_return;
2992  }
2993  PQclear(res);
2994  termPQExpBuffer(&savedMessage);
2995 
2996  /* We can release the address lists now. */
2997  release_all_addrinfo(conn);
2998 
2999  /*
3000  * Finish reading any remaining messages before
3001  * being considered as ready.
3002  */
3003  conn->status = CONNECTION_CONSUME;
3004  goto keep_going;
3005  }
3006 
3007  /*
3008  * Something went wrong with "show transaction_read_only". We
3009  * should try next addresses.
3010  */
3011  if (res)
3012  PQclear(res);
3013  restoreErrorMessage(conn, &savedMessage);
3015  libpq_gettext("test \"show transaction_read_only\" failed "
3016  " on \"%s:%s\"\n"),
3017  conn->connhost[conn->whichhost].host,
3018  conn->connhost[conn->whichhost].port);
3019  conn->status = CONNECTION_OK;
3020  sendTerminateConn(conn);
3021  pqDropConnection(conn, true);
3022 
3023  if (conn->addr_cur->ai_next != NULL ||
3024  conn->whichhost + 1 < conn->nconnhost)
3025  {
3026  conn->addr_cur = conn->addr_cur->ai_next;
3027  conn->status = CONNECTION_NEEDED;
3028  goto keep_going;
3029  }
3030 
3031  /* No more addresses to try. So we fail. */
3032  goto error_return;
3033  }
3034 
3035  default:
3037  libpq_gettext("invalid connection state %d, "
3038  "probably indicative of memory corruption\n"),
3039  conn->status);
3040  goto error_return;
3041  }
3042 
3043  /* Unreachable */
3044 
3045 error_return:
3046 
3047  pgpassfileWarning(conn);
3048 
3049  /*
3050  * We used to close the socket at this point, but that makes it awkward
3051  * for those above us if they wish to remove this socket from their own
3052  * records (an fd_set for example). We'll just have this socket closed
3053  * when PQfinish is called (which is compulsory even after an error, since
3054  * the connection structure must be freed).
3055  */
3056  conn->status = CONNECTION_BAD;
3057  return PGRES_POLLING_FAILED;
3058 }
int pqFlush(PGconn *conn)
Definition: fe-misc.c:966
#define connect(s, name, namelen)
Definition: win32.h:373
#define EWOULDBLOCK
Definition: win32.h:291
bool sigpipe_flag
Definition: libpq-int.h:411
int inEnd
Definition: libpq-int.h:434
void printfPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:234
int inStart
Definition: libpq-int.h:432
struct addrinfo * addr_cur
Definition: libpq-int.h:414
char * PQgetvalue(const PGresult *res, int tup_num, int field_num)
Definition: fe-exec.c:3067
static int connectNoDelay(PGconn *conn)
Definition: fe-connect.c:1270
int gid_t
Definition: win32.h:251
int uid_t
Definition: win32.h:250
int pg_fe_sendauth(AuthRequest areq, int payloadlen, PGconn *conn)
Definition: fe-auth.c:807
void termPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:128
int getpeereid(int sock, uid_t *uid, gid_t *gid)
Definition: getpeereid.c:35
bool sigpipe_so
Definition: libpq-int.h:410
char * pqBuildStartupPacket2(PGconn *conn, int *packetlen, const PQEnvironmentOption *options)
void appendPQExpBufferStr(PQExpBuffer str, const char *data)
Definition: pqexpbuffer.c:385
#define AUTH_REQ_OK
Definition: pqcomm.h:165
int pqCheckInBufferSpace(size_t bytes_needed, PGconn *conn)
Definition: fe-misc.c:413
static void pgpassfileWarning(PGconn *conn)
Definition: fe-connect.c:6325
char * requirepeer
Definition: libpq-int.h:357
char * host
Definition: libpq-int.h:307
struct sockaddr_storage addr
Definition: pqcomm.h:64
char * pqStrerror(int errnum, char *strerrbuf, size_t buflen)
Definition: thread.c:61
static void release_all_addrinfo(PGconn *conn)
Definition: fe-connect.c:3346
static int setKeepalivesIdle(PGconn *conn)
Definition: fe-connect.c:1409
#define socket(af, type, protocol)
Definition: win32.h:369
#define EINPROGRESS
Definition: win32.h:297
int pqGetInt(int *result, size_t bytes, PGconn *conn)
Definition: fe-misc.c:272
static bool saveErrorMessage(PGconn *conn, PQExpBuffer savedMessage)
Definition: fe-connect.c:1788
static void sendTerminateConn(PGconn *conn)
Definition: fe-connect.c:3374
void pqDropConnection(PGconn *conn, bool flushInput)
Definition: fe-connect.c:405
#define PG_PROTOCOL_MAJOR(v)
Definition: pqcomm.h:104
int PQntuples(const PGresult *res)
Definition: fe-exec.c:2673
#define PG_DIAG_SQLSTATE
Definition: postgres_ext.h:57
uint32 AuthRequest
Definition: pqcomm.h:179
#define AUTH_REQ_MD5
Definition: pqcomm.h:170
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:2596
PostgresPollingStatusType pqSetenvPoll(PGconn *conn)
Definition: fe-protocol2.c:50
#define SOCK_STRERROR
Definition: libpq-int.h:697
int PQsendQuery(PGconn *conn, const char *query)
Definition: fe-exec.c:1132
PGAsyncStatusType asyncStatus
Definition: libpq-int.h:379
PGSetenvStatusType setenv_state
Definition: libpq-int.h:415
static int useKeepalives(PGconn *conn)
Definition: fe-connect.c:1391
#define IS_AF_UNIX(fam)
Definition: ip.h:24
#define SOCK_ERRNO
Definition: libpq-int.h:696
int pqGetErrorNotice3(PGconn *conn, bool isError)
Definition: fe-protocol3.c:876
void appendPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:262
#define ERRCODE_APPNAME_UNKNOWN
Definition: fe-connect.c:90
pg_conn_host * connhost
Definition: libpq-int.h:397
int pqReadData(PGconn *conn)
Definition: fe-misc.c:634
const PQEnvironmentOption * next_eo
Definition: libpq-int.h:416
static void restoreErrorMessage(PGconn *conn, PQExpBuffer savedMessage)
Definition: fe-connect.c:1808
char * appname
Definition: libpq-int.h:338
PostgresPollingStatusType pqsecure_open_client(PGconn *conn)
Definition: fe-secure.c:175
ACCEPT_TYPE_ARG3 salen
Definition: pqcomm.h:65
char * target_session_attrs
Definition: libpq-int.h:363
#define STATUS_OK
Definition: c.h:975
pgsocket sock
Definition: libpq-int.h:400
uint32 ProtocolVersion
Definition: pqcomm.h:113
int pqGetc(char *result, PGconn *conn)
Definition: fe-misc.c:99
static void connectFailureMessage(PGconn *conn, int errorno)
Definition: fe-connect.c:1298
SockAddr raddr
Definition: libpq-int.h:403
#define PGINVALID_SOCKET
Definition: port.h:24
#define EINTR
Definition: win32.h:285
int pqsecure_initialize(PGconn *conn)
Definition: fe-secure.c:160
int PQconsumeInput(PGconn *conn)
Definition: fe-exec.c:1631
void appendPQExpBufferChar(PQExpBuffer str, char ch)
Definition: pqexpbuffer.c:396
char * sslmode
Definition: libpq-int.h:351
PQExpBufferData errorMessage
Definition: libpq-int.h:492
void PQclear(PGresult *res)
Definition: fe-exec.c:650
#define free(a)
Definition: header.h:65
char * PQresultErrorField(const PGresult *res, int fieldcode)
Definition: fe-exec.c:2658
#define NULL
Definition: c.h:229
struct addrinfo * addrlist
Definition: libpq-int.h:314
bool pg_set_noblock(pgsocket sock)
Definition: noblock.c:25
int PQisBusy(PGconn *conn)
Definition: fe-exec.c:1681
char * pqBuildStartupPacket3(PGconn *conn, int *packetlen, const PQEnvironmentOption *options)
ProtocolVersion pversion
Definition: libpq-int.h:404
ConnStatusType status
Definition: libpq-int.h:378
bool auth_req_received
Definition: libpq-int.h:406
static int setKeepalivesInterval(PGconn *conn)
Definition: fe-connect.c:1454
SockAddr laddr
Definition: libpq-int.h:402
PostgresPollingStatusType
Definition: libpq-fe.h:72
struct addrinfo * ai_next
Definition: getaddrinfo.h:107
int pqGetpwuid(uid_t uid, struct passwd *resultbuf, char *buffer, size_t buflen, struct passwd **result)
Definition: thread.c:95
int pqPacketSend(PGconn *conn, char pack_type, const void *buf, size_t buf_len)
Definition: fe-connect.c:3836
char * fbappname
Definition: libpq-int.h:339
size_t ai_addrlen
Definition: getaddrinfo.h:104
int inCursor
Definition: libpq-int.h:433
char * port
Definition: libpq-int.h:309
#define NEGOTIATE_SSL_CODE
Definition: pqcomm.h:205
int nconnhost
Definition: libpq-int.h:395
#define PG_PROTOCOL(m, n)
Definition: pqcomm.h:106
int pqGets_append(PQExpBuffer buf, PGconn *conn)
Definition: fe-misc.c:174
long val
Definition: informix.c:689
PGresult * PQgetResult(PGconn *conn)
Definition: fe-exec.c:1702
struct sockaddr * ai_addr
Definition: getaddrinfo.h:105
static int setKeepalivesCount(PGconn *conn)
Definition: fe-connect.c:1486
int whichhost
Definition: libpq-int.h:396
#define libpq_gettext(x)
Definition: libpq-int.h:683
bool send_appname
Definition: libpq-int.h:417
static const PQEnvironmentOption EnvironmentOptions[]
Definition: fe-connect.c:312
int ai_family
Definition: getaddrinfo.h:101
PGconn* PQconnectStart ( const char *  conninfo)

Definition at line 648 of file fe-connect.c.

References conn, connectDBStart(), CONNECTION_BAD, connectOptions1(), connectOptions2(), makeEmptyPGconn(), NULL, and pg_conn::status.

Referenced by PQconnectdb(), and PQping().

649 {
650  PGconn *conn;
651 
652  /*
653  * Allocate memory for the conn structure
654  */
655  conn = makeEmptyPGconn();
656  if (conn == NULL)
657  return NULL;
658 
659  /*
660  * Parse the conninfo string
661  */
662  if (!connectOptions1(conn, conninfo))
663  return conn;
664 
665  /*
666  * Compute derived options
667  */
668  if (!connectOptions2(conn))
669  return conn;
670 
671  /*
672  * Connect to the database
673  */
674  if (!connectDBStart(conn))
675  {
676  /* Just in case we failed to set it in connectDBStart */
677  conn->status = CONNECTION_BAD;
678  }
679 
680  return conn;
681 }
static bool connectOptions1(PGconn *conn, const char *conninfo)
Definition: fe-connect.c:734
PGconn * conn
Definition: streamutil.c:42
static int connectDBStart(PGconn *conn)
Definition: fe-connect.c:1569
static PGconn * makeEmptyPGconn(void)
Definition: fe-connect.c:3133
#define NULL
Definition: c.h:229
ConnStatusType status
Definition: libpq-int.h:378
static bool connectOptions2(PGconn *conn)
Definition: fe-connect.c:776
PGconn* PQconnectStartParams ( const char *const *  keywords,
const char *const *  values,
int  expand_dbname 
)

Definition at line 569 of file fe-connect.c.

References conn, connectDBStart(), CONNECTION_BAD, connectOptions2(), conninfo_array_parse(), pg_conn::errorMessage, fillPGconn(), makeEmptyPGconn(), NULL, PQconninfoFree(), and pg_conn::status.

Referenced by libpqrcv_connect(), PQconnectdbParams(), and PQpingParams().

572 {
573  PGconn *conn;
574  PQconninfoOption *connOptions;
575 
576  /*
577  * Allocate memory for the conn structure
578  */
579  conn = makeEmptyPGconn();
580  if (conn == NULL)
581  return NULL;
582 
583  /*
584  * Parse the conninfo arrays
585  */
586  connOptions = conninfo_array_parse(keywords, values,
587  &conn->errorMessage,
588  true, expand_dbname);
589  if (connOptions == NULL)
590  {
591  conn->status = CONNECTION_BAD;
592  /* errorMessage is already set */
593  return conn;
594  }
595 
596  /*
597  * Move option values into conn structure
598  */
599  if (!fillPGconn(conn, connOptions))
600  {
601  PQconninfoFree(connOptions);
602  return conn;
603  }
604 
605  /*
606  * Free the option info - all is in conn now
607  */
608  PQconninfoFree(connOptions);
609 
610  /*
611  * Compute derived options
612  */
613  if (!connectOptions2(conn))
614  return conn;
615 
616  /*
617  * Connect to the database
618  */
619  if (!connectDBStart(conn))
620  {
621  /* Just in case we failed to set it in connectDBStart */
622  conn->status = CONNECTION_BAD;
623  }
624 
625  return conn;
626 }
PGconn * conn
Definition: streamutil.c:42
static int connectDBStart(PGconn *conn)
Definition: fe-connect.c:1569
void PQconninfoFree(PQconninfoOption *connOptions)
Definition: fe-connect.c:5784
static PGconn * makeEmptyPGconn(void)
Definition: fe-connect.c:3133
PQExpBufferData errorMessage
Definition: libpq-int.h:492
#define NULL
Definition: c.h:229
static bool fillPGconn(PGconn *conn, PQconninfoOption *connOptions)
Definition: fe-connect.c:692
ConnStatusType status
Definition: libpq-int.h:378
static Datum values[MAXATTR]
Definition: bootstrap.c:163
static bool connectOptions2(PGconn *conn)
Definition: fe-connect.c:776
static PQconninfoOption * conninfo_array_parse(const char *const *keywords, const char *const *values, PQExpBuffer errorMessage, bool use_defaults, int expand_dbname)
Definition: fe-connect.c:4872
PQconninfoOption* PQconninfo ( PGconn conn)

Definition at line 5743 of file fe-connect.c.

References conninfo_init(), conninfo_storeval(), _internalPQconninfoOption::connofs, initPQExpBuffer(), _internalPQconninfoOption::keyword, NULL, PQExpBufferDataBroken, and termPQExpBuffer().

Referenced by exec_command_conninfo(), GenerateRecoveryConf(), and libpqrcv_get_conninfo().

5744 {
5745  PQExpBufferData errorBuf;
5746  PQconninfoOption *connOptions;
5747 
5748  if (conn == NULL)
5749  return NULL;
5750 
5751  /* We don't actually report any errors here, but callees want a buffer */
5752  initPQExpBuffer(&errorBuf);
5753  if (PQExpBufferDataBroken(errorBuf))
5754  return NULL; /* out of memory already :-( */
5755 
5756  connOptions = conninfo_init(&errorBuf);
5757 
5758  if (connOptions != NULL)
5759  {
5761 
5762  for (option = PQconninfoOptions; option->keyword; option++)
5763  {
5764  char **connmember;
5765 
5766  if (option->connofs < 0)
5767  continue;
5768 
5769  connmember = (char **) ((char *) conn + option->connofs);
5770 
5771  if (*connmember)
5772  conninfo_storeval(connOptions, option->keyword, *connmember,
5773  &errorBuf, true, false);
5774  }
5775  }
5776 
5777  termPQExpBuffer(&errorBuf);
5778 
5779  return connOptions;
5780 }
static PQconninfoOption * conninfo_storeval(PQconninfoOption *connOptions, const char *keyword, const char *value, PQExpBuffer errorMessage, bool ignoreMissing, bool uri_decode)
Definition: fe-connect.c:5660
void termPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:128
static PQconninfoOption * conninfo_init(PQExpBuffer errorMessage)
Definition: fe-connect.c:4600
static const internalPQconninfoOption PQconninfoOptions[]
Definition: fe-connect.c:162
#define PQExpBufferDataBroken(buf)
Definition: pqexpbuffer.h:67
#define NULL
Definition: c.h:229
void initPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:89
void PQconninfoFree ( PQconninfoOption connOptions)

Definition at line 5784 of file fe-connect.c.

References free, _PQconninfoOption::keyword, NULL, and _PQconninfoOption::val.

Referenced by check_pghost_envvar(), connectDatabase(), connectOptions1(), conninfo_array_parse(), conninfo_parse(), conninfo_uri_parse(), dblink_connstr_check(), exec_command_conninfo(), GenerateRecoveryConf(), GetConnection(), libpqrcv_check_conninfo(), libpqrcv_get_conninfo(), PQconndefaults(), and PQconnectStartParams().

5785 {
5787 
5788  if (connOptions == NULL)
5789  return;
5790 
5791  for (option = connOptions; option->keyword != NULL; option++)
5792  {
5793  if (option->val != NULL)
5794  free(option->val);
5795  }
5796  free(connOptions);
5797 }
#define free(a)
Definition: header.h:65
#define NULL
Definition: c.h:229
PQconninfoOption* PQconninfoParse ( const char *  conninfo,
char **  errmsg 
)

Definition at line 4578 of file fe-connect.c.

References PQExpBufferData::data, initPQExpBuffer(), NULL, parse_connection_string(), PQExpBufferDataBroken, and termPQExpBuffer().

Referenced by connectDatabase(), dblink_connstr_check(), GetConnection(), libpqrcv_check_conninfo(), and main().

4579 {
4580  PQExpBufferData errorBuf;
4581  PQconninfoOption *connOptions;
4582 
4583  if (errmsg)
4584  *errmsg = NULL; /* default */
4585  initPQExpBuffer(&errorBuf);
4586  if (PQExpBufferDataBroken(errorBuf))
4587  return NULL; /* out of memory already :-( */
4588  connOptions = parse_connection_string(conninfo, &errorBuf, false);
4589  if (connOptions == NULL && errmsg)
4590  *errmsg = errorBuf.data;
4591  else
4592  termPQExpBuffer(&errorBuf);
4593  return connOptions;
4594 }
void termPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:128
static PQconninfoOption * parse_connection_string(const char *conninfo, PQExpBuffer errorMessage, bool use_defaults)
Definition: fe-connect.c:4640
#define PQExpBufferDataBroken(buf)
Definition: pqexpbuffer.h:67
#define NULL
Definition: c.h:229
int errmsg(const char *fmt,...)
Definition: elog.c:797
void initPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:89
int PQconsumeInput ( PGconn conn)

Definition at line 1631 of file fe-exec.c.

References pqFlush(), pqIsnonblocking, and pqReadData().

Referenced by CopyStreamReceive(), dblink_get_notify(), dblink_is_busy(), doCustom(), GetIdleSlot(), libpqrcv_PQexec(), libpqrcv_receive(), main(), pgfdw_get_result(), PQconnectPoll(), StreamLogicalLog(), and try_complete_step().

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 }
int pqFlush(PGconn *conn)
Definition: fe-misc.c:966
#define pqIsnonblocking(conn)
Definition: libpq-int.h:677
int pqReadData(PGconn *conn)
Definition: fe-misc.c:634
PGresult* PQcopyResult ( const PGresult src,
int  flags 
)

Definition at line 291 of file fe-exec.c.

References pg_result::attDescs, pg_result::client_encoding, pg_result::cmdStatus, PGEventResultCopy::dest, dupEvents(), pg_result::events, i, pgresAttValue::len, pg_result::nEvents, pg_result::noticeHooks, pg_result::ntups, NULL, pg_result::numAttributes, PGEvent::passThrough, PG_COPYRES_ATTRS, PG_COPYRES_EVENTS, PG_COPYRES_NOTICEHOOKS, PG_COPYRES_TUPLES, PGEVT_RESULTCOPY, PGRES_TUPLES_OK, PQclear(), PQmakeEmptyPGresult(), PQsetResultAttrs(), PQsetvalue(), PGEvent::proc, PGEvent::resultInitialized, PGEventResultCopy::src, TRUE, pg_result::tuples, and pgresAttValue::value.

Referenced by pqRowProcessor().

292 {
293  PGresult *dest;
294  int i;
295 
296  if (!src)
297  return NULL;
298 
300  if (!dest)
301  return NULL;
302 
303  /* Always copy these over. Is cmdStatus really useful here? */
304  dest->client_encoding = src->client_encoding;
305  strcpy(dest->cmdStatus, src->cmdStatus);
306 
307  /* Wants attrs? */
308  if (flags & (PG_COPYRES_ATTRS | PG_COPYRES_TUPLES))
309  {
310  if (!PQsetResultAttrs(dest, src->numAttributes, src->attDescs))
311  {
312  PQclear(dest);
313  return NULL;
314  }
315  }
316 
317  /* Wants to copy tuples? */
318  if (flags & PG_COPYRES_TUPLES)
319  {
320  int tup,
321  field;
322 
323  for (tup = 0; tup < src->ntups; tup++)
324  {
325  for (field = 0; field < src->numAttributes; field++)
326  {
327  if (!PQsetvalue(dest, tup, field,
328  src->tuples[tup][field].value,
329  src->tuples[tup][field].len))
330  {
331  PQclear(dest);
332  return NULL;
333  }
334  }
335  }
336  }
337 
338  /* Wants to copy notice hooks? */
339  if (flags & PG_COPYRES_NOTICEHOOKS)
340  dest->noticeHooks = src->noticeHooks;
341 
342  /* Wants to copy PGEvents? */
343  if ((flags & PG_COPYRES_EVENTS) && src->nEvents > 0)
344  {
345  dest->events = dupEvents(src->events, src->nEvents);
346  if (!dest->events)
347  {
348  PQclear(dest);
349  return NULL;
350  }
351  dest->nEvents = src->nEvents;
352  }
353 
354  /* Okay, trigger PGEVT_RESULTCOPY event */
355  for (i = 0; i < dest->nEvents; i++)
356  {
357  if (src->events[i].resultInitialized)
358  {
359  PGEventResultCopy evt;
360 
361  evt.src = src;
362  evt.dest = dest;
363  if (!dest->events[i].proc(PGEVT_RESULTCOPY, &evt,
364  dest->events[i].passThrough))
365  {
366  PQclear(dest);
367  return NULL;
368  }
369  dest->events[i].resultInitialized = TRUE;
370  }
371  }
372 
373  return dest;
374 }
static PGEvent * dupEvents(PGEvent *events, int count)
Definition: fe-exec.c:382
const PGresult * src
Definition: libpq-events.h:60
bool resultInitialized
Definition: libpq-int.h:164
int PQsetvalue(PGresult *res, int tup_num, int field_num, char *value, int len)
Definition: fe-exec.c:421
int nEvents
Definition: libpq-int.h:188
PGresAttDesc * attDescs
Definition: libpq-int.h:171
#define PG_COPYRES_TUPLES
Definition: libpq-fe.h:35
PGresAttValue ** tuples
Definition: libpq-int.h:172
#define PG_COPYRES_EVENTS
Definition: libpq-fe.h:36
PGNoticeHooks noticeHooks
Definition: libpq-int.h:186
#define PG_COPYRES_NOTICEHOOKS
Definition: libpq-fe.h:37
int PQsetResultAttrs(PGresult *res, int numAttributes, PGresAttDesc *attDescs)
Definition: fe-exec.c:226
PGresult * PQmakeEmptyPGresult(PGconn *conn, ExecStatusType status)
Definition: fe-exec.c:140
int numAttributes
Definition: libpq-int.h:170
#define PG_COPYRES_ATTRS
Definition: libpq-fe.h:34
void PQclear(PGresult *res)
Definition: fe-exec.c:650
int ntups
Definition: libpq-int.h:169
#define NULL
Definition: c.h:229
PGEventProc proc
Definition: libpq-int.h:160
char cmdStatus[CMDSTATUS_LEN]
Definition: libpq-int.h:178
int i
void * passThrough
Definition: libpq-int.h:162
char * value
Definition: libpq-int.h:138
#define TRUE
Definition: c.h:217
PGEvent * events
Definition: libpq-int.h:187
PGresult * dest
Definition: libpq-events.h:61
int client_encoding
Definition: libpq-int.h:189
char* PQdb ( const PGconn conn)
PGresult* PQdescribePortal ( PGconn conn,
const char *  portal 
)

Definition at line 2082 of file fe-exec.c.

References NULL, PQexecFinish(), PQexecStart(), and PQsendDescribe().

2083 {
2084  if (!PQexecStart(conn))
2085  return NULL;
2086  if (!PQsendDescribe(conn, 'P', portal))
2087  return NULL;
2088  return PQexecFinish(conn);
2089 }
static int PQsendDescribe(PGconn *conn, char desc_type, const char *desc_target)
Definition: fe-exec.c:2127
#define NULL
Definition: c.h:229
static PGresult * PQexecFinish(PGconn *conn)
Definition: fe-exec.c:2002
static bool PQexecStart(PGconn *conn)
Definition: fe-exec.c:1928
PGresult* PQdescribePrepared ( PGconn conn,
const char *  stmt 
)

Definition at line 2063 of file fe-exec.c.

References NULL, PQexecFinish(), PQexecStart(), and PQsendDescribe().

Referenced by ECPGdescribe().

2064 {
2065  if (!PQexecStart(conn))
2066  return NULL;
2067  if (!PQsendDescribe(conn, 'S', stmt))
2068  return NULL;
2069  return PQexecFinish(conn);
2070 }
static int PQsendDescribe(PGconn *conn, char desc_type, const char *desc_target)
Definition: fe-exec.c:2127
#define NULL
Definition: c.h:229
static PGresult * PQexecFinish(PGconn *conn)
Definition: fe-exec.c:2002
static bool PQexecStart(PGconn *conn)
Definition: fe-exec.c:1928
void PQdisplayTuples ( const PGresult res,
FILE *  fp,
int  fillAlign,
const char *  fieldSep,
int  printHeader,
int  quiet 
)

Definition at line 571 of file fe-print.c.

References DEFAULT_FIELD_SEP, fill(), free, i, libpq_gettext, malloc, NULL, PQfname(), PQgetlength(), PQgetvalue(), PQnfields(), and PQntuples().

578 {
579 #define DEFAULT_FIELD_SEP " "
580 
581  int i,
582  j;
583  int nFields;
584  int nTuples;
585  int *fLength = NULL;
586 
587  if (fieldSep == NULL)
588  fieldSep = DEFAULT_FIELD_SEP;
589 
590  /* Get some useful info about the results */
591  nFields = PQnfields(res);
592  nTuples = PQntuples(res);
593 
594  if (fp == NULL)
595  fp = stdout;
596 
597  /* Figure the field lengths to align to */
598  /* will be somewhat time consuming for very large results */
599  if (fillAlign)
600  {
601  fLength = (int *) malloc(nFields * sizeof(int));
602  if (!fLength)
603  {
604  fprintf(stderr, libpq_gettext("out of memory\n"));
605  abort();
606  }
607 
608  for (j = 0; j < nFields; j++)
609  {
610  fLength[j] = strlen(PQfname(res, j));
611  for (i = 0; i < nTuples; i++)
612  {
613  int flen = PQgetlength(res, i, j);
614 
615  if (flen > fLength[j])
616  fLength[j] = flen;
617  }
618  }
619  }
620 
621  if (printHeader)
622  {
623  /* first, print out the attribute names */
624  for (i = 0; i < nFields; i++)
625  {
626  fputs(PQfname(res, i), fp);
627  if (fillAlign)
628  fill(strlen(PQfname(res, i)), fLength[i], ' ', fp);
629  fputs(fieldSep, fp);
630  }
631  fprintf(fp, "\n");
632 
633  /* Underline the attribute names */
634  for (i = 0; i < nFields; i++)
635  {
636  if (fillAlign)
637  fill(0, fLength[i], '-', fp);
638  fputs(fieldSep, fp);
639  }
640  fprintf(fp, "\n");
641  }
642 
643  /* next, print out the instances */
644  for (i = 0; i < nTuples; i++)
645  {
646  for (j = 0; j < nFields; j++)
647  {
648  fprintf(fp, "%s", PQgetvalue(res, i, j));
649  if (fillAlign)
650  fill(strlen(PQgetvalue(res, i, j)), fLength[j], ' ', fp);
651  fputs(fieldSep, fp);
652  }
653  fprintf(fp, "\n");
654  }
655 
656  if (!quiet)
657  fprintf(fp, "\nQuery returned %d row%s.\n", PQntuples(res),
658  (PQntuples(res) == 1) ? "" : "s");
659 
660  fflush(fp);
661 
662  if (fLength)
663  free(fLength);
664 }
static void fill(int length, int max, char filler, FILE *fp)
Definition: fe-print.c:754
int PQgetlength(const PGresult *res, int tup_num, int field_num)
Definition: fe-exec.c:3078
int PQnfields(const PGresult *res)
Definition: fe-exec.c:2681
char * PQgetvalue(const PGresult *res, int tup_num, int field_num)
Definition: fe-exec.c:3067
char * PQfname(const PGresult *res, int field_num)
Definition: fe-exec.c:2759
int PQntuples(const PGresult *res)
Definition: fe-exec.c:2673
#define malloc(a)
Definition: header.h:50
#define free(a)
Definition: header.h:65
#define DEFAULT_FIELD_SEP
#define NULL
Definition: c.h:229
int i
#define libpq_gettext(x)
Definition: libpq-int.h:683
int PQdsplen ( const char *  s,
int  encoding 
)

Definition at line 1197 of file fe-misc.c.

References pg_encoding_dsplen().

Referenced by pg_wcsformat(), pg_wcssize(), pg_wcswidth(), and strlen_max_width().

1198 {
1199  return pg_encoding_dsplen(encoding, s);
1200 }
int pg_encoding_dsplen(int encoding, const char *mbstr)
Definition: wchar.c:1796
static char * encoding
Definition: initdb.c:122
char* PQencryptPassword ( const char *  passwd,
const char *  user 
)

Definition at line 1098 of file fe-auth.c.

References free, malloc, MD5_PASSWD_LEN, NULL, and pg_md5_encrypt().

Referenced by exec_command_password(), and main().

1099 {
1100  char *crypt_pwd;
1101 
1102  crypt_pwd = malloc(MD5_PASSWD_LEN + 1);
1103  if (!crypt_pwd)
1104  return NULL;
1105 
1106  if (!pg_md5_encrypt(passwd, user, strlen(user), crypt_pwd))
1107  {
1108  free(crypt_pwd);
1109  return NULL;
1110  }
1111 
1112  return crypt_pwd;
1113 }
#define malloc(a)
Definition: header.h:50
bool pg_md5_encrypt(const char *passwd, const char *salt, size_t salt_len, char *buf)
Definition: md5.c:323
#define MD5_PASSWD_LEN
Definition: md5.h:19
#define free(a)
Definition: header.h:65
#define NULL
Definition: c.h:229
static char * user
Definition: pg_regress.c:92
int PQendcopy ( PGconn conn)

Definition at line 2522 of file fe-exec.c.

References PG_PROTOCOL_MAJOR, pqEndcopy2(), pqEndcopy3(), and pg_conn::pversion.

Referenced by ecpg_check_PQresult(), init(), and libpqrcv_endstreaming().

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 }
#define PG_PROTOCOL_MAJOR(v)
Definition: pqcomm.h:104
int pqEndcopy3(PGconn *conn)
ProtocolVersion pversion
Definition: libpq-int.h:404
int pqEndcopy2(PGconn *conn)
int PQenv2encoding ( void  )

Definition at line 1206 of file fe-misc.c.

References encoding, pg_char_to_encoding(), and PG_SQL_ASCII.

Referenced by main().

1207 {
1208  char *str;
1209  int encoding = PG_SQL_ASCII;
1210 
1211  str = getenv("PGCLIENTENCODING");
1212  if (str && *str != '\0')
1213  {
1214  encoding = pg_char_to_encoding(str);
1215  if (encoding < 0)
1216  encoding = PG_SQL_ASCII;
1217  }
1218  return encoding;
1219 }
int pg_char_to_encoding(const char *name)
Definition: encnames.c:551
static char * encoding
Definition: initdb.c:122
char* PQerrorMessage ( const PGconn conn)

Definition at line 5934 of file fe-connect.c.

References PQExpBufferData::data, pg_conn::errorMessage, and libpq_gettext.

Referenced by _connectDB(), _doSetSessionAuth(), _doSetWithOids(), _selectOutputSchema(), _selectTablespace(), AcceptResult(), BaseBackup(), check_conn(), check_loadable_libraries(), CheckCopyStreamStop(), cluster_one_database(), connect_pg_server(), connectDatabase(), ConnectDatabase(), connectToServer(), CopyStreamPoll(), CopyStreamReceive(), CreateReplicationSlot(), dblink_connect(), dblink_error_message(), dblink_get_conn(), dblink_res_error(), dblink_send_query(), die_on_query_failure(), do_connect(), do_lo_export(), do_lo_import(), do_lo_unlink(), doConnect(), doCustom(), DropReplicationSlot(), dumpBlobs(), dumpTableData_copy(), ecpg_check_PQresult(), ecpg_raise_backend(), ECPGconnect(), EndDBCopyMode(), executeCommand(), executeQuery(), executeQueryOrDie(), ExecuteSqlCommand(), ExecuteSqlCommandBuf(), executeStatement(), fetch_file_range(), GetConnection(), GetQueryResult(), handleCopyIn(), handleCopyOut(), HandleEndOfCopyStream(), init(), init_slot(), libpq_executeFileMap(), libpqConnect(), libpqrcv_connect(), libpqrcv_create_slot(), libpqrcv_endstreaming(), libpqrcv_exec(), libpqrcv_identify_system(), libpqrcv_readtimelinehistoryfile(), libpqrcv_receive(), libpqrcv_send(), libpqrcv_startstreaming(), main(), my_truncate(), overwrite(), pg_attribute_noreturn(), pgfdw_report_error(), pickout(), ProcessXLogDataMsg(), psql_get_variable(), ReceiveAndUnpackTarFile(), receiveFileChunks(), ReceiveTarFile(), ReceiveXlogStream(), reindex_one_database(), reindex_system_catalogs(), run_permutation(), run_vacuum_command(), RunIdentifySystem(), sendCommand(), sendFeedback(), SendQuery(), sql_conn(), sql_exec(), start_postmaster(), StartRestoreBlob(), storeQueryResult(), StreamLogicalLog(), threadRun(), try_complete_step(), tryExecuteStatement(), and vacuumlo().

5935 {
5936  if (!conn)
5937  return libpq_gettext("connection pointer is NULL\n");
5938 
5939  return conn->errorMessage.data;
5940 }
PQExpBufferData errorMessage
Definition: libpq-int.h:492
#define libpq_gettext(x)
Definition: libpq-int.h:683
unsigned char* PQescapeBytea ( const unsigned char *  from,
size_t  from_length,
size_t *  to_length 
)

Definition at line 3630 of file fe-exec.c.

References NULL, PQescapeByteaInternal(), and static_std_strings.

3631 {
3632  return PQescapeByteaInternal(NULL, from, from_length, to_length,
3634  false /* can't use hex */ );
3635 }
static bool static_std_strings
Definition: fe-exec.c:50
#define NULL
Definition: c.h:229
static unsigned char * PQescapeByteaInternal(PGconn *conn, const unsigned char *from, size_t from_length, size_t *to_length, bool std_strings, bool use_hex)
Definition: fe-exec.c:3521
unsigned char* PQescapeByteaConn ( PGconn conn,
const unsigned char *  from,
size_t  from_length,
size_t *  to_length 
)

Definition at line 3618 of file fe-exec.c.

References NULL, PQescapeByteaInternal(), pg_conn::std_strings, and pg_conn::sversion.

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 }
int sversion
Definition: libpq-int.h:405
bool std_strings
Definition: libpq-int.h:424
#define NULL
Definition: c.h:229
static unsigned char * PQescapeByteaInternal(PGconn *conn, const unsigned char *from, size_t from_length, size_t *to_length, bool std_strings, bool use_hex)
Definition: fe-exec.c:3521
char* PQescapeIdentifier ( PGconn conn,
const char *  str,
size_t  len 
)

Definition at line 3474 of file fe-exec.c.

References PQescapeInternal().

Referenced by init(), psql_get_variable(), stringlist_to_identifierstr(), and vacuumlo().

3475 {
3476  return PQescapeInternal(conn, str, len, true);
3477 }
static char * PQescapeInternal(PGconn *conn, const char *str, size_t len, bool as_ident)
Definition: fe-exec.c:3347
char* PQescapeLiteral ( PGconn conn,
const char *  str,
size_t  len 
)

Definition at line 3468 of file fe-exec.c.

References PQescapeInternal().

Referenced by libpqrcv_startstreaming(), and psql_get_variable().

3469 {
3470  return PQescapeInternal(conn, str, len, false);
3471 }
static char * PQescapeInternal(PGconn *conn, const char *str, size_t len, bool as_ident)
Definition: fe-exec.c:3347
size_t PQescapeString ( char *  to,
const char *  from,
size_t  length 
)

Definition at line 3332 of file fe-exec.c.

References NULL, PQescapeStringInternal(), static_client_encoding, and static_std_strings.

Referenced by get_comma_elts(), and quote_postgres().

3333 {
3334  return PQescapeStringInternal(NULL, to, from, length, NULL,
3337 }
static bool static_std_strings
Definition: fe-exec.c:50
int length(const List *list)
Definition: list.c:1271
static int static_client_encoding
Definition: fe-exec.c:49
#define NULL
Definition: c.h:229
static size_t PQescapeStringInternal(PGconn *conn, char *to, const char *from, size_t length, int *error, int encoding, bool std_strings)
Definition: fe-exec.c:3239
size_t PQescapeStringConn ( PGconn conn,
char *  to,
const char *  from,
size_t  length,
int *  error 
)

Definition at line 3314 of file fe-exec.c.

References pg_conn::client_encoding, PQescapeStringInternal(), and pg_conn::std_strings.

Referenced by appendStringLiteralConn(), BaseBackup(), check_loadable_libraries(), and do_lo_import().

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 }
int length(const List *list)
Definition: list.c:1271
static void error(void)
Definition: sql-dyntest.c:147
bool std_strings
Definition: libpq-int.h:424
static size_t PQescapeStringInternal(PGconn *conn, char *to, const char *from, size_t length, int *error, int encoding, bool std_strings)
Definition: fe-exec.c:3239
int client_encoding
Definition: libpq-int.h:423
PGresult* PQexec ( PGconn conn,
const char *  query 
)

Definition at line 1846 of file fe-exec.c.

References NULL, PQexecFinish(), PQexecStart(), and PQsendQuery().

Referenced by _doSetSessionAuth(), _doSetWithOids(), _selectOutputSchema(), _selectTablespace(), check_loadable_libraries(), CreateReplicationSlot(), dblink_close(), dblink_exec(), dblink_fetch(), dblink_open(), deallocate_one(), do_sql_command(), DropReplicationSlot(), ecpg_autostart_transaction(), ecpg_execute(), ecpg_is_type_an_array(), ECPGsetcommit(), ECPGtrans(), ExecQueryUsingCursor(), executeCommand(), executeMaintenanceCommand(), executeQuery(), executeQueryOrDie(), ExecuteSqlCommand(), ExecuteSqlQuery(), ExecuteSqlStatement(), executeStatement(), get_create_object_cmd(), init(), libpq_executeFileMap(), libpqConnect(), libpqProcessFileList(), lo_initialize(), lockTableForWorker(), lookup_object_oid(), main(), pgfdw_subxact_callback(), pgfdw_xact_callback(), PQsetClientEncoding(), PSQLexec(), PSQLexecWatch(), ReceiveXlogStream(), run_permutation(), run_simple_query(), RunIdentifySystem(), SendQuery(), sql_exec(), StreamLogicalLog(), tryExecuteStatement(), and vacuumlo().

1847 {
1848  if (!PQexecStart(conn))
1849  return NULL;
1850  if (!PQsendQuery(conn, query))
1851  return NULL;
1852  return PQexecFinish(conn);
1853 }
int PQsendQuery(PGconn *conn, const char *query)
Definition: fe-exec.c:1132
#define NULL
Definition: c.h:229
static PGresult * PQexecFinish(PGconn *conn)
Definition: fe-exec.c:2002
static bool PQexecStart(PGconn *conn)
Definition: fe-exec.c:1928
PGresult* PQexecParams ( PGconn conn,
const char *  command,
int  nParams,
const Oid paramTypes,
const char *const *  paramValues,
const int *  paramLengths,
const int *  paramFormats,
int  resultFormat 
)

Definition at line 1860 of file fe-exec.c.

References NULL, PQexecFinish(), PQexecStart(), and PQsendQueryParams().

Referenced by ecpg_execute(), libpqGetFile(), and main().

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 }
int PQsendQueryParams(PGconn *conn, const char *command, int nParams, const Oid *paramTypes, const char *const *paramValues, const int *paramLengths, const int *paramFormats, int resultFormat)
Definition: fe-exec.c:1183
#define NULL
Definition: c.h:229
static PGresult * PQexecFinish(PGconn *conn)
Definition: fe-exec.c:2002
static bool PQexecStart(PGconn *conn)
Definition: fe-exec.c:1928
PGresult* PQexecPrepared ( PGconn conn,
const char *  stmtName,
int  nParams,
const char *const *  paramValues,
const int *  paramLengths,
const int *  paramFormats,
int  resultFormat 
)

Definition at line 1907 of file fe-exec.c.

References NULL, PQexecFinish(), PQexecStart(), and PQsendQueryPrepared().

Referenced by ecpg_execute(), and try_complete_step().

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 }
#define NULL
Definition: c.h:229
static PGresult * PQexecFinish(PGconn *conn)
Definition: fe-exec.c:2002
int PQsendQueryPrepared(PGconn *conn, const char *stmtName, int nParams, const char *const *paramValues, const int *paramLengths, const int *paramFormats, int resultFormat)
Definition: fe-exec.c:1325
static bool PQexecStart(PGconn *conn)
Definition: fe-exec.c:1928
int PQfformat ( const PGresult res,
int  field_num 
)

Definition at line 2900 of file fe-exec.c.

References pg_result::attDescs, check_field_number(), and pgresAttDesc::format.

Referenced by ecpg_get_data(), ecpg_store_result(), and receiveFileChunks().

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 }
PGresAttDesc * attDescs
Definition: libpq-int.h:171
static int check_field_number(const PGresult *res, int field_num)
Definition: fe-exec.c:2702
void PQfinish ( PGconn conn)

Definition at line 3491 of file fe-connect.c.

References closePGconn(), and freePGconn().

Referenced by _connectDB(), BaseBackup(), check_for_isn_and_int8_passing_mismatch(), check_for_jsonb_9_4_usage(), check_for_pg_role_prefix(), check_for_prepared_transactions(), check_for_reg_data_type_usage(), check_is_install_user(), check_loadable_libraries(), check_proper_datallowconn(), CheckConnection(), cluster_all_databases(), cluster_one_database(), connect_pg_server(), connectDatabase(), ConnectDatabase(), connectToServer(), createNewConnection(), dblink_connect(), dblink_disconnect(), dblink_exec(), dblink_get_conn(), dblink_record_internal(), dblink_security_check(), disconnect_all(), disconnect_and_exit(), DisconnectDatabase(), do_connect(), doConnect(), doCustom(), dumpCreateDB(), dumpTablespaces(), ecpg_finish(), executeCommand(), executeQuery(), executeQueryOrDie(), exit_nicely(), get_db_infos(), get_loadable_libraries(), get_rel_infos(), get_tablespace_paths(), GetConnection(), init(), libpqrcv_disconnect(), LogStreamerMain(), main(), new_9_0_populate_pg_largeobject_metadata(), old_9_3_check_for_line_data_type_usage(), old_9_6_check_for_unknown_data_type_usage(), pgfdw_xact_callback(), PQping(), PQpingParams(), ReconnectToServer(), reindex_all_databases(), reindex_one_database(), reindex_system_catalogs(), run_vacuum_command(), set_frozenxids(), sql_conn(), sql_exec(), start_postmaster(), StreamLog(), StreamLogicalLog(), threadRun(), vacuum_all_databases(), and vacuumlo().

3492 {
3493  if (conn)
3494  {
3495  closePGconn(conn);
3496  freePGconn(conn);
3497  }
3498 }
static void closePGconn(PGconn *conn)
Definition: fe-connect.c:3401
static void freePGconn(PGconn *conn)
Definition: fe-connect.c:3229
int PQflush ( PGconn conn)

Definition at line 3187 of file fe-exec.c.

References pqFlush().

Referenced by CheckCopyStreamStop(), HandleEndOfCopyStream(), libpqrcv_endstreaming(), libpqrcv_send(), prepareToTerminate(), ProcessXLogDataMsg(), and sendFeedback().

3188 {
3189  return pqFlush(conn);
3190 }
int pqFlush(PGconn *conn)
Definition: fe-misc.c:966
int PQfmod ( const PGresult res,
int  field_num 
)

Definition at line 2933 of file fe-exec.c.

References pg_result::attDescs, pgresAttDesc::atttypmod, and check_field_number().

Referenced by ECPGget_desc().

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 }
PGresAttDesc * attDescs
Definition: libpq-int.h:171
int atttypmod
Definition: libpq-fe.h:243
static int check_field_number(const PGresult *res, int field_num)
Definition: fe-exec.c:2702
PGresult* PQfn ( PGconn conn,
int  fnid,
int *  result_buf,
int *  result_len,
int  result_is_int,
const PQArgBlock args,
int  nargs 
)

Definition at line 2556 of file fe-exec.c.

References pg_conn::asyncStatus, pg_conn::errorMessage, libpq_gettext, NULL, PG_PROTOCOL_MAJOR, PGASYNC_IDLE, PGINVALID_SOCKET, pqFunctionCall2(), pqFunctionCall3(), printfPQExpBuffer(), pg_conn::pversion, resetPQExpBuffer(), pg_conn::result, and pg_conn::sock.

Referenced by lo_close(), lo_creat(), lo_create(), lo_lseek(), lo_lseek64(), lo_open(), lo_read(), lo_tell(), lo_tell64(), lo_truncate(), lo_truncate64(), lo_unlink(), and lo_write().

2563 {
2564  *result_len = 0;
2565 
2566  if (!conn)
2567  return NULL;
2568 
2569  /* clear the error string */
2571 
2572  if (conn->sock == PGINVALID_SOCKET || conn->asyncStatus != PGASYNC_IDLE ||
2573  conn->result != NULL)
2574  {
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 }
void printfPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:234
PGresult * pqFunctionCall2(PGconn *conn, Oid fnid, int *result_buf, int *actual_result_len, int result_is_int, const PQArgBlock *args, int nargs)
PGresult * pqFunctionCall3(PGconn *conn, Oid fnid, int *result_buf, int *actual_result_len, int result_is_int, const PQArgBlock *args, int nargs)
#define PG_PROTOCOL_MAJOR(v)
Definition: pqcomm.h:104
PGresult * result
Definition: libpq-int.h:451
PGAsyncStatusType asyncStatus
Definition: libpq-int.h:379
pgsocket sock
Definition: libpq-int.h:400
#define PGINVALID_SOCKET
Definition: port.h:24
PQExpBufferData errorMessage
Definition: libpq-int.h:492
#define NULL
Definition: c.h:229
ProtocolVersion pversion
Definition: libpq-int.h:404
void resetPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:145
#define libpq_gettext(x)
Definition: libpq-int.h:683
char* PQfname ( const PGresult res,
int  field_num 
)

Definition at line 2759 of file fe-exec.c.

References pg_result::attDescs, check_field_number(), pgresAttDesc::name, and NULL.

Referenced by do_header(), dumpTableData_insert(), ecpg_build_compat_sqlda(), ecpg_build_native_sqlda(), ECPGget_desc(), indexOfColumn(), libpqrcv_processTuples(), main(), PQdisplayTuples(), PQprint(), PQprintTuples(), printCrosstab(), printQuery(), printResultSet(), sql_exec(), sqlda_compat_empty_size(), and StoreQueryTuple().

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 }
PGresAttDesc * attDescs
Definition: libpq-int.h:171
static int check_field_number(const PGresult *res, int field_num)
Definition: fe-exec.c:2702
#define NULL
Definition: c.h:229
char * name
Definition: libpq-fe.h:237
int PQfnumber ( const PGresult res,
const char *  field_name 
)

Definition at line 2781 of file fe-exec.c.

References pg_result::attDescs, free, i, pgresAttDesc::name, NULL, pg_result::numAttributes, and pg_tolower().

Referenced by binary_upgrade_set_pg_class_oids(), binary_upgrade_set_type_oids_by_rel_oid(), binary_upgrade_set_type_oids_by_type_oid(), buildMatViewRefreshDependencies(), check_for_isn_and_int8_passing_mismatch(), check_for_jsonb_9_4_usage(), check_for_reg_data_type_usage(), check_proper_datallowconn(), collectComments(), collectSecLabels(), dropRoles(), dumpAgg(), dumpBaseType(), dumpCollation(), dumpCompositeType(), dumpCompositeTypeColComments(), dumpConversion(), dumpDatabase(), dumpDomain(), dumpEnumType(), dumpFunc(), dumpOpclass(), dumpOpfamily(), dumpOpr(), dumpRangeType(), dumpRoles(), dumpTableSchema(), dumpTSConfig(), dumpUserMappings(), findLastBuiltinOid_V71(), get_db_infos(), get_rel_infos(), get_tablespace_paths(), getAccessMethods(), getAggregates(), getBlobs(), getCasts(), getCollations(), getConstraints(), getConversions(), getDefaultACLs(), getDependencies(), getDomainConstraints(), getEventTriggers(), getExtendedStatistics(), getExtensionMembership(), getExtensions(), getForeignDataWrappers(), getForeignServers(), getFuncs(), getIndexes(), getInherits(), getNamespaces(), getOpclasses(), getOperators(), getOpfamilies(), getPartitions(), getPolicies(), getProcLangs(), getPublications(), getPublicationTables(), getRules(), getSubscriptions(), getTableAttrs(), getTables(), getTransforms(), getTriggers(), getTSConfigurations(), getTSDictionaries(), getTSParsers(), getTSTemplates(), getTypes(), new_9_0_populate_pg_largeobject_metadata(), old_9_3_check_for_line_data_type_usage(), old_9_6_check_for_unknown_data_type_usage(), processExtensionTables(), set_frozenxids(), and show_binary_results().

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