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().

#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 }
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
union PQArgBlock::@94 u
void PQclear(PGresult *res)
Definition: fe-exec.c:650
#define NULL
Definition: c.h:226
Oid fn_lo_close
Definition: libpq-int.h:270
int isint
Definition: libpq-fe.h:223
PGlobjfuncs * lobjfuncs
Definition: libpq-int.h:430
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 }
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
union PQArgBlock::@94 u
#define InvalidOid
Definition: postgres_ext.h:36
void PQclear(PGresult *res)
Definition: fe-exec.c:650
#define NULL
Definition: c.h:226
Oid fn_lo_creat
Definition: libpq-int.h:271
int isint
Definition: libpq-fe.h:223
PGlobjfuncs * lobjfuncs
Definition: libpq-int.h:430
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 }
void printfPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:234
Oid fn_lo_create
Definition: libpq-int.h:272
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
union PQArgBlock::@94 u
PQExpBufferData errorMessage
Definition: libpq-int.h:498
#define InvalidOid
Definition: postgres_ext.h:36
void PQclear(PGresult *res)
Definition: fe-exec.c:650
#define NULL
Definition: c.h:226
int isint
Definition: libpq-fe.h:223
PGlobjfuncs * lobjfuncs
Definition: libpq-int.h:430
#define libpq_gettext(x)
Definition: libpq-int.h:689
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(), 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:19
char * pqStrerror(int errnum, char *strerrbuf, size_t buflen)
Definition: thread.c:61
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:65
int lo_open(PGconn *conn, Oid lobjId, int mode)
Definition: fe-lobj.c:58
PQExpBufferData errorMessage
Definition: libpq-int.h:498
#define LO_BUFSIZE
Definition: fe-lobj.c:43
static char * filename
Definition: pg_dumpall.c:84
int lo_read(PGconn *conn, int fd, char *buf, size_t len)
Definition: fe-lobj.c:259
#define close(a)
Definition: win32.h:17
#define libpq_gettext(x)
Definition: libpq-int.h:689
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:84
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:84
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 }
Oid fn_lo_lseek
Definition: libpq-int.h:274
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
union PQArgBlock::@94 u
void PQclear(PGresult *res)
Definition: fe-exec.c:650
#define NULL
Definition: c.h:226
int isint
Definition: libpq-fe.h:223
PGlobjfuncs * lobjfuncs
Definition: libpq-int.h:430
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 }
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:43
static pg_int64 lo_hton64(pg_int64 host64)
Definition: fe-lobj.c:1062
union PQArgBlock::@94 u
PQExpBufferData errorMessage
Definition: libpq-int.h:498
void PQclear(PGresult *res)
Definition: fe-exec.c:650
#define NULL
Definition: c.h:226
Oid fn_lo_lseek64
Definition: libpq-int.h:275
int isint
Definition: libpq-fe.h:223
PGlobjfuncs * lobjfuncs
Definition: libpq-int.h:430
int * ptr
Definition: libpq-fe.h:226
#define libpq_gettext(x)
Definition: libpq-int.h:689
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 }
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:269
union PQArgBlock::@94 u
void PQclear(PGresult *res)
Definition: fe-exec.c:650
#define NULL
Definition: c.h:226
int isint
Definition: libpq-fe.h:223
PGlobjfuncs * lobjfuncs
Definition: libpq-int.h:430
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 }
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:280
static char * buf
Definition: pg_test_fsync.c:65
union PQArgBlock::@94 u
PQExpBufferData errorMessage
Definition: libpq-int.h:498
void PQclear(PGresult *res)
Definition: fe-exec.c:650
#define NULL
Definition: c.h:226
int isint
Definition: libpq-fe.h:223
PGlobjfuncs * lobjfuncs
Definition: libpq-int.h:430
#define libpq_gettext(x)
Definition: libpq-int.h:689
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 }
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
union PQArgBlock::@94 u
Oid fn_lo_tell
Definition: libpq-int.h:276
void PQclear(PGresult *res)
Definition: fe-exec.c:650
#define NULL
Definition: c.h:226
int isint
Definition: libpq-fe.h:223
PGlobjfuncs * lobjfuncs
Definition: libpq-int.h:430
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 }
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:43
Oid fn_lo_tell64
Definition: libpq-int.h:277
union PQArgBlock::@94 u
PQExpBufferData errorMessage
Definition: libpq-int.h:498
void PQclear(PGresult *res)
Definition: fe-exec.c:650
#define NULL
Definition: c.h:226
int isint
Definition: libpq-fe.h:223
PGlobjfuncs * lobjfuncs
Definition: libpq-int.h:430
#define libpq_gettext(x)
Definition: libpq-int.h:689
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 }
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:278
union PQArgBlock::@94 u
PQExpBufferData errorMessage
Definition: libpq-int.h:498
void PQclear(PGresult *res)
Definition: fe-exec.c:650
#define NULL
Definition: c.h:226
int isint
Definition: libpq-fe.h:223
PGlobjfuncs * lobjfuncs
Definition: libpq-int.h:430
#define libpq_gettext(x)
Definition: libpq-int.h:689
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 }
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
union PQArgBlock::@94 u
Oid fn_lo_truncate64
Definition: libpq-int.h:279
PQExpBufferData errorMessage
Definition: libpq-int.h:498
void PQclear(PGresult *res)
Definition: fe-exec.c:650
#define NULL
Definition: c.h:226
int isint
Definition: libpq-fe.h:223
PGlobjfuncs * lobjfuncs
Definition: libpq-int.h:430
int * ptr
Definition: libpq-fe.h:226
#define libpq_gettext(x)
Definition: libpq-int.h:689
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 }
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
union PQArgBlock::@94 u
void PQclear(PGresult *res)
Definition: fe-exec.c:650
#define NULL
Definition: c.h:226
Oid fn_lo_unlink
Definition: libpq-int.h:273
int isint
Definition: libpq-fe.h:223
PGlobjfuncs * lobjfuncs
Definition: libpq-int.h:430
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 }
void printfPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:234
Oid fn_lo_write
Definition: libpq-int.h:281
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:65
union PQArgBlock::@94 u
PQExpBufferData errorMessage
Definition: libpq-int.h:498
void PQclear(PGresult *res)
Definition: fe-exec.c:650
#define NULL
Definition: c.h:226
int isint
Definition: libpq-fe.h:223
PGlobjfuncs * lobjfuncs
Definition: libpq-int.h:430
int * ptr
Definition: libpq-fe.h:226
#define libpq_gettext(x)
Definition: libpq-int.h:689
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 475 of file encnames.c.

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

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().

