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

Go to the source code of this file.

Data Structures

struct  pgNotify
 
struct  _PQprintOpt
 
struct  _PQconninfoOption
 
struct  PQArgBlock
 
struct  pgresAttDesc
 

Macros

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

Typedefs

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

Enumerations

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

Functions

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

Macro Definition Documentation

#define PG_COPYRES_ATTRS   0x01

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

Referenced by PQcopyResult(), and pqRowProcessor().

#define PG_COPYRES_EVENTS   0x04

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

Referenced by PQcopyResult(), and pqRowProcessor().

#define PG_COPYRES_NOTICEHOOKS   0x08

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

Referenced by PQcopyResult(), and pqRowProcessor().

#define PG_COPYRES_TUPLES   0x02 /* Implies PG_COPYRES_ATTRS */

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

Referenced by PQcopyResult().

#define PQfreeNotify (   ptr)    PQfreemem(ptr)

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

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

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

Referenced by pg_fe_sendauth(), and pg_SASL_init().

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

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

Referenced by main().

Typedef Documentation

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

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

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

typedef void(* pgthreadlock_t)(int acquire)

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

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

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

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

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

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

Enumeration Type Documentation

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Function Documentation

int lo_close ( PGconn conn,
int  fd 
)

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

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

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

101 {
102  PQArgBlock argv[1];
103  PGresult *res;
104  int retval;
105  int result_len;
106 
107  if (conn == NULL || conn->lobjfuncs == NULL)
108  {
109  if (lo_initialize(conn) < 0)
110  return -1;
111  }
112 
113  argv[0].isint = 1;
114  argv[0].len = 4;
115  argv[0].u.integer = fd;
116  res = PQfn(conn, conn->lobjfuncs->fn_lo_close,
117  &retval, &result_len, 1, argv, 1);
118  if (PQresultStatus(res) == PGRES_COMMAND_OK)
119  {
120  PQclear(res);
121  return retval;
122  }
123  else
124  {
125  PQclear(res);
126  return -1;
127  }
128 }
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:229
Oid fn_lo_close
Definition: libpq-int.h:268
int isint
Definition: libpq-fe.h:223
PGlobjfuncs * lobjfuncs
Definition: libpq-int.h:428
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:229
Oid fn_lo_creat
Definition: libpq-int.h:269
int isint
Definition: libpq-fe.h:223
PGlobjfuncs * lobjfuncs
Definition: libpq-int.h:428
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:270
unsigned int Oid
Definition: postgres_ext.h:31
PGresult * PQfn(PGconn *conn, int fnid, int *result_buf, int *result_len, int result_is_int, const PQArgBlock *args, int nargs)
Definition: fe-exec.c:2556
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:2596
union PQArgBlock::@94 u
PQExpBufferData errorMessage
Definition: libpq-int.h:501
#define InvalidOid
Definition: postgres_ext.h:36
void PQclear(PGresult *res)
Definition: fe-exec.c:650
#define NULL
Definition: c.h:229
int isint
Definition: libpq-fe.h:223
PGlobjfuncs * lobjfuncs
Definition: libpq-int.h:428
#define libpq_gettext(x)
Definition: libpq-int.h:692
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:501
#define LO_BUFSIZE
Definition: fe-lobj.c:43
static char * filename
Definition: pg_dumpall.c:87
int lo_read(PGconn *conn, int fd, char *buf, size_t len)
Definition: fe-lobj.c:259
#define close(a)
Definition: win32.h:17
#define libpq_gettext(x)
Definition: libpq-int.h:692
Oid lo_import ( PGconn conn,
const char *  filename 
)

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

References InvalidOid, and lo_import_internal().

Referenced by do_lo_import(), and main().

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

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

References lo_import_internal().

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

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

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

Referenced by overwrite(), and pickout().