476 {
477  unsigned int nel = lengthof(pg_encname_tbl);
478  const pg_encname *base = pg_encname_tbl,
479  *last = base + nel - 1,
480  *position;
481  int result;
482  char buff[NAMEDATALEN],
483  *key;
484 
485  if (name == NULL || *name == '\0')
486  return -1;
487 
488  if (strlen(name) >= NAMEDATALEN)
489  {
490 #ifdef FRONTEND
491  fprintf(stderr, "encoding name too long\n");
492  return -1;
493 #else
494  ereport(ERROR,
495  (errcode(ERRCODE_NAME_TOO_LONG),
496  errmsg("encoding name too long")));
497 #endif
498  }
499  key = clean_encoding_name(name, buff);
500 
501  while (last >= base)
502  {
503  position = base + ((last - base) >> 1);
504  result = key[0] - position->name[0];
505 
506  if (result == 0)
507  {
508  result = strcmp(key, position->name);
509  if (result == 0)
510  return position->encoding;
511  }
512  if (result < 0)
513  last = position - 1;
514  else
515  base = position + 1;
516  }
517  return -1;
518 }
int errcode(int sqlerrcode)
Definition: elog.c:575
#define lengthof(array)
Definition: c.h:558
#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:226
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:449
const char* pg_encoding_to_char ( int  encoding)
int pg_valid_server_encoding_id ( int  encoding)

Definition at line 439 of file encnames.c.

References PG_VALID_BE_ENCODING.

Referenced by setup_locale_encoding().

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

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

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

Referenced by get_prompt().

5987 {
5988  if (!conn || conn->status != CONNECTION_OK)
5989  return 0;
5990  return conn->be_pid;
5991 }
ConnStatusType status
Definition: libpq-int.h:380
int be_pid
Definition: libpq-int.h:422
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:181
int PQcancel ( PGcancel cancel,
char *  errbuf,
int  errbufsize 
)

Definition at line 3793 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().

3794 {
3795  if (!cancel)
3796  {
3797  strlcpy(errbuf, "PQcancel() -- no cancel object supplied", errbufsize);
3798  return FALSE;
3799  }
3800 
3801  return internal_cancel(&cancel->raddr, cancel->be_pid, cancel->be_key,
3802  errbuf, errbufsize);
3803 }
static int internal_cancel(SockAddr *raddr, int be_pid, int be_key, char *errbuf, int errbufsize)
Definition: fe-connect.c:3689
int be_pid
Definition: libpq-int.h:511
#define FALSE
Definition: c.h:218
int be_key
Definition: libpq-int.h:512
size_t strlcpy(char *dst, const char *src, size_t siz)
Definition: strlcpy.c:45
SockAddr raddr
Definition: libpq-int.h:510
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(), 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(), 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_command(), libpqrcv_create_slot(), libpqrcv_endstreaming(), 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(), 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:199
bool resultInitialized
Definition: libpq-int.h:166
PGresult_data * next
Definition: libpq-int.h:107
int nEvents
Definition: libpq-int.h:190
PGresAttDesc * attDescs
Definition: libpq-int.h:173
PGresAttValue ** tuples
Definition: libpq-int.h:174
PGresult_data * curBlock
Definition: libpq-int.h:210
#define free(a)
Definition: header.h:60
PGresParamDesc * paramDescs
Definition: libpq-int.h:178
#define NULL
Definition: c.h:226
PGEventProc proc
Definition: libpq-int.h:162
int i
void * passThrough
Definition: libpq-int.h:164
PGEvent * events
Definition: libpq-int.h:189
char * name
Definition: libpq-int.h:163
int PQclientEncoding ( const PGconn conn)

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

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

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

6021 {
6022  if (!conn || conn->status != CONNECTION_OK)
6023  return -1;
6024  return conn->client_encoding;
6025 }
ConnStatusType status
Definition: libpq-int.h:380
int client_encoding
Definition: libpq-int.h:426
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:226
char cmdStatus[CMDSTATUS_LEN]
Definition: libpq-int.h:180
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:188
char * c
void pqInternalNotice(const PGNoticeHooks *hooks, const char *fmt,...)
Definition: fe-exec.c:801
char cmdStatus[CMDSTATUS_LEN]
Definition: libpq-int.h:180
PQconninfoOption* PQconndefaults ( void  )

Definition at line 1108 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().

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

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

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

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

528 {
529  PGconn *conn = PQconnectStart(conninfo);
530 
531  if (conn && conn->status != CONNECTION_BAD)
532  (void) connectDBComplete(conn);
533 
534  return conn;
535 }
PGconn * conn
Definition: streamutil.c:45
static int connectDBComplete(PGconn *conn)
Definition: fe-connect.c:1715
PGconn * PQconnectStart(const char *conninfo)
Definition: fe-connect.c:653
ConnStatusType status
Definition: libpq-int.h:380
PGconn* PQconnectdbParams ( const char *const *  keywords,
const char *const *  values,
int  expand_dbname 
)

Definition at line 471 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(), libpqrcv_connect(), main(), sql_conn(), and vacuumlo().

474 {
475  PGconn *conn = PQconnectStartParams(keywords, values, expand_dbname);
476 
477  if (conn && conn->status != CONNECTION_BAD)
478  (void) connectDBComplete(conn);
479 
480  return conn;
481 
482 }
PGconn * conn
Definition: streamutil.c:45
static int connectDBComplete(PGconn *conn)
Definition: fe-connect.c:1715
ConnStatusType status
Definition: libpq-int.h:380
static Datum values[MAXATTR]
Definition: bootstrap.c:162
PGconn * PQconnectStartParams(const char *const *keywords, const char *const *values, int expand_dbname)
Definition: fe-connect.c:574
int PQconnectionNeedsPassword ( const PGconn conn)