367 {
368  PQArgBlock argv[3];
369  PGresult *res;
370  int retval;
371  int result_len;
372 
373  if (conn == NULL || conn->lobjfuncs == NULL)
374  {
375  if (lo_initialize(conn) < 0)
376  return -1;
377  }
378 
379  argv[0].isint = 1;
380  argv[0].len = 4;
381  argv[0].u.integer = fd;
382 
383  argv[1].isint = 1;
384  argv[1].len = 4;
385  argv[1].u.integer = offset;
386 
387  argv[2].isint = 1;
388  argv[2].len = 4;
389  argv[2].u.integer = whence;
390 
391  res = PQfn(conn, conn->lobjfuncs->fn_lo_lseek,
392  &retval, &result_len, 1, argv, 3);
393  if (PQresultStatus(res) == PGRES_COMMAND_OK)
394  {
395  PQclear(res);
396  return retval;
397  }
398  else
399  {
400  PQclear(res);
401  return -1;
402  }
403 }
Oid fn_lo_lseek
Definition: libpq-int.h:272
PGresult * PQfn(PGconn *conn, int fnid, int *result_buf, int *result_len, int result_is_int, const PQArgBlock *args, int nargs)
Definition: fe-exec.c:2556
static int fd(const char *x, int i)
Definition: preproc-init.c:105
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:2596
union PQArgBlock::@94 u
void PQclear(PGresult *res)
Definition: fe-exec.c:650
#define NULL
Definition: c.h:229
int isint
Definition: libpq-fe.h:223
PGlobjfuncs * lobjfuncs
Definition: libpq-int.h:428
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:47
static pg_int64 lo_hton64(pg_int64 host64)
Definition: fe-lobj.c:1062
union PQArgBlock::@94 u
PQExpBufferData errorMessage
Definition: libpq-int.h:501
void PQclear(PGresult *res)
Definition: fe-exec.c:650
#define NULL
Definition: c.h:229
Oid fn_lo_lseek64
Definition: libpq-int.h:273
int isint
Definition: libpq-fe.h:223
PGlobjfuncs * lobjfuncs
Definition: libpq-int.h:428
int * ptr
Definition: libpq-fe.h:226
#define libpq_gettext(x)
Definition: libpq-int.h:692
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:267
union PQArgBlock::@94 u
void PQclear(PGresult *res)
Definition: fe-exec.c:650
#define NULL
Definition: c.h:229
int isint
Definition: libpq-fe.h:223
PGlobjfuncs * lobjfuncs
Definition: libpq-int.h:428
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:278
static char * buf
Definition: pg_test_fsync.c:65
union PQArgBlock::@94 u
PQExpBufferData errorMessage
Definition: libpq-int.h:501
void PQclear(PGresult *res)
Definition: fe-exec.c:650
#define NULL
Definition: c.h:229
int isint
Definition: libpq-fe.h:223
PGlobjfuncs * lobjfuncs
Definition: libpq-int.h:428
#define libpq_gettext(x)
Definition: libpq-int.h:692
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:274
void PQclear(PGresult *res)
Definition: fe-exec.c:650
#define NULL
Definition: c.h:229
int isint
Definition: libpq-fe.h:223
PGlobjfuncs * lobjfuncs
Definition: libpq-int.h:428
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:47
Oid fn_lo_tell64
Definition: libpq-int.h:275
union PQArgBlock::@94 u
PQExpBufferData errorMessage
Definition: libpq-int.h:501
void PQclear(PGresult *res)
Definition: fe-exec.c:650
#define NULL
Definition: c.h:229
int isint
Definition: libpq-fe.h:223
PGlobjfuncs * lobjfuncs
Definition: libpq-int.h:428
#define libpq_gettext(x)
Definition: libpq-int.h:692
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:276
union PQArgBlock::@94 u
PQExpBufferData errorMessage
Definition: libpq-int.h:501
void PQclear(PGresult *res)
Definition: fe-exec.c:650
#define NULL
Definition: c.h:229
int isint
Definition: libpq-fe.h:223
PGlobjfuncs * lobjfuncs
Definition: libpq-int.h:428
#define libpq_gettext(x)
Definition: libpq-int.h:692
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:277
PQExpBufferData errorMessage
Definition: libpq-int.h:501
void PQclear(PGresult *res)
Definition: fe-exec.c:650
#define NULL
Definition: c.h:229
int isint
Definition: libpq-fe.h:223
PGlobjfuncs * lobjfuncs
Definition: libpq-int.h:428
int * ptr
Definition: libpq-fe.h:226
#define libpq_gettext(x)
Definition: libpq-int.h:692
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:229
Oid fn_lo_unlink
Definition: libpq-int.h:271
int isint
Definition: libpq-fe.h:223
PGlobjfuncs * lobjfuncs
Definition: libpq-int.h:428
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:279
PGresult * PQfn(PGconn *conn, int fnid, int *result_buf, int *result_len, int result_is_int, const PQArgBlock *args, int nargs)
Definition: fe-exec.c:2556
static int fd(const char *x, int i)
Definition: preproc-init.c:105
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:2596
static char * buf
Definition: pg_test_fsync.c:65
union PQArgBlock::@94 u
PQExpBufferData errorMessage
Definition: libpq-int.h:501
void PQclear(PGresult *res)
Definition: fe-exec.c:650
#define NULL
Definition: c.h:229
int isint
Definition: libpq-fe.h:223
PGlobjfuncs * lobjfuncs
Definition: libpq-int.h:428
int * ptr
Definition: libpq-fe.h:226
#define libpq_gettext(x)
Definition: libpq-int.h:692
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:562
#define NAMEDATALEN
#define ERROR
Definition: elog.h:43
static const pg_encname pg_encname_tbl[]
Definition: encnames.c:38
#define ereport(elevel, rest)
Definition: elog.h:122
#define NULL
Definition: c.h:229
const char * name
Definition: encode.c:521
int errmsg(const char *fmt,...)
Definition: elog.c:797
static char * clean_encoding_name(const char *key, char *newkey)
Definition: encnames.c: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 6037 of file fe-connect.c.

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

Referenced by get_prompt().

6038 {
6039  if (!conn || conn->status != CONNECTION_OK)
6040  return 0;
6041  return conn->be_pid;
6042 }
ConnStatusType status
Definition: libpq-int.h:378
int be_pid
Definition: libpq-int.h:420
int PQbinaryTuples ( const PGresult res)

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

References pg_result::binary.

Referenced by ProcessResult().

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

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

3845 {
3846  if (!cancel)
3847  {
3848  strlcpy(errbuf, "PQcancel() -- no cancel object supplied", errbufsize);
3849  return FALSE;
3850  }
3851 
3852  return internal_cancel(&cancel->raddr, cancel->be_pid, cancel->be_key,
3853  errbuf, errbufsize);
3854 }
static int internal_cancel(SockAddr *raddr, int be_pid, int be_key, char *errbuf, int errbufsize)
Definition: fe-connect.c:3740
int be_pid
Definition: libpq-int.h:514
#define FALSE
Definition: c.h:221
int be_key
Definition: libpq-int.h:515
size_t strlcpy(char *dst, const char *src, size_t siz)
Definition: strlcpy.c:45
SockAddr raddr
Definition: libpq-int.h:513
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(), pg_attribute_noreturn(), pgfdw_get_result(), pgfdw_report_error(), pgfdw_subxact_callback(), pgfdw_xact_callback(), postgresAcquireSampleRowsFunc(), postgresAnalyzeForeignTable(), postgresEndDirectModify(), postgresEndForeignModify(), postgresExecForeignDelete(), postgresExecForeignInsert(), postgresExecForeignUpdate(), postgresImportForeignSchema(), postgresReScanForeignScan(), pqClearAsyncResult(), PQconnectPoll(), PQcopyResult(), pqEndcopy2(), pqEndcopy3(), PQexecFinish(), PQexecStart(), pqGetErrorNotice2(), pqGetErrorNotice3(), pqInternalNotice(), PQmakeEmptyPGresult(), pqRowProcessor(), PQsetClientEncoding(), pqSetenvPoll(), prepare_common(), prepare_foreign_modify(), processExtensionTables(), ProcessResult(), PSQLexecWatch(), receiveFileChunks(), ReceiveXlogStream(), reindex_all_databases(), run_permutation(), run_simple_query(), RunIdentifySystem(), sendCommand(), SendQuery(), set_frozenxids(), sql_exec(), start_lo_xact(), store_returning_result(), storeQueryResult(), StreamLogicalLog(), try_complete_step(), tryExecuteStatement(), vacuum_all_databases(), vacuum_one_database(), and vacuumlo().

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

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

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

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

6072 {
6073  if (!conn || conn->status != CONNECTION_OK)
6074  return -1;
6075  return conn->client_encoding;
6076 }
ConnStatusType status
Definition: libpq-int.h:378
int client_encoding
Definition: libpq-int.h:424
char* PQcmdStatus ( PGresult res)

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