Definition at line 5994 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().

5995 {
5996  char *password;
5997 
5998  if (!conn)
5999  return false;
6000  password = PQpass(conn);
6001  if (conn->password_needed &&
6002  (password == NULL || password[0] == '\0'))
6003  return true;
6004  else
6005  return false;
6006 }
static char password[100]
Definition: streamutil.c:44
bool password_needed
Definition: libpq-int.h:410
char * PQpass(const PGconn *conn)
Definition: fe-connect.c:5844
#define NULL
Definition: c.h:226
int PQconnectionUsedPassword ( const PGconn conn)

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

References pg_conn::password_needed.

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

6010 {
6011  if (!conn)
6012  return false;
6013  if (conn->password_needed)
6014  return true;
6015  else
6016  return false;
6017 }
bool password_needed
Definition: libpq-int.h:410
PostgresPollingStatusType PQconnectPoll ( PGconn conn)

Definition at line 1849 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_GSS_CONT, 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, FD_CLOEXEC, 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, malloc, pg_conn::md5Salt, 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(), pqGetnchar(), 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(), and PQresetPoll().

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

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

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

Referenced by PQconnectdb(), and PQping().

654 {
655  PGconn *conn;
656 
657  /*
658  * Allocate memory for the conn structure
659  */
660  conn = makeEmptyPGconn();
661  if (conn == NULL)
662  return NULL;
663 
664  /*
665  * Parse the conninfo string
666  */
667  if (!connectOptions1(conn, conninfo))
668  return conn;
669 
670  /*
671  * Compute derived options
672  */
673  if (!connectOptions2(conn))
674  return conn;
675 
676  /*
677  * Connect to the database
678  */
679  if (!connectDBStart(conn))
680  {
681  /* Just in case we failed to set it in connectDBStart */
682  conn->status = CONNECTION_BAD;
683  }
684 
685  return conn;
686 }
static bool connectOptions1(PGconn *conn, const char *conninfo)
Definition: fe-connect.c:739
PGconn * conn
Definition: streamutil.c:45
static int connectDBStart(PGconn *conn)
Definition: fe-connect.c:1574
static PGconn * makeEmptyPGconn(void)
Definition: fe-connect.c:3160
#define NULL
Definition: c.h:226
ConnStatusType status
Definition: libpq-int.h:380
static bool connectOptions2(PGconn *conn)
Definition: fe-connect.c:781
PGconn* PQconnectStartParams ( const char *const *  keywords,
const char *const *  values,
int  expand_dbname 
)

Definition at line 574 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 PQconnectdbParams(), and PQpingParams().

577 {
578  PGconn *conn;
579  PQconninfoOption *connOptions;
580 
581  /*
582  * Allocate memory for the conn structure
583  */
584  conn = makeEmptyPGconn();
585  if (conn == NULL)
586  return NULL;
587 
588  /*
589  * Parse the conninfo arrays
590  */
591  connOptions = conninfo_array_parse(keywords, values,
592  &conn->errorMessage,
593  true, expand_dbname);
594  if (connOptions == NULL)
595  {
596  conn->status = CONNECTION_BAD;
597  /* errorMessage is already set */
598  return conn;
599  }
600 
601  /*
602  * Move option values into conn structure
603  */
604  if (!fillPGconn(conn, connOptions))
605  {
606  PQconninfoFree(connOptions);
607  return conn;
608  }
609 
610  /*
611  * Free the option info - all is in conn now
612  */
613  PQconninfoFree(connOptions);
614 
615  /*
616  * Compute derived options
617  */
618  if (!connectOptions2(conn))
619  return conn;
620 
621  /*
622  * Connect to the database
623  */
624  if (!connectDBStart(conn))
625  {
626  /* Just in case we failed to set it in connectDBStart */
627  conn->status = CONNECTION_BAD;
628  }
629 
630  return conn;
631 }
PGconn * conn
Definition: streamutil.c:45
static int connectDBStart(PGconn *conn)
Definition: fe-connect.c:1574
void PQconninfoFree(PQconninfoOption *connOptions)
Definition: fe-connect.c:5810
static PGconn * makeEmptyPGconn(void)
Definition: fe-connect.c:3160
PQExpBufferData errorMessage
Definition: libpq-int.h:498
#define NULL
Definition: c.h:226
static bool fillPGconn(PGconn *conn, PQconninfoOption *connOptions)
Definition: fe-connect.c:697
ConnStatusType status
Definition: libpq-int.h:380
static Datum values[MAXATTR]
Definition: bootstrap.c:162
static bool connectOptions2(PGconn *conn)
Definition: fe-connect.c:781
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:4898
PQconninfoOption* PQconninfo ( PGconn conn)

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

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

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