References pg_result::cmdStatus, and NULL.

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

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

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

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

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

3015 {
3016  char *p,
3017  *c;
3018 
3019  if (!res)
3020  return "";
3021 
3022  if (strncmp(res->cmdStatus, "INSERT ", 7) == 0)
3023  {
3024  p = res->cmdStatus + 7;
3025  /* INSERT: skip oid and space */
3026  while (*p && *p != ' ')
3027  p++;
3028  if (*p == 0)
3029  goto interpret_error; /* no space? */
3030  p++;
3031  }
3032  else if (strncmp(res->cmdStatus, "SELECT ", 7) == 0 ||
3033  strncmp(res->cmdStatus, "DELETE ", 7) == 0 ||
3034  strncmp(res->cmdStatus, "UPDATE ", 7) == 0)
3035  p = res->cmdStatus + 7;
3036  else if (strncmp(res->cmdStatus, "FETCH ", 6) == 0)
3037  p = res->cmdStatus + 6;
3038  else if (strncmp(res->cmdStatus, "MOVE ", 5) == 0 ||
3039  strncmp(res->cmdStatus, "COPY ", 5) == 0)
3040  p = res->cmdStatus + 5;
3041  else
3042  return "";
3043 
3044  /* check that we have an integer (at least one digit, nothing else) */
3045  for (c = p; *c; c++)
3046  {
3047  if (!isdigit((unsigned char) *c))
3048  goto interpret_error;
3049  }
3050  if (c == p)
3051  goto interpret_error;
3052 
3053  return p;
3054 
3055 interpret_error:
3057  "could not interpret result from server: %s",
3058  res->cmdStatus);
3059  return "";
3060 }
PGNoticeHooks noticeHooks
Definition: libpq-int.h:186
char * c
void pqInternalNotice(const PGNoticeHooks *hooks, const char *fmt,...)
Definition: fe-exec.c:801
char cmdStatus[CMDSTATUS_LEN]
Definition: libpq-int.h:178
PQconninfoOption* PQconndefaults ( void  )

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

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

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

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

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

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

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

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

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

473 {
474  PGconn *conn = PQconnectStartParams(keywords, values, expand_dbname);
475 
476  if (conn && conn->status != CONNECTION_BAD)
477  (void) connectDBComplete(conn);
478 
479  return conn;
480 
481 }
PGconn * conn
Definition: streamutil.c:42
static int connectDBComplete(PGconn *conn)
Definition: fe-connect.c:1714
ConnStatusType status
Definition: libpq-int.h:378
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:573
int PQconnectionNeedsPassword ( const PGconn conn)

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

6046 {
6047  char *password;
6048 
6049  if (!conn)
6050  return false;
6051  password = PQpass(conn);
6052  if (conn->password_needed &&
6053  (password == NULL || password[0] == '\0'))
6054  return true;
6055  else
6056  return false;
6057 }
static char password[100]
Definition: streamutil.c:41
bool password_needed
Definition: libpq-int.h:408
char * PQpass(const PGconn *conn)
Definition: fe-connect.c:5895
#define NULL
Definition: c.h:229
int PQconnectionUsedPassword ( const PGconn conn)

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

References pg_conn::password_needed.

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

6061 {
6062  if (!conn)
6063  return false;
6064  if (conn->password_needed)
6065  return true;
6066  else
6067  return false;
6068 }
bool password_needed
Definition: libpq-int.h:408
PostgresPollingStatusType PQconnectPoll ( PGconn conn)

Definition at line 1848 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, pg_conn::auth_req_inbuf, pg_conn::auth_req_inlen, AUTH_REQ_MD5, AUTH_REQ_OK, pg_conn::auth_req_received, AUTH_REQ_SASL, AUTH_REQ_SASL_CONT, 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(), libpqrcv_connect(), and PQresetPoll().

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

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

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

Referenced by PQconnectdb(), and PQping().

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

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

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

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

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

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