5770 {
5771  PQExpBufferData errorBuf;
5772  PQconninfoOption *connOptions;
5773 
5774  if (conn == NULL)
5775  return NULL;
5776 
5777  /* We don't actually report any errors here, but callees want a buffer */
5778  initPQExpBuffer(&errorBuf);
5779  if (PQExpBufferDataBroken(errorBuf))
5780  return NULL; /* out of memory already :-( */
5781 
5782  connOptions = conninfo_init(&errorBuf);
5783 
5784  if (connOptions != NULL)
5785  {
5787 
5788  for (option = PQconninfoOptions; option->keyword; option++)
5789  {
5790  char **connmember;
5791 
5792  if (option->connofs < 0)
5793  continue;
5794 
5795  connmember = (char **) ((char *) conn + option->connofs);
5796 
5797  if (*connmember)
5798  conninfo_storeval(connOptions, option->keyword, *connmember,
5799  &errorBuf, true, false);
5800  }
5801  }
5802 
5803  termPQExpBuffer(&errorBuf);
5804 
5805  return connOptions;
5806 }
static PQconninfoOption * conninfo_storeval(PQconninfoOption *connOptions, const char *keyword, const char *value, PQExpBuffer errorMessage, bool ignoreMissing, bool uri_decode)
Definition: fe-connect.c:5686
void termPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:128
static PQconninfoOption * conninfo_init(PQExpBuffer errorMessage)
Definition: fe-connect.c:4626
static const internalPQconninfoOption PQconninfoOptions[]
Definition: fe-connect.c:167
#define PQExpBufferDataBroken(buf)
Definition: pqexpbuffer.h:67
#define NULL
Definition: c.h:226
void initPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:89
void PQconninfoFree ( PQconninfoOption connOptions)

Definition at line 5810 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(), GenerateRecoveryConf(), GetConnection(), libpqrcv_check_conninfo(), libpqrcv_get_conninfo(), PQconndefaults(), and PQconnectStartParams().

5811 {
5813 
5814  if (connOptions == NULL)
5815  return;
5816 
5817  for (option = connOptions; option->keyword != NULL; option++)
5818  {
5819  if (option->val != NULL)
5820  free(option->val);
5821  }
5822  free(connOptions);
5823 }
#define free(a)
Definition: header.h:60
#define NULL
Definition: c.h:226
PQconninfoOption* PQconninfoParse ( const char *  conninfo,
char **  errmsg 
)

Definition at line 4604 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().

4605 {
4606  PQExpBufferData errorBuf;
4607  PQconninfoOption *connOptions;
4608 
4609  if (errmsg)
4610  *errmsg = NULL; /* default */
4611  initPQExpBuffer(&errorBuf);
4612  if (PQExpBufferDataBroken(errorBuf))
4613  return NULL; /* out of memory already :-( */
4614  connOptions = parse_connection_string(conninfo, &errorBuf, false);
4615  if (connOptions == NULL && errmsg)
4616  *errmsg = errorBuf.data;
4617  else
4618  termPQExpBuffer(&errorBuf);
4619  return connOptions;
4620 }
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:4666
#define PQExpBufferDataBroken(buf)
Definition: pqexpbuffer.h:67
#define NULL
Definition: c.h:226
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:683
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:166
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:190
PGresAttDesc * attDescs
Definition: libpq-int.h:173
#define PG_COPYRES_TUPLES
Definition: libpq-fe.h:35
PGresAttValue ** tuples
Definition: libpq-int.h:174
#define PG_COPYRES_EVENTS
Definition: libpq-fe.h:36
PGNoticeHooks noticeHooks
Definition: libpq-int.h:188
#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:172
#define PG_COPYRES_ATTRS
Definition: libpq-fe.h:34
void PQclear(PGresult *res)
Definition: fe-exec.c:650
int ntups
Definition: libpq-int.h:171
#define NULL
Definition: c.h:226
PGEventProc proc
Definition: libpq-int.h:162
char cmdStatus[CMDSTATUS_LEN]
Definition: libpq-int.h:180
int i
void * passThrough
Definition: libpq-int.h:164
char * value
Definition: libpq-int.h:140
#define TRUE
Definition: c.h:214
PGEvent * events
Definition: libpq-int.h:189
PGresult * dest
Definition: libpq-events.h:61
int client_encoding
Definition: libpq-int.h:191
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:226
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:226
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:45
#define free(a)
Definition: header.h:60
#define DEFAULT_FIELD_SEP
#define NULL
Definition: c.h:226
int i
#define libpq_gettext(x)
Definition: libpq-int.h:689
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:121
char* PQencryptPassword ( const char *  passwd,
const char *  user 
)

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

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

Referenced by exec_command(), and main().

818 {
819  char *crypt_pwd;
820 
821  crypt_pwd = malloc(MD5_PASSWD_LEN + 1);
822  if (!crypt_pwd)
823  return NULL;
824 
825  if (!pg_md5_encrypt(passwd, user, strlen(user), crypt_pwd))
826  {
827  free(crypt_pwd);
828  return NULL;
829  }
830 
831  return crypt_pwd;
832 }
#define malloc(a)
Definition: header.h:45
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:60
#define NULL
Definition: c.h:226
static char * user
Definition: pg_regress.c:90
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:406
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:475
static char * encoding
Definition: initdb.c:121
char* PQerrorMessage ( const PGconn conn)

Definition at line 5960 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_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_command(), libpqrcv_connect(), libpqrcv_create_slot(), libpqrcv_endstreaming(), libpqrcv_identify_system(), libpqrcv_readtimelinehistoryfile(), libpqrcv_receive(), libpqrcv_send(), libpqrcv_startstreaming(), main(), my_truncate(), overwrite(), 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().

5961 {
5962  if (!conn)
5963  return libpq_gettext("connection pointer is NULL\n");
5964 
5965  return conn->errorMessage.data;
5966 }
PQExpBufferData errorMessage
Definition: libpq-int.h:498
#define libpq_gettext(x)
Definition: libpq-int.h:689
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:226
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:407
bool std_strings
Definition: libpq-int.h:427
#define NULL
Definition: c.h:226
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:226
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:427
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:426
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:226
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:226
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:226
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:173
static int check_field_number(const PGresult *res, int field_num)
Definition: fe-exec.c:2702
void PQfinish ( PGconn conn)

Definition at line 3517 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_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().

3518 {
3519  if (conn)
3520  {
3521  closePGconn(conn);
3522  freePGconn(conn);
3523  }
3524 }
static void closePGconn(PGconn *conn)
Definition: fe-connect.c:3428
static void freePGconn(PGconn *conn)
Definition: fe-connect.c:3256
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:173
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:454
PGAsyncStatusType asyncStatus
Definition: libpq-int.h:381
pgsocket sock
Definition: libpq-int.h:402
#define PGINVALID_SOCKET
Definition: port.h:24
PQExpBufferData errorMessage
Definition: libpq-int.h:498
#define NULL
Definition: c.h:226
ProtocolVersion pversion
Definition: libpq-int.h:406
void resetPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:145
#define libpq_gettext(x)
Definition: libpq-int.h:689
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(), 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:173
static int check_field_number(const PGresult *res, int field_num)
Definition: fe-exec.c:2702
#define NULL
Definition: c.h:226
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(), 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