5821 {
5822  PQExpBufferData errorBuf;
5823  PQconninfoOption *connOptions;
5824 
5825  if (conn == NULL)
5826  return NULL;
5827 
5828  /* We don't actually report any errors here, but callees want a buffer */
5829  initPQExpBuffer(&errorBuf);
5830  if (PQExpBufferDataBroken(errorBuf))
5831  return NULL; /* out of memory already :-( */
5832 
5833  connOptions = conninfo_init(&errorBuf);
5834 
5835  if (connOptions != NULL)
5836  {
5838 
5839  for (option = PQconninfoOptions; option->keyword; option++)
5840  {
5841  char **connmember;
5842 
5843  if (option->connofs < 0)
5844  continue;
5845 
5846  connmember = (char **) ((char *) conn + option->connofs);
5847 
5848  if (*connmember)
5849  conninfo_storeval(connOptions, option->keyword, *connmember,
5850  &errorBuf, true, false);
5851  }
5852  }
5853 
5854  termPQExpBuffer(&errorBuf);
5855 
5856  return connOptions;
5857 }
static PQconninfoOption * conninfo_storeval(PQconninfoOption *connOptions, const char *keyword, const char *value, PQExpBuffer errorMessage, bool ignoreMissing, bool uri_decode)
Definition: fe-connect.c:5737
void termPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:128
static PQconninfoOption * conninfo_init(PQExpBuffer errorMessage)
Definition: fe-connect.c:4677
static const internalPQconninfoOption PQconninfoOptions[]
Definition: fe-connect.c:166
#define PQExpBufferDataBroken(buf)
Definition: pqexpbuffer.h:67
#define NULL
Definition: c.h:229
void initPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:89
void PQconninfoFree ( PQconninfoOption connOptions)

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

5862 {
5864 
5865  if (connOptions == NULL)
5866  return;
5867 
5868  for (option = connOptions; option->keyword != NULL; option++)
5869  {
5870  if (option->val != NULL)
5871  free(option->val);
5872  }
5873  free(connOptions);
5874 }
#define free(a)
Definition: header.h:65
#define NULL
Definition: c.h:229
PQconninfoOption* PQconninfoParse ( const char *  conninfo,
char **  errmsg 
)

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

4656 {
4657  PQExpBufferData errorBuf;
4658  PQconninfoOption *connOptions;
4659 
4660  if (errmsg)
4661  *errmsg = NULL; /* default */
4662  initPQExpBuffer(&errorBuf);
4663  if (PQExpBufferDataBroken(errorBuf))
4664  return NULL; /* out of memory already :-( */
4665  connOptions = parse_connection_string(conninfo, &errorBuf, false);
4666  if (connOptions == NULL && errmsg)
4667  *errmsg = errorBuf.data;
4668  else
4669  termPQExpBuffer(&errorBuf);
4670  return connOptions;
4671 }
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:4717
#define PQExpBufferDataBroken(buf)
Definition: pqexpbuffer.h:67
#define NULL
Definition: c.h:229
int errmsg(const char *fmt,...)
Definition: elog.c:797
void initPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:89
int PQconsumeInput ( PGconn conn)

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

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

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

1632 {
1633  if (!conn)
1634  return 0;
1635 
1636  /*
1637  * for non-blocking connections try to flush the send-queue, otherwise we
1638  * may never get a response for something that may not have already been
1639  * sent because it's in our write buffer!
1640  */
1641  if (pqIsnonblocking(conn))
1642  {
1643  if (pqFlush(conn) < 0)
1644  return 0;
1645  }
1646 
1647  /*
1648  * Load more data, if available. We do this no matter what state we are
1649  * in, since we are probably getting called because the application wants
1650  * to get rid of a read-select condition. Note that we will NOT block
1651  * waiting for more input.
1652  */
1653  if (pqReadData(conn) < 0)
1654  return 0;
1655 
1656  /* Parsing of the data waits till later. */
1657  return 1;
1658 }
int pqFlush(PGconn *conn)
Definition: fe-misc.c:966
#define pqIsnonblocking(conn)
Definition: libpq-int.h:686
int pqReadData(PGconn *conn)
Definition: fe-misc.c:634
PGresult* PQcopyResult ( const PGresult src,
int  flags 
)

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

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

Referenced by pqRowProcessor().

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

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

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

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

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

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

Referenced by ECPGdescribe().

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

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

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

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

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

Referenced by exec_command(), and main().

931 {
932  char *crypt_pwd;
933 
934  crypt_pwd = malloc(MD5_PASSWD_LEN + 1);
935  if (!crypt_pwd)
936  return NULL;
937 
938  if (!pg_md5_encrypt(passwd, user, strlen(user), crypt_pwd))
939  {
940  free(crypt_pwd);
941  return NULL;
942  }
943 
944  return crypt_pwd;
945 }
#define malloc(a)
Definition: header.h:50
bool pg_md5_encrypt(const char *passwd, const char *salt, size_t salt_len, char *buf)
Definition: md5.c:323
#define MD5_PASSWD_LEN
Definition: md5.h:19
#define free(a)
Definition: header.h:65
#define NULL
Definition: c.h:229
static char * user
Definition: pg_regress.c:92
int PQendcopy ( PGconn conn)

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

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

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

2523 {
2524  if (!conn)
2525  return 0;
2526 
2527  if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
2528  return pqEndcopy3(conn);
2529  else
2530  return pqEndcopy2(conn);
2531 }
#define PG_PROTOCOL_MAJOR(v)
Definition: pqcomm.h:104
int pqEndcopy3(PGconn *conn)
ProtocolVersion pversion
Definition: libpq-int.h:404
int pqEndcopy2(PGconn *conn)
int PQenv2encoding ( void  )

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

References encoding, pg_char_to_encoding(), and PG_SQL_ASCII.

Referenced by main().

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

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

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

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

6012 {
6013  if (!conn)
6014  return libpq_gettext("connection pointer is NULL\n");
6015 
6016  return conn->errorMessage.data;
6017 }
PQExpBufferData errorMessage
Definition: libpq-int.h:501
#define libpq_gettext(x)
Definition: libpq-int.h:692
unsigned char* PQescapeBytea ( const unsigned char *  from,
size_t  from_length,
size_t *  to_length 
)

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

References NULL, PQescapeByteaInternal(), and static_std_strings.

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

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

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

3621 {
3622  if (!conn)
3623  return NULL;
3624  return PQescapeByteaInternal(conn, from, from_length, to_length,
3625  conn->std_strings,
3626  (conn->sversion >= 90000));
3627 }
int sversion
Definition: libpq-int.h:405
bool std_strings
Definition: libpq-int.h:425
#define NULL
Definition: c.h:229
static unsigned char * PQescapeByteaInternal(PGconn *conn, const unsigned char *from, size_t from_length, size_t *to_length, bool std_strings, bool use_hex)
Definition: fe-exec.c:3521
char* PQescapeIdentifier ( PGconn conn,
const char *  str,
size_t  len 
)

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

References PQescapeInternal().

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

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

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

References PQescapeInternal().

Referenced by libpqrcv_startstreaming(), and psql_get_variable().

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

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

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

Referenced by get_comma_elts(), and quote_postgres().

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

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

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

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

3317 {
3318  if (!conn)
3319  {
3320  /* force empty-string result */
3321  *to = '\0';
3322  if (error)
3323  *error = 1;
3324  return 0;
3325  }
3326  return PQescapeStringInternal(conn, to, from, length, error,
3327  conn->client_encoding,
3328  conn->std_strings);
3329 }
int length(const List *list)
Definition: list.c:1271
static void error(void)
Definition: sql-dyntest.c:147
bool std_strings
Definition: libpq-int.h:425
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:424
PGresult* PQexec ( PGconn conn,
const char *  query 
)

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

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

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

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

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

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

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

1868 {
1869  if (!PQexecStart(conn))
1870  return NULL;
1871  if (!PQsendQueryParams(conn, command,
1872  nParams, paramTypes, paramValues, paramLengths,
1873  paramFormats, resultFormat))
1874  return NULL;
1875  return PQexecFinish(conn);
1876 }
int PQsendQueryParams(PGconn *conn, const char *command, int nParams, const Oid *paramTypes, const char *const *paramValues, const int *paramLengths, const int *paramFormats, int resultFormat)
Definition: fe-exec.c:1183
#define NULL
Definition: c.h:229
static PGresult * PQexecFinish(PGconn *conn)
Definition: fe-exec.c:2002
static bool PQexecStart(PGconn *conn)
Definition: fe-exec.c:1928
PGresult* PQexecPrepared ( PGconn conn,
const char *  stmtName,
int  nParams,
const char *const *  paramValues,
const int *  paramLengths,
const int *  paramFormats,
int  resultFormat 
)

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

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

Referenced by ecpg_execute(), and try_complete_step().

1914 {
1915  if (!PQexecStart(conn))
1916  return NULL;
1917  if (!PQsendQueryPrepared(conn, stmtName,
1918  nParams, paramValues, paramLengths,
1919  paramFormats, resultFormat))
1920  return NULL;
1921  return PQexecFinish(conn);
1922 }
#define NULL
Definition: c.h:229
static PGresult * PQexecFinish(PGconn *conn)
Definition: fe-exec.c:2002
int PQsendQueryPrepared(PGconn *conn, const char *stmtName, int nParams, const char *const *paramValues, const int *paramLengths, const int *paramFormats, int resultFormat)
Definition: fe-exec.c:1325
static bool PQexecStart(PGconn *conn)
Definition: fe-exec.c:1928
int PQfformat ( const PGresult res,
int  field_num 
)

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

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

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

2901 {
2902  if (!check_field_number(res, field_num))
2903  return 0;
2904  if (res->attDescs)
2905  return res->attDescs[field_num].format;
2906  else
2907  return 0;
2908 }
PGresAttDesc * attDescs
Definition: libpq-int.h:171
static int check_field_number(const PGresult *res, int field_num)
Definition: fe-exec.c:2702
void PQfinish ( PGconn conn)

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

References closePGconn(), and freePGconn().

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

3569 {
3570  if (conn)
3571  {
3572  closePGconn(conn);
3573  freePGconn(conn);
3574  }
3575 }
static void closePGconn(PGconn *conn)
Definition: fe-connect.c:3470
static void freePGconn(PGconn *conn)
Definition: fe-connect.c:3298
int PQflush ( PGconn conn)

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

References pqFlush().

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

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

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

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

Referenced by ECPGget_desc().

2934 {
2935  if (!check_field_number(res, field_num))
2936  return 0;
2937  if (res->attDescs)
2938  return res->attDescs[field_num].atttypmod;
2939  else
2940  return 0;
2941 }
PGresAttDesc * attDescs
Definition: libpq-int.h:171
int atttypmod
Definition: libpq-fe.h:243
static int check_field_number(const PGresult *res, int field_num)
Definition: fe-exec.c:2702
PGresult* PQfn ( PGconn conn,
int  fnid,
int *  result_buf,
int *  result_len,
int  result_is_int,
const PQArgBlock args,
int  nargs 
)

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

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

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

2563 {
2564  *result_len = 0;
2565 
2566  if (!conn)
2567  return NULL;
2568 
2569  /* clear the error string */
2571 
2572  if (conn->sock == PGINVALID_SOCKET || conn->asyncStatus != PGASYNC_IDLE ||
2573  conn->result != NULL)
2574  {
2576  libpq_gettext("connection in wrong state\n"));
2577  return NULL;
2578  }
2579 
2580  if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
2581  return pqFunctionCall3(conn, fnid,
2582  result_buf, result_len,
2583  result_is_int,
2584  args, nargs);
2585  else
2586  return pqFunctionCall2(conn, fnid,
2587  result_buf, result_len,
2588  result_is_int,
2589  args, nargs);
2590 }
void printfPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:234
PGresult * pqFunctionCall2(PGconn *conn, Oid fnid, int *result_buf, int *actual_result_len, int result_is_int, const PQArgBlock *args, int nargs)
PGresult * pqFunctionCall3(PGconn *conn, Oid fnid, int *result_buf, int *actual_result_len, int result_is_int, const PQArgBlock *args, int nargs)
#define PG_PROTOCOL_MAJOR(v)
Definition: pqcomm.h:104
PGresult * result
Definition: libpq-int.h:452
PGAsyncStatusType asyncStatus
Definition: libpq-int.h:379
pgsocket sock
Definition: libpq-int.h:400
#define PGINVALID_SOCKET
Definition: port.h:24
PQExpBufferData errorMessage
Definition: libpq-int.h:501
#define NULL
Definition: c.h:229
ProtocolVersion pversion
Definition: libpq-int.h:404
void resetPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:145
#define libpq_gettext(x)
Definition: libpq-int.h:692
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:171
static int check_field_number(const PGresult *res, int field_num)
Definition: fe-exec.c:2702
#define NULL
Definition: c.h:229
char * name
Definition: libpq-fe.h:237