PostgreSQL Source Code  git master
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 LIBPQ_HAS_PIPELINING   1
 
#define LIBPQ_HAS_TRACE_FLAGS   1
 
#define LIBPQ_HAS_SSL_LIBRARY_DETECTION   1
 
#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 PQTRACE_SUPPRESS_TIMESTAMPS   (1<<0)
 
#define PQTRACE_REGRESS_MODE   (1<<1)
 
#define PQ_QUERY_PARAM_MAX_LIMIT   65535
 
#define PQfreeNotify(ptr)   PQfreemem(ptr)
 
#define PQnoPasswordSupplied   "fe_sendauth: no password supplied\n"
 

Typedefs

typedef struct pg_conn PGconn
 
typedef struct pg_cancel_conn PGcancelConn
 
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)
 
typedef int(* PQsslKeyPassHook_OpenSSL_type) (char *buf, int size, PGconn *conn)
 

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 , CONNECTION_GSS_STARTUP ,
  CONNECTION_CHECK_TARGET , CONNECTION_CHECK_STANDBY , CONNECTION_ALLOCATED
}
 
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 , PGRES_PIPELINE_SYNC , PGRES_PIPELINE_ABORTED
}
 
enum  PGTransactionStatusType {
  PQTRANS_IDLE , PQTRANS_ACTIVE , PQTRANS_INTRANS , PQTRANS_INERROR ,
  PQTRANS_UNKNOWN
}
 
enum  PGVerbosity { PQERRORS_TERSE , PQERRORS_DEFAULT , PQERRORS_VERBOSE , PQERRORS_SQLSTATE }
 
enum  PGContextVisibility { PQSHOW_CONTEXT_NEVER , PQSHOW_CONTEXT_ERRORS , PQSHOW_CONTEXT_ALWAYS }
 
enum  PGPing { PQPING_OK , PQPING_REJECT , PQPING_NO_RESPONSE , PQPING_NO_ATTEMPT }
 
enum  PGpipelineStatus { PQ_PIPELINE_OFF , PQ_PIPELINE_ON , PQ_PIPELINE_ABORTED }
 

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)
 
PGcancelConnPQcancelCreate (PGconn *conn)
 
int PQcancelStart (PGcancelConn *cancelConn)
 
int PQcancelBlocking (PGcancelConn *cancelConn)
 
PostgresPollingStatusType PQcancelPoll (PGcancelConn *cancelConn)
 
ConnStatusType PQcancelStatus (const PGcancelConn *cancelConn)
 
int PQcancelSocket (const PGcancelConn *cancelConn)
 
char * PQcancelErrorMessage (const PGcancelConn *cancelConn)
 
void PQcancelReset (PGcancelConn *cancelConn)
 
void PQcancelFinish (PGcancelConn *cancelConn)
 
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 * PQhostaddr (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)
 
PGpipelineStatus PQpipelineStatus (const PGconn *conn)
 
int PQconnectionNeedsPassword (const PGconn *conn)
 
int PQconnectionUsedPassword (const PGconn *conn)
 
int PQconnectionUsedGSSAPI (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)
 
int PQgssEncInUse (PGconn *conn)
 
void * PQgetgssctx (PGconn *conn)
 
PGVerbosity PQsetErrorVerbosity (PGconn *conn, PGVerbosity verbosity)
 
PGContextVisibility PQsetErrorContextVisibility (PGconn *conn, PGContextVisibility show_context)
 
PQnoticeReceiver PQsetNoticeReceiver (PGconn *conn, PQnoticeReceiver proc, void *arg)
 
PQnoticeProcessor PQsetNoticeProcessor (PGconn *conn, PQnoticeProcessor proc, void *arg)
 
pgthreadlock_t PQregisterThreadLock (pgthreadlock_t newhandler)
 
void PQtrace (PGconn *conn, FILE *debug_port)
 
void PQuntrace (PGconn *conn)
 
void PQsetTraceFlags (PGconn *conn, int flags)
 
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)
 
int PQenterPipelineMode (PGconn *conn)
 
int PQexitPipelineMode (PGconn *conn)
 
int PQpipelineSync (PGconn *conn)
 
int PQsendFlushRequest (PGconn *conn)
 
int PQsendPipelineSync (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 *buffer, 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)
 
PGresultPQclosePrepared (PGconn *conn, const char *stmt)
 
PGresultPQclosePortal (PGconn *conn, const char *portal)
 
int PQsendClosePrepared (PGconn *conn, const char *stmt)
 
int PQsendClosePortal (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)
 
size_t PQresultMemorySize (const PGresult *res)
 
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 *po)
 
void PQdisplayTuples (const PGresult *res, FILE *fp, int fillAlign, const char *fieldSep, int printHeader, int quiet)
 
void PQprintTuples (const PGresult *res, FILE *fout, int PrintAttNames, int TerseOutput, int colWidth)
 
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 PQmblenBounded (const char *s, int encoding)
 
int PQdsplen (const char *s, int encoding)
 
int PQenv2encoding (void)
 
char * PQencryptPassword (const char *passwd, const char *user)
 
char * PQencryptPasswordConn (PGconn *conn, const char *passwd, const char *user, const char *algorithm)
 
PGresultPQchangePassword (PGconn *conn, const char *user, const char *passwd)
 
int pg_char_to_encoding (const char *name)
 
const char * pg_encoding_to_char (int encoding)
 
int pg_valid_server_encoding_id (int encoding)
 
PQsslKeyPassHook_OpenSSL_type PQgetSSLKeyPassHook_OpenSSL (void)
 
void PQsetSSLKeyPassHook_OpenSSL (PQsslKeyPassHook_OpenSSL_type hook)
 
int PQdefaultSSLKeyPassHook_OpenSSL (char *buf, int size, PGconn *conn)
 

Macro Definition Documentation

◆ LIBPQ_HAS_PIPELINING

#define LIBPQ_HAS_PIPELINING   1

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

◆ LIBPQ_HAS_SSL_LIBRARY_DETECTION

#define LIBPQ_HAS_SSL_LIBRARY_DETECTION   1

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

◆ LIBPQ_HAS_TRACE_FLAGS

#define LIBPQ_HAS_TRACE_FLAGS   1

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

◆ PG_COPYRES_ATTRS

#define PG_COPYRES_ATTRS   0x01

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

◆ PG_COPYRES_EVENTS

#define PG_COPYRES_EVENTS   0x04

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

◆ PG_COPYRES_NOTICEHOOKS

#define PG_COPYRES_NOTICEHOOKS   0x08

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

◆ PG_COPYRES_TUPLES

#define PG_COPYRES_TUPLES   0x02 /* Implies PG_COPYRES_ATTRS */

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

◆ PQ_QUERY_PARAM_MAX_LIMIT

#define PQ_QUERY_PARAM_MAX_LIMIT   65535

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

◆ PQfreeNotify

#define PQfreeNotify (   ptr)    PQfreemem(ptr)

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

◆ PQnoPasswordSupplied

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

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

◆ PQsetdb

#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 303 of file libpq-fe.h.

◆ PQTRACE_REGRESS_MODE

#define PQTRACE_REGRESS_MODE   (1<<1)

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

◆ PQTRACE_SUPPRESS_TIMESTAMPS

#define PQTRACE_SUPPRESS_TIMESTAMPS   (1<<0)

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

Typedef Documentation

◆ PGcancel

typedef struct pg_cancel PGcancel

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

◆ PGcancelConn

typedef struct pg_cancel_conn PGcancelConn

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

◆ PGconn

typedef struct pg_conn PGconn

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

◆ PGnotify

typedef struct pgNotify PGnotify

◆ PGresAttDesc

typedef struct pgresAttDesc PGresAttDesc

◆ PGresult

typedef struct pg_result PGresult

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

◆ pgthreadlock_t

typedef void(* pgthreadlock_t) (int acquire)

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

◆ pqbool

typedef char pqbool

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

◆ PQconninfoOption

◆ PQnoticeProcessor

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

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

◆ PQnoticeReceiver

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

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

◆ PQprintOpt

typedef struct _PQprintOpt PQprintOpt

◆ PQsslKeyPassHook_OpenSSL_type

typedef int(* PQsslKeyPassHook_OpenSSL_type) (char *buf, int size, PGconn *conn)

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

Enumeration Type Documentation

◆ ConnStatusType

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 
CONNECTION_GSS_STARTUP 
CONNECTION_CHECK_TARGET 
CONNECTION_CHECK_STANDBY 
CONNECTION_ALLOCATED 

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

59 {
62  /* Non-blocking mode only below here */
63 
64  /*
65  * The existence of these should never be relied upon - they should only
66  * be used for user feedback or similar purposes.
67  */
68  CONNECTION_STARTED, /* Waiting for connection to be made. */
69  CONNECTION_MADE, /* Connection OK; waiting to send. */
70  CONNECTION_AWAITING_RESPONSE, /* Waiting for a response from the
71  * postmaster. */
72  CONNECTION_AUTH_OK, /* Received authentication; waiting for
73  * backend startup. */
74  CONNECTION_SETENV, /* This state is no longer used. */
75  CONNECTION_SSL_STARTUP, /* Negotiating SSL. */
76  CONNECTION_NEEDED, /* Internal state: connect() needed. */
77  CONNECTION_CHECK_WRITABLE, /* Checking if session is read-write. */
78  CONNECTION_CONSUME, /* Consuming any extra messages. */
79  CONNECTION_GSS_STARTUP, /* Negotiating GSSAPI. */
80  CONNECTION_CHECK_TARGET, /* Internal state: checking target server
81  * properties. */
82  CONNECTION_CHECK_STANDBY, /* Checking if server is in standby mode. */
83  CONNECTION_ALLOCATED /* Waiting for connection attempt to be
84  * started. */
ConnStatusType
Definition: libpq-fe.h:59
@ CONNECTION_CONSUME
Definition: libpq-fe.h:78
@ CONNECTION_CHECK_STANDBY
Definition: libpq-fe.h:82
@ CONNECTION_STARTED
Definition: libpq-fe.h:68
@ CONNECTION_AWAITING_RESPONSE
Definition: libpq-fe.h:70
@ CONNECTION_MADE
Definition: libpq-fe.h:69
@ CONNECTION_CHECK_WRITABLE
Definition: libpq-fe.h:77
@ CONNECTION_BAD
Definition: libpq-fe.h:61
@ CONNECTION_OK
Definition: libpq-fe.h:60
@ CONNECTION_GSS_STARTUP
Definition: libpq-fe.h:79
@ CONNECTION_ALLOCATED
Definition: libpq-fe.h:83
@ CONNECTION_SSL_STARTUP
Definition: libpq-fe.h:75
@ CONNECTION_AUTH_OK
Definition: libpq-fe.h:72
@ CONNECTION_CHECK_TARGET
Definition: libpq-fe.h:80
@ CONNECTION_NEEDED
Definition: libpq-fe.h:76
@ CONNECTION_SETENV
Definition: libpq-fe.h:74

◆ ExecStatusType

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 
PGRES_PIPELINE_SYNC 
PGRES_PIPELINE_ABORTED 

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

98 {
99  PGRES_EMPTY_QUERY = 0, /* empty query string was executed */
100  PGRES_COMMAND_OK, /* a query command that doesn't return
101  * anything was executed properly by the
102  * backend */
103  PGRES_TUPLES_OK, /* a query command that returns tuples was
104  * executed properly by the backend, PGresult
105  * contains the result tuples */
106  PGRES_COPY_OUT, /* Copy Out data transfer in progress */
107  PGRES_COPY_IN, /* Copy In data transfer in progress */
108  PGRES_BAD_RESPONSE, /* an unexpected response was recv'd from the
109  * backend */
110  PGRES_NONFATAL_ERROR, /* notice or warning message */
111  PGRES_FATAL_ERROR, /* query failed */
112  PGRES_COPY_BOTH, /* Copy In/Out data transfer in progress */
113  PGRES_SINGLE_TUPLE, /* single tuple from larger resultset */
114  PGRES_PIPELINE_SYNC, /* pipeline synchronization point */
115  PGRES_PIPELINE_ABORTED /* Command didn't run because of an abort
116  * earlier in a pipeline */
ExecStatusType
Definition: libpq-fe.h:98
@ PGRES_COPY_IN
Definition: libpq-fe.h:107
@ PGRES_COPY_BOTH
Definition: libpq-fe.h:112
@ PGRES_COMMAND_OK
Definition: libpq-fe.h:100
@ PGRES_FATAL_ERROR
Definition: libpq-fe.h:111
@ PGRES_SINGLE_TUPLE
Definition: libpq-fe.h:113
@ PGRES_COPY_OUT
Definition: libpq-fe.h:106
@ PGRES_EMPTY_QUERY
Definition: libpq-fe.h:99
@ PGRES_PIPELINE_SYNC
Definition: libpq-fe.h:114
@ PGRES_BAD_RESPONSE
Definition: libpq-fe.h:108
@ PGRES_PIPELINE_ABORTED
Definition: libpq-fe.h:115
@ PGRES_NONFATAL_ERROR
Definition: libpq-fe.h:110
@ PGRES_TUPLES_OK
Definition: libpq-fe.h:103

◆ PGContextVisibility

Enumerator
PQSHOW_CONTEXT_NEVER 
PQSHOW_CONTEXT_ERRORS 
PQSHOW_CONTEXT_ALWAYS 

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

137 {
138  PQSHOW_CONTEXT_NEVER, /* never show CONTEXT field */
139  PQSHOW_CONTEXT_ERRORS, /* show CONTEXT for errors only (default) */
140  PQSHOW_CONTEXT_ALWAYS /* always show CONTEXT field */
PGContextVisibility
Definition: libpq-fe.h:137
@ PQSHOW_CONTEXT_NEVER
Definition: libpq-fe.h:138
@ PQSHOW_CONTEXT_ALWAYS
Definition: libpq-fe.h:140
@ PQSHOW_CONTEXT_ERRORS
Definition: libpq-fe.h:139

◆ PGPing

enum PGPing
Enumerator
PQPING_OK 
PQPING_REJECT 
PQPING_NO_RESPONSE 
PQPING_NO_ATTEMPT 

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

149 {
150  PQPING_OK, /* server is accepting connections */
151  PQPING_REJECT, /* server is alive but rejecting connections */
152  PQPING_NO_RESPONSE, /* could not establish connection */
153  PQPING_NO_ATTEMPT /* connection not attempted (bad params) */
154 } PGPing;
PGPing
Definition: libpq-fe.h:149
@ PQPING_OK
Definition: libpq-fe.h:150
@ PQPING_REJECT
Definition: libpq-fe.h:151
@ PQPING_NO_RESPONSE
Definition: libpq-fe.h:152
@ PQPING_NO_ATTEMPT
Definition: libpq-fe.h:153

◆ PGpipelineStatus

Enumerator
PQ_PIPELINE_OFF 
PQ_PIPELINE_ON 
PQ_PIPELINE_ABORTED 

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

160 {
PGpipelineStatus
Definition: libpq-fe.h:160
@ PQ_PIPELINE_OFF
Definition: libpq-fe.h:161
@ PQ_PIPELINE_ABORTED
Definition: libpq-fe.h:163
@ PQ_PIPELINE_ON
Definition: libpq-fe.h:162

◆ PGTransactionStatusType

Enumerator
PQTRANS_IDLE 
PQTRANS_ACTIVE 
PQTRANS_INTRANS 
PQTRANS_INERROR 
PQTRANS_UNKNOWN 

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

120 {
121  PQTRANS_IDLE, /* connection idle */
122  PQTRANS_ACTIVE, /* command in progress */
123  PQTRANS_INTRANS, /* idle, within transaction block */
124  PQTRANS_INERROR, /* idle, within failed transaction */
125  PQTRANS_UNKNOWN /* cannot determine status */
PGTransactionStatusType
Definition: libpq-fe.h:120
@ PQTRANS_INTRANS
Definition: libpq-fe.h:123
@ PQTRANS_IDLE
Definition: libpq-fe.h:121
@ PQTRANS_ACTIVE
Definition: libpq-fe.h:122
@ PQTRANS_UNKNOWN
Definition: libpq-fe.h:125
@ PQTRANS_INERROR
Definition: libpq-fe.h:124

◆ PGVerbosity

Enumerator
PQERRORS_TERSE 
PQERRORS_DEFAULT 
PQERRORS_VERBOSE 
PQERRORS_SQLSTATE 

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

129 {
130  PQERRORS_TERSE, /* single-line error messages */
131  PQERRORS_DEFAULT, /* recommended style */
132  PQERRORS_VERBOSE, /* all the facts, ma'am */
133  PQERRORS_SQLSTATE /* only error severity and SQLSTATE code */
134 } PGVerbosity;
PGVerbosity
Definition: libpq-fe.h:129
@ PQERRORS_VERBOSE
Definition: libpq-fe.h:132
@ PQERRORS_DEFAULT
Definition: libpq-fe.h:131
@ PQERRORS_TERSE
Definition: libpq-fe.h:130
@ PQERRORS_SQLSTATE
Definition: libpq-fe.h:133

◆ PostgresPollingStatusType

Enumerator
PGRES_POLLING_FAILED 
PGRES_POLLING_READING 
PGRES_POLLING_WRITING 
PGRES_POLLING_OK 
PGRES_POLLING_ACTIVE 

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

88 {
90  PGRES_POLLING_READING, /* These two indicate that one may */
91  PGRES_POLLING_WRITING, /* use select before polling again. */
93  PGRES_POLLING_ACTIVE /* unused; keep for awhile for backwards
94  * compatibility */
PostgresPollingStatusType
Definition: libpq-fe.h:88
@ PGRES_POLLING_ACTIVE
Definition: libpq-fe.h:93
@ PGRES_POLLING_OK
Definition: libpq-fe.h:92
@ PGRES_POLLING_READING
Definition: libpq-fe.h:90
@ PGRES_POLLING_WRITING
Definition: libpq-fe.h:91
@ PGRES_POLLING_FAILED
Definition: libpq-fe.h:89

Function Documentation

◆ lo_close()

int lo_close ( PGconn conn,
int  fd 
)

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

97 {
98  PQArgBlock argv[1];
99  PGresult *res;
100  int retval;
101  int result_len;
102 
103  if (lo_initialize(conn) < 0)
104  return -1;
105 
106  argv[0].isint = 1;
107  argv[0].len = 4;
108  argv[0].u.integer = fd;
110  &retval, &result_len, 1, argv, 1);
112  {
113  PQclear(res);
114  return retval;
115  }
116  else
117  {
118  PQclear(res);
119  return -1;
120  }
121 }
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:2942
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:3371
static int lo_initialize(PGconn *conn)
Definition: fe-lobj.c:843
static int fd(const char *x, int i)
Definition: preproc-init.c:105
PGconn * conn
Definition: streamutil.c:54
int isint
Definition: libpq-fe.h:257
int integer
Definition: libpq-fe.h:261
union PQArgBlock::@172 u
Oid fn_lo_close
Definition: libpq-int.h:281
PGlobjfuncs * lobjfuncs
Definition: libpq-int.h:507

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

Referenced by dumpLOs(), EndRestoreLO(), exportFile(), importFile(), lo_export(), lo_import_internal(), my_truncate(), overwrite(), and pickout().

◆ lo_creat()

Oid lo_creat ( PGconn conn,
int  mode 
)

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

439 {
440  PQArgBlock argv[1];
441  PGresult *res;
442  int retval;
443  int result_len;
444 
445  if (lo_initialize(conn) < 0)
446  return InvalidOid;
447 
448  argv[0].isint = 1;
449  argv[0].len = 4;
450  argv[0].u.integer = mode;
452  &retval, &result_len, 1, argv, 1);
454  {
455  PQclear(res);
456  return (Oid) retval;
457  }
458  else
459  {
460  PQclear(res);
461  return InvalidOid;
462  }
463 }
static PgChecksumMode mode
Definition: pg_checksums.c:56
#define InvalidOid
Definition: postgres_ext.h:36
unsigned int Oid
Definition: postgres_ext.h:31
Oid fn_lo_creat
Definition: libpq-int.h:282

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

Referenced by importFile(), and lo_import_internal().

◆ lo_create()

Oid lo_create ( PGconn conn,
Oid  lobjId 
)

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

475 {
476  PQArgBlock argv[1];
477  PGresult *res;
478  int retval;
479  int result_len;
480 
481  if (lo_initialize(conn) < 0)
482  return InvalidOid;
483 
484  /* Must check this on-the-fly because it's not there pre-8.1 */
485  if (conn->lobjfuncs->fn_lo_create == 0)
486  {
487  libpq_append_conn_error(conn, "cannot determine OID of function %s",
488  "lo_create");
489  return InvalidOid;
490  }
491 
492  argv[0].isint = 1;
493  argv[0].len = 4;
494  argv[0].u.integer = lobjId;
496  &retval, &result_len, 1, argv, 1);
498  {
499  PQclear(res);
500  return (Oid) retval;
501  }
502  else
503  {
504  PQclear(res);
505  return InvalidOid;
506  }
507 }
void libpq_append_conn_error(PGconn *conn, const char *fmt,...)
Definition: fe-misc.c:1325
Oid fn_lo_create
Definition: libpq-int.h:283

References conn, pgLobjfuncs::fn_lo_create, PQArgBlock::integer, InvalidOid, PQArgBlock::isint, PQArgBlock::len, libpq_append_conn_error(), lo_initialize(), pg_conn::lobjfuncs, PGRES_COMMAND_OK, PQclear(), PQfn(), PQresultStatus(), res, and PQArgBlock::u.

Referenced by lo_import_internal(), and StartRestoreLO().

◆ lo_export()

int lo_export ( PGconn conn,
Oid  lobjId,
const char *  filename 
)

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

749 {
750  int result = 1;
751  int fd;
752  int nbytes,
753  tmp;
754  char buf[LO_BUFSIZE];
755  int lobj;
756  char sebuf[PG_STRERROR_R_BUFLEN];
757 
758  /*
759  * open the large object.
760  */
761  lobj = lo_open(conn, lobjId, INV_READ);
762  if (lobj == -1)
763  {
764  /* we assume lo_open() already set a suitable error message */
765  return -1;
766  }
767 
768  /*
769  * create the file to be written to
770  */
771  fd = open(filename, O_CREAT | O_WRONLY | O_TRUNC | PG_BINARY, 0666);
772  if (fd < 0)
773  {
774  /* We must do lo_close before setting the errorMessage */
775  int save_errno = errno;
776 
777  (void) lo_close(conn, lobj);
778  /* deliberately overwrite any error from lo_close */
780  libpq_append_conn_error(conn, "could not open file \"%s\": %s",
781  filename,
782  strerror_r(save_errno, sebuf, sizeof(sebuf)));
783  return -1;
784  }
785 
786  /*
787  * read in from the large object and write to the file
788  */
789  while ((nbytes = lo_read(conn, lobj, buf, LO_BUFSIZE)) > 0)
790  {
791  tmp = write(fd, buf, nbytes);
792  if (tmp != nbytes)
793  {
794  /* We must do lo_close before setting the errorMessage */
795  int save_errno = errno;
796 
797  (void) lo_close(conn, lobj);
798  (void) close(fd);
799  /* deliberately overwrite any error from lo_close */
801  libpq_append_conn_error(conn, "could not write to file \"%s\": %s",
802  filename,
803  strerror_r(save_errno, sebuf, sizeof(sebuf)));
804  return -1;
805  }
806  }
807 
808  /*
809  * If lo_read() failed, we are now in an aborted transaction so there's no
810  * need for lo_close(); furthermore, if we tried it we'd overwrite the
811  * useful error result with a useless one. So skip lo_close() if we got a
812  * failure result.
813  */
814  if (nbytes < 0 ||
815  lo_close(conn, lobj) != 0)
816  {
817  /* assume lo_read() or lo_close() left a suitable error message */
818  result = -1;
819  }
820 
821  /* if we already failed, don't overwrite that msg with a close error */
822  if (close(fd) != 0 && result >= 0)
823  {
824  libpq_append_conn_error(conn, "could not write to file \"%s\": %s",
825  filename, strerror_r(errno, sebuf, sizeof(sebuf)));
826  result = -1;
827  }
828 
829  return result;
830 }
#define PG_BINARY
Definition: c.h:1260
int lo_close(PGconn *conn, int fd)
Definition: fe-lobj.c:96
#define LO_BUFSIZE
Definition: fe-lobj.c:42
int lo_read(PGconn *conn, int fd, char *buf, size_t len)
Definition: fe-lobj.c:245
int lo_open(PGconn *conn, Oid lobjId, int mode)
Definition: fe-lobj.c:57
#define close(a)
Definition: win32.h:12
#define write(a, b, c)
Definition: win32.h:14
#define INV_READ
Definition: libpq-fs.h:22
#define pqClearConnErrorState(conn)
Definition: libpq-int.h:872
static char * filename
Definition: pg_dumpall.c:121
static char * buf
Definition: pg_test_fsync.c:73
#define PG_STRERROR_R_BUFLEN
Definition: port.h:256
#define strerror_r
Definition: port.h:255

References buf, close, conn, fd(), filename, INV_READ, libpq_append_conn_error(), LO_BUFSIZE, lo_close(), lo_open(), lo_read(), PG_BINARY, PG_STRERROR_R_BUFLEN, pqClearConnErrorState, strerror_r, and write.

Referenced by do_lo_export(), and main().

◆ lo_import()

Oid lo_import ( PGconn conn,
const char *  filename 
)

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

627 {
629 }
static Oid lo_import_internal(PGconn *conn, const char *filename, Oid oid)
Definition: fe-lobj.c:647

References conn, filename, InvalidOid, and lo_import_internal().

Referenced by do_lo_import(), and main().

◆ lo_import_with_oid()

Oid lo_import_with_oid ( PGconn conn,
const char *  filename,
Oid  lobjId 
)

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

642 {
643  return lo_import_internal(conn, filename, lobjId);
644 }

References conn, filename, and lo_import_internal().

◆ lo_lseek()

int lo_lseek ( PGconn conn,
int  fd,
int  offset,
int  whence 
)

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

345 {
346  PQArgBlock argv[3];
347  PGresult *res;
348  int retval;
349  int result_len;
350 
351  if (lo_initialize(conn) < 0)
352  return -1;
353 
354  argv[0].isint = 1;
355  argv[0].len = 4;
356  argv[0].u.integer = fd;
357 
358  argv[1].isint = 1;
359  argv[1].len = 4;
360  argv[1].u.integer = offset;
361 
362  argv[2].isint = 1;
363  argv[2].len = 4;
364  argv[2].u.integer = whence;
365 
367  &retval, &result_len, 1, argv, 3);
369  {
370  PQclear(res);
371  return retval;
372  }
373  else
374  {
375  PQclear(res);
376  return -1;
377  }
378 }
Oid fn_lo_lseek
Definition: libpq-int.h:285

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

Referenced by overwrite(), and pickout().

◆ lo_lseek64()

pg_int64 lo_lseek64 ( PGconn conn,
int  fd,
pg_int64  offset,
int  whence 
)

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

386 {
387  PQArgBlock argv[3];
388  PGresult *res;
389  pg_int64 retval;
390  int result_len;
391 
392  if (lo_initialize(conn) < 0)
393  return -1;
394 
395  if (conn->lobjfuncs->fn_lo_lseek64 == 0)
396  {
397  libpq_append_conn_error(conn, "cannot determine OID of function %s",
398  "lo_lseek64");
399  return -1;
400  }
401 
402  argv[0].isint = 1;
403  argv[0].len = 4;
404  argv[0].u.integer = fd;
405 
406  offset = lo_hton64(offset);
407  argv[1].isint = 0;
408  argv[1].len = 8;
409  argv[1].u.ptr = (int *) &offset;
410 
411  argv[2].isint = 1;
412  argv[2].len = 4;
413  argv[2].u.integer = whence;
414 
416  (void *) &retval, &result_len, 0, argv, 3);
417  if (PQresultStatus(res) == PGRES_COMMAND_OK && result_len == 8)
418  {
419  PQclear(res);
420  return lo_ntoh64(retval);
421  }
422  else
423  {
424  PQclear(res);
425  return -1;
426  }
427 }
static pg_int64 lo_ntoh64(pg_int64 net64)
Definition: fe-lobj.c:1048
static pg_int64 lo_hton64(pg_int64 host64)
Definition: fe-lobj.c:1023
PG_INT64_TYPE pg_int64
Definition: postgres_ext.h:47
int * ptr
Definition: libpq-fe.h:260
Oid fn_lo_lseek64
Definition: libpq-int.h:286

References conn, fd(), pgLobjfuncs::fn_lo_lseek64, PQArgBlock::integer, PQArgBlock::isint, PQArgBlock::len, libpq_append_conn_error(), lo_hton64(), lo_initialize(), lo_ntoh64(), pg_conn::lobjfuncs, PGRES_COMMAND_OK, PQclear(), PQfn(), PQresultStatus(), PQArgBlock::ptr, res, and PQArgBlock::u.

Referenced by overwrite(), and pickout().

◆ lo_open()

int lo_open ( PGconn conn,
Oid  lobjId,
int  mode 
)

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

58 {
59  int fd;
60  int result_len;
61  PQArgBlock argv[2];
62  PGresult *res;
63 
64  if (lo_initialize(conn) < 0)
65  return -1;
66 
67  argv[0].isint = 1;
68  argv[0].len = 4;
69  argv[0].u.integer = lobjId;
70 
71  argv[1].isint = 1;
72  argv[1].len = 4;
73  argv[1].u.integer = mode;
74 
75  res = PQfn(conn, conn->lobjfuncs->fn_lo_open, &fd, &result_len, 1, argv, 2);
77  {
78  PQclear(res);
79  return fd;
80  }
81  else
82  {
83  PQclear(res);
84  return -1;
85  }
86 }
Oid fn_lo_open
Definition: libpq-int.h:280

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

Referenced by dumpLOs(), exportFile(), importFile(), lo_export(), lo_import_internal(), my_truncate(), overwrite(), pickout(), and StartRestoreLO().

◆ lo_read()

int lo_read ( PGconn conn,
int  fd,
char *  buf,
size_t  len 
)

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

246 {
247  PQArgBlock argv[2];
248  PGresult *res;
249  int result_len;
250 
251  if (lo_initialize(conn) < 0)
252  return -1;
253 
254  /*
255  * Long ago, somebody thought it'd be a good idea to declare this function
256  * as taking size_t ... but the underlying backend function only accepts a
257  * signed int32 length. So throw error if the given value overflows
258  * int32.
259  */
260  if (len > (size_t) INT_MAX)
261  {
262  libpq_append_conn_error(conn, "argument of lo_read exceeds integer range");
263  return -1;
264  }
265 
266  argv[0].isint = 1;
267  argv[0].len = 4;
268  argv[0].u.integer = fd;
269 
270  argv[1].isint = 1;
271  argv[1].len = 4;
272  argv[1].u.integer = (int) len;
273 
275  (void *) buf, &result_len, 0, argv, 2);
277  {
278  PQclear(res);
279  return result_len;
280  }
281  else
282  {
283  PQclear(res);
284  return -1;
285  }
286 }
const void size_t len
Oid fn_lo_read
Definition: libpq-int.h:291

References buf, conn, fd(), pgLobjfuncs::fn_lo_read, PQArgBlock::integer, PQArgBlock::isint, PQArgBlock::len, len, libpq_append_conn_error(), lo_initialize(), pg_conn::lobjfuncs, PGRES_COMMAND_OK, PQclear(), PQfn(), PQresultStatus(), res, and PQArgBlock::u.

Referenced by lo_export().

◆ lo_tell()

int lo_tell ( PGconn conn,
int  fd 
)

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

516 {
517  int retval;
518  PQArgBlock argv[1];
519  PGresult *res;
520  int result_len;
521 
522  if (lo_initialize(conn) < 0)
523  return -1;
524 
525  argv[0].isint = 1;
526  argv[0].len = 4;
527  argv[0].u.integer = fd;
528 
530  &retval, &result_len, 1, argv, 1);
532  {
533  PQclear(res);
534  return retval;
535  }
536  else
537  {
538  PQclear(res);
539  return -1;
540  }
541 }
Oid fn_lo_tell
Definition: libpq-int.h:287

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

◆ lo_tell64()

pg_int64 lo_tell64 ( PGconn conn,
int  fd 
)

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

549 {
550  pg_int64 retval;
551  PQArgBlock argv[1];
552  PGresult *res;
553  int result_len;
554 
555  if (lo_initialize(conn) < 0)
556  return -1;
557 
558  if (conn->lobjfuncs->fn_lo_tell64 == 0)
559  {
560  libpq_append_conn_error(conn, "cannot determine OID of function %s",
561  "lo_tell64");
562  return -1;
563  }
564 
565  argv[0].isint = 1;
566  argv[0].len = 4;
567  argv[0].u.integer = fd;
568 
570  (void *) &retval, &result_len, 0, argv, 1);
571  if (PQresultStatus(res) == PGRES_COMMAND_OK && result_len == 8)
572  {
573  PQclear(res);
574  return lo_ntoh64(retval);
575  }
576  else
577  {
578  PQclear(res);
579  return -1;
580  }
581 }
Oid fn_lo_tell64
Definition: libpq-int.h:288

References conn, fd(), pgLobjfuncs::fn_lo_tell64, PQArgBlock::integer, PQArgBlock::isint, PQArgBlock::len, libpq_append_conn_error(), lo_initialize(), lo_ntoh64(), pg_conn::lobjfuncs, PGRES_COMMAND_OK, PQclear(), PQfn(), PQresultStatus(), res, and PQArgBlock::u.

Referenced by pickout().

◆ lo_truncate()

int lo_truncate ( PGconn conn,
int  fd,
size_t  len 
)

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

132 {
133  PQArgBlock argv[2];
134  PGresult *res;
135  int retval;
136  int result_len;
137 
138  if (lo_initialize(conn) < 0)
139  return -1;
140 
141  /* Must check this on-the-fly because it's not there pre-8.3 */
142  if (conn->lobjfuncs->fn_lo_truncate == 0)
143  {
144  libpq_append_conn_error(conn, "cannot determine OID of function %s",
145  "lo_truncate");
146  return -1;
147  }
148 
149  /*
150  * Long ago, somebody thought it'd be a good idea to declare this function
151  * as taking size_t ... but the underlying backend function only accepts a
152  * signed int32 length. So throw error if the given value overflows
153  * int32. (A possible alternative is to automatically redirect the call
154  * to lo_truncate64; but if the caller wanted to rely on that backend
155  * function being available, he could have called lo_truncate64 for
156  * himself.)
157  */
158  if (len > (size_t) INT_MAX)
159  {
160  libpq_append_conn_error(conn, "argument of lo_truncate exceeds integer range");
161  return -1;
162  }
163 
164  argv[0].isint = 1;
165  argv[0].len = 4;
166  argv[0].u.integer = fd;
167 
168  argv[1].isint = 1;
169  argv[1].len = 4;
170  argv[1].u.integer = (int) len;
171 
173  &retval, &result_len, 1, argv, 2);
174 
176  {
177  PQclear(res);
178  return retval;
179  }
180  else
181  {
182  PQclear(res);
183  return -1;
184  }
185 }
Oid fn_lo_truncate
Definition: libpq-int.h:289

References conn, fd(), pgLobjfuncs::fn_lo_truncate, PQArgBlock::integer, PQArgBlock::isint, PQArgBlock::len, len, libpq_append_conn_error(), lo_initialize(), pg_conn::lobjfuncs, PGRES_COMMAND_OK, PQclear(), PQfn(), PQresultStatus(), res, and PQArgBlock::u.

◆ lo_truncate64()

int lo_truncate64 ( PGconn conn,
int  fd,
pg_int64  len 
)

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

196 {
197  PQArgBlock argv[2];
198  PGresult *res;
199  int retval;
200  int result_len;
201 
202  if (lo_initialize(conn) < 0)
203  return -1;
204 
205  if (conn->lobjfuncs->fn_lo_truncate64 == 0)
206  {
207  libpq_append_conn_error(conn, "cannot determine OID of function %s",
208  "lo_truncate64");
209  return -1;
210  }
211 
212  argv[0].isint = 1;
213  argv[0].len = 4;
214  argv[0].u.integer = fd;
215 
216  len = lo_hton64(len);
217  argv[1].isint = 0;
218  argv[1].len = 8;
219  argv[1].u.ptr = (int *) &len;
220 
222  &retval, &result_len, 1, argv, 2);
223 
225  {
226  PQclear(res);
227  return retval;
228  }
229  else
230  {
231  PQclear(res);
232  return -1;
233  }
234 }
Oid fn_lo_truncate64
Definition: libpq-int.h:290

References conn, fd(), pgLobjfuncs::fn_lo_truncate64, PQArgBlock::integer, PQArgBlock::isint, PQArgBlock::len, len, libpq_append_conn_error(), lo_hton64(), lo_initialize(), pg_conn::lobjfuncs, PGRES_COMMAND_OK, PQclear(), PQfn(), PQresultStatus(), PQArgBlock::ptr, res, and PQArgBlock::u.

Referenced by my_truncate().

◆ lo_unlink()

int lo_unlink ( PGconn conn,
Oid  lobjId 
)

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

590 {
591  PQArgBlock argv[1];
592  PGresult *res;
593  int result_len;
594  int retval;
595 
596  if (lo_initialize(conn) < 0)
597  return -1;
598 
599  argv[0].isint = 1;
600  argv[0].len = 4;
601  argv[0].u.integer = lobjId;
602 
604  &retval, &result_len, 1, argv, 1);
606  {
607  PQclear(res);
608  return retval;
609  }
610  else
611  {
612  PQclear(res);
613  return -1;
614  }
615 }
Oid fn_lo_unlink
Definition: libpq-int.h:284

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

Referenced by do_lo_unlink(), and vacuumlo().

◆ lo_write()

int lo_write ( PGconn conn,
int  fd,
const char *  buf,
size_t  len 
)

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

296 {
297  PQArgBlock argv[2];
298  PGresult *res;
299  int result_len;
300  int retval;
301 
302  if (lo_initialize(conn) < 0)
303  return -1;
304 
305  /*
306  * Long ago, somebody thought it'd be a good idea to declare this function
307  * as taking size_t ... but the underlying backend function only accepts a
308  * signed int32 length. So throw error if the given value overflows
309  * int32.
310  */
311  if (len > (size_t) INT_MAX)
312  {
313  libpq_append_conn_error(conn, "argument of lo_write exceeds integer range");
314  return -1;
315  }
316 
317  argv[0].isint = 1;
318  argv[0].len = 4;
319  argv[0].u.integer = fd;
320 
321  argv[1].isint = 0;
322  argv[1].len = (int) len;
323  argv[1].u.ptr = (int *) unconstify(char *, buf);
324 
326  &retval, &result_len, 1, argv, 2);
328  {
329  PQclear(res);
330  return retval;
331  }
332  else
333  {
334  PQclear(res);
335  return -1;
336  }
337 }
#define unconstify(underlying_type, expr)
Definition: c.h:1232
Oid fn_lo_write
Definition: libpq-int.h:292

References buf, conn, fd(), pgLobjfuncs::fn_lo_write, PQArgBlock::integer, PQArgBlock::isint, PQArgBlock::len, len, libpq_append_conn_error(), lo_initialize(), pg_conn::lobjfuncs, PGRES_COMMAND_OK, PQclear(), PQfn(), PQresultStatus(), PQArgBlock::ptr, res, PQArgBlock::u, and unconstify.

Referenced by lo_import_internal().

◆ pg_char_to_encoding()

int pg_char_to_encoding ( const char *  name)

Definition at line 549 of file encnames.c.

550 {
551  unsigned int nel = lengthof(pg_encname_tbl);
552  const pg_encname *base = pg_encname_tbl,
553  *last = base + nel - 1,
554  *position;
555  int result;
556  char buff[NAMEDATALEN],
557  *key;
558 
559  if (name == NULL || *name == '\0')
560  return -1;
561 
562  if (strlen(name) >= NAMEDATALEN)
563  return -1; /* it's certainly not in the table */
564 
565  key = clean_encoding_name(name, buff);
566 
567  while (last >= base)
568  {
569  position = base + ((last - base) >> 1);
570  result = key[0] - position->name[0];
571 
572  if (result == 0)
573  {
574  result = strcmp(key, position->name);
575  if (result == 0)
576  return position->encoding;
577  }
578  if (result < 0)
579  last = position - 1;
580  else
581  base = position + 1;
582  }
583  return -1;
584 }
#define lengthof(array)
Definition: c.h:775
static const pg_encname pg_encname_tbl[]
Definition: encnames.c:39
static char * clean_encoding_name(const char *key, char *newkey)
Definition: encnames.c:524
#define NAMEDATALEN
const char * name

References clean_encoding_name(), sort-test::key, lengthof, name, NAMEDATALEN, and pg_encname_tbl.

Referenced by pg_valid_client_encoding(), and pg_valid_server_encoding().

◆ pg_encoding_to_char()

const char* pg_encoding_to_char ( int  encoding)

Definition at line 587 of file encnames.c.

588 {
590  {
591  const pg_enc2name *p = &pg_enc2name_tbl[encoding];
592 
593  Assert(encoding == p->encoding);
594  return p->name;
595  }
596  return "";
597 }
const pg_enc2name pg_enc2name_tbl[]
Definition: encnames.c:308
Assert(fmt[strlen(fmt) - 1] !='\n')
int32 encoding
Definition: pg_database.h:41
#define PG_VALID_ENCODING(_enc)
Definition: pg_wchar.h:287
pg_enc encoding
Definition: pg_wchar.h:342
const char * name
Definition: pg_wchar.h:341

References Assert(), encoding, pg_enc2name::encoding, pg_enc2name::name, pg_enc2name_tbl, and PG_VALID_ENCODING.

◆ pg_valid_server_encoding_id()

int pg_valid_server_encoding_id ( int  encoding)

Definition at line 513 of file encnames.c.

514 {
516 }
#define PG_VALID_BE_ENCODING(_enc)
Definition: pg_wchar.h:281

References encoding, and PG_VALID_BE_ENCODING.

◆ PQbackendPID()

int PQbackendPID ( const PGconn conn)

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

6983 {
6984  if (!conn || conn->status != CONNECTION_OK)
6985  return 0;
6986  return conn->be_pid;
6987 }
int be_pid
Definition: libpq-int.h:498
ConnStatusType status
Definition: libpq-int.h:429

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

Referenced by get_prompt(), libpqrcv_get_backend_pid(), main(), send_cancellable_query_impl(), and StartLogStreamer().

◆ PQbinaryTuples()

int PQbinaryTuples ( const PGresult res)

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

3458 {
3459  if (!res)
3460  return 0;
3461  return res->binary;
3462 }
int binary
Definition: libpq-int.h:182

References pg_result::binary, and res.

Referenced by HandleCopyResult().

◆ PQcancel()

int PQcancel ( PGcancel cancel,
char *  errbuf,
int  errbufsize 
)

Definition at line 462 of file fe-cancel.c.

463 {
464  int save_errno = SOCK_ERRNO;
465  pgsocket tmpsock = PGINVALID_SOCKET;
466  int maxlen;
467  struct
468  {
469  uint32 packetlen;
471  } crp;
472 
473  if (!cancel)
474  {
475  strlcpy(errbuf, "PQcancel() -- no cancel object supplied", errbufsize);
476  /* strlcpy probably doesn't change errno, but be paranoid */
477  SOCK_ERRNO_SET(save_errno);
478  return false;
479  }
480 
481  /*
482  * We need to open a temporary connection to the postmaster. Do this with
483  * only kernel calls.
484  */
485  if ((tmpsock = socket(cancel->raddr.addr.ss_family, SOCK_STREAM, 0)) == PGINVALID_SOCKET)
486  {
487  strlcpy(errbuf, "PQcancel() -- socket() failed: ", errbufsize);
488  goto cancel_errReturn;
489  }
490 
491  /*
492  * Since this connection will only be used to send a single packet of
493  * data, we don't need NODELAY. We also don't set the socket to
494  * nonblocking mode, because the API definition of PQcancel requires the
495  * cancel to be sent in a blocking way.
496  *
497  * We do set socket options related to keepalives and other TCP timeouts.
498  * This ensures that this function does not block indefinitely when
499  * reasonable keepalive and timeout settings have been provided.
500  */
501  if (cancel->raddr.addr.ss_family != AF_UNIX &&
502  cancel->keepalives != 0)
503  {
504 #ifndef WIN32
505  if (!optional_setsockopt(tmpsock, SOL_SOCKET, SO_KEEPALIVE, 1))
506  {
507  strlcpy(errbuf, "PQcancel() -- setsockopt(SO_KEEPALIVE) failed: ", errbufsize);
508  goto cancel_errReturn;
509  }
510 
511 #ifdef PG_TCP_KEEPALIVE_IDLE
512  if (!optional_setsockopt(tmpsock, IPPROTO_TCP, PG_TCP_KEEPALIVE_IDLE,
513  cancel->keepalives_idle))
514  {
515  strlcpy(errbuf, "PQcancel() -- setsockopt(" PG_TCP_KEEPALIVE_IDLE_STR ") failed: ", errbufsize);
516  goto cancel_errReturn;
517  }
518 #endif
519 
520 #ifdef TCP_KEEPINTVL
521  if (!optional_setsockopt(tmpsock, IPPROTO_TCP, TCP_KEEPINTVL,
522  cancel->keepalives_interval))
523  {
524  strlcpy(errbuf, "PQcancel() -- setsockopt(TCP_KEEPINTVL) failed: ", errbufsize);
525  goto cancel_errReturn;
526  }
527 #endif
528 
529 #ifdef TCP_KEEPCNT
530  if (!optional_setsockopt(tmpsock, IPPROTO_TCP, TCP_KEEPCNT,
531  cancel->keepalives_count))
532  {
533  strlcpy(errbuf, "PQcancel() -- setsockopt(TCP_KEEPCNT) failed: ", errbufsize);
534  goto cancel_errReturn;
535  }
536 #endif
537 
538 #else /* WIN32 */
539 
540 #ifdef SIO_KEEPALIVE_VALS
541  if (!pqSetKeepalivesWin32(tmpsock,
542  cancel->keepalives_idle,
543  cancel->keepalives_interval))
544  {
545  strlcpy(errbuf, "PQcancel() -- WSAIoctl(SIO_KEEPALIVE_VALS) failed: ", errbufsize);
546  goto cancel_errReturn;
547  }
548 #endif /* SIO_KEEPALIVE_VALS */
549 #endif /* WIN32 */
550 
551  /* TCP_USER_TIMEOUT works the same way on Unix and Windows */
552 #ifdef TCP_USER_TIMEOUT
553  if (!optional_setsockopt(tmpsock, IPPROTO_TCP, TCP_USER_TIMEOUT,
554  cancel->pgtcp_user_timeout))
555  {
556  strlcpy(errbuf, "PQcancel() -- setsockopt(TCP_USER_TIMEOUT) failed: ", errbufsize);
557  goto cancel_errReturn;
558  }
559 #endif
560  }
561 
562 retry3:
563  if (connect(tmpsock, (struct sockaddr *) &cancel->raddr.addr,
564  cancel->raddr.salen) < 0)
565  {
566  if (SOCK_ERRNO == EINTR)
567  /* Interrupted system call - we'll just try again */
568  goto retry3;
569  strlcpy(errbuf, "PQcancel() -- connect() failed: ", errbufsize);
570  goto cancel_errReturn;
571  }
572 
573  /* Create and send the cancel request packet. */
574 
575  crp.packetlen = pg_hton32((uint32) sizeof(crp));
576  crp.cp.cancelRequestCode = (MsgType) pg_hton32(CANCEL_REQUEST_CODE);
577  crp.cp.backendPID = pg_hton32(cancel->be_pid);
578  crp.cp.cancelAuthCode = pg_hton32(cancel->be_key);
579 
580 retry4:
581  if (send(tmpsock, (char *) &crp, sizeof(crp), 0) != (int) sizeof(crp))
582  {
583  if (SOCK_ERRNO == EINTR)
584  /* Interrupted system call - we'll just try again */
585  goto retry4;
586  strlcpy(errbuf, "PQcancel() -- send() failed: ", errbufsize);
587  goto cancel_errReturn;
588  }
589 
590  /*
591  * Wait for the postmaster to close the connection, which indicates that
592  * it's processed the request. Without this delay, we might issue another
593  * command only to find that our cancel zaps that command instead of the
594  * one we thought we were canceling. Note we don't actually expect this
595  * read to obtain any data, we are just waiting for EOF to be signaled.
596  */
597 retry5:
598  if (recv(tmpsock, (char *) &crp, 1, 0) < 0)
599  {
600  if (SOCK_ERRNO == EINTR)
601  /* Interrupted system call - we'll just try again */
602  goto retry5;
603  /* we ignore other error conditions */
604  }
605 
606  /* All done */
607  closesocket(tmpsock);
608  SOCK_ERRNO_SET(save_errno);
609  return true;
610 
611 cancel_errReturn:
612 
613  /*
614  * Make sure we don't overflow the error buffer. Leave space for the \n at
615  * the end, and for the terminating zero.
616  */
617  maxlen = errbufsize - strlen(errbuf) - 2;
618  if (maxlen >= 0)
619  {
620  /*
621  * We can't invoke strerror here, since it's not signal-safe. Settle
622  * for printing the decimal value of errno. Even that has to be done
623  * the hard way.
624  */
625  int val = SOCK_ERRNO;
626  char buf[32];
627  char *bufp;
628 
629  bufp = buf + sizeof(buf) - 1;
630  *bufp = '\0';
631  do
632  {
633  *(--bufp) = (val % 10) + '0';
634  val /= 10;
635  } while (val > 0);
636  bufp -= 6;
637  memcpy(bufp, "error ", 6);
638  strncat(errbuf, bufp, maxlen);
639  strcat(errbuf, "\n");
640  }
641  if (tmpsock != PGINVALID_SOCKET)
642  closesocket(tmpsock);
643  SOCK_ERRNO_SET(save_errno);
644  return false;
645 }
unsigned int uint32
Definition: c.h:493
static bool optional_setsockopt(int fd, int protoid, int optid, int value)
Definition: fe-cancel.c:430
long val
Definition: informix.c:664
#define SOCK_ERRNO
Definition: libpq-int.h:920
#define SOCK_ERRNO_SET(e)
Definition: libpq-int.h:922
#define pg_hton32(x)
Definition: pg_bswap.h:121
int pgsocket
Definition: port.h:29
#define PGINVALID_SOCKET
Definition: port.h:31
size_t strlcpy(char *dst, const char *src, size_t siz)
Definition: strlcpy.c:45
#define closesocket
Definition: port.h:349
#define CANCEL_REQUEST_CODE
Definition: pqcomm.h:132
ProtocolVersion MsgType
Definition: pqcomm.h:101
struct sockaddr_storage addr
Definition: pqcomm.h:32
socklen_t salen
Definition: pqcomm.h:33
int pgtcp_user_timeout
Definition: fe-cancel.c:45
int keepalives_interval
Definition: fe-cancel.c:48
int keepalives_idle
Definition: fe-cancel.c:47
int keepalives_count
Definition: fe-cancel.c:50
SockAddr raddr
Definition: fe-cancel.c:42
int be_pid
Definition: fe-cancel.c:43
int keepalives
Definition: fe-cancel.c:46
int be_key
Definition: fe-cancel.c:44
#define EINTR
Definition: win32_port.h:374
#define recv(s, buf, len, flags)
Definition: win32_port.h:496
#define send(s, buf, len, flags)
Definition: win32_port.h:497
#define socket(af, type, protocol)
Definition: win32_port.h:490
#define connect(s, name, namelen)
Definition: win32_port.h:494

References SockAddr::addr, pg_cancel::be_key, pg_cancel::be_pid, buf, CANCEL_REQUEST_CODE, closesocket, connect, EINTR, pg_cancel::keepalives, pg_cancel::keepalives_count, pg_cancel::keepalives_idle, pg_cancel::keepalives_interval, optional_setsockopt(), pg_hton32, PGINVALID_SOCKET, pg_cancel::pgtcp_user_timeout, pg_cancel::raddr, recv, SockAddr::salen, send, SOCK_ERRNO, SOCK_ERRNO_SET, socket, strlcpy(), and val.

Referenced by DisconnectDatabase(), handle_sigint(), pgfdw_cancel_query_begin(), PQrequestCancel(), ShutdownWorkersHard(), sigTermHandler(), and test_cancel().

◆ PQcancelBlocking()

int PQcancelBlocking ( PGcancelConn cancelConn)

Definition at line 171 of file fe-cancel.c.

172 {
174  return 0;
175  return pqConnectDBComplete(&cancelConn->conn);
176 }
static PGcancel *volatile cancelConn
Definition: cancel.c:43
int PQcancelStart(PGcancelConn *cancelConn)
Definition: fe-cancel.c:185
int pqConnectDBComplete(PGconn *conn)
Definition: fe-connect.c:2408

References cancelConn, PQcancelStart(), and pqConnectDBComplete().

Referenced by dblink_cancel_query(), disconnectDatabase(), test_cancel(), and try_complete_step().

◆ PQcancelCreate()

PGcancelConn* PQcancelCreate ( PGconn conn)

Definition at line 65 of file fe-cancel.c.

66 {
68  pg_conn_host originalHost;
69 
70  if (cancelConn == NULL)
71  return NULL;
72 
73  /* Check we have an open connection */
74  if (!conn)
75  {
76  libpq_append_conn_error(cancelConn, "passed connection was NULL");
77  return (PGcancelConn *) cancelConn;
78  }
79 
80  if (conn->sock == PGINVALID_SOCKET)
81  {
82  libpq_append_conn_error(cancelConn, "passed connection is not open");
83  return (PGcancelConn *) cancelConn;
84  }
85 
86  /*
87  * Indicate that this connection is used to send a cancellation
88  */
89  cancelConn->cancelRequest = true;
90 
92  return (PGcancelConn *) cancelConn;
93 
94  /*
95  * Compute derived options
96  */
98  return (PGcancelConn *) cancelConn;
99 
100  /*
101  * Copy cancellation token data from the original connnection
102  */
105 
106  /*
107  * Cancel requests should not iterate over all possible hosts. The request
108  * needs to be sent to the exact host and address that the original
109  * connection used. So we manually create the host and address arrays with
110  * a single element after freeing the host array that we generated from
111  * the connection options.
112  */
114  cancelConn->nconnhost = 1;
115  cancelConn->naddr = 1;
116 
117  cancelConn->connhost = calloc(cancelConn->nconnhost, sizeof(pg_conn_host));
118  if (!cancelConn->connhost)
119  goto oom_error;
120 
121  originalHost = conn->connhost[conn->whichhost];
122  if (originalHost.host)
123  {
124  cancelConn->connhost[0].host = strdup(originalHost.host);
125  if (!cancelConn->connhost[0].host)
126  goto oom_error;
127  }
128  if (originalHost.hostaddr)
129  {
130  cancelConn->connhost[0].hostaddr = strdup(originalHost.hostaddr);
131  if (!cancelConn->connhost[0].hostaddr)
132  goto oom_error;
133  }
134  if (originalHost.port)
135  {
136  cancelConn->connhost[0].port = strdup(originalHost.port);
137  if (!cancelConn->connhost[0].port)
138  goto oom_error;
139  }
140  if (originalHost.password)
141  {
142  cancelConn->connhost[0].password = strdup(originalHost.password);
143  if (!cancelConn->connhost[0].password)
144  goto oom_error;
145  }
146 
147  cancelConn->addr = calloc(cancelConn->naddr, sizeof(AddrInfo));
148  if (!cancelConn->connhost)
149  goto oom_error;
150 
151  cancelConn->addr[0].addr = conn->raddr;
152  cancelConn->addr[0].family = conn->raddr.addr.ss_family;
153 
155  return (PGcancelConn *) cancelConn;
156 
157 oom_error:
159  libpq_append_conn_error(cancelConn, "out of memory");
160  return (PGcancelConn *) cancelConn;
161 }
bool pqConnectOptions2(PGconn *conn)
Definition: fe-connect.c:1109
void pqReleaseConnHosts(PGconn *conn)
Definition: fe-connect.c:4507
PGconn * pqMakeEmptyPGconn(void)
Definition: fe-connect.c:4327
bool pqCopyPGconn(PGconn *srcConn, PGconn *dstConn)
Definition: fe-connect.c:945
#define calloc(a, b)
Definition: header.h:55
char * host
Definition: libpq-int.h:346
char * password
Definition: libpq-int.h:349
char * port
Definition: libpq-int.h:348
char * hostaddr
Definition: libpq-int.h:347
pgsocket sock
Definition: libpq-int.h:463
int be_key
Definition: libpq-int.h:499
SockAddr raddr
Definition: libpq-int.h:466
int whichhost
Definition: libpq-int.h:445
pg_conn_host * connhost
Definition: libpq-int.h:446

References SockAddr::addr, pg_cancel::be_key, pg_conn::be_key, pg_cancel::be_pid, pg_conn::be_pid, calloc, cancelConn, conn, CONNECTION_ALLOCATED, CONNECTION_BAD, pg_conn::connhost, pg_conn_host::host, pg_conn_host::hostaddr, libpq_append_conn_error(), pg_conn_host::password, PGINVALID_SOCKET, pg_conn_host::port, pqConnectOptions2(), pqCopyPGconn(), pqMakeEmptyPGconn(), pqReleaseConnHosts(), pg_conn::raddr, pg_conn::sock, pg_conn::status, and pg_conn::whichhost.

Referenced by dblink_cancel_query(), disconnectDatabase(), test_cancel(), and try_complete_step().

◆ PQcancelErrorMessage()

char* PQcancelErrorMessage ( const PGcancelConn cancelConn)

Definition at line 305 of file fe-cancel.c.

306 {
307  return PQerrorMessage(&cancelConn->conn);
308 }
char * PQerrorMessage(const PGconn *conn)
Definition: fe-connect.c:6948

References cancelConn, and PQerrorMessage().

Referenced by dblink_cancel_query(), test_cancel(), and try_complete_step().

◆ PQcancelFinish()

void PQcancelFinish ( PGcancelConn cancelConn)

Definition at line 333 of file fe-cancel.c.

334 {
335  PQfinish(&cancelConn->conn);
336 }
void PQfinish(PGconn *conn)
Definition: fe-connect.c:4669

References cancelConn, and PQfinish().

Referenced by dblink_cancel_query(), disconnectDatabase(), test_cancel(), and try_complete_step().

◆ PQcancelPoll()

PostgresPollingStatusType PQcancelPoll ( PGcancelConn cancelConn)

Definition at line 207 of file fe-cancel.c.

208 {
209  PGconn *conn = &cancelConn->conn;
210  int n;
211 
212  /*
213  * We leave most of the connection establishement to PQconnectPoll, since
214  * it's very similar to normal connection establishment. But once we get
215  * to the CONNECTION_AWAITING_RESPONSE we need to start doing our own
216  * thing.
217  */
219  {
220  return PQconnectPoll(conn);
221  }
222 
223  /*
224  * At this point we are waiting on the server to close the connection,
225  * which is its way of communicating that the cancel has been handled.
226  */
227 
228  n = pqReadData(conn);
229 
230  if (n == 0)
231  return PGRES_POLLING_READING;
232 
233 #ifndef WIN32
234 
235  /*
236  * If we receive an error report it, but only if errno is non-zero.
237  * Otherwise we assume it's an EOF, which is what we expect from the
238  * server.
239  *
240  * We skip this for Windows, because Windows is a bit special in its EOF
241  * behaviour for TCP. Sometimes it will error with an ECONNRESET when
242  * there is a clean connection closure. See these threads for details:
243  * https://www.postgresql.org/message-id/flat/90b34057-4176-7bb0-0dbb-9822a5f6425b%40greiz-reinsdorf.de
244  *
245  * https://www.postgresql.org/message-id/flat/CA%2BhUKG%2BOeoETZQ%3DQw5Ub5h3tmwQhBmDA%3DnuNO3KG%3DzWfUypFAw%40mail.gmail.com
246  *
247  * PQcancel ignores such errors and reports success for the cancellation
248  * anyway, so even if this is not always correct we do the same here.
249  */
250  if (n < 0 && errno != 0)
251  {
253  return PGRES_POLLING_FAILED;
254  }
255 #endif
256 
257  /*
258  * We don't expect any data, only connection closure. So if we strangely
259  * do receive some data we consider that an error.
260  */
261  if (n > 0)
262  {
263  libpq_append_conn_error(conn, "received unexpected response from server");
265  return PGRES_POLLING_FAILED;
266  }
267 
268  /*
269  * Getting here means that we received an EOF, which is what we were
270  * expecting -- the cancel request has completed.
271  */
272  cancelConn->conn.status = CONNECTION_OK;
274  return PGRES_POLLING_OK;
275 }
PostgresPollingStatusType PQconnectPoll(PGconn *conn)
Definition: fe-connect.c:2547
int pqReadData(PGconn *conn)
Definition: fe-misc.c:566
void resetPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:146
PQExpBufferData errorMessage
Definition: libpq-int.h:621

References cancelConn, conn, CONNECTION_AWAITING_RESPONSE, CONNECTION_BAD, CONNECTION_OK, pg_conn::errorMessage, libpq_append_conn_error(), PGRES_POLLING_FAILED, PGRES_POLLING_OK, PGRES_POLLING_READING, PQconnectPoll(), pqReadData(), resetPQExpBuffer(), and pg_conn::status.

Referenced by pqConnectDBComplete(), and test_cancel().

◆ PQcancelReset()

void PQcancelReset ( PGcancelConn cancelConn)

Definition at line 317 of file fe-cancel.c.

318 {
319  pqClosePGconn(&cancelConn->conn);
320  cancelConn->conn.status = CONNECTION_ALLOCATED;
321  cancelConn->conn.whichhost = 0;
322  cancelConn->conn.whichaddr = 0;
323  cancelConn->conn.try_next_host = false;
324  cancelConn->conn.try_next_addr = false;
325 }
void pqClosePGconn(PGconn *conn)
Definition: fe-connect.c:4623

References cancelConn, CONNECTION_ALLOCATED, and pqClosePGconn().

Referenced by test_cancel().

◆ PQcancelSocket()

int PQcancelSocket ( const PGcancelConn cancelConn)

Definition at line 294 of file fe-cancel.c.

295 {
296  return PQsocket(&cancelConn->conn);
297 }
int PQsocket(const PGconn *conn)
Definition: fe-connect.c:6974

References cancelConn, and PQsocket().

Referenced by test_cancel().

◆ PQcancelStart()

int PQcancelStart ( PGcancelConn cancelConn)

Definition at line 185 of file fe-cancel.c.

186 {
187  if (!cancelConn || cancelConn->conn.status == CONNECTION_BAD)
188  return 0;
189 
190  if (cancelConn->conn.status != CONNECTION_ALLOCATED)
191  {
193  "cancel request is already being sent on this connection");
194  cancelConn->conn.status = CONNECTION_BAD;
195  return 0;
196  }
197 
198  return pqConnectDBStart(&cancelConn->conn);
199 }
int pqConnectDBStart(PGconn *conn)
Definition: fe-connect.c:2330

References cancelConn, CONNECTION_ALLOCATED, CONNECTION_BAD, libpq_append_conn_error(), and pqConnectDBStart().

Referenced by PQcancelBlocking(), and test_cancel().

◆ PQcancelStatus()

ConnStatusType PQcancelStatus ( const PGcancelConn cancelConn)

Definition at line 283 of file fe-cancel.c.

284 {
285  return PQstatus(&cancelConn->conn);
286 }
ConnStatusType PQstatus(const PGconn *conn)
Definition: fe-connect.c:6895

References cancelConn, and PQstatus().

Referenced by test_cancel().

◆ PQchangePassword()

PGresult* PQchangePassword ( PGconn conn,
const char *  user,
const char *  passwd 
)

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

1403 {
1404  char *encrypted_password = PQencryptPasswordConn(conn, passwd,
1405  user, NULL);
1406 
1407  if (!encrypted_password)
1408  {
1409  /* PQencryptPasswordConn() already registered the error */
1410  return NULL;
1411  }
1412  else
1413  {
1414  char *fmtpw = PQescapeLiteral(conn, encrypted_password,
1415  strlen(encrypted_password));
1416 
1417  /* no longer needed, so clean up now */
1418  PQfreemem(encrypted_password);
1419 
1420  if (!fmtpw)
1421  {
1422  /* PQescapeLiteral() already registered the error */
1423  return NULL;
1424  }
1425  else
1426  {
1427  char *fmtuser = PQescapeIdentifier(conn, user, strlen(user));
1428 
1429  if (!fmtuser)
1430  {
1431  /* PQescapeIdentifier() already registered the error */
1432  PQfreemem(fmtpw);
1433  return NULL;
1434  }
1435  else
1436  {
1438  PGresult *res;
1439 
1440  initPQExpBuffer(&buf);
1441  printfPQExpBuffer(&buf, "ALTER USER %s PASSWORD %s",
1442  fmtuser, fmtpw);
1443 
1444  res = PQexec(conn, buf.data);
1445 
1446  /* clean up */
1447  termPQExpBuffer(&buf);
1448  PQfreemem(fmtuser);
1449  PQfreemem(fmtpw);
1450 
1451  return res;
1452  }
1453  }
1454  }
1455 }
char * PQencryptPasswordConn(PGconn *conn, const char *passwd, const char *user, const char *algorithm)
Definition: fe-auth.c:1277
void PQfreemem(void *ptr)
Definition: fe-exec.c:3992
char * PQescapeIdentifier(PGconn *conn, const char *str, size_t len)
Definition: fe-exec.c:4270
char * PQescapeLiteral(PGconn *conn, const char *str, size_t len)
Definition: fe-exec.c:4264
PGresult * PQexec(PGconn *conn, const char *query)
Definition: fe-exec.c:2224
static char * user
Definition: pg_regress.c:120
void printfPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:235
void initPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:90
void termPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:129

References buf, conn, initPQExpBuffer(), PQencryptPasswordConn(), PQescapeIdentifier(), PQescapeLiteral(), PQexec(), PQfreemem(), printfPQExpBuffer(), res, termPQExpBuffer(), and user.

Referenced by exec_command_password().

◆ PQclear()

void PQclear ( PGresult res)

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

720 {
721  PGresult_data *block;
722  int i;
723 
724  /* As a convenience, do nothing for a NULL pointer */
725  if (!res)
726  return;
727  /* Also, do nothing if the argument is OOM_result */
728  if ((const PGresult *) res == &OOM_result)
729  return;
730 
731  /* Close down any events we may have */
732  for (i = 0; i < res->nEvents; i++)
733  {
734  /* only send DESTROY to successfully-initialized event procs */
736  {
738 
739  evt.result = res;
740  (void) res->events[i].proc(PGEVT_RESULTDESTROY, &evt,
741  res->events[i].passThrough);
742  }
743  free(res->events[i].name);
744  }
745 
746  free(res->events);
747 
748  /* Free all the subsidiary blocks */
749  while ((block = res->curBlock) != NULL)
750  {
751  res->curBlock = block->next;
752  free(block);
753  }
754 
755  /* Free the top-level tuple pointer array */
756  free(res->tuples);
757 
758  /* zero out the pointer fields to catch programming errors */
759  res->attDescs = NULL;
760  res->tuples = NULL;
761  res->paramDescs = NULL;
762  res->errFields = NULL;
763  res->events = NULL;
764  res->nEvents = 0;
765  /* res->curBlock was zeroed out earlier */
766 
767  /* Free the PGresult structure itself */
768  free(res);
769 }
static const PGresult OOM_result
Definition: fe-exec.c:48
#define free(a)
Definition: header.h:65
int i
Definition: isn.c:73
@ PGEVT_RESULTDESTROY
Definition: libpq-events.h:34
void * passThrough
Definition: libpq-int.h:165
char * name
Definition: libpq-int.h:164
PGEventProc proc
Definition: libpq-int.h:163
bool resultInitialized
Definition: libpq-int.h:167
int nEvents
Definition: libpq-int.h:191
PGresAttValue ** tuples
Definition: libpq-int.h:175
PGresAttDesc * attDescs
Definition: libpq-int.h:174
PGMessageField * errFields
Definition: libpq-int.h:200
PGresParamDesc * paramDescs
Definition: libpq-int.h:179
PGEvent * events
Definition: libpq-int.h:190
PGresult_data * curBlock
Definition: libpq-int.h:211
PGresult_data * next
Definition: libpq-int.h:108

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

Referenced by pqClearAsyncResult(), PQcopyResult(), PQexecFinish(), PQexecStart(), pqInternalNotice(), PQmakeEmptyPGresult(), and pqRowProcessor().

◆ PQclientEncoding()

int PQclientEncoding ( const PGconn conn)

◆ PQclosePortal()

PGresult* PQclosePortal ( PGconn conn,
const char *  portal 
)

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

2502 {
2503  if (!PQexecStart(conn))
2504  return NULL;
2505  if (!PQsendTypedCommand(conn, PqMsg_Close, 'P', portal))
2506  return NULL;
2507  return PQexecFinish(conn);
2508 }
static PGresult * PQexecFinish(PGconn *conn)
Definition: fe-exec.c:2372
static int PQsendTypedCommand(PGconn *conn, char command, char type, const char *target)
Definition: fe-exec.c:2551
static bool PQexecStart(PGconn *conn)
Definition: fe-exec.c:2306
#define PqMsg_Close
Definition: protocol.h:20

References conn, PQexecFinish(), PQexecStart(), PqMsg_Close, and PQsendTypedCommand().

Referenced by test_prepared().

◆ PQclosePrepared()

PGresult* PQclosePrepared ( PGconn conn,
const char *  stmt 
)

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

2484 {
2485  if (!PQexecStart(conn))
2486  return NULL;
2487  if (!PQsendTypedCommand(conn, PqMsg_Close, 'S', stmt))
2488  return NULL;
2489  return PQexecFinish(conn);
2490 }
#define stmt
Definition: indent_codes.h:59

References conn, PQexecFinish(), PQexecStart(), PqMsg_Close, PQsendTypedCommand(), and stmt.

Referenced by test_prepared().

◆ PQcmdStatus()

char* PQcmdStatus ( PGresult res)

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

3713 {
3714  if (!res)
3715  return NULL;
3716  return res->cmdStatus;
3717 }
char cmdStatus[CMDSTATUS_LEN]
Definition: libpq-int.h:181

References pg_result::cmdStatus, and res.

Referenced by dblink_exec(), ecpg_process_output(), ExecQueryAndProcessResults(), materializeResult(), PrintQueryResult(), PrintQueryStatus(), and test_pipelined_insert().

◆ PQcmdTuples()

char* PQcmdTuples ( PGresult res)

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

3783 {
3784  char *p,
3785  *c;
3786 
3787  if (!res)
3788  return "";
3789 
3790  if (strncmp(res->cmdStatus, "INSERT ", 7) == 0)
3791  {
3792  p = res->cmdStatus + 7;
3793  /* INSERT: skip oid and space */
3794  while (*p && *p != ' ')
3795  p++;
3796  if (*p == 0)
3797  goto interpret_error; /* no space? */
3798  p++;
3799  }
3800  else if (strncmp(res->cmdStatus, "SELECT ", 7) == 0 ||
3801  strncmp(res->cmdStatus, "DELETE ", 7) == 0 ||
3802  strncmp(res->cmdStatus, "UPDATE ", 7) == 0)
3803  p = res->cmdStatus + 7;
3804  else if (strncmp(res->cmdStatus, "FETCH ", 6) == 0 ||
3805  strncmp(res->cmdStatus, "MERGE ", 6) == 0)
3806  p = res->cmdStatus + 6;
3807  else if (strncmp(res->cmdStatus, "MOVE ", 5) == 0 ||
3808  strncmp(res->cmdStatus, "COPY ", 5) == 0)
3809  p = res->cmdStatus + 5;
3810  else
3811  return "";
3812 
3813  /* check that we have an integer (at least one digit, nothing else) */
3814  for (c = p; *c; c++)
3815  {
3816  if (!isdigit((unsigned char) *c))
3817  goto interpret_error;
3818  }
3819  if (c == p)
3820  goto interpret_error;
3821 
3822  return p;
3823 
3824 interpret_error:
3826  "could not interpret result from server: %s",
3827  res->cmdStatus);
3828  return "";
3829 }
void pqInternalNotice(const PGNoticeHooks *hooks, const char *fmt,...)
Definition: fe-exec.c:936
char * c
PGNoticeHooks noticeHooks
Definition: libpq-int.h:189

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

Referenced by ecpg_process_output(), execute_dml_stmt(), execute_foreign_modify(), and SetResultVariables().

◆ PQconndefaults()

PQconninfoOption* PQconndefaults ( void  )

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

1820 {
1821  PQExpBufferData errorBuf;
1822  PQconninfoOption *connOptions;
1823 
1824  /* We don't actually report any errors here, but callees want a buffer */
1825  initPQExpBuffer(&errorBuf);
1826  if (PQExpBufferDataBroken(errorBuf))
1827  return NULL; /* out of memory already :-( */
1828 
1829  connOptions = conninfo_init(&errorBuf);
1830  if (connOptions != NULL)
1831  {
1832  /* pass NULL errorBuf to ignore errors */
1833  if (!conninfo_add_defaults(connOptions, NULL))
1834  {
1835  PQconninfoFree(connOptions);
1836  connOptions = NULL;
1837  }
1838  }
1839 
1840  termPQExpBuffer(&errorBuf);
1841  return connOptions;
1842 }
static PQconninfoOption * conninfo_init(PQExpBuffer errorMessage)
Definition: fe-connect.c:5551
static bool conninfo_add_defaults(PQconninfoOption *options, PQExpBuffer errorMessage)
Definition: fe-connect.c:5978
void PQconninfoFree(PQconninfoOption *connOptions)
Definition: fe-connect.c:6781
#define PQExpBufferDataBroken(buf)
Definition: pqexpbuffer.h:67

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

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

◆ PQconnectdb()

PGconn* PQconnectdb ( const char *  conninfo)

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

734 {
735  PGconn *conn = PQconnectStart(conninfo);
736 
737  if (conn && conn->status != CONNECTION_BAD)
738  (void) pqConnectDBComplete(conn);
739 
740  return conn;
741 }
PGconn * PQconnectStart(const char *conninfo)
Definition: fe-connect.c:861

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

Referenced by get_db_conn(), and main().

◆ PQconnectdbParams()

PGconn* PQconnectdbParams ( const char *const *  keywords,
const char *const *  values,
int  expand_dbname 
)

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

681 {
682  PGconn *conn = PQconnectStartParams(keywords, values, expand_dbname);
683 
684  if (conn && conn->status != CONNECTION_BAD)
685  (void) pqConnectDBComplete(conn);
686 
687  return conn;
688 }
static Datum values[MAXATTR]
Definition: bootstrap.c:152
PGconn * PQconnectStartParams(const char *const *keywords, const char *const *values, int expand_dbname)
Definition: fe-connect.c:780

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

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

◆ PQconnectionNeedsPassword()

int PQconnectionNeedsPassword ( const PGconn conn)

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

7000 {
7001  char *password;
7002 
7003  if (!conn)
7004  return false;
7005  password = PQpass(conn);
7006  if (conn->password_needed &&
7007  (password == NULL || password[0] == '\0'))
7008  return true;
7009  else
7010  return false;
7011 }
char * PQpass(const PGconn *conn)
Definition: fe-connect.c:6810
static char * password
Definition: streamutil.c:53
bool password_needed
Definition: libpq-int.h:470

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

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

◆ PQconnectionUsedGSSAPI()

int PQconnectionUsedGSSAPI ( const PGconn conn)

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

7026 {
7027  if (!conn)
7028  return false;
7029  if (conn->gssapi_used)
7030  return true;
7031  else
7032  return false;
7033 }
bool gssapi_used
Definition: libpq-int.h:471

References conn, and pg_conn::gssapi_used.

Referenced by dblink_security_check(), and pgfdw_security_check().

◆ PQconnectionUsedPassword()

int PQconnectionUsedPassword ( const PGconn conn)

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

7015 {
7016  if (!conn)
7017  return false;
7018  if (conn->password_needed)
7019  return true;
7020  else
7021  return false;
7022 }

References conn, and pg_conn::password_needed.

Referenced by ConnectDatabase(), dblink_security_check(), libpqrcv_connect(), and pgfdw_security_check().

◆ PQconnectPoll()

PostgresPollingStatusType PQconnectPoll ( PGconn conn)

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

2548 {
2549  bool reset_connection_state_machine = false;
2550  bool need_new_connection = false;
2551  PGresult *res;
2552  char sebuf[PG_STRERROR_R_BUFLEN];
2553  int optval;
2554 
2555  if (conn == NULL)
2556  return PGRES_POLLING_FAILED;
2557 
2558  /* Get the new data */
2559  switch (conn->status)
2560  {
2561  /*
2562  * We really shouldn't have been polled in these two cases, but we
2563  * can handle it.
2564  */
2565  case CONNECTION_BAD:
2566  return PGRES_POLLING_FAILED;
2567  case CONNECTION_OK:
2568  return PGRES_POLLING_OK;
2569 
2570  /* These are reading states */
2572  case CONNECTION_AUTH_OK:
2574  case CONNECTION_CONSUME:
2576  {
2577  /* Load waiting data */
2578  int n = pqReadData(conn);
2579 
2580  if (n < 0)
2581  goto error_return;
2582  if (n == 0)
2583  return PGRES_POLLING_READING;
2584 
2585  break;
2586  }
2587 
2588  /* These are writing states, so we just proceed. */
2589  case CONNECTION_STARTED:
2590  case CONNECTION_MADE:
2591  break;
2592 
2593  /* Special cases: proceed without waiting. */
2595  case CONNECTION_NEEDED:
2598  break;
2599 
2600  default:
2601  libpq_append_conn_error(conn, "invalid connection state, probably indicative of memory corruption");
2602  goto error_return;
2603  }
2604 
2605 
2606 keep_going: /* We will come back to here until there is
2607  * nothing left to do. */
2608 
2609  /* Time to advance to next address, or next host if no more addresses? */
2610  if (conn->try_next_addr)
2611  {
2612  if (conn->whichaddr < conn->naddr)
2613  {
2614  conn->whichaddr++;
2615  reset_connection_state_machine = true;
2616  }
2617  else
2618  conn->try_next_host = true;
2619  conn->try_next_addr = false;
2620  }
2621 
2622  /* Time to advance to next connhost[] entry? */
2623  if (conn->try_next_host)
2624  {
2625  pg_conn_host *ch;
2626  struct addrinfo hint;
2627  struct addrinfo *addrlist;
2628  int thisport;
2629  int ret;
2630  char portstr[MAXPGPATH];
2631 
2632  if (conn->whichhost + 1 < conn->nconnhost)
2633  conn->whichhost++;
2634  else
2635  {
2636  /*
2637  * Oops, no more hosts.
2638  *
2639  * If we are trying to connect in "prefer-standby" mode, then drop
2640  * the standby requirement and start over. Don't do this for
2641  * cancel requests though, since we are certain the list of
2642  * servers won't change as the target_server_type option is not
2643  * applicable to those connections.
2644  *
2645  * Otherwise, an appropriate error message is already set up, so
2646  * we just need to set the right status.
2647  */
2649  conn->nconnhost > 0 &&
2650  !conn->cancelRequest)
2651  {
2653  conn->whichhost = 0;
2654  }
2655  else
2656  goto error_return;
2657  }
2658 
2659  /* Drop any address info for previous host */
2661 
2662  /*
2663  * Look up info for the new host. On failure, log the problem in
2664  * conn->errorMessage, then loop around to try the next host. (Note
2665  * we don't clear try_next_host until we've succeeded.)
2666  */
2667  ch = &conn->connhost[conn->whichhost];
2668 
2669  /* Initialize hint structure */
2670  MemSet(&hint, 0, sizeof(hint));
2671  hint.ai_socktype = SOCK_STREAM;
2672  hint.ai_family = AF_UNSPEC;
2673 
2674  /* Figure out the port number we're going to use. */
2675  if (ch->port == NULL || ch->port[0] == '\0')
2676  thisport = DEF_PGPORT;
2677  else
2678  {
2679  if (!pqParseIntParam(ch->port, &thisport, conn, "port"))
2680  goto error_return;
2681 
2682  if (thisport < 1 || thisport > 65535)
2683  {
2684  libpq_append_conn_error(conn, "invalid port number: \"%s\"", ch->port);
2685  goto keep_going;
2686  }
2687  }
2688  snprintf(portstr, sizeof(portstr), "%d", thisport);
2689 
2690  /* Use pg_getaddrinfo_all() to resolve the address */
2691  switch (ch->type)
2692  {
2693  case CHT_HOST_NAME:
2694  ret = pg_getaddrinfo_all(ch->host, portstr, &hint,
2695  &addrlist);
2696  if (ret || !addrlist)
2697  {
2698  libpq_append_conn_error(conn, "could not translate host name \"%s\" to address: %s",
2699  ch->host, gai_strerror(ret));
2700  goto keep_going;
2701  }
2702  break;
2703 
2704  case CHT_HOST_ADDRESS:
2705  hint.ai_flags = AI_NUMERICHOST;
2706  ret = pg_getaddrinfo_all(ch->hostaddr, portstr, &hint,
2707  &addrlist);
2708  if (ret || !addrlist)
2709  {
2710  libpq_append_conn_error(conn, "could not parse network address \"%s\": %s",
2711  ch->hostaddr, gai_strerror(ret));
2712  goto keep_going;
2713  }
2714  break;
2715 
2716  case CHT_UNIX_SOCKET:
2717  hint.ai_family = AF_UNIX;
2718  UNIXSOCK_PATH(portstr, thisport, ch->host);
2719  if (strlen(portstr) >= UNIXSOCK_PATH_BUFLEN)
2720  {
2721  libpq_append_conn_error(conn, "Unix-domain socket path \"%s\" is too long (maximum %d bytes)",
2722  portstr,
2723  (int) (UNIXSOCK_PATH_BUFLEN - 1));
2724  goto keep_going;
2725  }
2726 
2727  /*
2728  * NULL hostname tells pg_getaddrinfo_all to parse the service
2729  * name as a Unix-domain socket path.
2730  */
2731  ret = pg_getaddrinfo_all(NULL, portstr, &hint,
2732  &addrlist);
2733  if (ret || !addrlist)
2734  {
2735  libpq_append_conn_error(conn, "could not translate Unix-domain socket path \"%s\" to address: %s",
2736  portstr, gai_strerror(ret));
2737  goto keep_going;
2738  }
2739  break;
2740  }
2741 
2742  /*
2743  * Store a copy of the addrlist in private memory so we can perform
2744  * randomization for load balancing.
2745  */
2746  ret = store_conn_addrinfo(conn, addrlist);
2747  pg_freeaddrinfo_all(hint.ai_family, addrlist);
2748  if (ret)
2749  goto error_return; /* message already logged */
2750 
2751  /*
2752  * If random load balancing is enabled we shuffle the addresses.
2753  */
2755  {
2756  /*
2757  * This is the "inside-out" variant of the Fisher-Yates shuffle
2758  * algorithm. Notionally, we append each new value to the array
2759  * and then swap it with a randomly-chosen array element (possibly
2760  * including itself, else we fail to generate permutations with
2761  * the last integer last). The swap step can be optimized by
2762  * combining it with the insertion.
2763  *
2764  * We don't need to initialize conn->prng_state here, because that
2765  * already happened in pqConnectOptions2.
2766  */
2767  for (int i = 1; i < conn->naddr; i++)
2768  {
2769  int j = pg_prng_uint64_range(&conn->prng_state, 0, i);
2770  AddrInfo temp = conn->addr[j];
2771 
2772  conn->addr[j] = conn->addr[i];
2773  conn->addr[i] = temp;
2774  }
2775  }
2776 
2777  reset_connection_state_machine = true;
2778  conn->try_next_host = false;
2779  }
2780 
2781  /* Reset connection state machine? */
2782  if (reset_connection_state_machine)
2783  {
2784  /*
2785  * (Re) initialize our connection control variables for a set of
2786  * connection attempts to a single server address. These variables
2787  * must persist across individual connection attempts, but we must
2788  * reset them when we start to consider a new server.
2789  */
2790  conn->pversion = PG_PROTOCOL(3, 0);
2791  conn->send_appname = true;
2792 #ifdef USE_SSL
2793  /* initialize these values based on SSL mode */
2794  conn->allow_ssl_try = (conn->sslmode[0] != 'd'); /* "disable" */
2795  conn->wait_ssl_try = (conn->sslmode[0] == 'a'); /* "allow" */
2796 #endif
2797 #ifdef ENABLE_GSS
2798  conn->try_gss = (conn->gssencmode[0] != 'd'); /* "disable" */
2799 #endif
2800 
2801  reset_connection_state_machine = false;
2802  need_new_connection = true;
2803  }
2804 
2805  /* Force a new connection (perhaps to the same server as before)? */
2806  if (need_new_connection)
2807  {
2808  /* Drop any existing connection */
2809  pqDropConnection(conn, true);
2810 
2811  /* Reset all state obtained from old server */
2813 
2814  /* Drop any PGresult we might have, too */
2819 
2820  /* Reset conn->status to put the state machine in the right state */
2822 
2823  need_new_connection = false;
2824  }
2825 
2826  /* Now try to advance the state machine for this connection */
2827  switch (conn->status)
2828  {
2829  case CONNECTION_NEEDED:
2830  {
2831  /*
2832  * Try to initiate a connection to one of the addresses
2833  * returned by pg_getaddrinfo_all(). conn->whichaddr is the
2834  * next one to try.
2835  *
2836  * The extra level of braces here is historical. It's not
2837  * worth reindenting this whole switch case to remove 'em.
2838  */
2839  {
2840  char host_addr[NI_MAXHOST];
2841  int sock_type;
2842  AddrInfo *addr_cur;
2843 
2844  /*
2845  * Advance to next possible host, if we've tried all of
2846  * the addresses for the current host.
2847  */
2848  if (conn->whichaddr == conn->naddr)
2849  {
2850  conn->try_next_host = true;
2851  goto keep_going;
2852  }
2853  addr_cur = &conn->addr[conn->whichaddr];
2854 
2855  /* Remember current address for possible use later */
2856  memcpy(&conn->raddr, &addr_cur->addr, sizeof(SockAddr));
2857 
2858  /*
2859  * Set connip, too. Note we purposely ignore strdup
2860  * failure; not a big problem if it fails.
2861  */
2862  if (conn->connip != NULL)
2863  {
2864  free(conn->connip);
2865  conn->connip = NULL;
2866  }
2867  getHostaddr(conn, host_addr, NI_MAXHOST);
2868  if (host_addr[0])
2869  conn->connip = strdup(host_addr);
2870 
2871  /* Try to create the socket */
2872  sock_type = SOCK_STREAM;
2873 #ifdef SOCK_CLOEXEC
2874 
2875  /*
2876  * Atomically mark close-on-exec, if possible on this
2877  * platform, so that there isn't a window where a
2878  * subprogram executed by another thread inherits the
2879  * socket. See fallback code below.
2880  */
2881  sock_type |= SOCK_CLOEXEC;
2882 #endif
2883 #ifdef SOCK_NONBLOCK
2884 
2885  /*
2886  * We might as well skip a system call for nonblocking
2887  * mode too, if we can.
2888  */
2889  sock_type |= SOCK_NONBLOCK;
2890 #endif
2891  conn->sock = socket(addr_cur->family, sock_type, 0);
2892  if (conn->sock == PGINVALID_SOCKET)
2893  {
2894  int errorno = SOCK_ERRNO;
2895 
2896  /*
2897  * Silently ignore socket() failure if we have more
2898  * addresses to try; this reduces useless chatter in
2899  * cases where the address list includes both IPv4 and
2900  * IPv6 but kernel only accepts one family.
2901  */
2902  if (conn->whichaddr < conn->naddr ||
2903  conn->whichhost + 1 < conn->nconnhost)
2904  {
2905  conn->try_next_addr = true;
2906  goto keep_going;
2907  }
2908  emitHostIdentityInfo(conn, host_addr);
2909  libpq_append_conn_error(conn, "could not create socket: %s",
2910  SOCK_STRERROR(errorno, sebuf, sizeof(sebuf)));
2911  goto error_return;
2912  }
2913 
2914  /*
2915  * Once we've identified a target address, all errors
2916  * except the preceding socket()-failure case should be
2917  * prefixed with host-identity information. (If the
2918  * connection succeeds, the contents of conn->errorMessage
2919  * won't matter, so this is harmless.)
2920  */
2921  emitHostIdentityInfo(conn, host_addr);
2922 
2923  /*
2924  * Select socket options: no delay of outgoing data for
2925  * TCP sockets, nonblock mode, close-on-exec. Try the
2926  * next address if any of this fails.
2927  */
2928  if (addr_cur->family != AF_UNIX)
2929  {
2930  if (!connectNoDelay(conn))
2931  {
2932  /* error message already created */
2933  conn->try_next_addr = true;
2934  goto keep_going;
2935  }
2936  }
2937 #ifndef SOCK_NONBLOCK
2938  if (!pg_set_noblock(conn->sock))
2939  {
2940  libpq_append_conn_error(conn, "could not set socket to nonblocking mode: %s",
2941  SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
2942  conn->try_next_addr = true;
2943  goto keep_going;
2944  }
2945 #endif
2946 
2947 #ifndef SOCK_CLOEXEC
2948 #ifdef F_SETFD
2949  if (fcntl(conn->sock, F_SETFD, FD_CLOEXEC) == -1)
2950  {
2951  libpq_append_conn_error(conn, "could not set socket to close-on-exec mode: %s",
2952  SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
2953  conn->try_next_addr = true;
2954  goto keep_going;
2955  }
2956 #endif /* F_SETFD */
2957 #endif
2958 
2959  if (addr_cur->family != AF_UNIX)
2960  {
2961 #ifndef WIN32
2962  int on = 1;
2963 #endif
2964  int usekeepalives = useKeepalives(conn);
2965  int err = 0;
2966 
2967  if (usekeepalives < 0)
2968  {
2969  libpq_append_conn_error(conn, "keepalives parameter must be an integer");
2970  err = 1;
2971  }
2972  else if (usekeepalives == 0)
2973  {
2974  /* Do nothing */
2975  }
2976 #ifndef WIN32
2977  else if (setsockopt(conn->sock,
2978  SOL_SOCKET, SO_KEEPALIVE,
2979  (char *) &on, sizeof(on)) < 0)
2980  {
2981  libpq_append_conn_error(conn, "%s(%s) failed: %s",
2982  "setsockopt",
2983  "SO_KEEPALIVE",
2984  SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
2985  err = 1;
2986  }
2987  else if (!setKeepalivesIdle(conn)
2989  || !setKeepalivesCount(conn))
2990  err = 1;
2991 #else /* WIN32 */
2992 #ifdef SIO_KEEPALIVE_VALS
2993  else if (!prepKeepalivesWin32(conn))
2994  err = 1;
2995 #endif /* SIO_KEEPALIVE_VALS */
2996 #endif /* WIN32 */
2997  else if (!setTCPUserTimeout(conn))
2998  err = 1;
2999 
3000  if (err)
3001  {
3002  conn->try_next_addr = true;
3003  goto keep_going;
3004  }
3005  }
3006 
3007  /*----------
3008  * We have three methods of blocking SIGPIPE during
3009  * send() calls to this socket:
3010  *
3011  * - setsockopt(sock, SO_NOSIGPIPE)
3012  * - send(sock, ..., MSG_NOSIGNAL)
3013  * - setting the signal mask to SIG_IGN during send()
3014  *
3015  * The third method requires three syscalls per send,
3016  * so we prefer either of the first two, but they are
3017  * less portable. The state is tracked in the following
3018  * members of PGconn:
3019  *
3020  * conn->sigpipe_so - we have set up SO_NOSIGPIPE
3021  * conn->sigpipe_flag - we're specifying MSG_NOSIGNAL
3022  *
3023  * If we can use SO_NOSIGPIPE, then set sigpipe_so here
3024  * and we're done. Otherwise, set sigpipe_flag so that
3025  * we will try MSG_NOSIGNAL on sends. If we get an error
3026  * with MSG_NOSIGNAL, we'll clear that flag and revert to
3027  * signal masking.
3028  *----------
3029  */
3030  conn->sigpipe_so = false;
3031 #ifdef MSG_NOSIGNAL
3032  conn->sigpipe_flag = true;
3033 #else
3034  conn->sigpipe_flag = false;
3035 #endif /* MSG_NOSIGNAL */
3036 
3037 #ifdef SO_NOSIGPIPE
3038  optval = 1;
3039  if (setsockopt(conn->sock, SOL_SOCKET, SO_NOSIGPIPE,
3040  (char *) &optval, sizeof(optval)) == 0)
3041  {
3042  conn->sigpipe_so = true;
3043  conn->sigpipe_flag = false;
3044  }
3045 #endif /* SO_NOSIGPIPE */
3046 
3047  /*
3048  * Start/make connection. This should not block, since we
3049  * are in nonblock mode. If it does, well, too bad.
3050  */
3051  if (connect(conn->sock, (struct sockaddr *) &addr_cur->addr.addr,
3052  addr_cur->addr.salen) < 0)
3053  {
3054  if (SOCK_ERRNO == EINPROGRESS ||
3055 #ifdef WIN32
3056  SOCK_ERRNO == EWOULDBLOCK ||
3057 #endif
3058  SOCK_ERRNO == EINTR)
3059  {
3060  /*
3061  * This is fine - we're in non-blocking mode, and
3062  * the connection is in progress. Tell caller to
3063  * wait for write-ready on socket.
3064  */
3066  return PGRES_POLLING_WRITING;
3067  }
3068  /* otherwise, trouble */
3069  }
3070  else
3071  {
3072  /*
3073  * Hm, we're connected already --- seems the "nonblock
3074  * connection" wasn't. Advance the state machine and
3075  * go do the next stuff.
3076  */
3078  goto keep_going;
3079  }
3080 
3081  /*
3082  * This connection failed. Add the error report to
3083  * conn->errorMessage, then try the next address if any.
3084  */
3086  conn->try_next_addr = true;
3087  goto keep_going;
3088  }
3089  }
3090 
3091  case CONNECTION_STARTED:
3092  {
3093  socklen_t optlen = sizeof(optval);
3094 
3095  /*
3096  * Write ready, since we've made it here, so the connection
3097  * has been made ... or has failed.
3098  */
3099 
3100  /*
3101  * Now check (using getsockopt) that there is not an error
3102  * state waiting for us on the socket.
3103  */
3104 
3105  if (getsockopt(conn->sock, SOL_SOCKET, SO_ERROR,
3106  (char *) &optval, &optlen) == -1)
3107  {
3108  libpq_append_conn_error(conn, "could not get socket error status: %s",
3109  SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
3110  goto error_return;
3111  }
3112  else if (optval != 0)
3113  {
3114  /*
3115  * When using a nonblocking connect, we will typically see
3116  * connect failures at this point, so provide a friendly
3117  * error message.
3118  */
3119  connectFailureMessage(conn, optval);
3120 
3121  /*
3122  * Try the next address if any, just as in the case where
3123  * connect() returned failure immediately.
3124  */
3125  conn->try_next_addr = true;
3126  goto keep_going;
3127  }
3128 
3129  /* Fill in the client address */
3130  conn->laddr.salen = sizeof(conn->laddr.addr);
3131  if (getsockname(conn->sock,
3132  (struct sockaddr *) &conn->laddr.addr,
3133  &conn->laddr.salen) < 0)
3134  {
3135  libpq_append_conn_error(conn, "could not get client address from socket: %s",
3136  SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
3137  goto error_return;
3138  }
3139 
3140  /*
3141  * Make sure we can write before advancing to next step.
3142  */
3144  return PGRES_POLLING_WRITING;
3145  }
3146 
3147  case CONNECTION_MADE:
3148  {
3149  char *startpacket;
3150  int packetlen;
3151 
3152  /*
3153  * Implement requirepeer check, if requested and it's a
3154  * Unix-domain socket.
3155  */
3156  if (conn->requirepeer && conn->requirepeer[0] &&
3157  conn->raddr.addr.ss_family == AF_UNIX)
3158  {
3159 #ifndef WIN32
3160  char *remote_username;
3161 #endif
3162  uid_t uid;
3163  gid_t gid;
3164 
3165  errno = 0;
3166  if (getpeereid(conn->sock, &uid, &gid) != 0)
3167  {
3168  /*
3169  * Provide special error message if getpeereid is a
3170  * stub
3171  */
3172  if (errno == ENOSYS)
3173  libpq_append_conn_error(conn, "requirepeer parameter is not supported on this platform");
3174  else
3175  libpq_append_conn_error(conn, "could not get peer credentials: %s",
3176  strerror_r(errno, sebuf, sizeof(sebuf)));
3177  goto error_return;
3178  }
3179 
3180 #ifndef WIN32
3181  remote_username = pg_fe_getusername(uid,
3182  &conn->errorMessage);
3183  if (remote_username == NULL)
3184  goto error_return; /* message already logged */
3185 
3186  if (strcmp(remote_username, conn->requirepeer) != 0)
3187  {
3188  libpq_append_conn_error(conn, "requirepeer specifies \"%s\", but actual peer user name is \"%s\"",
3189  conn->requirepeer, remote_username);
3190  free(remote_username);
3191  goto error_return;
3192  }
3193  free(remote_username);
3194 #else /* WIN32 */
3195  /* should have failed with ENOSYS above */
3196  Assert(false);
3197 #endif /* WIN32 */
3198  }
3199 
3200  if (conn->raddr.addr.ss_family == AF_UNIX)
3201  {
3202  /* Don't request SSL or GSSAPI over Unix sockets */
3203 #ifdef USE_SSL
3204  conn->allow_ssl_try = false;
3205 #endif
3206 #ifdef ENABLE_GSS
3207  conn->try_gss = false;
3208 #endif
3209  }
3210 
3211 #ifdef ENABLE_GSS
3212 
3213  /*
3214  * If GSSAPI encryption is enabled, then call
3215  * pg_GSS_have_cred_cache() which will return true if we can
3216  * acquire credentials (and give us a handle to use in
3217  * conn->gcred), and then send a packet to the server asking
3218  * for GSSAPI Encryption (and skip past SSL negotiation and
3219  * regular startup below).
3220  */
3221  if (conn->try_gss && !conn->gctx)
3222  conn->try_gss = pg_GSS_have_cred_cache(&conn->gcred);
3223  if (conn->try_gss && !conn->gctx)
3224  {
3226 
3227  if (pqPacketSend(conn, 0, &pv, sizeof(pv)) != STATUS_OK)
3228  {
3229  libpq_append_conn_error(conn, "could not send GSSAPI negotiation packet: %s",
3230  SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
3231  goto error_return;
3232  }
3233 
3234  /* Ok, wait for response */
3236  return PGRES_POLLING_READING;
3237  }
3238  else if (!conn->gctx && conn->gssencmode[0] == 'r')
3239  {
3241  "GSSAPI encryption required but was impossible (possibly no credential cache, no server support, or using a local socket)");
3242  goto error_return;
3243  }
3244 #endif
3245 
3246 #ifdef USE_SSL
3247 
3248  /*
3249  * Enable the libcrypto callbacks before checking if SSL needs
3250  * to be done. This is done before sending the startup packet
3251  * as depending on the type of authentication done, like MD5
3252  * or SCRAM that use cryptohashes, the callbacks would be
3253  * required even without a SSL connection
3254  */
3255  if (pqsecure_initialize(conn, false, true) < 0)
3256  goto error_return;
3257 
3258  /*
3259  * If SSL is enabled and we haven't already got encryption of
3260  * some sort running, request SSL instead of sending the
3261  * startup message.
3262  */
3263  if (conn->allow_ssl_try && !conn->wait_ssl_try &&
3264  !conn->ssl_in_use
3265 #ifdef ENABLE_GSS
3266  && !conn->gssenc
3267 #endif
3268  )
3269  {
3270  ProtocolVersion pv;
3271 
3272  /*
3273  * Send the SSL request packet.
3274  *
3275  * Theoretically, this could block, but it really
3276  * shouldn't since we only got here if the socket is
3277  * write-ready.
3278  */
3280  if (pqPacketSend(conn, 0, &pv, sizeof(pv)) != STATUS_OK)
3281  {
3282  libpq_append_conn_error(conn, "could not send SSL negotiation packet: %s",
3283  SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
3284  goto error_return;
3285  }
3286  /* Ok, wait for response */
3288  return PGRES_POLLING_READING;
3289  }
3290 #endif /* USE_SSL */
3291 
3292  /*
3293  * For cancel requests this is as far as we need to go in the
3294  * connection establishment. Now we can actually send our
3295  * cancellation request.
3296  */
3297  if (conn->cancelRequest)
3298  {
3299  CancelRequestPacket cancelpacket;
3300 
3301  packetlen = sizeof(cancelpacket);
3303  cancelpacket.backendPID = pg_hton32(conn->be_pid);
3304  cancelpacket.cancelAuthCode = pg_hton32(conn->be_key);
3305  if (pqPacketSend(conn, 0, &cancelpacket, packetlen) != STATUS_OK)
3306  {
3307  libpq_append_conn_error(conn, "could not send cancel packet: %s",
3308  SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
3309  goto error_return;
3310  }
3312  return PGRES_POLLING_READING;
3313  }
3314 
3315  /*
3316  * Build the startup packet.
3317  */
3318  startpacket = pqBuildStartupPacket3(conn, &packetlen,
3320  if (!startpacket)
3321  {
3322  libpq_append_conn_error(conn, "out of memory");
3323  goto error_return;
3324  }
3325 
3326  /*
3327  * Send the startup packet.
3328  *
3329  * Theoretically, this could block, but it really shouldn't
3330  * since we only got here if the socket is write-ready.
3331  */
3332  if (pqPacketSend(conn, 0, startpacket, packetlen) != STATUS_OK)
3333  {
3334  libpq_append_conn_error(conn, "could not send startup packet: %s",
3335  SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
3336  free(startpacket);
3337  goto error_return;
3338  }
3339 
3340  free(startpacket);
3341 
3343  return PGRES_POLLING_READING;
3344  }
3345 
3346  /*
3347  * Handle SSL negotiation: wait for postmaster messages and
3348  * respond as necessary.
3349  */
3351  {
3352 #ifdef USE_SSL
3353  PostgresPollingStatusType pollres;
3354 
3355  /*
3356  * On first time through, get the postmaster's response to our
3357  * SSL negotiation packet.
3358  */
3359  if (!conn->ssl_in_use)
3360  {
3361  /*
3362  * We use pqReadData here since it has the logic to
3363  * distinguish no-data-yet from connection closure. Since
3364  * conn->ssl isn't set, a plain recv() will occur.
3365  */
3366  char SSLok;
3367  int rdresult;
3368 
3369  rdresult = pqReadData(conn);
3370  if (rdresult < 0)
3371  {
3372  /* errorMessage is already filled in */
3373  goto error_return;
3374  }
3375  if (rdresult == 0)
3376  {
3377  /* caller failed to wait for data */
3378  return PGRES_POLLING_READING;
3379  }
3380  if (pqGetc(&SSLok, conn) < 0)
3381  {
3382  /* should not happen really */
3383  return PGRES_POLLING_READING;
3384  }
3385  if (SSLok == 'S')
3386  {
3387  /* mark byte consumed */
3388  conn->inStart = conn->inCursor;
3389 
3390  /*
3391  * Set up global SSL state if required. The crypto
3392  * state has already been set if libpq took care of
3393  * doing that, so there is no need to make that happen
3394  * again.
3395  */
3396  if (pqsecure_initialize(conn, true, false) != 0)
3397  goto error_return;
3398  }
3399  else if (SSLok == 'N')
3400  {
3401  /* mark byte consumed */
3402  conn->inStart = conn->inCursor;
3403  /* OK to do without SSL? */
3404  if (conn->sslmode[0] == 'r' || /* "require" */
3405  conn->sslmode[0] == 'v') /* "verify-ca" or
3406  * "verify-full" */
3407  {
3408  /* Require SSL, but server does not want it */
3409  libpq_append_conn_error(conn, "server does not support SSL, but SSL was required");
3410  goto error_return;
3411  }
3412  /* Otherwise, proceed with normal startup */
3413  conn->allow_ssl_try = false;
3414  /* We can proceed using this connection */
3416  return PGRES_POLLING_WRITING;
3417  }
3418  else if (SSLok == 'E')
3419  {
3420  /*
3421  * Server failure of some sort, such as failure to
3422  * fork a backend process. We need to process and
3423  * report the error message, which might be formatted
3424  * according to either protocol 2 or protocol 3.
3425  * Rather than duplicate the code for that, we flip
3426  * into AWAITING_RESPONSE state and let the code there
3427  * deal with it. Note we have *not* consumed the "E"
3428  * byte here.
3429  */
3431  goto keep_going;
3432  }
3433  else
3434  {
3435  libpq_append_conn_error(conn, "received invalid response to SSL negotiation: %c",
3436  SSLok);
3437  goto error_return;
3438  }
3439  }
3440 
3441  /*
3442  * Begin or continue the SSL negotiation process.
3443  */
3444  pollres = pqsecure_open_client(conn);
3445  if (pollres == PGRES_POLLING_OK)
3446  {
3447  /*
3448  * At this point we should have no data already buffered.
3449  * If we do, it was received before we performed the SSL
3450  * handshake, so it wasn't encrypted and indeed may have
3451  * been injected by a man-in-the-middle.
3452  */
3453  if (conn->inCursor != conn->inEnd)
3454  {
3455  libpq_append_conn_error(conn, "received unencrypted data after SSL response");
3456  goto error_return;
3457  }
3458 
3459  /* SSL handshake done, ready to send startup packet */
3461  return PGRES_POLLING_WRITING;
3462  }
3463  if (pollres == PGRES_POLLING_FAILED)
3464  {
3465  /*
3466  * Failed ... if sslmode is "prefer" then do a non-SSL
3467  * retry
3468  */
3469  if (conn->sslmode[0] == 'p' /* "prefer" */
3470  && conn->allow_ssl_try /* redundant? */
3471  && !conn->wait_ssl_try) /* redundant? */
3472  {
3473  /* only retry once */
3474  conn->allow_ssl_try = false;
3475  need_new_connection = true;
3476  goto keep_going;
3477  }
3478  /* Else it's a hard failure */
3479  goto error_return;
3480  }
3481  /* Else, return POLLING_READING or POLLING_WRITING status */
3482  return pollres;
3483 #else /* !USE_SSL */
3484  /* can't get here */
3485  goto error_return;
3486 #endif /* USE_SSL */
3487  }
3488 
3490  {
3491 #ifdef ENABLE_GSS
3492  PostgresPollingStatusType pollres;
3493 
3494  /*
3495  * If we haven't yet, get the postmaster's response to our
3496  * negotiation packet
3497  */
3498  if (conn->try_gss && !conn->gctx)
3499  {
3500  char gss_ok;
3501  int rdresult = pqReadData(conn);
3502 
3503  if (rdresult < 0)
3504  /* pqReadData fills in error message */
3505  goto error_return;
3506  else if (rdresult == 0)
3507  /* caller failed to wait for data */
3508  return PGRES_POLLING_READING;
3509  if (pqGetc(&gss_ok, conn) < 0)
3510  /* shouldn't happen... */
3511  return PGRES_POLLING_READING;
3512 
3513  if (gss_ok == 'E')
3514  {
3515  /*
3516  * Server failure of some sort. Assume it's a
3517  * protocol version support failure, and let's see if
3518  * we can't recover (if it's not, we'll get a better
3519  * error message on retry). Server gets fussy if we
3520  * don't hang up the socket, though.
3521  */
3522  conn->try_gss = false;
3523  need_new_connection = true;
3524  goto keep_going;
3525  }
3526 
3527  /* mark byte consumed */
3528  conn->inStart = conn->inCursor;
3529 
3530  if (gss_ok == 'N')
3531  {
3532  /* Server doesn't want GSSAPI; fall back if we can */
3533  if (conn->gssencmode[0] == 'r')
3534  {
3535  libpq_append_conn_error(conn, "server doesn't support GSSAPI encryption, but it was required");
3536  goto error_return;
3537  }
3538 
3539  conn->try_gss = false;
3540  /* We can proceed using this connection */
3542  return PGRES_POLLING_WRITING;
3543  }
3544  else if (gss_ok != 'G')
3545  {
3546  libpq_append_conn_error(conn, "received invalid response to GSSAPI negotiation: %c",
3547  gss_ok);
3548  goto error_return;
3549  }
3550  }
3551 
3552  /* Begin or continue GSSAPI negotiation */
3553  pollres = pqsecure_open_gss(conn);
3554  if (pollres == PGRES_POLLING_OK)
3555  {
3556  /*
3557  * At this point we should have no data already buffered.
3558  * If we do, it was received before we performed the GSS
3559  * handshake, so it wasn't encrypted and indeed may have
3560  * been injected by a man-in-the-middle.
3561  */
3562  if (conn->inCursor != conn->inEnd)
3563  {
3564  libpq_append_conn_error(conn, "received unencrypted data after GSSAPI encryption response");
3565  goto error_return;
3566  }
3567 
3568  /* All set for startup packet */
3570  return PGRES_POLLING_WRITING;
3571  }
3572  else if (pollres == PGRES_POLLING_FAILED)
3573  {
3574  if (conn->gssencmode[0] == 'p')
3575  {
3576  /*
3577  * We failed, but we can retry on "prefer". Have to
3578  * drop the current connection to do so, though.
3579  */
3580  conn->try_gss = false;
3581  need_new_connection = true;
3582  goto keep_going;
3583  }
3584  /* Else it's a hard failure */
3585  goto error_return;
3586  }
3587  /* Else, return POLLING_READING or POLLING_WRITING status */
3588  return pollres;
3589 #else /* !ENABLE_GSS */
3590  /* unreachable */
3591  goto error_return;
3592 #endif /* ENABLE_GSS */
3593  }
3594 
3595  /*
3596  * Handle authentication exchange: wait for postmaster messages
3597  * and respond as necessary.
3598  */
3600  {
3601  char beresp;
3602  int msgLength;
3603  int avail;
3604  AuthRequest areq;
3605  int res;
3606 
3607  /*
3608  * Scan the message from current point (note that if we find
3609  * the message is incomplete, we will return without advancing
3610  * inStart, and resume here next time).
3611  */
3612  conn->inCursor = conn->inStart;
3613 
3614  /* Read type byte */
3615  if (pqGetc(&beresp, conn))
3616  {
3617  /* We'll come back when there is more data */
3618  return PGRES_POLLING_READING;
3619  }
3620 
3621  /*
3622  * Validate message type: we expect only an authentication
3623  * request, NegotiateProtocolVersion, or an error here.
3624  * Anything else probably means it's not Postgres on the other
3625  * end at all.
3626  */
3627  if (beresp != PqMsg_AuthenticationRequest &&
3628  beresp != PqMsg_ErrorResponse &&
3630  {
3631  libpq_append_conn_error(conn, "expected authentication request from server, but received %c",
3632  beresp);
3633  goto error_return;
3634  }
3635 
3636  /* Read message length word */
3637  if (pqGetInt(&msgLength, 4, conn))
3638  {
3639  /* We'll come back when there is more data */
3640  return PGRES_POLLING_READING;
3641  }
3642 
3643  /*
3644  * Try to validate message length before using it.
3645  *
3646  * Authentication requests can't be very large, although GSS
3647  * auth requests may not be that small. Same for
3648  * NegotiateProtocolVersion.
3649  *
3650  * Errors can be a little larger, but not huge. If we see a
3651  * large apparent length in an error, it means we're really
3652  * talking to a pre-3.0-protocol server; cope. (Before
3653  * version 14, the server also used the old protocol for
3654  * errors that happened before processing the startup packet.)
3655  */
3656  if (beresp == PqMsg_AuthenticationRequest &&
3657  (msgLength < 8 || msgLength > 2000))
3658  {
3659  libpq_append_conn_error(conn, "received invalid authentication request");
3660  goto error_return;
3661  }
3662  if (beresp == PqMsg_NegotiateProtocolVersion &&
3663  (msgLength < 8 || msgLength > 2000))
3664  {
3665  libpq_append_conn_error(conn, "received invalid protocol negotiation message");
3666  goto error_return;
3667  }
3668 
3669 #define MAX_ERRLEN 30000
3670  if (beresp == PqMsg_ErrorResponse &&
3671  (msgLength < 8 || msgLength > MAX_ERRLEN))
3672  {
3673  /* Handle error from a pre-3.0 server */
3674  conn->inCursor = conn->inStart + 1; /* reread data */
3676  {
3677  /*
3678  * We may not have authenticated the server yet, so
3679  * don't let the buffer grow forever.
3680  */
3681  avail = conn->inEnd - conn->inCursor;
3682  if (avail > MAX_ERRLEN)
3683  {
3684  libpq_append_conn_error(conn, "received invalid error message");
3685  goto error_return;
3686  }
3687 
3688  /* We'll come back when there is more data */
3689  return PGRES_POLLING_READING;
3690  }
3691  /* OK, we read the message; mark data consumed */
3692  conn->inStart = conn->inCursor;
3693 
3694  /*
3695  * Before 7.2, the postmaster didn't always end its
3696  * messages with a newline, so add one if needed to
3697  * conform to libpq conventions.
3698  */
3699  if (conn->errorMessage.len == 0 ||
3700  conn->errorMessage.data[conn->errorMessage.len - 1] != '\n')
3701  {
3703  }
3704 
3705  goto error_return;
3706  }
3707 #undef MAX_ERRLEN
3708 
3709  /*
3710  * Can't process if message body isn't all here yet.
3711  *
3712  * After this check passes, any further EOF during parsing
3713  * implies that the server sent a bad/truncated message.
3714  * Reading more bytes won't help in that case, so don't return
3715  * PGRES_POLLING_READING after this point.
3716  */
3717  msgLength -= 4;
3718  avail = conn->inEnd - conn->inCursor;
3719  if (avail < msgLength)
3720  {
3721  /*
3722  * Before returning, try to enlarge the input buffer if
3723  * needed to hold the whole message; see notes in
3724  * pqParseInput3.
3725  */
3726  if (pqCheckInBufferSpace(conn->inCursor + (size_t) msgLength,
3727  conn))
3728  goto error_return;
3729  /* We'll come back when there is more data */
3730  return PGRES_POLLING_READING;
3731  }
3732 
3733  /* Handle errors. */
3734  if (beresp == PqMsg_ErrorResponse)
3735  {
3736  if (pqGetErrorNotice3(conn, true))
3737  {
3738  libpq_append_conn_error(conn, "received invalid error message");
3739  goto error_return;
3740  }
3741  /* OK, we read the message; mark data consumed */
3742  conn->inStart = conn->inCursor;
3743 
3744  /*
3745  * If error is "cannot connect now", try the next host if
3746  * any (but we don't want to consider additional addresses
3747  * for this host, nor is there much point in changing SSL
3748  * or GSS mode). This is helpful when dealing with
3749  * standby servers that might not be in hot-standby state.
3750  */
3751  if (strcmp(conn->last_sqlstate,
3753  {
3754  conn->try_next_host = true;
3755  goto keep_going;
3756  }
3757 
3758  /* Check to see if we should mention pgpassfile */
3760 
3761 #ifdef ENABLE_GSS
3762 
3763  /*
3764  * If gssencmode is "prefer" and we're using GSSAPI, retry
3765  * without it.
3766  */
3767  if (conn->gssenc && conn->gssencmode[0] == 'p')
3768  {
3769  /* only retry once */
3770  conn->try_gss = false;
3771  need_new_connection = true;
3772  goto keep_going;
3773  }
3774 #endif
3775 
3776 #ifdef USE_SSL
3777 
3778  /*
3779  * if sslmode is "allow" and we haven't tried an SSL
3780  * connection already, then retry with an SSL connection
3781  */
3782  if (conn->sslmode[0] == 'a' /* "allow" */
3783  && !conn->ssl_in_use
3784  && conn->allow_ssl_try
3785  && conn->wait_ssl_try)
3786  {
3787  /* only retry once */
3788  conn->wait_ssl_try = false;
3789  need_new_connection = true;
3790  goto keep_going;
3791  }
3792 
3793  /*
3794  * if sslmode is "prefer" and we're in an SSL connection,
3795  * then do a non-SSL retry
3796  */
3797  if (conn->sslmode[0] == 'p' /* "prefer" */
3798  && conn->ssl_in_use
3799  && conn->allow_ssl_try /* redundant? */
3800  && !conn->wait_ssl_try) /* redundant? */
3801  {
3802  /* only retry once */
3803  conn->allow_ssl_try = false;
3804  need_new_connection = true;
3805  goto keep_going;
3806  }
3807 #endif
3808 
3809  goto error_return;
3810  }
3811  else if (beresp == PqMsg_NegotiateProtocolVersion)
3812  {
3814  {
3815  libpq_append_conn_error(conn, "received invalid protocol negotiation message");
3816  goto error_return;
3817  }
3818  /* OK, we read the message; mark data consumed */
3819  conn->inStart = conn->inCursor;
3820  goto error_return;
3821  }
3822 
3823  /* It is an authentication request. */
3824  conn->auth_req_received = true;
3825 
3826  /* Get the type of request. */
3827  if (pqGetInt((int *) &areq, 4, conn))
3828  {
3829  /* can't happen because we checked the length already */
3830  libpq_append_conn_error(conn, "received invalid authentication request");
3831  goto error_return;
3832  }
3833  msgLength -= 4;
3834 
3835  /*
3836  * Process the rest of the authentication request message, and
3837  * respond to it if necessary.
3838  *
3839  * Note that conn->pghost must be non-NULL if we are going to
3840  * avoid the Kerberos code doing a hostname look-up.
3841  */
3842  res = pg_fe_sendauth(areq, msgLength, conn);
3843 
3844  /* OK, we have processed the message; mark data consumed */
3845  conn->inStart = conn->inCursor;
3846 
3847  if (res != STATUS_OK)
3848  goto error_return;
3849 
3850  /*
3851  * Just make sure that any data sent by pg_fe_sendauth is
3852  * flushed out. Although this theoretically could block, it
3853  * really shouldn't since we don't send large auth responses.
3854  */
3855  if (pqFlush(conn))
3856  goto error_return;
3857 
3858  if (areq == AUTH_REQ_OK)
3859  {
3860  /* We are done with authentication exchange */
3862 
3863  /*
3864  * Set asyncStatus so that PQgetResult will think that
3865  * what comes back next is the result of a query. See
3866  * below.
3867  */
3869  }
3870 
3871  /* Look to see if we have more data yet. */
3872  goto keep_going;
3873  }
3874 
3875  case CONNECTION_AUTH_OK:
3876  {
3877  /*
3878  * Now we expect to hear from the backend. A ReadyForQuery
3879  * message indicates that startup is successful, but we might
3880  * also get an Error message indicating failure. (Notice
3881  * messages indicating nonfatal warnings are also allowed by
3882  * the protocol, as are ParameterStatus and BackendKeyData
3883  * messages.) Easiest way to handle this is to let
3884  * PQgetResult() read the messages. We just have to fake it
3885  * out about the state of the connection, by setting
3886  * asyncStatus = PGASYNC_BUSY (done above).
3887  */
3888 
3889  if (PQisBusy(conn))
3890  return PGRES_POLLING_READING;
3891 
3892  res = PQgetResult(conn);
3893 
3894  /*
3895  * NULL return indicating we have gone to IDLE state is
3896  * expected
3897  */
3898  if (res)
3899  {
3901  libpq_append_conn_error(conn, "unexpected message from server during startup");
3902  else if (conn->send_appname &&
3903  (conn->appname || conn->fbappname))
3904  {
3905  /*
3906  * If we tried to send application_name, check to see
3907  * if the error is about that --- pre-9.0 servers will
3908  * reject it at this stage of the process. If so,
3909  * close the connection and retry without sending
3910  * application_name. We could possibly get a false
3911  * SQLSTATE match here and retry uselessly, but there
3912  * seems no great harm in that; we'll just get the
3913  * same error again if it's unrelated.
3914  */
3915  const char *sqlstate;
3916 
3918  if (sqlstate &&
3919  strcmp(sqlstate, ERRCODE_APPNAME_UNKNOWN) == 0)
3920  {
3921  PQclear(res);
3922  conn->send_appname = false;
3923  need_new_connection = true;
3924  goto keep_going;
3925  }
3926  }
3927 
3928  /*
3929  * if the resultStatus is FATAL, then conn->errorMessage
3930  * already has a copy of the error; needn't copy it back.
3931  * But add a newline if it's not there already, since
3932  * postmaster error messages may not have one.
3933  */
3934  if (conn->errorMessage.len <= 0 ||
3935  conn->errorMessage.data[conn->errorMessage.len - 1] != '\n')
3937  PQclear(res);
3938  goto error_return;
3939  }
3940 
3941  /* Almost there now ... */
3943  goto keep_going;
3944  }
3945 
3947  {
3948  /*
3949  * If a read-write, read-only, primary, or standby connection
3950  * is required, see if we have one.
3951  */
3954  {
3955  bool read_only_server;
3956 
3957  /*
3958  * If the server didn't report
3959  * "default_transaction_read_only" or "in_hot_standby" at
3960  * startup, we must determine its state by sending the
3961  * query "SHOW transaction_read_only". This GUC exists in
3962  * all server versions that support 3.0 protocol.
3963  */
3966  {
3967  /*
3968  * We use PQsendQueryContinue so that
3969  * conn->errorMessage does not get cleared. We need
3970  * to preserve any error messages related to previous
3971  * hosts we have tried and failed to connect to.
3972  */
3975  "SHOW transaction_read_only"))
3976  goto error_return;
3977  /* We'll return to this state when we have the answer */
3979  return PGRES_POLLING_READING;
3980  }
3981 
3982  /* OK, we can make the test */
3983  read_only_server =
3986 
3988  read_only_server : !read_only_server)
3989  {
3990  /* Wrong server state, reject and try the next host */
3992  libpq_append_conn_error(conn, "session is read-only");
3993  else
3994  libpq_append_conn_error(conn, "session is not read-only");
3995 
3996  /* Close connection politely. */
3999 
4000  /*
4001  * Try next host if any, but we don't want to consider
4002  * additional addresses for this host.
4003  */
4004  conn->try_next_host = true;
4005  goto keep_going;
4006  }
4007  }
4011  {
4012  /*
4013  * If the server didn't report "in_hot_standby" at
4014  * startup, we must determine its state by sending the
4015  * query "SELECT pg_catalog.pg_is_in_recovery()". Servers
4016  * before 9.0 don't have that function, but by the same
4017  * token they don't have any standby mode, so we may just
4018  * assume the result.
4019  */
4020  if (conn->sversion < 90000)
4022 
4024  {
4025  /*
4026  * We use PQsendQueryContinue so that
4027  * conn->errorMessage does not get cleared. We need
4028  * to preserve any error messages related to previous
4029  * hosts we have tried and failed to connect to.
4030  */
4033  "SELECT pg_catalog.pg_is_in_recovery()"))
4034  goto error_return;
4035  /* We'll return to this state when we have the answer */
4037  return PGRES_POLLING_READING;
4038  }
4039 
4040  /* OK, we can make the test */
4044  {
4045  /* Wrong server state, reject and try the next host */
4047  libpq_append_conn_error(conn, "server is in hot standby mode");
4048  else
4049  libpq_append_conn_error(conn, "server is not in hot standby mode");
4050 
4051  /* Close connection politely. */
4054 
4055  /*
4056  * Try next host if any, but we don't want to consider
4057  * additional addresses for this host.
4058  */
4059  conn->try_next_host = true;
4060  goto keep_going;
4061  }
4062  }
4063 
4064  /*
4065  * For non cancel requests we can release the address list
4066  * now. For cancel requests we never actually resolve
4067  * addresses and instead the addrinfo exists for the lifetime
4068  * of the connection.
4069  */
4070  if (!conn->cancelRequest)
4072 
4073  /*
4074  * Contents of conn->errorMessage are no longer interesting
4075  * (and it seems some clients expect it to be empty after a
4076  * successful connection).
4077  */
4079 
4080  /* We are open for business! */
4082  return PGRES_POLLING_OK;
4083  }
4084 
4085  case CONNECTION_CONSUME:
4086  {
4087  /*
4088  * This state just makes sure the connection is idle after
4089  * we've obtained the result of a SHOW or SELECT query. Once
4090  * we're clear, return to CONNECTION_CHECK_TARGET state to
4091  * decide what to do next. We must transiently set status =
4092  * CONNECTION_OK in order to use the result-consuming
4093  * subroutines.
4094  */
4096  if (!PQconsumeInput(conn))
4097  goto error_return;
4098 
4099  if (PQisBusy(conn))
4100  {
4102  return PGRES_POLLING_READING;
4103  }
4104 
4105  /* Call PQgetResult() again until we get a NULL result */
4106  res = PQgetResult(conn);
4107  if (res != NULL)
4108  {
4109  PQclear(res);
4111  return PGRES_POLLING_READING;
4112  }
4113 
4115  goto keep_going;
4116  }
4117 
4119  {
4120  /*
4121  * Waiting for result of "SHOW transaction_read_only". We
4122  * must transiently set status = CONNECTION_OK in order to use
4123  * the result-consuming subroutines.
4124  */
4126  if (!PQconsumeInput(conn))
4127  goto error_return;
4128 
4129  if (PQisBusy(conn))
4130  {
4132  return PGRES_POLLING_READING;
4133  }
4134 
4135  res = PQgetResult(conn);
4136  if (res && PQresultStatus(res) == PGRES_TUPLES_OK &&
4137  PQntuples(res) == 1)
4138  {
4139  char *val = PQgetvalue(res, 0, 0);
4140 
4141  /*
4142  * "transaction_read_only = on" proves that at least one
4143  * of default_transaction_read_only and in_hot_standby is
4144  * on, but we don't actually know which. We don't care
4145  * though for the purpose of identifying a read-only
4146  * session, so satisfy the CONNECTION_CHECK_TARGET code by
4147  * claiming they are both on. On the other hand, if it's
4148  * a read-write session, they are certainly both off.
4149  */
4150  if (strncmp(val, "on", 2) == 0)
4151  {
4154  }
4155  else
4156  {
4159  }
4160  PQclear(res);
4161 
4162  /* Finish reading messages before continuing */
4164  goto keep_going;
4165  }
4166 
4167  /* Something went wrong with "SHOW transaction_read_only". */
4168  PQclear(res);
4169 
4170  /* Append error report to conn->errorMessage. */
4171  libpq_append_conn_error(conn, "\"%s\" failed",
4172  "SHOW transaction_read_only");
4173 
4174  /* Close connection politely. */
4177 
4178  /* Try next host. */
4179  conn->try_next_host = true;
4180  goto keep_going;
4181  }
4182 
4184  {
4185  /*
4186  * Waiting for result of "SELECT pg_is_in_recovery()". We
4187  * must transiently set status = CONNECTION_OK in order to use
4188  * the result-consuming subroutines.
4189  */
4191  if (!PQconsumeInput(conn))
4192  goto error_return;
4193 
4194  if (PQisBusy(conn))
4195  {
4197  return PGRES_POLLING_READING;
4198  }
4199 
4200  res = PQgetResult(conn);
4201  if (res && PQresultStatus(res) == PGRES_TUPLES_OK &&
4202  PQntuples(res) == 1)
4203  {
4204  char *val = PQgetvalue(res, 0, 0);
4205 
4206  if (strncmp(val, "t", 1) == 0)
4208  else
4210  PQclear(res);
4211 
4212  /* Finish reading messages before continuing */
4214  goto keep_going;
4215  }
4216 
4217  /* Something went wrong with "SELECT pg_is_in_recovery()". */
4218  PQclear(res);
4219 
4220  /* Append error report to conn->errorMessage. */
4221  libpq_append_conn_error(conn, "\"%s\" failed",
4222  "SELECT pg_is_in_recovery()");
4223 
4224  /* Close connection politely. */
4227 
4228  /* Try next host. */
4229  conn->try_next_host = true;
4230  goto keep_going;
4231  }
4232 
4233  default:
4235  "invalid connection state %d, probably indicative of memory corruption",
4236  conn->status);
4237  goto error_return;
4238  }
4239 
4240  /* Unreachable */
4241 
4242 error_return:
4243 
4244  /*
4245  * We used to close the socket at this point, but that makes it awkward
4246  * for those above us if they wish to remove this socket from their own
4247  * records (an fd_set for example). We'll just have this socket closed
4248  * when PQfinish is called (which is compulsory even after an error, since
4249  * the connection structure must be freed).
4250  */
4252  return PGRES_POLLING_FAILED;
4253 }
#define STATUS_OK
Definition: c.h:1156
#define MemSet(start, val, len)
Definition: c.h:1007
void err(int eval, const char *fmt,...)
Definition: err.c:43
int pg_fe_sendauth(AuthRequest areq, int payloadlen, PGconn *conn)
Definition: fe-auth.c:962
char * pg_fe_getusername(uid_t user_id, PQExpBuffer errorMessage)
Definition: fe-auth.c:1170
#define MAX_ERRLEN
void pqDropConnection(PGconn *conn, bool flushInput)
Definition: fe-connect.c:460
static const PQEnvironmentOption EnvironmentOptions[]
Definition: fe-connect.c:367
static void sendTerminateConn(PGconn *conn)
Definition: fe-connect.c:4589
static int setKeepalivesCount(PGconn *conn)
Definition: fe-connect.c:2194
static int useKeepalives(PGconn *conn)
Definition: fe-connect.c:2107
static int store_conn_addrinfo(PGconn *conn, struct addrinfo *addrlist)
Definition: fe-connect.c:4536
static void connectFailureMessage(PGconn *conn, int errorno)
Definition: fe-connect.c:2087
static void release_conn_addrinfo(PGconn *conn)
Definition: fe-connect.c:4575
#define ERRCODE_APPNAME_UNKNOWN
Definition: fe-connect.c:86
static int setKeepalivesInterval(PGconn *conn)
Definition: fe-connect.c:2159
static int setKeepalivesIdle(PGconn *conn)
Definition: fe-connect.c:2125
bool pqParseIntParam(const char *value, int *result, PGconn *conn, const char *context)
Definition: fe-connect.c:7483
static void pgpassfileWarning(PGconn *conn)
Definition: fe-connect.c:7354
static void emitHostIdentityInfo(PGconn *conn, const char *host_addr)
Definition: fe-connect.c:2031
static int setTCPUserTimeout(PGconn *conn)
Definition: fe-connect.c:2291
static void pqDropServerData(PGconn *conn)
Definition: fe-connect.c:573
static int connectNoDelay(PGconn *conn)
Definition: fe-connect.c:1972
static void getHostaddr(PGconn *conn, char *host_addr, int host_addr_len)
Definition: fe-connect.c:1998
#define ERRCODE_CANNOT_CONNECT_NOW
Definition: fe-connect.c:91
int pqPacketSend(PGconn *conn, char pack_type, const void *buf, size_t buf_len)
Definition: fe-connect.c:4777
int PQsendQueryContinue(PGconn *conn, const char *query)
Definition: fe-exec.c:1431
int PQntuples(const PGresult *res)
Definition: fe-exec.c:3441
int PQconsumeInput(PGconn *conn)
Definition: fe-exec.c:1960
char * PQgetvalue(const PGresult *res, int tup_num, int field_num)
Definition: fe-exec.c:3836
void pqClearAsyncResult(PGconn *conn)
Definition: fe-exec.c:777
int PQisBusy(PGconn *conn)
Definition: fe-exec.c:2007
char * PQresultErrorField(const PGresult *res, int fieldcode)
Definition: fe-exec.c:3426
PGresult * PQgetResult(PGconn *conn)
Definition: fe-exec.c:2038
bool pg_GSS_have_cred_cache(gss_cred_id_t *cred_out)
int pqFlush(PGconn *conn)
Definition: fe-misc.c:954
int pqGetc(char *result, PGconn *conn)
Definition: fe-misc.c:78
int pqGetInt(int *result, size_t bytes, PGconn *conn)
Definition: fe-misc.c:217
int pqCheckInBufferSpace(size_t bytes_needed, PGconn *conn)
Definition: fe-misc.c:352
int pqGets_append(PQExpBuffer buf, PGconn *conn)
Definition: fe-misc.c:143
int pqGetNegotiateProtocolVersion3(PGconn *conn)
int pqGetErrorNotice3(PGconn *conn, bool isError)
Definition: fe-protocol3.c:881
char * pqBuildStartupPacket3(PGconn *conn, int *packetlen, const PQEnvironmentOption *options)
PostgresPollingStatusType pqsecure_open_gss(PGconn *conn)
PostgresPollingStatusType pqsecure_open_client(PGconn *conn)
Definition: fe-secure.c:153
int pqsecure_initialize(PGconn *conn, bool do_ssl, bool do_crypto)
Definition: fe-secure.c:138
void pg_freeaddrinfo_all(int hint_ai_family, struct addrinfo *ai)
Definition: ip.c:82
int pg_getaddrinfo_all(const char *hostname, const char *servname, const struct addrinfo *hintp, struct addrinfo **result)
Definition: ip.c:53
int j
Definition: isn.c:74
@ PGASYNC_IDLE
Definition: libpq-int.h:221
@ PGASYNC_BUSY
Definition: libpq-int.h:222
@ LOAD_BALANCE_RANDOM
Definition: libpq-int.h:250
#define SOCK_STRERROR
Definition: libpq-int.h:921
@ CHT_UNIX_SOCKET
Definition: libpq-int.h:311
@ CHT_HOST_ADDRESS
Definition: libpq-int.h:310
@ CHT_HOST_NAME
Definition: libpq-int.h:309
@ PG_BOOL_YES
Definition: libpq-int.h:257
@ PG_BOOL_NO
Definition: libpq-int.h:258
@ PG_BOOL_UNKNOWN
Definition: libpq-int.h:256
@ SERVER_TYPE_STANDBY
Definition: libpq-int.h:241
@ SERVER_TYPE_PRIMARY
Definition: libpq-int.h:240
@ SERVER_TYPE_READ_WRITE
Definition: libpq-int.h:238
@ SERVER_TYPE_PREFER_STANDBY_PASS2
Definition: libpq-int.h:243
@ SERVER_TYPE_PREFER_STANDBY
Definition: libpq-int.h:242
@ SERVER_TYPE_READ_ONLY
Definition: libpq-int.h:239
#define MAXPGPATH
uint64 pg_prng_uint64_range(pg_prng_state *state, uint64 rmin, uint64 rmax)
Definition: pg_prng.c:144
static char portstr[16]
Definition: pg_regress.c:117
bool pg_set_noblock(pgsocket sock)
Definition: noblock.c:25
#define snprintf
Definition: port.h:238
unsigned int socklen_t
Definition: port.h:40
int getpeereid(int sock, uid_t *uid, gid_t *gid)
Definition: getpeereid.c:33
#define PG_DIAG_SQLSTATE
Definition: postgres_ext.h:56
#define UNIXSOCK_PATH(path, port, sockdir)
Definition: pqcomm.h:44
#define UNIXSOCK_PATH_BUFLEN
Definition: pqcomm.h:60
#define NEGOTIATE_GSS_CODE
Definition: pqcomm.h:148
#define NEGOTIATE_SSL_CODE
Definition: pqcomm.h:147
uint32 ProtocolVersion
Definition: pqcomm.h:99
uint32 AuthRequest
Definition: pqcomm.h:121
#define PG_PROTOCOL(m, n)
Definition: pqcomm.h:89
void appendPQExpBufferChar(PQExpBuffer str, char ch)
Definition: pqexpbuffer.c:378
#define AUTH_REQ_OK
Definition: protocol.h:70
#define PqMsg_AuthenticationRequest
Definition: protocol.h:50
#define PqMsg_NegotiateProtocolVersion
Definition: protocol.h:59
#define PqMsg_ErrorResponse
Definition: protocol.h:44
const char * gai_strerror(int ecode)
int family
Definition: pqcomm.h:38
SockAddr addr
Definition: pqcomm.h:39
MsgType cancelRequestCode
Definition: pqcomm.h:137
uint32 backendPID
Definition: pqcomm.h:138
uint32 cancelAuthCode
Definition: pqcomm.h:139
pg_conn_host_type type
Definition: libpq-int.h:345
SockAddr laddr
Definition: libpq-int.h:465
bool try_next_host
Definition: libpq-int.h:490
AddrInfo * addr
Definition: libpq-int.h:493
bool sigpipe_flag
Definition: libpq-int.h:473
int nconnhost
Definition: libpq-int.h:444
ProtocolVersion pversion
Definition: libpq-int.h:467
bool send_appname
Definition: libpq-int.h:495
PGTransactionStatusType xactStatus
Definition: libpq-int.h:431
bool cancelRequest
Definition: libpq-int.h:412
int inCursor
Definition: libpq-int.h:515
PGTernaryBool in_hot_standby
Definition: libpq-int.h:504
int inEnd
Definition: libpq-int.h:516
char * fbappname
Definition: libpq-int.h:376
int naddr
Definition: libpq-int.h:491
int inStart
Definition: libpq-int.h:514
char * connip
Definition: libpq-int.h:447
int sversion
Definition: libpq-int.h:468
bool auth_req_received
Definition: libpq-int.h:469
PGTernaryBool default_transaction_read_only
Definition: libpq-int.h:503
bool sigpipe_so
Definition: libpq-int.h:472
int whichaddr
Definition: libpq-int.h:492
char * appname
Definition: libpq-int.h:375
char * sslmode
Definition: libpq-int.h:390
pg_prng_state prng_state
Definition: libpq-int.h:508
char * gssencmode
Definition: libpq-int.h:401
char last_sqlstate[6]
Definition: libpq-int.h:432
PGAsyncStatusType asyncStatus
Definition: libpq-int.h:430
PGLoadBalanceType load_balance_type
Definition: libpq-int.h:487
PGpipelineStatus pipelineStatus
Definition: libpq-int.h:436
PGTargetServerType target_server_type
Definition: libpq-int.h:486
bool try_next_addr
Definition: libpq-int.h:489
char * requirepeer
Definition: libpq-int.h:400
bool ssl_in_use
Definition: libpq-int.h:551
ExecStatusType resultStatus
Definition: libpq-int.h:180
#define EWOULDBLOCK
Definition: win32_port.h:380
#define EINPROGRESS
Definition: win32_port.h:386
int gid_t
Definition: win32_port.h:245
int uid_t
Definition: win32_port.h:244

References AddrInfo::addr, SockAddr::addr, pg_conn::addr, appendPQExpBufferChar(), pg_conn::appname, Assert(), pg_conn::asyncStatus, AUTH_REQ_OK, pg_conn::auth_req_received, CancelRequestPacket::backendPID, pg_conn::be_key, pg_conn::be_pid, CANCEL_REQUEST_CODE, CancelRequestPacket::cancelAuthCode, pg_conn::cancelRequest, CancelRequestPacket::cancelRequestCode, CHT_HOST_ADDRESS, CHT_HOST_NAME, CHT_UNIX_SOCKET, conn, connect, connectFailureMessage(), CONNECTION_AUTH_OK, CONNECTION_AWAITING_RESPONSE, CONNECTION_BAD, CONNECTION_CHECK_STANDBY, CONNECTION_CHECK_TARGET, CONNECTION_CHECK_WRITABLE, CONNECTION_CONSUME, CONNECTION_GSS_STARTUP, CONNECTION_MADE, CONNECTION_NEEDED, CONNECTION_OK, CONNECTION_SSL_STARTUP, CONNECTION_STARTED, connectNoDelay(), pg_conn::connhost, pg_conn::connip, PQExpBufferData::data, pg_conn::default_transaction_read_only, EINPROGRESS, EINTR, emitHostIdentityInfo(), EnvironmentOptions, err(), ERRCODE_APPNAME_UNKNOWN, ERRCODE_CANNOT_CONNECT_NOW, pg_conn::errorMessage, EWOULDBLOCK, AddrInfo::family, pg_conn::fbappname, free, gai_strerror(), getHostaddr(), getpeereid(), pg_conn::gssencmode, pg_conn_host::host, pg_conn_host::hostaddr, i, pg_conn::in_hot_standby, pg_conn::inCursor, pg_conn::inEnd, pg_conn::inStart, j, pg_conn::laddr, pg_conn::last_sqlstate, PQExpBufferData::len, libpq_append_conn_error(), LOAD_BALANCE_RANDOM, pg_conn::load_balance_type, MAX_ERRLEN, MAXPGPATH, MemSet, pg_conn::naddr, pg_conn::nconnhost, NEGOTIATE_GSS_CODE, NEGOTIATE_SSL_CODE, PG_BOOL_NO, PG_BOOL_UNKNOWN, PG_BOOL_YES, PG_DIAG_SQLSTATE, pg_fe_getusername(), pg_fe_sendauth(), pg_freeaddrinfo_all(), pg_getaddrinfo_all(), pg_GSS_have_cred_cache(), pg_hton32, pg_prng_uint64_range(), PG_PROTOCOL, pg_set_noblock(), PG_STRERROR_R_BUFLEN, PGASYNC_BUSY, PGASYNC_IDLE, PGINVALID_SOCKET, pgpassfileWarning(), PGRES_FATAL_ERROR, PGRES_POLLING_FAILED, PGRES_POLLING_OK, PGRES_POLLING_READING, PGRES_POLLING_WRITING, PGRES_TUPLES_OK, pg_conn::pipelineStatus, pg_conn_host::port, portstr, PQ_PIPELINE_OFF, pqBuildStartupPacket3(), pqCheckInBufferSpace(), PQclear(), pqClearAsyncResult(), pqClearConnErrorState, PQconsumeInput(), pqDropConnection(), pqDropServerData(), pqFlush(), pqGetc(), pqGetErrorNotice3(), pqGetInt(), pqGetNegotiateProtocolVersion3(), PQgetResult(), pqGets_append(), PQgetvalue(), PQisBusy(), PqMsg_AuthenticationRequest, PqMsg_ErrorResponse, PqMsg_NegotiateProtocolVersion, PQntuples(), pqPacketSend(), pqParseIntParam(), pqReadData(), PQresultErrorField(), PQresultStatus(), pqsecure_initialize(), pqsecure_open_client(), pqsecure_open_gss(), PQsendQueryContinue(), PQTRANS_IDLE, pg_conn::prng_state, pg_conn::pversion, pg_conn::raddr, release_conn_addrinfo(), pg_conn::requirepeer, res, pg_result::resultStatus, SockAddr::salen, pg_conn::send_appname, sendTerminateConn(), SERVER_TYPE_PREFER_STANDBY, SERVER_TYPE_PREFER_STANDBY_PASS2, SERVER_TYPE_PRIMARY, SERVER_TYPE_READ_ONLY, SERVER_TYPE_READ_WRITE, SERVER_TYPE_STANDBY, setKeepalivesCount(), setKeepalivesIdle(), setKeepalivesInterval(), setTCPUserTimeout(), pg_conn::sigpipe_flag, pg_conn::sigpipe_so, snprintf, pg_conn::sock, SOCK_ERRNO, SOCK_STRERROR, socket, pg_conn::ssl_in_use, pg_conn::sslmode, pg_conn::status, STATUS_OK, store_conn_addrinfo(), strerror_r, pg_conn::sversion, pg_conn::target_server_type, pg_conn::try_next_addr, pg_conn::try_next_host, pg_conn_host::type, UNIXSOCK_PATH, UNIXSOCK_PATH_BUFLEN, useKeepalives(), val, pg_conn::whichaddr, pg_conn::whichhost, and pg_conn::xactStatus.

Referenced by libpqrcv_connect(), libpqsrv_connect_internal(), PQcancelPoll(), pqConnectDBComplete(), pqConnectDBStart(), and PQresetPoll().

◆ PQconnectStart()

PGconn* PQconnectStart ( const char *  conninfo)

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

862 {
863  PGconn *conn;
864 
865  /*
866  * Allocate memory for the conn structure. Note that we also expect this
867  * to initialize conn->errorMessage to empty. All subsequent steps during
868  * connection initialization will only append to that buffer.
869  */
871  if (conn == NULL)
872  return NULL;
873 
874  /*
875  * Parse the conninfo string
876  */
877  if (!connectOptions1(conn, conninfo))
878  return conn;
879 
880  /*
881  * Compute derived options
882  */
883  if (!pqConnectOptions2(conn))
884  return conn;
885 
886  /*
887  * Connect to the database
888  */
889  if (!pqConnectDBStart(conn))
890  {
891  /* Just in case we failed to set it in pqConnectDBStart */
893  }
894 
895  return conn;
896 }
static bool connectOptions1(PGconn *conn, const char *conninfo)
Definition: fe-connect.c:986

References conn, CONNECTION_BAD, connectOptions1(), pqConnectDBStart(), pqConnectOptions2(), pqMakeEmptyPGconn(), and pg_conn::status.

Referenced by libpqsrv_connect(), PQconnectdb(), and PQping().

◆ PQconnectStartParams()

PGconn* PQconnectStartParams ( const char *const *  keywords,
const char *const *  values,
int  expand_dbname 
)

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

783 {
784  PGconn *conn;
785  PQconninfoOption *connOptions;
786 
787  /*
788  * Allocate memory for the conn structure. Note that we also expect this
789  * to initialize conn->errorMessage to empty. All subsequent steps during
790  * connection initialization will only append to that buffer.
791  */
793  if (conn == NULL)
794  return NULL;
795 
796  /*
797  * Parse the conninfo arrays
798  */
799  connOptions = conninfo_array_parse(keywords, values,
800  &conn->errorMessage,
801  true, expand_dbname);
802  if (connOptions == NULL)
803  {
805  /* errorMessage is already set */
806  return conn;
807  }
808 
809  /*
810  * Move option values into conn structure
811  */
812  if (!fillPGconn(conn, connOptions))
813  {
814  PQconninfoFree(connOptions);
815  return conn;
816  }
817 
818  /*
819  * Free the option info - all is in conn now
820  */
821  PQconninfoFree(connOptions);
822 
823  /*
824  * Compute derived options
825  */
826  if (!pqConnectOptions2(conn))
827  return conn;
828 
829  /*
830  * Connect to the database
831  */
832  if (!pqConnectDBStart(conn))
833  {
834  /* Just in case we failed to set it in pqConnectDBStart */
836  }
837 
838  return conn;
839 }
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:5820
static bool fillPGconn(PGconn *conn, PQconninfoOption *connOptions)
Definition: fe-connect.c:907

References conn, CONNECTION_BAD, conninfo_array_parse(), pg_conn::errorMessage, fillPGconn(), pqConnectDBStart(), pqConnectOptions2(), PQconninfoFree(), pqMakeEmptyPGconn(), pg_conn::status, and values.

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

◆ PQconninfo()

PQconninfoOption* PQconninfo ( PGconn conn)

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

6738 {
6739  PQExpBufferData errorBuf;
6740  PQconninfoOption *connOptions;
6741 
6742  if (conn == NULL)
6743  return NULL;
6744 
6745  /*
6746  * We don't actually report any errors here, but callees want a buffer,
6747  * and we prefer not to trash the conn's errorMessage.
6748  */
6749  initPQExpBuffer(&errorBuf);
6750  if (PQExpBufferDataBroken(errorBuf))
6751  return NULL; /* out of memory already :-( */
6752 
6753  connOptions = conninfo_init(&errorBuf);
6754 
6755  if (connOptions != NULL)
6756  {
6758 
6759  for (option = PQconninfoOptions; option->keyword; option++)
6760  {
6761  char **connmember;
6762 
6763  if (option->connofs < 0)
6764  continue;
6765 
6766  connmember = (char **) ((char *) conn + option->connofs);
6767 
6768  if (*connmember)
6769  conninfo_storeval(connOptions, option->keyword, *connmember,
6770  &errorBuf, true, false);
6771  }
6772  }
6773 
6774  termPQExpBuffer(&errorBuf);
6775 
6776  return connOptions;
6777 }
static PQconninfoOption * conninfo_storeval(PQconninfoOption *connOptions, const char *keyword, const char *value, PQExpBuffer errorMessage, bool ignoreMissing, bool uri_decode)
Definition: fe-connect.c:6655
static const internalPQconninfoOption PQconninfoOptions[]
Definition: fe-connect.c:189

References conn, conninfo_init(), conninfo_storeval(), initPQExpBuffer(), PQconninfoOptions, PQExpBufferDataBroken, and termPQExpBuffer().

Referenced by copy_connection(), do_connect(), GenerateRecoveryConfig(), and libpqrcv_get_conninfo().

◆ PQconninfoFree()

void PQconninfoFree ( PQconninfoOption connOptions)

◆ PQconninfoParse()

PQconninfoOption* PQconninfoParse ( const char *  conninfo,
char **  errmsg 
)

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

5530 {
5531  PQExpBufferData errorBuf;
5532  PQconninfoOption *connOptions;
5533 
5534  if (errmsg)
5535  *errmsg = NULL; /* default */
5536  initPQExpBuffer(&errorBuf);
5537  if (PQExpBufferDataBroken(errorBuf))
5538  return NULL; /* out of memory already :-( */
5539  connOptions = parse_connection_string(conninfo, &errorBuf, false);
5540  if (connOptions == NULL && errmsg)
5541  *errmsg = errorBuf.data;
5542  else
5543  termPQExpBuffer(&errorBuf);
5544  return connOptions;
5545 }
int errmsg(const char *fmt,...)
Definition: elog.c:1072
static PQconninfoOption * parse_connection_string(const char *connstr, PQExpBuffer errorMessage, bool use_defaults)
Definition: fe-connect.c:5590

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

Referenced by connectDatabase(), dblink_connstr_has_pw(), do_connect(), GetConnection(), libpqrcv_check_conninfo(), libpqrcv_get_dbname_from_conninfo(), and main().

◆ PQconsumeInput()

int PQconsumeInput ( PGconn conn)

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

1961 {
1962  if (!conn)
1963  return 0;
1964 
1965  /*
1966  * for non-blocking connections try to flush the send-queue, otherwise we
1967  * may never get a response for something that may not have already been
1968  * sent because it's in our write buffer!
1969  */
1970  if (pqIsnonblocking(conn))
1971  {
1972  if (pqFlush(conn) < 0)
1973  return 0;
1974  }
1975 
1976  /*
1977  * Load more data, if available. We do this no matter what state we are
1978  * in, since we are probably getting called because the application wants
1979  * to get rid of a read-select condition. Note that we will NOT block
1980  * waiting for more input.
1981  */
1982  if (pqReadData(conn) < 0)
1983  return 0;
1984 
1985  /* Parsing of the data waits till later. */
1986  return 1;
1987 }
#define pqIsnonblocking(conn)
Definition: libpq-int.h:888

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

Referenced by advanceConnectionState(), confirm_query_canceled_impl(), CopyStreamReceive(), dblink_get_notify(), dblink_is_busy(), do_sql_command_end(), ecpg_process_output(), libpqrcv_PQgetResult(), libpqrcv_receive(), libpqsrv_get_result(), main(), pgfdw_cancel_query_end(), pgfdw_exec_cleanup_query_end(), pgfdw_get_cleanup_result(), postgresForeignAsyncNotify(), PQconnectPoll(), PrintNotifications(), StreamLogicalLog(), test_nosync(), test_pipelined_insert(), test_uniqviol(), try_complete_step(), and wait_on_slots().

◆ PQcopyResult()

PGresult* PQcopyResult ( const PGresult src,
int  flags 
)

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

317 {
318  PGresult *dest;
319  int i;
320 
321  if (!src)
322  return NULL;
323 
325  if (!dest)
326  return NULL;
327 
328  /* Always copy these over. Is cmdStatus really useful here? */
329  dest->client_encoding = src->client_encoding;
330  strcpy(dest->cmdStatus, src->cmdStatus);
331 
332  /* Wants attrs? */
333  if (flags & (PG_COPYRES_ATTRS | PG_COPYRES_TUPLES))
334  {
335  if (!PQsetResultAttrs(dest, src->numAttributes, src->attDescs))
336  {
337  PQclear(dest);
338  return NULL;
339  }
340  }
341 
342  /* Wants to copy tuples? */
343  if (flags & PG_COPYRES_TUPLES)
344  {
345  int tup,
346  field;
347 
348  for (tup = 0; tup < src->ntups; tup++)
349  {
350  for (field = 0; field < src->numAttributes; field++)
351  {
352  if (!PQsetvalue(dest, tup, field,
353  src->tuples[tup][field].value,
354  src->tuples[tup][field].len))
355  {
356  PQclear(dest);
357  return NULL;
358  }
359  }
360  }
361  }
362 
363  /* Wants to copy notice hooks? */
364  if (flags & PG_COPYRES_NOTICEHOOKS)
365  dest->noticeHooks = src->noticeHooks;
366 
367  /* Wants to copy PGEvents? */
368  if ((flags & PG_COPYRES_EVENTS) && src->nEvents > 0)
369  {
370  dest->events = dupEvents(src->events, src->nEvents,
371  &dest->memorySize);
372  if (!dest->events)
373  {
374  PQclear(dest);
375  return NULL;
376  }
377  dest->nEvents = src->nEvents;
378  }
379 
380  /* Okay, trigger PGEVT_RESULTCOPY event */
381  for (i = 0; i < dest->nEvents; i++)
382  {
383  /* We don't fire events that had some previous failure */
384  if (src->events[i].resultInitialized)
385  {
386  PGEventResultCopy evt;
387 
388  evt.src = src;
389  evt.dest = dest;
390  if (dest->events[i].proc(PGEVT_RESULTCOPY, &evt,
391  dest->events[i].passThrough))
392  dest->events[i].resultInitialized = true;
393  }
394  }
395 
396  return dest;
397 }
int PQsetResultAttrs(PGresult *res, int numAttributes, PGresAttDesc *attDescs)
Definition: fe-exec.c:247
void PQclear(PGresult *res)
Definition: fe-exec.c:719
static PGEvent * dupEvents(PGEvent *events, int count, size_t *memSize)
Definition: fe-exec.c:406
PGresult * PQmakeEmptyPGresult(PGconn *conn, ExecStatusType status)
Definition: fe-exec.c:158
int PQsetvalue(PGresult *res, int tup_num, int field_num, char *value, int len)
Definition: fe-exec.c:450
@ PGEVT_RESULTCOPY
Definition: libpq-events.h:33
#define PG_COPYRES_TUPLES
Definition: libpq-fe.h:46
#define PG_COPYRES_ATTRS
Definition: libpq-fe.h:45
#define PG_COPYRES_EVENTS
Definition: libpq-fe.h:47
#define PG_COPYRES_NOTICEHOOKS
Definition: libpq-fe.h:48
const PGresult * src
Definition: libpq-events.h:60
PGresult * dest
Definition: libpq-events.h:61
int ntups
Definition: libpq-int.h:172
int numAttributes
Definition: libpq-int.h:173
int client_encoding
Definition: libpq-int.h:192
char * value
Definition: libpq-int.h:141

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

Referenced by pqRowProcessor().

◆ PQdb()

◆ PQdefaultSSLKeyPassHook_OpenSSL()

int PQdefaultSSLKeyPassHook_OpenSSL ( char *  buf,
int  size,
PGconn conn 
)

Definition at line 1985 of file fe-secure-openssl.c.

1986 {
1987  if (conn && conn->sslpassword)
1988  {
1989  if (strlen(conn->sslpassword) + 1 > size)
1990  fprintf(stderr, libpq_gettext("WARNING: sslpassword truncated\n"));
1991  strncpy(buf, conn->sslpassword, size);
1992  buf[size - 1] = '\0';
1993  return strlen(buf);
1994  }
1995  else
1996  {
1997  buf[0] = '\0';
1998  return 0;
1999  }
2000 }
#define libpq_gettext(x)
Definition: libpq-int.h:899
#define fprintf
Definition: port.h:242
static pg_noinline void Size size
Definition: slab.c:607
char * sslpassword
Definition: libpq-int.h:394

References buf, conn, fprintf, libpq_gettext, size, and pg_conn::sslpassword.

Referenced by PQssl_passwd_cb().

◆ PQdescribePortal()

PGresult* PQdescribePortal ( PGconn conn,
const char *  portal 
)

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

2437 {
2438  if (!PQexecStart(conn))
2439  return NULL;
2440  if (!PQsendTypedCommand(conn, PqMsg_Describe, 'P', portal))
2441  return NULL;
2442  return PQexecFinish(conn);
2443 }
#define PqMsg_Describe
Definition: protocol.h:21

References conn, PQexecFinish(), PQexecStart(), PqMsg_Describe, and PQsendTypedCommand().

Referenced by test_prepared().

◆ PQdescribePrepared()

PGresult* PQdescribePrepared ( PGconn conn,
const char *  stmt 
)

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

2418 {
2419  if (!PQexecStart(conn))
2420  return NULL;
2422  return NULL;
2423  return PQexecFinish(conn);
2424 }

References conn, PQexecFinish(), PQexecStart(), PqMsg_Describe, PQsendTypedCommand(), and stmt.

Referenced by DescribeQuery(), ECPGdescribe(), and test_prepared().

◆ PQdisplayTuples()

void PQdisplayTuples ( const PGresult res,
FILE *  fp,
int  fillAlign,
const char *  fieldSep,
int  printHeader,
int  quiet 
)

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

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

References DEFAULT_FIELD_SEP, fflush(), fill(), fprintf, free, i, j, libpq_gettext, malloc, PQfname(), PQgetlength(), PQgetvalue(), PQnfields(), PQntuples(), res, and generate_unaccent_rules::stdout.

◆ PQdsplen()

int PQdsplen ( const char *  s,
int  encoding 
)

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

1198 {
1199  return pg_encoding_dsplen(encoding, s);
1200 }
int pg_encoding_dsplen(int encoding, const char *mbstr)
Definition: wchar.c:2151

References encoding, and pg_encoding_dsplen().

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

◆ PQencryptPassword()

char* PQencryptPassword ( const char *  passwd,
const char *  user 
)

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

1235 {
1236  char *crypt_pwd;
1237  const char *errstr = NULL;
1238 
1239  crypt_pwd = malloc(MD5_PASSWD_LEN + 1);
1240  if (!crypt_pwd)
1241  return NULL;
1242 
1243  if (!pg_md5_encrypt(passwd, user, strlen(user), crypt_pwd, &errstr))
1244  {
1245  free(crypt_pwd);
1246  return NULL;
1247  }
1248 
1249  return crypt_pwd;
1250 }
#define MD5_PASSWD_LEN
Definition: md5.h:26
bool pg_md5_encrypt(const char *passwd, const char *salt, size_t salt_len, char *buf, const char **errstr)
Definition: md5_common.c:145

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

◆ PQencryptPasswordConn()

char* PQencryptPasswordConn ( PGconn conn,
const char *  passwd,
const char *  user,
const char *  algorithm 
)

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

1279 {
1280 #define MAX_ALGORITHM_NAME_LEN 50
1281  char algobuf[MAX_ALGORITHM_NAME_LEN + 1];
1282  char *crypt_pwd = NULL;
1283 
1284  if (!conn)
1285  return NULL;
1286 
1288 
1289  /* If no algorithm was given, ask the server. */
1290  if (algorithm == NULL)
1291  {
1292  PGresult *res;
1293  char *val;
1294 
1295  res = PQexec(conn, "show password_encryption");
1296  if (res == NULL)
1297  {
1298  /* PQexec() should've set conn->errorMessage already */
1299  return NULL;
1300  }
1302  {
1303  /* PQexec() should've set conn->errorMessage already */
1304  PQclear(res);
1305  return NULL;
1306  }
1307  if (PQntuples(res) != 1 || PQnfields(res) != 1)
1308  {
1309  PQclear(res);
1310  libpq_append_conn_error(conn, "unexpected shape of result set returned for SHOW");
1311  return NULL;
1312  }
1313  val = PQgetvalue(res, 0, 0);
1314 
1315  if (strlen(val) > MAX_ALGORITHM_NAME_LEN)
1316  {
1317  PQclear(res);
1318  libpq_append_conn_error(conn, "password_encryption value too long");
1319  return NULL;
1320  }
1321  strcpy(algobuf, val);
1322  PQclear(res);
1323 
1324  algorithm = algobuf;
1325  }
1326 
1327  /*
1328  * Also accept "on" and "off" as aliases for "md5", because
1329  * password_encryption was a boolean before PostgreSQL 10. We refuse to
1330  * send the password in plaintext even if it was "off".
1331  */
1332  if (strcmp(algorithm, "on") == 0 ||
1333  strcmp(algorithm, "off") == 0)
1334  algorithm = "md5";
1335 
1336  /*
1337  * Ok, now we know what algorithm to use
1338  */
1339  if (strcmp(algorithm, "scram-sha-256") == 0)
1340  {
1341  const char *errstr = NULL;
1342 
1343  crypt_pwd = pg_fe_scram_build_secret(passwd,
1345  &errstr);
1346  if (!crypt_pwd)
1347  libpq_append_conn_error(conn, "could not encrypt password: %s", errstr);
1348  }
1349  else if (strcmp(algorithm, "md5") == 0)
1350  {
1351  crypt_pwd = malloc(MD5_PASSWD_LEN + 1);
1352  if (crypt_pwd)
1353  {
1354  const char *errstr = NULL;
1355 
1356  if (!pg_md5_encrypt(passwd, user, strlen(user), crypt_pwd, &errstr))
1357  {
1358  libpq_append_conn_error(conn, "could not encrypt password: %s", errstr);
1359  free(crypt_pwd);
1360  crypt_pwd = NULL;
1361  }
1362  }
1363  else
1364  libpq_append_conn_error(conn, "out of memory");
1365  }
1366  else
1367  {
1368  libpq_append_conn_error(conn, "unrecognized password encryption algorithm \"%s\"",
1369  algorithm);
1370  return NULL;
1371  }
1372 
1373  return crypt_pwd;
1374 }
char * pg_fe_scram_build_secret(const char *password, int iterations, const char **errstr)
#define MAX_ALGORITHM_NAME_LEN
int scram_sha_256_iterations
Definition: libpq-int.h:548

References conn, free, libpq_append_conn_error(), malloc, MAX_ALGORITHM_NAME_LEN, MD5_PASSWD_LEN, pg_fe_scram_build_secret(), pg_md5_encrypt(), PGRES_TUPLES_OK, PQclear(), pqClearConnErrorState, PQexec(), PQgetvalue(), PQnfields(), PQntuples(), PQresultStatus(), res, pg_conn::scram_sha_256_iterations, user, and val.

Referenced by main(), and PQchangePassword().

◆ PQendcopy()

int PQendcopy ( PGconn conn)

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

2912 {
2913  if (!conn)
2914  return 0;
2915 
2916  return pqEndcopy3(conn);
2917 }
int pqEndcopy3(PGconn *conn)

References conn, and pqEndcopy3().

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

◆ PQenterPipelineMode()

int PQenterPipelineMode ( PGconn conn)

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

3005 {
3006  if (!conn)
3007  return 0;
3008 
3009  /* succeed with no action if already in pipeline mode */
3011  return 1;
3012 
3013  if (conn->asyncStatus != PGASYNC_IDLE)
3014  {
3015  libpq_append_conn_error(conn, "cannot enter pipeline mode, connection not idle");
3016  return 0;
3017  }
3018 
3020 
3021  return 1;
3022 }

References pg_conn::asyncStatus, conn, libpq_append_conn_error(), PGASYNC_IDLE, pg_conn::pipelineStatus, PQ_PIPELINE_OFF, and PQ_PIPELINE_ON.

Referenced by executeMetaCommand(), test_disallowed_in_pipeline(), test_multi_pipelines(), test_nosync(), test_pipeline_abort(), test_pipeline_idle(), test_pipelined_insert(), test_prepared(), test_simple_pipeline(), test_singlerowmode(), test_transaction(), and test_uniqviol().

◆ PQenv2encoding()

int PQenv2encoding ( void  )

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

1207 {
1208  char *str;
1209  int encoding = PG_SQL_ASCII;
1210 
1211  str = getenv("PGCLIENTENCODING");
1212  if (str && *str != '\0')
1213  {
1215  if (encoding < 0)
1217  }
1218  return encoding;
1219 }
@ PG_SQL_ASCII
Definition: pg_wchar.h:226
#define pg_char_to_encoding
Definition: pg_wchar.h:568

References encoding, pg_char_to_encoding, PG_SQL_ASCII, and generate_unaccent_rules::str.

Referenced by main().

◆ PQerrorMessage()

char* PQerrorMessage ( const PGconn conn)

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

6949 {
6950  if (!conn)
6951  return libpq_gettext("connection pointer is NULL\n");
6952 
6953  /*
6954  * The errorMessage buffer might be marked "broken" due to having
6955  * previously failed to allocate enough memory for the message. In that
6956  * case, tell the application we ran out of memory.
6957  */
6959  return libpq_gettext("out of memory\n");
6960 
6961  return conn->errorMessage.data;
6962 }
#define PQExpBufferBroken(str)
Definition: pqexpbuffer.h:59

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

Referenced by _doSetSessionAuth(), _selectOutputSchema(), _selectTableAccessMethod(), _selectTablespace(), AcceptResult(), advanceConnectionState(), BaseBackup(), check_loadable_libraries(), check_prepare_conn(), CheckCopyStreamStop(), cluster_one_database(), compile_database_list(), compile_relation_list_one_db(), confirm_query_canceled_impl(), connect_pg_server(), ConnectDatabase(), connectDatabase(), connectToServer(), copy_connection(), CopyStreamPoll(), CopyStreamReceive(), CreateReplicationSlot(), dblink_connect(), dblink_error_message(), dblink_get_conn(), dblink_res_error(), dblink_send_query(), DescribeQuery(), die_on_query_failure(), do_connect(), do_lo_export(), do_lo_import(), do_lo_unlink(), doConnect(), DropReplicationSlot(), dump_lo_buf(), dumpLOs(), dumpTableData_copy(), ecpg_check_PQresult(), ecpg_raise_backend(), ECPGconnect(), EndDBCopyMode(), exec_command_password(), ExecQueryAndProcessResults(), executeCommand(), executeQuery(), executeQueryOrDie(), ExecuteSqlCommand(), ExecuteSqlCommandBuf(), executeStatement(), GetConnection(), GetSlotInformation(), GetTableInfo(), handleCopyIn(), handleCopyOut(), HandleEndOfCopyStream(), initPopulateTable(), libpqrcv_alter_slot(), libpqrcv_connect(), libpqrcv_create_slot(), libpqrcv_endstreaming(), libpqrcv_exec(), libpqrcv_identify_system(), libpqrcv_readtimelinehistoryfile(), libpqrcv_receive(), libpqrcv_send(), libpqrcv_startstreaming(), main(), my_truncate(), overwrite(), pgfdw_cancel_query_end(), pgfdw_report_error(), pickout(), PQcancelErrorMessage(), prepareCommand(), process_queued_fetch_requests(), process_result(), ProcessXLogDataMsg(), psql_get_variable(), readCommandResponse(), ReceiveCopyData(), RetrieveDataDirCreatePerm(), RetrieveWalSegSize(), run_command(), run_permutation(), run_reindex_command(), run_vacuum_command(), RunIdentifySystem(), send_cancellable_query_impl(), sendFeedback(), SendQuery(), sql_conn(), sql_exec(), start_postmaster(), StartRestoreLO(), storeQueryResult(), StreamLogicalLog(), TableCommandResultHandler(), test_cancel(), test_disallowed_in_pipeline(), test_multi_pipelines(), test_nosync(), test_pipeline_abort(), test_pipeline_idle(), test_pipelined_insert(), test_prepared(), test_simple_pipeline(), test_singlerowmode(), test_transaction(), test_uniqviol(), threadRun(), try_complete_step(), tryExecuteStatement(), vacuumlo(), verify_btree_slot_handler(), verify_heap_slot_handler(), and wait_for_connection_state().

◆ PQescapeBytea()

unsigned char* PQescapeBytea ( const unsigned char *  from,
size_t  from_length,
size_t *  to_length 
)

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

4430 {
4431  return PQescapeByteaInternal(NULL, from, from_length, to_length,
4433  false /* can't use hex */ );
4434 }
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:4317
static bool static_std_strings
Definition: fe-exec.c:59

References PQescapeByteaInternal(), and static_std_strings.

◆ PQescapeByteaConn()

unsigned char* PQescapeByteaConn ( PGconn conn,
const unsigned char *  from,
size_t  from_length,
size_t *  to_length 
)

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

4416 {
4417  if (!conn)
4418  return NULL;
4419 
4420  if (conn->cmd_queue_head == NULL)
4422 
4423  return PQescapeByteaInternal(conn, from, from_length, to_length,
4424  conn->std_strings,
4425  (conn->sversion >= 90000));
4426 }
bool std_strings
Definition: libpq-int.h:502
PGcmdQueueEntry * cmd_queue_head
Definition: libpq-int.h:453

References pg_conn::cmd_queue_head, conn, pqClearConnErrorState, PQescapeByteaInternal(), pg_conn::std_strings, and pg_conn::sversion.

◆ PQescapeIdentifier()

char* PQescapeIdentifier ( PGconn conn,
const char *  str,
size_t  len 
)

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

4271 {
4272  return PQescapeInternal(conn, str, len, true);
4273 }
static char * PQescapeInternal(PGconn *conn, const char *str, size_t len, bool as_ident)
Definition: fe-exec.c:4142

References conn, len, PQescapeInternal(), and generate_unaccent_rules::str.

Referenced by initCreatePKeys(), initCreateTables(), main(), PQchangePassword(), psql_get_variable(), stringlist_to_identifierstr(), and vacuumlo().

◆ PQescapeLiteral()

char* PQescapeLiteral ( PGconn conn,
const char *  str,
size_t  len 
)

◆ PQescapeString()

size_t PQescapeString ( char *  to,
const char *  from,
size_t  length 
)

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

4128 {
4129  return PQescapeStringInternal(NULL, to, from, length, NULL,
4132 }
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:4031
static int static_client_encoding
Definition: fe-exec.c:58

References PQescapeStringInternal(), static_client_encoding, and static_std_strings.

Referenced by get_comma_elts(), and quote_postgres().

◆ PQescapeStringConn()

size_t PQescapeStringConn ( PGconn conn,
char *  to,
const char *  from,
size_t  length,
int *  error 
)

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

4108 {
4109  if (!conn)
4110  {
4111  /* force empty-string result */
4112  *to = '\0';
4113  if (error)
4114  *error = 1;
4115  return 0;
4116  }
4117 
4118  if (conn->cmd_queue_head == NULL)
4120 
4121  return PQescapeStringInternal(conn, to, from, length, error,
4123  conn->std_strings);
4124 }
static void error(void)
Definition: sql-dyntest.c:147

References pg_conn::client_encoding, pg_conn::cmd_queue_head, conn, error(), pqClearConnErrorState, PQescapeStringInternal(), and pg_conn::std_strings.

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

◆ PQexec()

PGresult* PQexec ( PGconn conn,
const char *  query 
)

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

2225 {
2226  if (!PQexecStart(conn))
2227  return NULL;
2228  if (!PQsendQuery(conn, query))
2229  return NULL;
2230  return PQexecFinish(conn);
2231 }
int PQsendQuery(PGconn *conn, const char *query)
Definition: fe-exec.c:1425

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

Referenced by _doSetSessionAuth(), _selectOutputSchema(), _selectTableAccessMethod(), _selectTablespace(), check_loadable_libraries(), check_prepare_conn(), CreateReplicationSlot(), deallocate_one(), DescribeQuery(), DropReplicationSlot(), ecpg_autostart_transaction(), ecpg_execute(), ECPGsetcommit(), ECPGtrans(), ExecQueryUsingCursor(), executeCommand(), executeMaintenanceCommand(), executeQuery(), executeQueryOrDie(), ExecuteSqlCommand(), ExecuteSqlQuery(), ExecuteSqlStatement(), executeStatement(), get_create_object_cmd(), GetConnection(), GetSlotInformation(), GetTableInfo(), init_libpq_conn(), initPopulateTable(), libpq_traverse_files(), lo_initialize(), lockTableForWorker(), lookup_object_oid(), main(), PQchangePassword(), PQencryptPasswordConn(), PQsetClientEncoding(), PSQLexec(), ReceiveXlogStream(), RetrieveDataDirCreatePerm(), RetrieveWalSegSize(), run_permutation(), run_simple_command(), run_simple_query(), RunIdentifySystem(), SendQuery(), sql_conn(), sql_exec(), StreamLogicalLog(), test_disallowed_in_pipeline(), test_pipeline_abort(), test_prepared(), test_transaction(), test_uniqviol(), tryExecuteStatement(), and vacuumlo().

◆ PQexecParams()

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 2238 of file fe-exec.c.

2246 {
2247  if (!PQexecStart(conn))
2248  return NULL;
2249  if (!PQsendQueryParams(conn, command,
2250  nParams, paramTypes, paramValues, paramLengths,
2251  paramFormats, resultFormat))
2252  return NULL;
2253  return PQexecFinish(conn);
2254 }
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:1501

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

Referenced by ecpg_execute(), libpq_fetch_file(), main(), and wait_for_connection_state().

◆ PQexecPrepared()

PGresult* PQexecPrepared ( PGconn conn,
const char *  stmtName,
int  nParams,
const char *const *  paramValues,
const int *  paramLengths,
const int *  paramFormats,
int  resultFormat 
)

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

2292 {
2293  if (!PQexecStart(conn))
2294  return NULL;
2295  if (!PQsendQueryPrepared(conn, stmtName,
2296  nParams, paramValues, paramLengths,
2297  paramFormats, resultFormat))
2298  return NULL;
2299  return PQexecFinish(conn);
2300 }
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:1642

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

Referenced by ecpg_execute(), and try_complete_step().

◆ PQexitPipelineMode()

int PQexitPipelineMode ( PGconn conn)

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

3036 {
3037  if (!conn)
3038  return 0;
3039 
3041  (conn->asyncStatus == PGASYNC_IDLE ||
3043  conn->cmd_queue_head == NULL)
3044  return 1;
3045 
3046  switch (conn->asyncStatus)
3047  {
3048  case PGASYNC_READY:
3049  case PGASYNC_READY_MORE:
3050  /* there are some uncollected results */
3051  libpq_append_conn_error(conn, "cannot exit pipeline mode with uncollected results");
3052  return 0;
3053 
3054  case PGASYNC_BUSY:
3055  libpq_append_conn_error(conn, "cannot exit pipeline mode while busy");
3056  return 0;
3057 
3058  case PGASYNC_IDLE:
3059  case PGASYNC_PIPELINE_IDLE:
3060  /* OK */
3061  break;
3062 
3063  case PGASYNC_COPY_IN:
3064  case PGASYNC_COPY_OUT:
3065  case PGASYNC_COPY_BOTH:
3066  libpq_append_conn_error(conn, "cannot exit pipeline mode while in COPY");
3067  }
3068 
3069  /* still work to process */
3070  if (conn->cmd_queue_head != NULL)
3071  {
3072  libpq_append_conn_error(conn, "cannot exit pipeline mode with uncollected results");
3073  return 0;
3074  }
3075 
3078 
3079  /* Flush any pending data in out buffer */
3080  if (pqFlush(conn) < 0)
3081  return 0; /* error message is setup already */
3082  return 1;
3083 }
@ PGASYNC_COPY_OUT
Definition: libpq-int.h:229
@ PGASYNC_READY_MORE
Definition: libpq-int.h:225
@ PGASYNC_READY
Definition: libpq-int.h:223
@ PGASYNC_COPY_BOTH
Definition: libpq-int.h:230
@ PGASYNC_COPY_IN
Definition: libpq-int.h:228
@ PGASYNC_PIPELINE_IDLE
Definition: libpq-int.h:231

References pg_conn::asyncStatus, pg_conn::cmd_queue_head, conn, libpq_append_conn_error(), PGASYNC_BUSY, PGASYNC_COPY_BOTH, PGASYNC_COPY_IN, PGASYNC_COPY_OUT, PGASYNC_IDLE, PGASYNC_PIPELINE_IDLE, PGASYNC_READY, PGASYNC_READY_MORE, pg_conn::pipelineStatus, PQ_PIPELINE_OFF, and pqFlush().

Referenced by discardUntilSync(), readCommandResponse(), test_disallowed_in_pipeline(), test_multi_pipelines(), test_pipeline_abort(), test_pipeline_idle(), test_pipelined_insert(), test_prepared(), test_simple_pipeline(), test_singlerowmode(), and test_transaction().

◆ PQfformat()

int PQfformat ( const PGresult res,
int  field_num 
)

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

3669 {
3670  if (!check_field_number(res, field_num))
3671  return 0;
3672  if (res->attDescs)
3673  return res->attDescs[field_num].format;
3674  else
3675  return 0;
3676 }
static int check_field_number(const PGresult *res, int field_num)
Definition: fe-exec.c:3470

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

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

◆ PQfinish()

void PQfinish ( PGconn conn)

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

4670 {
4671  if (conn)
4672  {
4674  freePGconn(conn);
4675  }
4676 }
static void freePGconn(PGconn *conn)
Definition: fe-connect.c:4426

References conn, freePGconn(), and pqClosePGconn().

Referenced by appendQualifiedRelation(), BaseBackup(), check_for_data_types_usage(), check_for_incompatible_polymorphics(), check_for_isn_and_int8_passing_mismatch(), check_for_pg_role_prefix(), check_for_prepared_transactions(), check_for_tables_with_oids(), check_for_user_defined_encoding_conversions(), check_for_user_defined_postfix_ops(), check_is_install_user(), check_loadable_libraries(), check_new_cluster_logical_replication_slots(), check_new_cluster_subscription_configuration(), check_old_cluster_subscription_state(), check_proper_datallowconn(), CheckConnection(), cluster_all_databases(), cluster_one_database(), ConnectDatabase(), connectDatabase(), connectToServer(), create_logical_replication_slots(), disconnect_atexit(), DisconnectDatabase(), disconnectDatabase(), do_connect(), doConnect(), dumpRoleGUCPrivs(), dumpRoleMembership(), dumpTablespaces(), ecpg_finish(), executeCommand(), executeQuery(), executeQueryOrDie(), exit_nicely(), expand_dbname_patterns(), finishCon(), get_db_infos(), get_db_subscription_count(), get_loadable_libraries(), get_old_cluster_logical_slot_infos(), get_parallel_object_list(), get_rel_infos(), get_tablespace_paths(), get_template0_info(), GetConnection(), libpqrcv_connect(), libpqrcv_disconnect(), libpqsrv_connect_internal(), libpqsrv_disconnect(), LogStreamerMain(), main(), old_9_6_invalidate_hash_indexes(), PQcancelFinish(), PQping(), PQpingParams(), ReconnectToServer(), reindex_all_databases(), reindex_one_database(), report_extension_updates(), run_reindex_command(), runInitSteps(), set_frozenxids(), set_locale_and_encoding(), sql_conn(), sql_exec(), start_postmaster(), StreamLog(), StreamLogicalLog(), vacuum_all_databases(), vacuum_one_database(), and vacuumlo().

◆ PQflush()

int PQflush ( PGconn conn)

◆ PQfmod()

int PQfmod ( const PGresult res,
int  field_num 
)

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

3702 {
3703  if (!check_field_number(res, field_num))
3704  return 0;
3705  if (res->attDescs)
3706  return res->attDescs[field_num].atttypmod;
3707  else
3708  return 0;
3709 }
int atttypmod
Definition: libpq-fe.h:277

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

Referenced by DescribeQuery(), and ECPGget_desc().

◆ PQfn()

PGresult* PQfn ( PGconn conn,
int  fnid,
int *  result_buf,
int *  result_len,
int  result_is_int,
const PQArgBlock args,
int  nargs 
)

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

2949 {
2950  *result_len = 0;
2951 
2952  if (!conn)
2953  return NULL;
2954 
2955  /*
2956  * Since this is the beginning of a query cycle, reset the error state.
2957  * However, in pipeline mode with something already queued, the error
2958  * buffer belongs to that command and we shouldn't clear it.
2959  */
2960  if (conn->cmd_queue_head == NULL)
2962 
2964  {
2965  libpq_append_conn_error(conn, "%s not allowed in pipeline mode", "PQfn");
2966  return NULL;
2967  }
2968 
2971  {
2972  libpq_append_conn_error(conn, "connection in wrong state");
2973  return NULL;
2974  }
2975 
2976  return pqFunctionCall3(conn, fnid,
2977  result_buf, result_len,
2978  result_is_int,
2979  args, nargs);
2980 }
PGresult * pqFunctionCall3(PGconn *conn, Oid fnid, int *result_buf, int *actual_result_len, int result_is_int, const PQArgBlock *args, int nargs)
#define pgHavePendingResult(conn)
Definition: libpq-int.h:881

References generate_unaccent_rules::args, pg_conn::asyncStatus, pg_conn::cmd_queue_head, conn, libpq_append_conn_error(), PGASYNC_IDLE, pgHavePendingResult, PGINVALID_SOCKET, pg_conn::pipelineStatus, PQ_PIPELINE_OFF, pqClearConnErrorState, pqFunctionCall3(), 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().

◆ PQfname()

char* PQfname ( const PGresult res,
int  field_num 
)

◆ PQfnumber()

int PQfnumber ( const PGresult res,
const char *  field_name 
)

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

3550 {
3551  char *field_case;
3552  bool in_quotes;
3553  bool all_lower = true;
3554  const char *iptr;
3555  char *optr;
3556  int i;
3557 
3558  if (!res)
3559  return -1;
3560 
3561  /*
3562  * Note: it is correct to reject a zero-length input string; the proper
3563  * input to match a zero-length field name would be "".
3564  */
3565  if (field_name == NULL ||
3566  field_name[0] == '\0' ||
3567  res->attDescs == NULL)
3568  return -1;
3569 
3570  /*
3571  * Check if we can avoid the strdup() and related work because the
3572  * passed-in string wouldn't be changed before we do the check anyway.
3573  */
3574  for (iptr = field_name; *iptr; iptr++)
3575  {
3576  char c = *iptr;
3577 
3578  if (c == '"' || c != pg_tolower((unsigned char) c))
3579  {
3580  all_lower = false;
3581  break;
3582  }
3583  }
3584 
3585  if (all_lower)
3586  for (i = 0; i < res->numAttributes; i++)
3587  if (strcmp(field_name, res->attDescs[i].name) == 0)
3588  return i;
3589 
3590  /* Fall through to the normal check if that didn't work out. */
3591 
3592  /*
3593  * Note: this code will not reject partially quoted strings, eg
3594  * foo"BAR"foo will become fooBARfoo when it probably ought to be an error
3595  * condition.
3596  */
3597  field_case = strdup(field_name);
3598  if (field_case == NULL)
3599  return -1; /* grotty */
3600 
3601  in_quotes = false;
3602  optr = field_case;
3603  for (iptr = field_case; *iptr; iptr++)
3604  {
3605  char c = *iptr;
3606 
3607  if (in_quotes)
3608  {
3609  if (c == '"')
3610  {
3611  if (iptr[1] == '"')
3612  {
3613  /* doubled quotes become a single quote */
3614  *optr++ = '"';
3615  iptr++;
3616  }
3617  else
3618  in_quotes = false;
3619  }
3620  else
3621  *optr++ = c;
3622  }
3623  else if (c == '"')
3624  in_quotes = true;
3625  else
3626  {
3627  c = pg_tolower((unsigned char) c);
3628  *optr++ = c;
3629  }
3630  }
3631  *optr = '\0';
3632 
3633  for (i = 0; i < res->numAttributes; i++)
3634  {
3635  if (strcmp(field_case, res->attDescs[i].name) == 0)
3636  {
3637  free(field_case);
3638  return i;
3639  }
3640  }
3641  free(field_case);
3642  return -1;
3643 }
unsigned char pg_tolower(unsigned char ch)
Definition: pgstrcasecmp.c:122

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

Referenced by append_depends_on_extension(), binary_upgrade_set_pg_class_oids(), binary_upgrade_set_type_oids_by_type_oid(), buildMatViewRefreshDependencies(), check_for_data_types_usage(), check_for_incompatible_polymorphics(), check_for_isn_and_int8_passing_mismatch(), check_for_pg_role_prefix(), check_for_tables_with_oids(), check_for_user_defined_encoding_conversions(), check_for_user_defined_postfix_ops(), check_proper_datallowconn(), collectComments(), collectSecLabels(), describeOneTableDetails(), dropRoles(), dumpAgg(), dumpBaseType(), dumpCollation(), dumpCompositeType(), dumpCompositeTypeColComments(), dumpConversion(), dumpDatabase(), dumpDomain(), dumpEnumType(), dumpFunc(), dumpOpclass(), dumpOpfamily(), dumpOpr(), dumpRangeType(), dumpRoleMembership(), dumpRoles(), dumpTableSchema(), dumpTSConfig(), dumpUserMappings(), get_db_infos(), get_old_cluster_logical_slot_infos(), get_rel_infos(), get_tablespace_paths(), get_template0_info(), getAccessMethods(), getAggregates(), getCasts(), getCollations(), getConstraints(), getConversions(), getDefaultACLs(), getDependencies(), getDomainConstraints(), getEventTriggers(), getExtendedStatistics(), getExtensionMembership(), getExtensions(), getForeignDataWrappers(), getForeignServers(), getFuncs(), getIndexes(), getInherits(), getLOs(), getNamespaces(), getOpclasses(), getOperators(), getOpfamilies(), getPolicies(), getProcLangs(), getPublicationNamespaces(), getPublications(), getPublicationTables(), getRules(), getSubscriptions(), getSubscriptionTables(), getTableAttrs(), getTables(), getTransforms(), getTriggers(), getTSConfigurations(), getTSDictionaries(), getTSParsers(), getTSTemplates(), getTypes(), old_9_6_invalidate_hash_indexes(), processExtensionTables(), report_extension_updates(), set_frozenxids(), and show_binary_results().

◆ PQfreeCancel()

void PQfreeCancel ( PGcancel cancel)

Definition at line 416 of file fe-cancel.c.

417 {
418  free(cancel);
419 }

References free.

Referenced by pgfdw_cancel_query_begin(), PQrequestCancel(), ResetCancelConn(), set_archive_cancel_info(), SetCancelConn(), and test_cancel().

◆ PQfreemem()

◆ PQfsize()

int PQfsize ( const PGresult res,
int  field_num 
)

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

3691 {
3692  if (!check_field_number(res, field_num))
3693  return 0;
3694  if (res->attDescs)
3695  return res->attDescs[field_num].typlen;
3696  else
3697  return 0;
3698 }

References pg_result::attDescs, check_field_number(), res, and pgresAttDesc::typlen.

Referenced by ecpg_build_compat_sqlda(), and ECPGget_desc().

◆ PQftable()

Oid PQftable ( const PGresult res,
int  field_num 
)

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

3647 {
3648  if (!check_field_number(res, field_num))
3649  return InvalidOid;
3650  if (res->attDescs)
3651  return res->attDescs[field_num].tableid;
3652  else
3653  return InvalidOid;
3654 }

References pg_result::attDescs, check_field_number(), InvalidOid, res, and pgresAttDesc::tableid.

◆ PQftablecol()

int PQftablecol ( const PGresult res,
int  field_num 
)

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

3658 {
3659  if (!check_field_number(res, field_num))
3660  return 0;
3661  if (res->attDescs)
3662  return res->attDescs[field_num].columnid;
3663  else
3664  return 0;
3665 }
int columnid
Definition: libpq-fe.h:273

References pg_result::attDescs, check_field_number(), pgresAttDesc::columnid, and res.

◆ PQftype()

Oid PQftype ( const PGresult res,
int  field_num 
)

◆ PQgetCancel()

PGcancel* PQgetCancel ( PGconn conn)

Definition at line 348 of file fe-cancel.c.

349 {
350  PGcancel *cancel;
351 
352  if (!conn)
353  return NULL;
354 
355  if (conn->sock == PGINVALID_SOCKET)
356  return NULL;
357 
358  cancel = malloc(sizeof(PGcancel));
359  if (cancel == NULL)
360  return NULL;
361 
362  memcpy(&cancel->raddr, &conn->raddr, sizeof(SockAddr));
363  cancel->be_pid = conn->be_pid;
364  cancel->be_key = conn->be_key;
365  /* We use -1 to indicate an unset connection option */
366  cancel->pgtcp_user_timeout = -1;
367  cancel->keepalives = -1;
368  cancel->keepalives_idle = -1;
369  cancel->keepalives_interval = -1;
370  cancel->keepalives_count = -1;
371  if (conn->pgtcp_user_timeout != NULL)
372  {
374  &cancel->pgtcp_user_timeout,
375  conn, "tcp_user_timeout"))
376  goto fail;
377  }
378  if (conn->keepalives != NULL)
379  {
381  &cancel->keepalives,
382  conn, "keepalives"))
383  goto fail;
384  }
385  if (conn->keepalives_idle != NULL)
386  {
388  &cancel->keepalives_idle,
389  conn, "keepalives_idle"))
390  goto fail;
391  }
392  if (conn->keepalives_interval != NULL)
393  {
395  &cancel->keepalives_interval,
396  conn, "keepalives_interval"))
397  goto fail;
398  }
399  if (conn->keepalives_count != NULL)
400  {
402  &cancel->keepalives_count,
403  conn, "keepalives_count"))
404  goto fail;
405  }
406 
407  return cancel;
408 
409 fail:
410  free(cancel);
411  return NULL;
412 }
char * keepalives_idle
Definition: libpq-int.h:385
char * keepalives
Definition: libpq-int.h:384
char * keepalives_interval
Definition: libpq-int.h:386
char * pgtcp_user_timeout
Definition: libpq-int.h:372
char * keepalives_count
Definition: libpq-int.h:388

References pg_cancel::be_key, pg_conn::be_key, pg_cancel::be_pid, pg_conn::be_pid, conn, free, pg_cancel::keepalives, pg_conn::keepalives, pg_cancel::keepalives_count, pg_conn::keepalives_count, pg_cancel::keepalives_idle, pg_conn::keepalives_idle, pg_cancel::keepalives_interval, pg_conn::keepalives_interval, malloc, PGINVALID_SOCKET, pg_cancel::pgtcp_user_timeout, pg_conn::pgtcp_user_timeout, pqParseIntParam(), pg_cancel::raddr, pg_conn::raddr, and pg_conn::sock.

Referenced by pgfdw_cancel_query_begin(), PQrequestCancel(), set_archive_cancel_info(), SetCancelConn(), and test_cancel().

◆ PQgetCopyData()

int PQgetCopyData ( PGconn conn,
char **  buffer,
int  async 
)

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

2779 {
2780  *buffer = NULL; /* for all failure cases */
2781  if (!conn)
2782  return -2;
2783  if (conn->asyncStatus != PGASYNC_COPY_OUT &&
2785  {
2786  libpq_append_conn_error(conn, "no COPY in progress");
2787  return -2;
2788  }
2789  return pqGetCopyData3(conn, buffer, async);
2790 }
int pqGetCopyData3(PGconn *conn, char **buffer, int async)

References pg_conn::asyncStatus, conn, libpq_append_conn_error(), PGASYNC_COPY_BOTH, PGASYNC_COPY_OUT, and pqGetCopyData3().

Referenced by CopyStreamReceive(), dumpTableData_copy(), ecpg_process_output(), handleCopyOut(), libpqrcv_receive(), ReceiveCopyData(), and StreamLogicalLog().

◆ PQgetgssctx()

void* PQgetgssctx ( PGconn conn)

Definition at line 724 of file fe-secure-gssapi.c.

725 {
726  if (!conn)
727  return NULL;
728 
729  return conn->gctx;
730 }

References conn.

◆ PQgetisnull()

int PQgetisnull ( const PGresult res,
int  tup_num,
int  field_num 
)

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

3862 {
3863  if (!check_tuple_field_number(res, tup_num, field_num))
3864  return 1; /* pretend it is null */
3865  if (res->tuples[tup_num][field_num].len == NULL_LEN)
3866  return 1;
3867  else
3868  return 0;
3869 }
static int check_tuple_field_number(const PGresult *res, int tup_num, int field_num)
Definition: fe-exec.c:3485
#define NULL_LEN
Definition: libpq-int.h:136

References check_tuple_field_number(), pgresAttValue::len, NULL_LEN, res, and pg_result::tuples.

Referenced by addFooterToPublicationDesc(), BaseBackup(), compile_database_list(), compile_relation_list_one_db(), describeOneTableDetails(), dumpAgg(), dumpBaseType(), dumpCollation(), dumpDatabase(), dumpDomain(), dumpFunc(), dumpRangeType(), dumpRoles(), dumpTableData_insert(), ecpg_get_data(), ecpg_set_compat_sqlda(), ecpg_set_native_sqlda(), ECPGget_desc(), ExecQueryTuples(), get_template0_info(), getAggregates(), getExtendedStatistics(), getForeignDataWrappers(), getForeignServers(), getFuncs(), getLOs(), getNamespaces(), getPolicies(), getProcLangs(), getPublicationTables(), GetSlotInformation(), getSubscriptions(), getSubscriptionTables(), getTableAttrs(), GetTableInfo(), getTables(), getTSDictionaries(), getTypes(), libpq_fetch_file(), libpq_traverse_files(), libpqrcv_create_slot(), libpqrcv_processTuples(), listTSConfigsVerbose(), listTSParsersVerbose(), make_tuple_from_result_row(), materializeResult(), postgresImportForeignSchema(), printCrosstab(), printQuery(), PrintResultInCrosstab(), process_queued_fetch_requests(), run_simple_query(), RunIdentifySystem(), sqlda_common_total_size(), StoreQueryTuple(), storeRow(), vacuum_one_database(), and verify_heap_slot_handler().

◆ PQgetlength()

int PQgetlength ( const PGresult res,
int  tup_num,
int  field_num 
)

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

3848 {
3849  if (!check_tuple_field_number(res, tup_num, field_num))
3850  return 0;
3851  if (res->tuples[tup_num][field_num].len != NULL_LEN)
3852  return res->tuples[tup_num][field_num].len;
3853  else
3854  return 0;
3855 }

References check_tuple_field_number(), pgresAttValue::len, NULL_LEN, res, and pg_result::tuples.

Referenced by createViewAsClause(), do_field(), ecpg_get_data(), ecpg_store_result(), ECPGget_desc(), libpq_fetch_file(), libpqrcv_readtimelinehistoryfile(), PQdisplayTuples(), process_queued_fetch_requests(), and show_binary_results().

◆ PQgetline()

int PQgetline ( PGconn conn,
char *  buffer,
int  length 
)

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

2817 {
2818  if (!buffer || length <= 0)
2819  return EOF;
2820  *buffer = '\0';
2821  /* length must be at least 3 to hold the \. terminator! */
2822  if (length < 3)
2823  return EOF;
2824 
2825  if (!conn)
2826  return EOF;
2827 
2828  return pqGetline3(conn, buffer, length);
2829 }
int pqGetline3(PGconn *conn, char *s, int maxlen)

References conn, and pqGetline3().

◆ PQgetlineAsync()

int PQgetlineAsync ( PGconn conn,
char *  buffer,
int  bufsize 
)

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

2864 {
2865  if (!conn)
2866  return -1;
2867 
2868  return pqGetlineAsync3(conn, buffer, bufsize);
2869 }
int pqGetlineAsync3(PGconn *conn, char *buffer, int bufsize)
#define bufsize
Definition: indent_globs.h:36

References bufsize, conn, and pqGetlineAsync3().

Referenced by pqGetline3().

◆ PQgetResult()

PGresult* PQgetResult ( PGconn conn)

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

2039 {
2040  PGresult *res;
2041 
2042  if (!conn)
2043  return NULL;
2044 
2045  /* Parse any available data, if our state permits. */
2046  parseInput(conn);
2047 
2048  /* If not ready to return something, block until we are. */
2049  while (conn->asyncStatus == PGASYNC_BUSY)
2050  {
2051  int flushResult;
2052 
2053  /*
2054  * If data remains unsent, send it. Else we might be waiting for the
2055  * result of a command the backend hasn't even got yet.
2056  */
2057  while ((flushResult = pqFlush(conn)) > 0)
2058  {
2059  if (pqWait(false, true, conn))
2060  {
2061  flushResult = -1;
2062  break;
2063  }
2064  }
2065 
2066  /*
2067  * Wait for some more data, and load it. (Note: if the connection has
2068  * been lost, pqWait should return immediately because the socket
2069  * should be read-ready, either with the last server data or with an
2070  * EOF indication. We expect therefore that this won't result in any
2071  * undue delay in reporting a previous write failure.)
2072  */
2073  if (flushResult ||
2074  pqWait(true, false, conn) ||
2075  pqReadData(conn) < 0)
2076  {
2077  /* Report the error saved by pqWait or pqReadData */
2080  return pqPrepareAsyncResult(conn);
2081  }
2082 
2083  /* Parse it. */
2084  parseInput(conn);
2085 
2086  /*
2087  * If we had a write error, but nothing above obtained a query result
2088  * or detected a read error, report the write error.
2089  */
2091  {
2094  return pqPrepareAsyncResult(conn);
2095  }
2096  }
2097 
2098  /* Return the appropriate thing. */
2099  switch (conn->asyncStatus)
2100  {
2101  case PGASYNC_IDLE:
2102  res = NULL; /* query is complete */
2103  break;
2104  case PGASYNC_PIPELINE_IDLE:
2106 
2107  /*
2108  * We're about to return the NULL that terminates the round of
2109  * results from the current query; prepare to send the results of
2110  * the next query, if any, when we're called next. If there's no
2111  * next element in the command queue, this gets us in IDLE state.
2112  */
2114  res = NULL; /* query is complete */
2115  break;
2116 
2117  case PGASYNC_READY:
2119 
2120  /* Advance the queue as appropriate */
2121  pqCommandQueueAdvance(conn, false,
2123 
2125  {
2126  /*
2127  * We're about to send the results of the current query. Set
2128  * us idle now, and ...
2129  */
2131 
2132  /*
2133  * ... in cases when we're sending a pipeline-sync result,
2134  * move queue processing forwards immediately, so that next
2135  * time we're called, we're prepared to return the next result
2136  * received from the server. In all other cases, leave the
2137  * queue state change for next time, so that a terminating
2138  * NULL result is sent.
2139  *
2140  * (In other words: we don't return a NULL after a pipeline
2141  * sync.)
2142  */
2145  }
2146  else
2147  {
2148  /* Set the state back to BUSY, allowing parsing to proceed. */
2150  }
2151  break;
2152  case PGASYNC_READY_MORE:
2154  /* Set the state back to BUSY, allowing parsing to proceed. */
2156  break;
2157  case PGASYNC_COPY_IN:
2159  break;
2160  case PGASYNC_COPY_OUT:
2162  break;
2163  case PGASYNC_COPY_BOTH:
2165  break;
2166  default:
2167  libpq_append_conn_error(conn, "unexpected asyncStatus: %d", (int) conn->asyncStatus);
2169  conn->asyncStatus = PGASYNC_IDLE; /* try to restore valid state */
2171  break;
2172  }
2173 
2174  /* Time to fire PGEVT_RESULTCREATE events, if there are any */
2175  if (res && res->nEvents > 0)
2177 
2178  return res;
2179 }
static void pqSaveWriteError(PGconn *conn)
Definition: fe-exec.c:818
void pqCommandQueueAdvance(PGconn *conn, bool isReadyForQuery, bool gotSync)
Definition: fe-exec.c:3104
void pqSaveErrorResult(PGconn *conn)
Definition: fe-exec.c:801
static PGresult * getCopyResult(PGconn *conn, ExecStatusType copytype)
Definition: fe-exec.c:2186
static void parseInput(PGconn *conn)
Definition: fe-exec.c:1996
static void pqPipelineProcessQueue(PGconn *conn)
Definition: fe-exec.c:3142
PGresult * pqPrepareAsyncResult(PGconn *conn)
Definition: fe-exec.c:849
int pqWait(int forRead, int forWrite, PGconn *conn)
Definition: fe-misc.c:979
int PQfireResultCreateEvents(PGconn *conn, PGresult *res)
Definition: libpq-events.c:185
bool write_failed
Definition: libpq-int.h:474

References Assert(), pg_conn::asyncStatus, conn, getCopyResult(), libpq_append_conn_error(), pg_result::nEvents, parseInput(), PGASYNC_BUSY, PGASYNC_COPY_BOTH, PGASYNC_COPY_IN, PGASYNC_COPY_OUT, PGASYNC_IDLE, PGASYNC_PIPELINE_IDLE, PGASYNC_READY, PGASYNC_READY_MORE, PGRES_COPY_BOTH, PGRES_COPY_IN, PGRES_COPY_OUT, PGRES_PIPELINE_SYNC, pg_conn::pipelineStatus, PQ_PIPELINE_OFF, pqCommandQueueAdvance(), PQfireResultCreateEvents(), pqFlush(), pqPipelineProcessQueue(), pqPrepareAsyncResult(), pqReadData(), pqSaveErrorResult(), pqSaveWriteError(), pqWait(), res, pg_result::resultStatus, and pg_conn::write_failed.

Referenced by advanceConnectionState(), BaseBackup(), ClearOrSaveAllResults(), confirm_query_canceled_impl(), consumeQueryResult(), discardUntilSync(), dumpTableData_copy(), ecpg_process_output(), EndDBCopyMode(), ExecQueryAndProcessResults(), handleCopyIn(), handleCopyOut(), HandleEndOfCopyStream(), libpqrcv_PQgetResult(), libpqsrv_get_result(), pgfdw_finish_pre_commit_cleanup(), pgfdw_get_cleanup_result(), PQconnectPoll(), pqEndcopy3(), PQexecFinish(), PQexecStart(), process_queued_fetch_requests(), process_result(), readCommandResponse(), ReceiveCopyData(), ReceiveXlogStream(), StreamLogicalLog(), test_multi_pipelines(), test_nosync(), test_pipeline_abort(), test_pipeline_idle(), test_pipelined_insert(), test_prepared(), test_simple_pipeline(), test_singlerowmode(), test_transaction(), test_uniqviol(), try_complete_step(), and wait_on_slots().

◆ PQgetssl()

void* PQgetssl ( PGconn conn)

Definition at line 1730 of file fe-secure-openssl.c.

1731 {
1732  if (!conn)
1733  return NULL;
1734  return conn->ssl;
1735 }

References conn.

◆ PQgetSSLKeyPassHook_OpenSSL()

PQsslKeyPassHook_OpenSSL_type PQgetSSLKeyPassHook_OpenSSL ( void  )

Definition at line 2003 of file fe-secure-openssl.c.

2004 {
2005  return PQsslKeyPassHook;
2006 }
static PQsslKeyPassHook_OpenSSL_type PQsslKeyPassHook

References PQsslKeyPassHook.

◆ PQgetvalue()

char* PQgetvalue ( const PGresult res,
int  tup_num,
int  field_num 
)

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

3837 {
3838  if (!check_tuple_field_number(res, tup_num, field_num))
3839  return NULL;
3840  return res->tuples[tup_num][field_num].value;
3841 }

References check_tuple_field_number(), res, pg_result::tuples, and pgresAttValue::value.

Referenced by _check_database_version(), add_tablespace_footer(), addFooterToPublicationDesc(), append_depends_on_extension(), appendQualifiedRelation(), BaseBackup(), binary_upgrade_set_pg_class_oids(), binary_upgrade_set_type_oids_by_type_oid(), buildMatViewRefreshDependencies(), check_for_data_types_usage(), check_for_incompatible_polymorphics(), check_for_isn_and_int8_passing_mismatch(), check_for_pg_role_prefix(), check_for_tables_with_oids(), check_for_user_defined_encoding_conversions(), check_for_user_defined_postfix_ops(), check_is_install_user(), check_new_cluster_logical_replication_slots(), check_new_cluster_subscription_configuration(), check_old_cluster_subscription_state(), check_proper_datallowconn(), cluster_all_databases(), collectComments(), collectRoleNames(), collectSecLabels(), compile_database_list(), compile_relation_list_one_db(), convertTSFunction(), createViewAsClause(), describeOneTableDetails(), describePublications(), describeRoles(), describeTableDetails(), do_field(), dropDBs(), dropRoles(), dropTablespaces(), dumpAgg(), dumpBaseType(), dumpCollation(), dumpCompositeType(), dumpCompositeTypeColComments(), dumpConversion(), dumpDatabase(), dumpDatabaseConfig(), dumpDatabases(), dumpDomain(), dumpEnumType(), dumpForeignServer(), dumpFunc(), dumpLOs(), dumpOpclass(), dumpOpfamily(), dumpOpr(), dumpRangeType(), dumpRoleGUCPrivs(), dumpRoleMembership(), dumpRoles(), dumpRule(), dumpSearchPath(), dumpSequence(), dumpSequenceData(), dumpStatisticsExt(), dumpTable(), dumpTableAttach(), dumpTableData_insert(), dumpTableSchema(), dumpTablespaces(), dumpTSConfig(), dumpTSDictionary(), dumpUserConfig(), dumpUserMappings(), ecpg_get_data(), ecpg_set_compat_sqlda(), ecpg_set_native_sqlda(), ecpg_store_result(), emitShSecLabels(), exec_command_password(), ExecQueryTuples(), expand_dbname_patterns(), expand_extension_name_patterns(), expand_foreign_server_name_patterns(), expand_schema_name_patterns(), expand_table_name_patterns(), get_create_object_cmd(), get_db_infos(), get_db_subscription_count(), get_language_name(), get_loadable_libraries(), get_next_possible_free_pg_type_oid(), get_old_cluster_logical_slot_infos(), get_parallel_object_list(), get_rel_infos(), get_remote_estimate(), get_synchronized_snapshot(), get_tablespace_paths(), get_template0_info(), getAccessMethods(), getAdditionalACLs(), getAggregates(), getCasts(), getCollations(), getConstraints(), getConversions(), getDefaultACLs(), getDependencies(), getDomainConstraints(), getEventTriggers(), getExtendedStatistics(), getExtensionMembership(), getExtensions(), getForeignDataWrappers(), getForeignServers(), getFormattedTypeName(), getFuncs(), getIndexes(), getInherits(), getLOs(), getNamespaces(), getOpclasses(), getOperators(), getOpfamilies(), getPartitioningInfo(), getPolicies(), getProcLangs(), getPublicationNamespaces(), getPublications(), getPublicationTables(), getRules(), GetSlotInformation(), getSubscriptions(), getSubscriptionTables(), getTableAttrs(), GetTableInfo(), getTables(), getTransforms(), getTriggers(), getTSConfigurations(), getTSDictionaries(), getTSParsers(), getTSTemplates(), getTypes(), libpq_fetch_file(), libpq_traverse_files(), libpqrcv_create_slot(), libpqrcv_endstreaming(), libpqrcv_identify_system(), libpqrcv_processTuples(), libpqrcv_readtimelinehistoryfile(), listExtensionContents(), listSchemas(), listTSConfigsVerbose(), listTSParsersVerbose(), lo_initialize(), lookup_object_oid(), main(), make_tuple_from_result_row(), materializeResult(), old_9_6_invalidate_hash_indexes(), postgresAnalyzeForeignTable(), postgresGetAnalyzeInfoForForeignTable(), postgresImportForeignSchema(), PQconnectPoll(), PQdisplayTuples(), PQencryptPasswordConn(), PQprintTuples(), printCrosstab(), printQuery(), PrintResultInCrosstab(), process_queued_fetch_requests(), process_result(), processExtensionTables(), readCommandResponse(), ReadEndOfStreamingResult(), ReceiveXlogStream(), reindex_all_databases(), report_extension_updates(), RetrieveDataDirCreatePerm(), RetrieveWalSegSize(), run_simple_query(), RunIdentifySystem(), set_frozenxids(), show_binary_results(), sql_exec(), sqlda_common_total_size(), StoreQueryTuple(), storeRow(), test_pipeline_abort(), test_singlerowmode(), test_transaction(), try_complete_step(), vacuum_all_databases(), vacuum_one_database(), vacuumlo(), verify_heap_slot_handler(), and wait_for_connection_state().

◆ PQgssEncInUse()

int PQgssEncInUse ( PGconn conn)

Definition at line 736 of file fe-secure-gssapi.c.

737 {
738  if (!conn || !conn->gctx)
739  return 0;
740 
741  return conn->gssenc;
742 }

References conn.

Referenced by printGSSInfo().

◆ PQhost()

char* PQhost ( const PGconn conn)

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

6828 {
6829  if (!conn)
6830  return NULL;
6831 
6832  if (conn->connhost != NULL)
6833  {
6834  /*
6835  * Return the verbatim host value provided by user, or hostaddr in its
6836  * lack.
6837  */
6838  if (conn->connhost[conn->whichhost].host != NULL &&
6839  conn->connhost[conn->whichhost].host[0] != '\0')
6840  return conn->connhost[conn->whichhost].host;
6841  else if (conn->connhost[conn->whichhost].hostaddr != NULL &&
6842  conn->connhost[conn->whichhost].hostaddr[0] != '\0')
6843  return conn->connhost[conn->whichhost].hostaddr;
6844  }
6845 
6846  return "";
6847 }

References conn, pg_conn::connhost, pg_conn_host::host, pg_conn_host::hostaddr, and pg_conn::whichhost.

Referenced by do_connect(), exec_command_conninfo(), get_prompt(), libpqrcv_get_senderinfo(), main(), pg_GSS_load_servicename(), and SyncVariables().

◆ PQhostaddr()

char* PQhostaddr ( const PGconn conn)

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

6851 {
6852  if (!conn)
6853  return NULL;
6854 
6855  /* Return the parsed IP address */
6856  if (conn->connhost != NULL && conn->connip != NULL)
6857  return conn->connip;
6858 
6859  return "";
6860 }

References conn, pg_conn::connhost, and pg_conn::connip.

Referenced by do_connect(), and exec_command_conninfo().

◆ PQinitOpenSSL()

void PQinitOpenSSL ( int  do_ssl,
int  do_crypto 
)

Definition at line 127 of file fe-secure.c.

128 {
129 #ifdef USE_SSL
130  pgtls_init_library(do_ssl, do_crypto);
131 #endif
132 }
void pgtls_init_library(bool do_ssl, int do_crypto)

References pgtls_init_library().

◆ PQinitSSL()

void PQinitSSL ( int  do_init)

Definition at line 115 of file fe-secure.c.

116 {
117 #ifdef USE_SSL
119 #endif
120 }
static void do_init(void)
Definition: pg_ctl.c:894

References do_init(), and pgtls_init_library().

◆ PQisBusy()

int PQisBusy ( PGconn conn)

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

2008 {
2009  if (!conn)
2010  return false;
2011 
2012  /* Parse any available data, if our state permits. */
2013  parseInput(conn);
2014 
2015  /*
2016  * PQgetResult will return immediately in all states except BUSY. Also,
2017  * if we've detected read EOF and dropped the connection, we can expect
2018  * that PQgetResult will fail immediately. Note that we do *not* check
2019  * conn->write_failed here --- once that's become set, we know we have
2020  * trouble, but we need to keep trying to read until we have a complete
2021  * server message or detect read EOF.
2022  */
2024 }

References pg_conn::asyncStatus, conn, CONNECTION_BAD, parseInput(), PGASYNC_BUSY, and pg_conn::status.

Referenced by advanceConnectionState(), confirm_query_canceled_impl(), dblink_is_busy(), libpqrcv_PQgetResult(), libpqsrv_get_result(), pgfdw_get_cleanup_result(), PQconnectPoll(), pqEndcopy3(), test_disallowed_in_pipeline(), test_pipelined_insert(), test_uniqviol(), try_complete_step(), and wait_on_slots().

◆ PQisnonblocking()

int PQisnonblocking ( const PGconn conn)

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

3944 {
3945  if (!conn || conn->status == CONNECTION_BAD)
3946  return false;
3947  return pqIsnonblocking(conn);
3948 }

References conn, CONNECTION_BAD, pqIsnonblocking, and pg_conn::status.

Referenced by test_disallowed_in_pipeline(), and test_simple_pipeline().

◆ PQisthreadsafe()

int PQisthreadsafe ( void  )

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

3953 {
3954  return true;
3955 }

◆ PQlibVersion()

int PQlibVersion ( void  )

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

65 {
66  return PG_VERSION_NUM;
67 }

◆ PQmakeEmptyPGresult()

PGresult* PQmakeEmptyPGresult ( PGconn conn,
ExecStatusType  status 
)

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

159 {
160  PGresult *result;
161 
162  result = (PGresult *) malloc(sizeof(PGresult));
163  if (!result)
164  return NULL;
165 
166  result->ntups = 0;
167  result->numAttributes = 0;
168  result->attDescs = NULL;
169  result->tuples = NULL;
170  result->tupArrSize = 0;
171  result->numParameters = 0;
172  result->paramDescs = NULL;
173  result->resultStatus = status;
174  result->cmdStatus[0] = '\0';
175  result->binary = 0;
176  result->events = NULL;
177  result->nEvents = 0;
178  result->errMsg = NULL;
179  result->errFields = NULL;
180  result->errQuery = NULL;
181  result->null_field[0] = '\0';
182  result->curBlock = NULL;
183  result->curOffset = 0;
184  result->spaceLeft = 0;
185  result->memorySize = sizeof(PGresult);
186 
187  if (conn)
188  {
189  /* copy connection data we might need for operations on PGresult */
190  result->noticeHooks = conn->noticeHooks;
192 
193  /* consider copying conn's errorMessage */
194  switch (status)
195  {
196  case PGRES_EMPTY_QUERY:
197  case PGRES_COMMAND_OK:
198  case PGRES_TUPLES_OK:
199  case PGRES_COPY_OUT:
200  case PGRES_COPY_IN:
201  case PGRES_COPY_BOTH:
202  case PGRES_SINGLE_TUPLE:
203  /* non-error cases */
204  break;
205  default:
206  /* we intentionally do not use or modify errorReported here */
207  pqSetResultError(result, &conn->errorMessage, 0);
208  break;
209  }
210 
211  /* copy events last; result must be valid if we need to PQclear */
212  if (conn->nEvents > 0)
213  {
214  result->events = dupEvents(conn->events, conn->nEvents,
215  &result->memorySize);
216  if (!result->events)
217  {
218  PQclear(result);
219  return NULL;
220  }
221  result->nEvents = conn->nEvents;
222  }
223  }
224  else
225  {
226  /* defaults... */
227  result->noticeHooks.noticeRec = NULL;
228  result->noticeHooks.noticeRecArg = NULL;
229  result->noticeHooks.noticeProc = NULL;
230  result->noticeHooks.noticeProcArg = NULL;
231  result->client_encoding = PG_SQL_ASCII;
232  }
233 
234  return result;
235 }
void pqSetResultError(PGresult *res, PQExpBuffer errorMessage, int offset)
Definition: fe-exec.c:690
struct pg_result PGresult
Definition: libpq-fe.h:181
void * noticeProcArg
Definition: libpq-int.h:158
PQnoticeReceiver noticeRec
Definition: libpq-int.h:155
PQnoticeProcessor noticeProc
Definition: libpq-int.h:157
void * noticeRecArg
Definition: libpq-int.h:156
int nEvents
Definition: libpq-int.h:425
PGNoticeHooks noticeHooks
Definition: libpq-int.h:421
PGEvent * events
Definition: libpq-int.h:424
size_t memorySize
Definition: libpq-int.h:215
int curOffset
Definition: libpq-int.h:212
char null_field[1]
Definition: libpq-int.h:204
char * errMsg
Definition: libpq-int.h:199
int numParameters
Definition: libpq-int.h:178
int spaceLeft
Definition: libpq-int.h:213
int tupArrSize
Definition: libpq-int.h:177
char * errQuery
Definition: libpq-int.h:201

References pg_result::attDescs, pg_result::binary, pg_result::client_encoding, pg_conn::client_encoding, pg_result::cmdStatus, conn, pg_result::curBlock, pg_result::curOffset, dupEvents(), pg_result::errFields, pg_result::errMsg, pg_conn::errorMessage, pg_result::errQuery, pg_result::events, pg_conn::events, malloc, pg_result::memorySize, pg_result::nEvents, pg_conn::nEvents, pg_result::noticeHooks, pg_conn::noticeHooks, PGNoticeHooks::noticeProc, PGNoticeHooks::noticeProcArg, PGNoticeHooks::noticeRec, PGNoticeHooks::noticeRecArg, pg_result::ntups, pg_result::null_field, pg_result::numAttributes, pg_result::numParameters, pg_result::paramDescs, PG_SQL_ASCII, PGRES_COMMAND_OK, PGRES_COPY_BOTH, PGRES_COPY_IN, PGRES_COPY_OUT, PGRES_EMPTY_QUERY, PGRES_SINGLE_TUPLE, PGRES_TUPLES_OK, PQclear(), pqSetResultError(), pg_result::resultStatus, pg_result::spaceLeft, pg_result::tupArrSize, and pg_result::tuples.

Referenced by ECPGallocate_desc(), getCopyResult(), getCopyStart(), getParamDescriptions(), getRowDescriptions(), PQcopyResult(), pqFunctionCall3(), pqGetErrorNotice3(), pqInternalNotice(), pqParseInput3(), pqPipelineProcessQueue(), and pqPrepareAsyncResult().

◆ PQmblen()

int PQmblen ( const char *  s,
int  encoding 
)

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

1178 {
1179  return pg_encoding_mblen(encoding, s);
1180 }
int pg_encoding_mblen(int encoding, const char *mbstr)
Definition: wchar.c:2130

References encoding, and pg_encoding_mblen().

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

◆ PQmblenBounded()

int PQmblenBounded ( const char *  s,
int  encoding 
)

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

1188 {
1189  return strnlen(s, pg_encoding_mblen(encoding, s));
1190 }
size_t strnlen(const char *str, size_t maxlen)
Definition: strnlen.c:26

References encoding, pg_encoding_mblen(), and strnlen().

Referenced by command_no_begin(), do_field(), is_select_command(), patternToSQLRegex(), quote_if_needed(), reportErrorPosition(), skip_white_space(), splitTableColumnsSpec(), strip_quotes(), and strtokx().

◆ PQnfields()

◆ PQnotifies()

PGnotify* PQnotifies ( PGconn conn)

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

2630 {
2631  PGnotify *event;
2632 
2633  if (!conn)
2634  return NULL;
2635 
2636  /* Parse any available data to see if we can extract NOTIFY messages. */
2637  parseInput(conn);
2638 
2639  event = conn->notifyHead;
2640  if (event)
2641  {
2642  conn->notifyHead = event->next;
2643  if (!conn->notifyHead)
2644  conn->notifyTail = NULL;
2645  event->next = NULL; /* don't let app see the internal state */
2646  }
2647  return event;
2648 }
struct pgNotify * next
Definition: libpq-fe.h:201
PGnotify * notifyHead
Definition: libpq-int.h:440
PGnotify * notifyTail
Definition: libpq-int.h:441

References conn, pgNotify::next, pg_conn::notifyHead, pg_conn::notifyTail, and parseInput().

Referenced by dblink_get_notify(), ecpg_process_output(), main(), PrintNotifications(), and try_complete_step().

◆ PQnparams()

int PQnparams ( const PGresult res)

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

3876 {
3877  if (!res)
3878  return 0;
3879  return res->numParameters;
3880 }

References pg_result::numParameters, and res.

◆ PQntuples()

int PQntuples ( const PGresult res)

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

3442 {
3443  if (!res)
3444  return 0;
3445  return res->ntups;
3446 }

References pg_result::ntups, and res.

Referenced by add_tablespace_footer(), addFooterToPublicationDesc(), append_depends_on_extension(), appendQualifiedRelation(), BaseBackup(), buildMatViewRefreshDependencies(), check_for_data_types_usage(), check_for_incompatible_polymorphics(), check_for_isn_and_int8_passing_mismatch(), check_for_pg_role_prefix(), check_for_prepared_transactions(), check_for_tables_with_oids(), check_for_user_defined_encoding_conversions(), check_for_user_defined_postfix_ops(), check_is_install_user(), check_new_cluster_logical_replication_slots(), check_new_cluster_subscription_configuration(), check_old_cluster_subscription_state(), check_proper_datallowconn(), cluster_all_databases(), collectComments(), collectRoleNames(), collectSecLabels(), compile_database_list(), compile_relation_list_one_db(), CreateReplicationSlot(), createViewAsClause(), describeOneTableDetails(), describePublications(), describeRoles(), describeTableDetails(), dropDBs(), DropReplicationSlot(), dropRoles(), dropTablespaces(), dumpCompositeType(), dumpCompositeTypeColComments(), dumpDatabase(), dumpDatabaseConfig(), dumpDatabases(), dumpEnumType(), dumpLOs(), dumpOpclass(), dumpOpfamily(), dumpRoleGUCPrivs(), dumpRoleMembership(), dumpRoles(), dumpRule(), dumpSequence(), dumpSequenceData(), dumpTable(), dumpTableData_insert(), dumpTablespaces(), dumpTSConfig(), dumpUserConfig(), dumpUserMappings(), ecpg_process_output(), ecpg_store_result(), ECPGget_desc(), emitShSecLabels(), ExecQueryAndProcessResults(), ExecQueryTuples(), ExecQueryUsingCursor(), execute_dml_stmt(), execute_foreign_modify(), ExecuteSqlQueryForSingleRow(), expand_dbname_patterns(), expand_extension_name_patterns(), expand_foreign_server_name_patterns(), expand_schema_name_patterns(), expand_table_name_patterns(), fetch_more_data(), get_create_object_cmd(), get_db_infos(), get_loadable_libraries(), get_old_cluster_logical_slot_infos(), get_parallel_object_list(), get_rel_infos(), get_tablespace_paths(), get_template0_info(), getAccessMethods(), getAdditionalACLs(), getAggregates(), getCasts(), getCollations(), getConstraints(), getConversions(), getDefaultACLs(), getDependencies(), getDomainConstraints(), getEventTriggers(), getExtendedStatistics(), getExtensionMembership(), getExtensions(), getForeignDataWrappers(), getForeignServers(), getFuncs(), getIndexes(), getInherits(), getLOs(), getNamespaces(), getOpclasses(), getOperators(), getOpfamilies(), getPartitioningInfo(), getPolicies(), getProcLangs(), getPublicationNamespaces(), getPublications(), getPublicationTables(), getRules(), GetSlotInformation(), getSubscriptions(), getSubscriptionTables(), getTableAttrs(), GetTableInfo(), getTables(), getTransforms(), getTriggers(), getTSConfigurations(), getTSDictionaries(), getTSParsers(), getTSTemplates(), getTypes(), libpq_fetch_file(), libpq_traverse_files(), libpqrcv_endstreaming(), libpqrcv_identify_system(), libpqrcv_processTuples(), libpqrcv_readtimelinehistoryfile(), listDbRoleSettings(), listExtensionContents(), listSchemas(), listTables(), listTSConfigsVerbose(), listTSParsersVerbose(), lo_initialize(), lookup_object_oid(), main(), make_tuple_from_result_row(), materializeResult(), old_9_6_invalidate_hash_indexes(), postgresAcquireSampleRowsFunc(), postgresAnalyzeForeignTable(), postgresGetAnalyzeInfoForForeignTable(), postgresImportForeignSchema(), PQconnectPoll(), PQdisplayTuples(), PQencryptPasswordConn(), PQprint(), PQprintTuples(), printCrosstab(), printQuery(), PrintResultInCrosstab(), process_queued_fetch_requests(), processExtensionTables(), readCommandResponse(), ReadEndOfStreamingResult(), ReceiveXlogStream(), reindex_all_databases(), report_extension_updates(), RetrieveDataDirCreatePerm(), RetrieveWalSegSize(), run_simple_query(), RunIdentifySystem(), set_frozenxids(), show_binary_results(), sql_exec(), StoreQueryTuple(), storeRow(), test_pipeline_abort(), test_singlerowmode(), test_transaction(), try_complete_step(), vacuum_all_databases(), vacuum_one_database(), vacuumlo(), verify_btree_slot_handler(), verify_heap_slot_handler(), and wait_for_connection_state().

◆ PQoidStatus()

char* PQoidStatus ( const PGresult res)

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

3726 {
3727  /*
3728  * This must be enough to hold the result. Don't laugh, this is better
3729  * than what this function used to do.
3730  */
3731  static char buf[24];
3732 
3733  size_t len;
3734 
3735  if (!res || strncmp(res->cmdStatus, "INSERT ", 7) != 0)
3736  return "";
3737 
3738  len = strspn(res->cmdStatus + 7, "0123456789");
3739  if (len > sizeof(buf) - 1)
3740  len = sizeof(buf) - 1;
3741  memcpy(buf, res->cmdStatus + 7, len);
3742  buf[len] = '\0';
3743 
3744  return buf;
3745 }

References buf, pg_result::cmdStatus, len, and res.

◆ PQoidValue()

Oid PQoidValue ( const PGresult res)

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

3754 {
3755  char *endptr = NULL;
3756  unsigned long result;
3757 
3758  if (!res ||
3759  strncmp(res->cmdStatus, "INSERT ", 7) != 0 ||
3760  res->cmdStatus[7] < '0' ||
3761  res->cmdStatus[7] > '9')
3762  return InvalidOid;
3763 
3764  result = strtoul(res->cmdStatus + 7, &endptr, 10);
3765 
3766  if (!endptr || (*endptr != ' ' && *endptr != '\0'))
3767  return InvalidOid;
3768  else
3769  return (Oid) result;
3770 }

References pg_result::cmdStatus, InvalidOid, and res.

Referenced by ecpg_process_output(), and PrintQueryStatus().

◆ PQoptions()

char* PQoptions ( const PGconn conn)

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

6888 {
6889  if (!conn)
6890  return NULL;
6891  return conn->pgoptions;
6892 }
char * pgoptions
Definition: libpq-int.h:374

References conn, and pg_conn::pgoptions.

◆ PQparameterStatus()

const char* PQparameterStatus ( const PGconn conn,
const char *  paramName 
)

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

6914 {
6915  const pgParameterStatus *pstatus;
6916 
6917  if (!conn || !paramName)
6918  return NULL;
6919  for (pstatus = conn->pstatus; pstatus != NULL; pstatus = pstatus->next)
6920  {
6921  if (strcmp(pstatus->name, paramName) == 0)
6922  return pstatus->value;
6923  }
6924  return NULL;
6925 }
struct pgParameterStatus * next
Definition: libpq-int.h:271
pgParameterStatus * pstatus
Definition: libpq-int.h:500

References conn, pgParameterStatus::name, pgParameterStatus::next, pg_conn::pstatus, and pgParameterStatus::value.

Referenced by _check_database_version(), applyRemoteGucs(), BaseBackup(), CheckServerVersionForStreaming(), connectDatabase(), connection_warnings(), ecpg_build_params(), GetConnection(), is_superuser(), main(), printVersion(), session_username(), setup_connection(), standard_strings(), and SyncVariables().

◆ PQparamtype()

Oid PQparamtype ( const PGresult res,
int  param_num 
)

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

3887 {
3888  if (!check_param_number(res, param_num))
3889  return InvalidOid;
3890  if (res->paramDescs)
3891  return res->paramDescs[param_num].typid;
3892  else
3893  return InvalidOid;
3894 }
static int check_param_number(const PGresult *res, int param_num)
Definition: fe-exec.c:3508

References check_param_number(), InvalidOid, pg_result::paramDescs, res, and pgresParamDesc::typid.

◆ PQpass()

char* PQpass ( const PGconn conn)

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

6811 {
6812  char *password = NULL;
6813 
6814  if (!conn)
6815  return NULL;
6816  if (conn->connhost != NULL)
6818  if (password == NULL)
6819  password = conn->pgpass;
6820  /* Historically we've returned "" not NULL for no password specified */
6821  if (password == NULL)
6822  password = "";
6823  return password;
6824 }
char * pgpass
Definition: libpq-int.h:380

References conn, pg_conn::connhost, password, pg_conn_host::password, pg_conn::pgpass, and pg_conn::whichhost.

Referenced by ConnectDatabase(), and PQconnectionNeedsPassword().

◆ PQping()

PGPing PQping ( const char *  conninfo)

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

750 {
751  PGconn *conn = PQconnectStart(conninfo);
752  PGPing ret;
753 
754  ret = internal_ping(conn);
755  PQfinish(conn);
756 
757  return ret;
758 }
static PGPing internal_ping(PGconn *conn)
Definition: fe-connect.c:4263

References conn, internal_ping(), PQconnectStart(), and PQfinish().

◆ PQpingParams()

PGPing PQpingParams ( const char *const *  keywords,
const char *const *  values,
int  expand_dbname 
)

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

699 {
700  PGconn *conn = PQconnectStartParams(keywords, values, expand_dbname);
701  PGPing ret;
702 
703  ret = internal_ping(conn);
704  PQfinish(conn);
705 
706  return ret;
707 }

References conn, internal_ping(), PQconnectStartParams(), PQfinish(), and values.

Referenced by main(), and regression_main().

◆ PQpipelineStatus()

PGpipelineStatus PQpipelineStatus ( const PGconn conn)

◆ PQpipelineSync()

int PQpipelineSync ( PGconn conn)

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

3233 {
3234  return pqPipelineSyncInternal(conn, true);
3235 }
static int pqPipelineSyncInternal(PGconn *conn, bool immediate_flush)
Definition: fe-exec.c:3254

References conn, and pqPipelineSyncInternal().

Referenced by discardUntilSync(), executeMetaCommand(), test_multi_pipelines(), test_pipeline_abort(), test_pipelined_insert(), test_prepared(), test_simple_pipeline(), test_singlerowmode(), and test_transaction().

◆ PQport()

char* PQport ( const PGconn conn)

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

6864 {
6865  if (!conn)
6866  return NULL;
6867 
6868  if (conn->connhost != NULL)
6869  return conn->connhost[conn->whichhost].port;
6870 
6871  return "";
6872 }

References conn, pg_conn::connhost, pg_conn_host::port, and pg_conn::whichhost.

Referenced by do_connect(), exec_command_conninfo(), get_prompt(), libpqrcv_get_senderinfo(), main(), and SyncVariables().

◆ PQprepare()

PGresult* PQprepare ( PGconn conn,
const char *  stmtName,
const char *  query,
int  nParams,
const Oid paramTypes 
)

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

2271 {
2272  if (!PQexecStart(conn))
2273  return NULL;
2274  if (!PQsendPrepare(conn, stmtName, query, nParams, paramTypes))
2275  return NULL;
2276  return PQexecFinish(conn);
2277 }
int PQsendPrepare(PGconn *conn, const char *stmtName, const char *query, int nParams, const Oid *paramTypes)
Definition: fe-exec.c:1545

References conn, PQexecFinish(), PQexecStart(), and PQsendPrepare().

Referenced by DescribeQuery(), init_libpq_conn(), main(), prepare_common(), prepareCommand(), and test_uniqviol().

◆ PQprint()

void PQprint ( FILE *  fout,
const PGresult res,
const PQprintOpt po 
)

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

69 {
70  int nFields;
71 
72  nFields = PQnfields(res);
73 
74  if (nFields > 0)
75  { /* only print rows with at least 1 field. */
76  int i,
77  j;
78  int nTups;
79  int *fieldMax = NULL; /* in case we don't use them */
80  unsigned char *fieldNotNum = NULL;
81  char *border = NULL;
82  char **fields = NULL;
83  const char **fieldNames = NULL;
84  int fieldMaxLen = 0;
85  int numFieldName;
86  int fs_len = strlen(po->fieldSep);
87  int total_line_length = 0;
88  bool usePipe = false;
89  char *pagerenv;
90 
91 #if !defined(WIN32)
92  sigset_t osigset;
93  bool sigpipe_masked = false;
94  bool sigpipe_pending;
95 #endif
96 
97 #ifdef TIOCGWINSZ
98  struct winsize screen_size;
99 #else
100  struct winsize
101  {
102  int ws_row;
103  int ws_col;
104  } screen_size;
105 #endif
106 
107  nTups = PQntuples(res);
108  fieldNames = (const char **) calloc(nFields, sizeof(char *));
109  fieldNotNum = (unsigned char *) calloc(nFields, 1);
110  fieldMax = (int *) calloc(nFields, sizeof(int));
111  if (!fieldNames || !fieldNotNum || !fieldMax)
112  {
113  fprintf(stderr, libpq_gettext("out of memory\n"));
114  goto exit;
115  }
116  for (numFieldName = 0;
117  po->fieldName && po->fieldName[numFieldName];
118  numFieldName++)
119  ;
120  for (j = 0; j < nFields; j++)
121  {
122  int len;
123  const char *s = (j < numFieldName && po->fieldName[j][0]) ?
124  po->fieldName[j] : PQfname(res, j);
125 
126  fieldNames[j] = s;
127  len = s ? strlen(s) : 0;
128  fieldMax[j] = len;
129  len += fs_len;
130  if (len > fieldMaxLen)
131  fieldMaxLen = len;
132  total_line_length += len;
133  }
134 
135  total_line_length += nFields * strlen(po->fieldSep) + 1;
136 
137  if (fout == NULL)
138  fout = stdout;
139  if (po->pager && fout == stdout && isatty(fileno(stdin)) &&
140  isatty(fileno(stdout)))
141  {
142  /*
143  * If we think there'll be more than one screen of output, try to
144  * pipe to the pager program.
145  */
146 #ifdef TIOCGWINSZ
147  if (ioctl(fileno(stdout), TIOCGWINSZ, &screen_size) == -1 ||
148  screen_size.ws_col == 0 ||
149  screen_size.ws_row == 0)
150  {
151  screen_size.ws_row = 24;
152  screen_size.ws_col = 80;
153  }
154 #else
155  screen_size.ws_row = 24;
156  screen_size.ws_col = 80;
157 #endif
158 
159  /*
160  * Since this function is no longer used by psql, we don't examine
161  * PSQL_PAGER. It's possible that the hypothetical external users
162  * of the function would like that to happen, but in the name of
163  * backwards compatibility, we'll stick to just examining PAGER.
164  */
165  pagerenv = getenv("PAGER");
166  /* if PAGER is unset, empty or all-white-space, don't use pager */
167  if (pagerenv != NULL &&
168  strspn(pagerenv, " \t\r\n") != strlen(pagerenv) &&
169  !po->html3 &&
170  ((po->expanded &&
171  nTups * (nFields + 1) >= screen_size.ws_row) ||
172  (!po->expanded &&
173  nTups * (total_line_length / screen_size.ws_col + 1) *
174  (1 + (po->standard != 0)) >= screen_size.ws_row -
175  (po->header != 0) *
176  (total_line_length / screen_size.ws_col + 1) * 2
177  - (po->header != 0) * 2 /* row count and newline */
178  )))
179  {
180  fflush(NULL);
181  fout = popen(pagerenv, "w");
182  if (fout)
183  {
184  usePipe = true;
185 #ifndef WIN32
186  if (pq_block_sigpipe(&osigset, &sigpipe_pending) == 0)
187  sigpipe_masked = true;
188 #endif /* WIN32 */
189  }
190  else
191  fout = stdout;
192  }
193  }
194 
195  if (!po->expanded && (po->align || po->html3))
196  {
197  fields = (char **) calloc((size_t) nTups + 1,
198  nFields * sizeof(char *));
199  if (!fields)
200  {
201  fprintf(stderr, libpq_gettext("out of memory\n"));
202  goto exit;
203  }
204  }
205  else if (po->header && !po->html3)
206  {
207  if (po->expanded)
208  {
209  if (po->align)
210  fprintf(fout, libpq_gettext("%-*s%s Value\n"),
211  fieldMaxLen - fs_len, libpq_gettext("Field"), po->fieldSep);
212  else
213  fprintf(fout, libpq_gettext("%s%sValue\n"), libpq_gettext("Field"), po->fieldSep);
214  }
215  else
216  {
217  int len = 0;
218 
219  for (j = 0; j < nFields; j++)
220  {
221  const char *s = fieldNames[j];
222 
223  fputs(s, fout);
224  len += strlen(s) + fs_len;
225  if ((j + 1) < nFields)
226  fputs(po->fieldSep, fout);
227  }
228  fputc('\n', fout);
229  for (len -= fs_len; len--; fputc('-', fout));
230  fputc('\n', fout);
231  }
232  }
233  if (po->expanded && po->html3)
234  {
235  if (po->caption)
236  fprintf(fout, "<center><h2>%s</h2></center>\n", po->caption);
237  else
238  fprintf(fout,
239  "<center><h2>"
240  "Query retrieved %d rows * %d fields"
241  "</h2></center>\n",
242  nTups, nFields);
243  }
244  for (i = 0; i < nTups; i++)
245  {
246  if (po->expanded)
247  {
248  if (po->html3)
249  fprintf(fout,
250  "<table %s><caption align=\"top\">%d</caption>\n",
251  po->tableOpt ? po->tableOpt : "", i);
252  else
253  fprintf(fout, libpq_gettext("-- RECORD %d --\n"), i);
254  }
255  for (j = 0; j < nFields; j++)
256  {
257  if (!do_field(po, res, i, j, fs_len, fields, nFields,
258  fieldNames, fieldNotNum,
259  fieldMax, fieldMaxLen, fout))
260  goto exit;
261  }
262  if (po->html3 && po->expanded)
263  fputs("</table>\n", fout);
264  }
265  if (!po->expanded && (po->align || po->html3))
266  {
267  if (po->html3)
268  {
269  if (po->header)
270  {
271  if (po->caption)
272  fprintf(fout,
273  "<table %s><caption align=\"top\">%s</caption>\n",
274  po->tableOpt ? po->tableOpt : "",
275  po->caption);
276  else
277  fprintf(fout,
278  "<table %s><caption align=\"top\">"
279  "Retrieved %d rows * %d fields"
280  "</caption>\n",
281  po->tableOpt ? po->tableOpt : "", nTups, nFields);
282  }
283  else
284  fprintf(fout, "<table %s>", po->tableOpt ? po->tableOpt : "");
285  }
286  if (po->header)
287  border = do_header(fout, po, nFields, fieldMax, fieldNames,
288  fieldNotNum, fs_len, res);
289  for (i = 0; i < nTups; i++)
290  output_row(fout, po, nFields, fields,
291  fieldNotNum, fieldMax, border, i);
292  }
293  if (po->header && !po->html3)
294  fprintf(fout, "(%d row%s)\n\n", PQntuples(res),
295  (PQntuples(res) == 1) ? "" : "s");
296  if (po->html3 && !po->expanded)
297  fputs("</table>\n", fout);
298 
299 exit:
300  free(fieldMax);
301  free(fieldNotNum);
302  free(border);
303  if (fields)
304  {
305  /* if calloc succeeded, this shouldn't overflow size_t */
306  size_t numfields = ((size_t) nTups + 1) * (size_t) nFields;
307 
308  while (numfields-- > 0)
309  free(fields[numfields]);
310  free(fields);
311  }
312  free(fieldNames);
313  if (usePipe)
314  {
315 #ifdef WIN32
316  _pclose(fout);
317 #else
318  pclose(fout);
319 
320  /* we can't easily verify if EPIPE occurred, so say it did */
321  if (sigpipe_masked)
322  pq_reset_sigpipe(&osigset, sigpipe_pending, true);
323 #endif /* WIN32 */
324  }
325  }
326 }
static char * do_header(FILE *fout, const PQprintOpt *po, const int nFields, int *fieldMax, const char **fieldNames, unsigned char *fieldNotNum, const int fs_len, const PGresult *res)
Definition: fe-print.c:445
static bool do_field(const PQprintOpt *po, const PGresult *res, const int i, const int j, const int fs_len, char **fields, const int nFields, const char **fieldNames, unsigned char *fieldNotNum, int *fieldMax, const int fieldMaxLen, FILE *fout)
Definition: fe-print.c:330
static void output_row(FILE *fout, const PQprintOpt *po, const int nFields, char **fields, unsigned char *fieldNotNum, int *fieldMax, char *border, const int row_index)
Definition: fe-print.c:531
void pq_reset_sigpipe(sigset_t *osigset, bool sigpipe_pending, bool got_epipe)
Definition: fe-secure.c:569
int pq_block_sigpipe(sigset_t *osigset, bool *sigpipe_pending)
Definition: fe-secure.c:519
exit(1)
pqbool align
Definition: libpq-fe.h:214
pqbool pager
Definition: libpq-fe.h:218
pqbool standard
Definition: libpq-fe.h:215
pqbool html3
Definition: libpq-fe.h:216
char * caption
Definition: libpq-fe.h:221
pqbool header
Definition: libpq-fe.h:213
pqbool expanded
Definition: libpq-fe.h:217
char * fieldSep
Definition: libpq-fe.h:219
char ** fieldName
Definition: libpq-fe.h:222
char * tableOpt
Definition: libpq-fe.h:220

References _PQprintOpt::align, calloc, _PQprintOpt::caption, do_field(), do_header(), exit(), _PQprintOpt::expanded, fflush(), _PQprintOpt::fieldName, _PQprintOpt::fieldSep, fprintf, free, _PQprintOpt::header, _PQprintOpt::html3, i, j, len, libpq_gettext, output_row(), _PQprintOpt::pager, pq_block_sigpipe(), pq_reset_sigpipe(), PQfname(), PQnfields(), PQntuples(), res, _PQprintOpt::standard, generate_unaccent_rules::stdout, and _PQprintOpt::tableOpt.

Referenced by printResultSet().

◆ PQprintTuples()

void PQprintTuples ( const PGresult res,
FILE *  fout,
int  PrintAttNames,
int  TerseOutput,
int  colWidth 
)

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

677 {
678  int nFields;
679  int nTups;
680  int i,
681  j;
682  char formatString[80];
683  char *tborder = NULL;
684 
685  nFields = PQnfields(res);
686  nTups = PQntuples(res);
687 
688  if (colWidth > 0)
689  sprintf(formatString, "%%s %%-%ds", colWidth);
690  else
691  sprintf(formatString, "%%s %%s");
692 
693  if (nFields > 0)
694  { /* only print rows with at least 1 field. */
695 
696  if (!TerseOutput)
697  {
698  int width;
699 
700  width = nFields * 14;
701  tborder = (char *) malloc(width + 1);
702  if (!tborder)
703  {
704  fprintf(stderr, libpq_gettext("out of memory\n"));
705  return;
706  }
707  for (i = 0; i < width; i++)
708  tborder[i] = '-';
709  tborder[width] = '\0';
710  fprintf(fout, "%s\n", tborder);
711  }
712 
713  for (i = 0; i < nFields; i++)
714  {
715  if (PrintAttNames)
716  {
717  fprintf(fout, formatString,
718  TerseOutput ? "" : "|",
719  PQfname(res, i));
720  }
721  }
722 
723  if (PrintAttNames)
724  {
725  if (TerseOutput)
726  fprintf(fout, "\n");
727  else
728  fprintf(fout, "|\n%s\n", tborder);
729  }
730 
731  for (i = 0; i < nTups; i++)
732  {
733  for (j = 0; j < nFields; j++)
734  {
735  const char *pval = PQgetvalue(res, i, j);
736 
737  fprintf(fout, formatString,
738  TerseOutput ? "" : "|",
739  pval ? pval : "");
740  }
741  if (TerseOutput)
742  fprintf(fout, "\n");
743  else
744  fprintf(fout, "|\n%s\n", tborder);
745  }
746  }
747 
748  free(tborder);
749 }
#define sprintf
Definition: port.h:240

References fprintf, free, i, j, libpq_gettext, malloc, PQfname(), PQgetvalue(), PQnfields(), PQntuples(), res, and sprintf.

◆ PQprotocolVersion()

int PQprotocolVersion ( const PGconn conn)

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

6929 {
6930  if (!conn)
6931  return 0;
6932  if (conn->status == CONNECTION_BAD)
6933  return 0;
6934  return PG_PROTOCOL_MAJOR(conn->pversion);
6935 }
#define PG_PROTOCOL_MAJOR(v)
Definition: pqcomm.h:87

References conn, CONNECTION_BAD, PG_PROTOCOL_MAJOR, pg_conn::pversion, and pg_conn::status.

Referenced by handleCopyIn().

◆ PQputCopyData()

int PQputCopyData ( PGconn conn,
const char *  buffer,
int  nbytes 
)

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

2658 {
2659  if (!conn)
2660  return -1;
2661  if (conn->asyncStatus != PGASYNC_COPY_IN &&
2663  {
2664  libpq_append_conn_error(conn, "no COPY in progress");
2665  return -1;
2666  }
2667 
2668  /*
2669  * Process any NOTICE or NOTIFY messages that might be pending in the
2670  * input buffer. Since the server might generate many notices during the
2671  * COPY, we want to clean those out reasonably promptly to prevent
2672  * indefinite expansion of the input buffer. (Note: the actual read of
2673  * input data into the input buffer happens down inside pqSendSome, but
2674  * it's not authorized to get rid of the data again.)
2675  */
2676  parseInput(conn);
2677 
2678  if (nbytes > 0)
2679  {
2680  /*
2681  * Try to flush any previously sent data in preference to growing the
2682  * output buffer. If we can't enlarge the buffer enough to hold the
2683  * data, return 0 in the nonblock case, else hard error. (For
2684  * simplicity, always assume 5 bytes of overhead.)
2685  */
2686  if ((conn->outBufSize - conn->outCount - 5) < nbytes)
2687  {
2688  if (pqFlush(conn) < 0)
2689  return -1;
2690  if (pqCheckOutBufferSpace(conn->outCount + 5 + (size_t) nbytes,
2691  conn))
2692  return pqIsnonblocking(conn) ? 0 : -1;
2693  }
2694  /* Send the data (too simple to delegate to fe-protocol files) */
2695  if (pqPutMsgStart(PqMsg_CopyData, conn) < 0 ||
2696  pqPutnchar(buffer, nbytes, conn) < 0 ||
2697  pqPutMsgEnd(conn) < 0)
2698  return -1;
2699  }
2700  return 1;
2701 }
int pqCheckOutBufferSpace(size_t bytes_needed, PGconn *conn)
Definition: fe-misc.c:288
int pqPutMsgStart(char msg_type, PGconn *conn)
Definition: fe-misc.c:459
int pqPutnchar(const char *s, size_t len, PGconn *conn)
Definition: fe-misc.c:203
int pqPutMsgEnd(PGconn *conn)
Definition: fe-misc.c:518
#define PqMsg_CopyData
Definition: protocol.h:65
int outBufSize
Definition: libpq-int.h:520
int outCount
Definition: libpq-int.h:521

References pg_conn::asyncStatus, conn, libpq_append_conn_error(), pg_conn::outBufSize, pg_conn::outCount, parseInput(), PGASYNC_COPY_BOTH, PGASYNC_COPY_IN, pqCheckOutBufferSpace(), pqFlush(), pqIsnonblocking, PqMsg_CopyData, pqPutMsgEnd(), pqPutMsgStart(), and pqPutnchar().

Referenced by BaseBackup(), ExecuteSqlCommandBuf(), handleCopyIn(), libpqrcv_send(), PQputnbytes(), and sendFeedback().

◆ PQputCopyEnd()

int PQputCopyEnd ( PGconn conn,
const char *  errormsg 
)

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

2712 {
2713  if (!conn)
2714  return -1;
2715  if (conn->asyncStatus != PGASYNC_COPY_IN &&
2717  {
2718  libpq_append_conn_error(conn, "no COPY in progress");
2719  return -1;
2720  }
2721 
2722  /*
2723  * Send the COPY END indicator. This is simple enough that we don't
2724  * bother delegating it to the fe-protocol files.
2725  */
2726  if (errormsg)
2727  {
2728  /* Send COPY FAIL */
2729  if (pqPutMsgStart(PqMsg_CopyFail, conn) < 0 ||
2730  pqPuts(errormsg, conn) < 0 ||
2731  pqPutMsgEnd(conn) < 0)
2732  return -1;
2733  }
2734  else
2735  {
2736  /* Send COPY DONE */
2737  if (pqPutMsgStart(PqMsg_CopyDone, conn) < 0 ||
2738  pqPutMsgEnd(conn) < 0)
2739  return -1;
2740  }
2741 
2742  /*
2743  * If we sent the COPY command in extended-query mode, we must issue a
2744  * Sync as well.
2745  */
2746  if (conn->cmd_queue_head &&
2748  {
2749  if (pqPutMsgStart(PqMsg_Sync, conn) < 0 ||
2750  pqPutMsgEnd(conn) < 0)
2751  return -1;
2752  }
2753 
2754  /* Return to active duty */
2757  else
2759 
2760  /* Try to flush data */
2761  if (pqFlush(conn) < 0)
2762  return -1;
2763 
2764  return 1;
2765 }
int pqPuts(const char *s, PGconn *conn)
Definition: fe-misc.c:153
@ PGQUERY_SIMPLE
Definition: libpq-int.h:320
#define PqMsg_CopyDone
Definition: protocol.h:64
#define PqMsg_Sync
Definition: protocol.h:27
#define PqMsg_CopyFail
Definition: protocol.h:29
PGQueryClass queryclass
Definition: libpq-int.h:333

References pg_conn::asyncStatus, pg_conn::cmd_queue_head, conn, libpq_append_conn_error(), PGASYNC_BUSY, PGASYNC_COPY_BOTH, PGASYNC_COPY_IN, PGASYNC_COPY_OUT, PGQUERY_SIMPLE, pqFlush(), PqMsg_CopyDone, PqMsg_CopyFail, PqMsg_Sync, pqPutMsgEnd(), pqPutMsgStart(), pqPuts(), and PGcmdQueueEntry::queryclass.

Referenced by BaseBackup(), CheckCopyStreamStop(), EndDBCopyMode(), handleCopyIn(), HandleEndOfCopyStream(), libpqrcv_endstreaming(), PQexecStart(), prepareToTerminate(), and ProcessXLogDataMsg().

◆ PQputline()

int PQputline ( PGconn conn,
const char *  string 
)

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

2881 {
2882  return PQputnbytes(conn, string, strlen(string));
2883 }
int PQputnbytes(PGconn *conn, const char *buffer, int nbytes)
Definition: fe-exec.c:2890

References conn, and PQputnbytes().

Referenced by initPopulateTable().

◆ PQputnbytes()

int PQputnbytes ( PGconn conn,
const char *  buffer,
int  nbytes 
)

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

2891 {
2892  if (PQputCopyData(conn, buffer, nbytes) > 0)
2893  return 0;
2894  else
2895  return EOF;
2896 }
int PQputCopyData(PGconn *conn, const char *buffer, int nbytes)
Definition: fe-exec.c:2657

References conn, and PQputCopyData().

Referenced by PQputline().

◆ PQregisterThreadLock()

pgthreadlock_t PQregisterThreadLock ( pgthreadlock_t  newhandler)

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

7552 {
7554 
7555  if (newhandler)
7556  pg_g_threadlock = newhandler;
7557  else
7559 
7560  return prev;
7561 }
static void default_threadlock(int acquire)
Definition: fe-connect.c:7534
pgthreadlock_t pg_g_threadlock
Definition: fe-connect.c:444
void(* pgthreadlock_t)(int acquire)
Definition: libpq-fe.h:431

References default_threadlock(), and pg_g_threadlock.

◆ PQrequestCancel()

int PQrequestCancel ( PGconn conn)

Definition at line 660 of file fe-cancel.c.

661 {
662  int r;
663  PGcancel *cancel;
664 
665  /* Check we have an open connection */
666  if (!conn)
667  return false;
668 
669  if (conn->sock == PGINVALID_SOCKET)
670  {
672  "PQrequestCancel() -- connection is not open\n",
675  conn->errorReported = 0;
676 
677  return false;
678  }
679 
680  cancel = PQgetCancel(conn);
681  if (cancel)
682  {
683  r = PQcancel(cancel, conn->errorMessage.data,
685  PQfreeCancel(cancel);
686  }
687  else
688  {
689  strlcpy(conn->errorMessage.data, "out of memory",
691  r = false;
692  }
693 
694  if (!r)
695  {
697  conn->errorReported = 0;
698  }
699 
700  return r;
701 }
PGcancel * PQgetCancel(PGconn *conn)
Definition: fe-cancel.c:348
int PQcancel(PGcancel *cancel, char *errbuf, int errbufsize)
Definition: fe-cancel.c:462
void PQfreeCancel(PGcancel *cancel)
Definition: fe-cancel.c:416
int errorReported
Definition: libpq-int.h:622

References conn, PQExpBufferData::data, pg_conn::errorMessage, pg_conn::errorReported, PQExpBufferData::len, PQExpBufferData::maxlen, PGINVALID_SOCKET, PQcancel(), PQfreeCancel(), PQgetCancel(), pg_conn::sock, and strlcpy().

Referenced by test_cancel().

◆ PQreset()

void PQreset ( PGconn conn)

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

4684 {
4685  if (conn)
4686  {
4688 
4690  {
4691  /*
4692  * Notify event procs of successful reset.
4693  */
4694  int i;
4695 
4696  for (i = 0; i < conn->nEvents; i++)
4697  {
4698  PGEventConnReset evt;
4699 
4700  evt.conn = conn;
4701  (void) conn->events[i].proc(PGEVT_CONNRESET, &evt,
4702  conn->events[i].passThrough);
4703  }
4704  }
4705  }
4706 }
@ PGEVT_CONNRESET
Definition: libpq-events.h:30

References conn, PGEventConnReset::conn, pg_conn::events, i, pg_conn::nEvents, PGEvent::passThrough, PGEVT_CONNRESET, pqClosePGconn(), pqConnectDBComplete(), pqConnectDBStart(), and PGEvent::proc.

Referenced by CheckConnection().

◆ PQresetPoll()

PostgresPollingStatusType PQresetPoll ( PGconn conn)

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

4736 {
4737  if (conn)
4738  {
4740 
4741  if (status == PGRES_POLLING_OK)
4742  {
4743  /*
4744  * Notify event procs of successful reset.
4745  */
4746  int i;
4747 
4748  for (i = 0; i < conn->nEvents; i++)
4749  {
4750  PGEventConnReset evt;
4751 
4752  evt.conn = conn;
4753  (void) conn->events[i].proc(PGEVT_CONNRESET, &evt,
4754  conn->events[i].passThrough);
4755  }
4756  }
4757 
4758  return status;
4759  }
4760 
4761  return PGRES_POLLING_FAILED;
4762 }

References conn, PGEventConnReset::conn, pg_conn::events, i, pg_conn::nEvents, PGEvent::passThrough, PGEVT_CONNRESET, PGRES_POLLING_FAILED, PGRES_POLLING_OK, PQconnectPoll(), and PGEvent::proc.

◆ PQresetStart()

int PQresetStart ( PGconn conn)

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

4717 {
4718  if (conn)
4719  {
4721 
4722  return pqConnectDBStart(conn);
4723  }
4724 
4725  return 0;
4726 }

References conn, pqClosePGconn(), and pqConnectDBStart().

◆ PQresStatus()

char* PQresStatus ( ExecStatusType  status)

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

3380 {
3381  if ((unsigned int) status >= lengthof(pgresStatus))
3382  return libpq_gettext("invalid ExecStatusType code");
3383  return pgresStatus[status];
3384 }
char *const pgresStatus[]
Definition: fe-exec.c:32

References lengthof, libpq_gettext, and pgresStatus.

Referenced by BaseBackup(), process_result(), test_multi_pipelines(), test_nosync(), test_pipeline_abort(), test_pipeline_idle(), test_pipelined_insert(), test_prepared(), test_simple_pipeline(), test_singlerowmode(), test_transaction(), and try_complete_step().

◆ PQresultAlloc()

void* PQresultAlloc ( PGresult res,
size_t  nBytes 
)

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

542 {
543  /* Fail if argument is NULL or OOM_result */
544  if (!res || (const PGresult *) res == &OOM_result)
545  return NULL;
546 
547  return pqResultAlloc(res, nBytes, true);
548 }
void * pqResultAlloc(PGresult *res, size_t nBytes, bool isBinary)
Definition: fe-exec.c:561

References OOM_result, pqResultAlloc(), and res.

Referenced by PQsetResultAttrs().

◆ PQresultErrorField()

char* PQresultErrorField ( const PGresult res,
int  fieldcode 
)

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

3427 {
3428  PGMessageField *pfield;
3429 
3430  if (!res)
3431  return NULL;
3432  for (pfield = res->errFields; pfield != NULL; pfield = pfield->next)
3433  {
3434  if (pfield->code == fieldcode)
3435  return pfield->contents;
3436  }
3437  return NULL;
3438 }
struct pgMessageField * next
Definition: libpq-int.h:147
char contents[FLEXIBLE_ARRAY_MEMBER]
Definition: libpq-int.h:149

References pgMessageField::code, pgMessageField::contents, pg_result::errFields, pgMessageField::next, and res.

Referenced by BaseBackup(), confirm_query_canceled_impl(), CreateReplicationSlot(), dblink_res_error(), ecpg_raise_backend(), ECPGnoticeReceiver(), GetTableInfo(), libpqrcv_exec(), minimal_error_message(), pgfdw_report_error(), pgpassfileWarning(), pqBuildErrorMessage3(), PQconnectPoll(), readCommandResponse(), SetResultVariables(), should_processing_continue(), TableCommandResultHandler(), test_pipeline_abort(), and try_complete_step().

◆ PQresultErrorMessage()

◆ PQresultMemorySize()

size_t PQresultMemorySize ( const PGresult res)

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

662 {
663  if (!res)
664  return 0;
665  return res->memorySize;
666 }

References pg_result::memorySize, and res.

◆ PQresultStatus()

ExecStatusType PQresultStatus ( const PGresult res)

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

3372 {
3373  if (!res)
3374  return PGRES_FATAL_ERROR;
3375  return res->resultStatus;
3376 }

References PGRES_FATAL_ERROR, res, and pg_result::resultStatus.

Referenced by _doSetSessionAuth(), _selectOutputSchema(), _selectTableAccessMethod(), _selectTablespace(), AcceptResult(), advanceConnectionState(), BaseBackup(), check_loadable_libraries(), check_prepare_conn(), ClearOrSaveResult(), close_cursor(), compile_database_list(), compile_relation_list_one_db(), confirm_query_canceled_impl(), create_cursor(), CreateReplicationSlot(), dblink_close(), dblink_exec(), dblink_fetch(), dblink_open(), dblink_record_internal(), deallocate_query(), DescribeQuery(), discardUntilSync(), do_sql_command_end(), DropReplicationSlot(), dumpTableData_copy(), ecpg_check_PQresult(), ecpg_process_output(), EndDBCopyMode(), exec_command_password(), ExecQueryAndProcessResults(), ExecQueryUsingCursor(), execute_dml_stmt(), execute_foreign_modify(), executeCommand(), executeMaintenanceCommand(), executeQuery(), executeQueryOrDie(), ExecuteSqlCommand(), ExecuteSqlQuery(), ExecuteSqlStatement(), executeStatement(), fetch_more_data(), get_create_object_cmd(), get_remote_estimate(), GetConnection(), GetSlotInformation(), GetTableInfo(), handleCopyIn(), handleCopyOut(), HandleCopyResult(), HandleEndOfCopyStream(), init_libpq_conn(), initPopulateTable(), libpq_fetch_file(), libpq_traverse_files(), libpqrcv_alter_slot(), libpqrcv_connect(), libpqrcv_create_slot(), libpqrcv_endstreaming(), libpqrcv_exec(), libpqrcv_identify_system(), libpqrcv_PQexec(), libpqrcv_readtimelinehistoryfile(), libpqrcv_receive(), libpqrcv_startstreaming(), libpqsrv_get_result_last(), lo_close(), lo_creat(), lo_create(), 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(), materializeResult(), pgfdw_exec_cleanup_query_end(), postgresAcquireSampleRowsFunc(), postgresAnalyzeForeignTable(), postgresGetAnalyzeInfoForForeignTable(), postgresImportForeignSchema(), postgresReScanForeignScan(), PQconnectPoll(), PQencryptPasswordConn(), prepare_foreign_modify(), prepareCommand(), PrintQueryResult(), PrintResultInCrosstab(), process_queued_fetch_requests(), process_result(), readCommandResponse(), ReceiveCopyData(), ReceiveXlogStream(), RetrieveDataDirCreatePerm(), RetrieveWalSegSize(), run_permutation(), run_simple_command(), run_simple_query(), RunIdentifySystem(), SendQuery(), should_processing_continue(), sql_conn(), sql_exec(), storeQueryResult(), StreamLogicalLog(), TableCommandResultHandler(), test_disallowed_in_pipeline(), test_multi_pipelines(), test_nosync(), test_pipeline_abort(), test_pipeline_idle(), test_pipelined_insert(), test_prepared(), test_simple_pipeline(), test_singlerowmode(), test_transaction(), test_uniqviol(), try_complete_step(), tryExecuteStatement(), vacuumlo(), verify_btree_slot_handler(), verify_heap_slot_handler(), and wait_for_connection_state().

◆ PQresultVerboseErrorMessage()

char* PQresultVerboseErrorMessage ( const PGresult res,
PGVerbosity  verbosity,
PGContextVisibility  show_context 
)

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

3398 {
3399  PQExpBufferData workBuf;
3400 
3401  /*
3402  * Because the caller is expected to free the result string, we must
3403  * strdup any constant result. We use plain strdup and document that
3404  * callers should expect NULL if out-of-memory.
3405  */
3406  if (!res ||
3409  return strdup(libpq_gettext("PGresult is not an error result\n"));
3410 
3411  initPQExpBuffer(&workBuf);
3412 
3413  pqBuildErrorMessage3(&workBuf, res, verbosity, show_context);
3414 
3415  /* If insufficient memory to format the message, fail cleanly */
3416  if (PQExpBufferDataBroken(workBuf))
3417  {
3418  termPQExpBuffer(&workBuf);
3419  return strdup(libpq_gettext("out of memory\n"));
3420  }
3421 
3422  return workBuf.data;
3423 }
void pqBuildErrorMessage3(PQExpBuffer msg, const PGresult *res, PGVerbosity verbosity, PGContextVisibility show_context)

References PQExpBufferData::data, initPQExpBuffer(), libpq_gettext, PGRES_FATAL_ERROR, PGRES_NONFATAL_ERROR, pqBuildErrorMessage3(), PQExpBufferDataBroken, res, pg_result::resultStatus, and termPQExpBuffer().

Referenced by exec_command_errverbose().

◆ PQsendClosePortal()

int PQsendClosePortal ( PGconn conn,
const char *  portal 
)

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

2532 {
2533  return PQsendTypedCommand(conn, PqMsg_Close, 'P', portal);
2534 }

References conn, PqMsg_Close, and PQsendTypedCommand().

Referenced by test_prepared().

◆ PQsendClosePrepared()

int PQsendClosePrepared ( PGconn conn,
const char *  stmt 
)

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

2519 {
2520  return PQsendTypedCommand(conn, PqMsg_Close, 'S', stmt);
2521 }

References conn, PqMsg_Close, PQsendTypedCommand(), and stmt.

Referenced by test_prepared().

◆ PQsendDescribePortal()

int PQsendDescribePortal ( PGconn conn,
const char *  portal 
)

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

2467 {
2468  return PQsendTypedCommand(conn, PqMsg_Describe, 'P', portal);
2469 }

References conn, PqMsg_Describe, and PQsendTypedCommand().

Referenced by test_prepared().

◆ PQsendDescribePrepared()

int PQsendDescribePrepared ( PGconn conn,
const char *  stmt 
)

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

2454 {
2455  return PQsendTypedCommand(conn, PqMsg_Describe, 'S', stmt);
2456 }

References conn, PqMsg_Describe, PQsendTypedCommand(), and stmt.

Referenced by test_prepared().

◆ PQsendFlushRequest()

int PQsendFlushRequest ( PGconn conn)

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

3332 {
3333  if (!conn)
3334  return 0;
3335 
3336  /* Don't try to send if we know there's no live connection. */
3337  if (conn->status != CONNECTION_OK)
3338  {
3339  libpq_append_conn_error(conn, "no connection to the server");
3340  return 0;
3341  }
3342 
3343  /* Can't send while already busy, either, unless enqueuing for later */
3344  if (conn->asyncStatus != PGASYNC_IDLE &&
3346  {
3347  libpq_append_conn_error(conn, "another command is already in progress");
3348  return 0;
3349  }
3350 
3351  if (pqPutMsgStart(PqMsg_Flush, conn) < 0 ||
3352  pqPutMsgEnd(conn) < 0)
3353  {
3354  return 0;
3355  }
3356 
3357  /*
3358  * Give the data a push (in pipeline mode, only if we're past the size
3359  * threshold). In nonblock mode, don't complain if we're unable to send
3360  * it all; PQgetResult() will do any additional flushing needed.
3361  */
3362  if (pqPipelineFlush(conn) < 0)
3363  return 0;
3364 
3365  return 1;
3366 }
static int pqPipelineFlush(PGconn *conn)
Definition: fe-exec.c:3976
#define PqMsg_Flush
Definition: protocol.h:24

References pg_conn::asyncStatus, conn, CONNECTION_OK, libpq_append_conn_error(), PGASYNC_IDLE, pg_conn::pipelineStatus, PQ_PIPELINE_OFF, PqMsg_Flush, pqPipelineFlush(), pqPutMsgEnd(), pqPutMsgStart(), and pg_conn::status.

Referenced by test_nosync(), test_pipeline_idle(), test_singlerowmode(), and test_uniqviol().

◆ PQsendPipelineSync()

int PQsendPipelineSync ( PGconn conn)

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

3243 {
3244  return pqPipelineSyncInternal(conn, false);
3245 }

References conn, and pqPipelineSyncInternal().

Referenced by executeMetaCommand(), and test_multi_pipelines().

◆ PQsendPrepare()

int PQsendPrepare ( PGconn conn,
const char *  stmtName,
const char *  query,
int  nParams,
const Oid paramTypes 
)

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

1548 {
1549  PGcmdQueueEntry *entry = NULL;
1550 
1551  if (!PQsendQueryStart(conn, true))
1552  return 0;
1553 
1554  /* check the arguments */
1555  if (!stmtName)
1556  {
1557  libpq_append_conn_error(conn, "statement name is a null pointer");
1558  return 0;
1559  }
1560  if (!query)
1561  {
1562  libpq_append_conn_error(conn, "command string is a null pointer");
1563  return 0;
1564  }
1565  if (nParams < 0 || nParams > PQ_QUERY_PARAM_MAX_LIMIT)
1566  {
1567  libpq_append_conn_error(conn, "number of parameters must be between 0 and %d",
1569  return 0;
1570  }
1571 
1572  entry = pqAllocCmdQueueEntry(conn);
1573  if (entry == NULL)
1574  return 0; /* error msg already set */
1575 
1576  /* construct the Parse message */
1577  if (pqPutMsgStart(PqMsg_Parse, conn) < 0 ||
1578  pqPuts(stmtName, conn) < 0 ||
1579  pqPuts(query, conn) < 0)
1580  goto sendFailed;
1581 
1582  if (nParams > 0 && paramTypes)
1583  {
1584  int i;
1585 
1586  if (pqPutInt(nParams, 2, conn) < 0)
1587  goto sendFailed;
1588  for (i = 0; i < nParams; i++)
1589  {
1590  if (pqPutInt(paramTypes[i], 4, conn) < 0)
1591  goto sendFailed;
1592  }
1593  }
1594  else
1595  {
1596  if (pqPutInt(0, 2, conn) < 0)
1597  goto sendFailed;
1598  }
1599  if (pqPutMsgEnd(conn) < 0)
1600  goto sendFailed;
1601 
1602  /* Add a Sync, unless in pipeline mode. */
1604  {
1605  if (pqPutMsgStart(PqMsg_Sync, conn) < 0 ||
1606  pqPutMsgEnd(conn) < 0)
1607  goto sendFailed;
1608  }
1609 
1610  /* remember we are doing just a Parse */
1611  entry->queryclass = PGQUERY_PREPARE;
1612 
1613  /* and remember the query text too, if possible */
1614  /* if insufficient memory, query just winds up NULL */
1615  entry->query = strdup(query);
1616 
1617  /*
1618  * Give the data a push (in pipeline mode, only if we're past the size
1619  * threshold). In nonblock mode, don't complain if we're unable to send
1620  * it all; PQgetResult() will do any additional flushing needed.
1621  */
1622  if (pqPipelineFlush(conn) < 0)
1623  goto sendFailed;
1624 
1625  /* OK, it's launched! */
1626  pqAppendCmdQueueEntry(conn, entry);
1627 
1628  return 1;
1629 
1630 sendFailed:
1631  pqRecycleCmdQueueEntry(conn, entry);
1632  /* error message should be set up already */
1633  return 0;
1634 }
static void pqAppendCmdQueueEntry(PGconn *conn, PGcmdQueueEntry *entry)
Definition: fe-exec.c:1348
static PGcmdQueueEntry * pqAllocCmdQueueEntry(PGconn *conn)
Definition: fe-exec.c:1315
static bool PQsendQueryStart(PGconn *conn, bool newQuery)
Definition: fe-exec.c:1682
static void pqRecycleCmdQueueEntry(PGconn *conn, PGcmdQueueEntry *entry)
Definition: fe-exec.c:1395
int pqPutInt(int value, size_t bytes, PGconn *conn)
Definition: fe-misc.c:254
#define PQ_QUERY_PARAM_MAX_LIMIT
Definition: libpq-fe.h:470
@ PGQUERY_PREPARE
Definition: libpq-int.h:322
#define PqMsg_Parse
Definition: protocol.h:25

References conn, i, libpq_append_conn_error(), PGQUERY_PREPARE, pg_conn::pipelineStatus, PQ_PIPELINE_OFF, PQ_QUERY_PARAM_MAX_LIMIT, pqAllocCmdQueueEntry(), pqAppendCmdQueueEntry(), PqMsg_Parse, PqMsg_Sync, pqPipelineFlush(), pqPutInt(), pqPutMsgEnd(), pqPutMsgStart(), pqPuts(), pqRecycleCmdQueueEntry(), PQsendQueryStart(), PGcmdQueueEntry::query, and PGcmdQueueEntry::queryclass.

Referenced by PQprepare(), prepare_foreign_modify(), test_pipelined_insert(), test_prepared(), and test_transaction().

◆ PQsendQuery()

◆ PQsendQueryParams()

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 at line 1501 of file fe-exec.c.

1509 {
1510  if (!PQsendQueryStart(conn, true))
1511  return 0;
1512 
1513  /* check the arguments */
1514  if (!command)
1515  {
1516  libpq_append_conn_error(conn, "command string is a null pointer");
1517  return 0;
1518  }
1519  if (nParams < 0 || nParams > PQ_QUERY_PARAM_MAX_LIMIT)
1520  {
1521  libpq_append_conn_error(conn, "number of parameters must be between 0 and %d",
1523  return 0;
1524  }
1525 
1526  return PQsendQueryGuts(conn,
1527  command,
1528  "", /* use unnamed statement */
1529  nParams,
1530  paramTypes,
1531  paramValues,
1532  paramLengths,
1533  paramFormats,
1534  resultFormat);
1535 }
static int PQsendQueryGuts(PGconn *conn, const char *command, const char *stmtName, int nParams, const Oid *paramTypes, const char *const *paramValues, const int *paramLengths, const int *paramFormats, int resultFormat)
Definition: fe-exec.c:1764

References conn, libpq_append_conn_error(), PQ_QUERY_PARAM_MAX_LIMIT, PQsendQueryGuts(), and PQsendQueryStart().

Referenced by create_cursor(), ExecQueryAndProcessResults(), execute_dml_stmt(), libpqsrv_exec_params(), PQexecParams(), send_cancellable_query_impl(), sendCommand(), test_multi_pipelines(), test_nosync(), test_pipeline_abort(), test_pipeline_idle(), test_pipelined_insert(), test_simple_pipeline(), test_singlerowmode(), and test_transaction().

◆ PQsendQueryPrepared()

int PQsendQueryPrepared ( PGconn conn,
const char *  stmtName,
int  nParams,
const char *const *  paramValues,
const int *  paramLengths,
const int *  paramFormats,
int  resultFormat 
)

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

1649 {
1650  if (!PQsendQueryStart(conn, true))
1651  return 0;
1652 
1653  /* check the arguments */
1654  if (!stmtName)
1655  {
1656  libpq_append_conn_error(conn, "statement name is a null pointer");
1657  return 0;
1658  }
1659  if (nParams < 0 || nParams > PQ_QUERY_PARAM_MAX_LIMIT)
1660  {
1661  libpq_append_conn_error(conn, "number of parameters must be between 0 and %d",
1663  return 0;
1664  }
1665 
1666  return PQsendQueryGuts(conn,
1667  NULL, /* no command to parse */
1668  stmtName,
1669  nParams,
1670  NULL, /* no param types */
1671  paramValues,
1672  paramLengths,
1673  paramFormats,
1674  resultFormat);
1675 }

References conn, libpq_append_conn_error(), PQ_QUERY_PARAM_MAX_LIMIT, PQsendQueryGuts(), and PQsendQueryStart().

Referenced by execute_foreign_modify(), PQexecPrepared(), process_queued_fetch_requests(), sendCommand(), test_pipelined_insert(), test_transaction(), and test_uniqviol().

◆ PQserverVersion()

◆ PQsetClientEncoding()

int PQsetClientEncoding ( PGconn conn,
const char *  encoding 
)

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

7045 {
7046  char qbuf[128];
7047  static const char query[] = "set client_encoding to '%s'";
7048  PGresult *res;
7049  int status;
7050 
7051  if (!conn || conn->status != CONNECTION_OK)
7052  return -1;
7053 
7054  if (!encoding)
7055  return -1;
7056 
7057  /* Resolve special "auto" value from the locale */
7058  if (strcmp(encoding, "auto") == 0)
7060 
7061  /* check query buffer overflow */
7062  if (sizeof(qbuf) < (sizeof(query) + strlen(encoding)))
7063  return -1;
7064 
7065  /* ok, now send a query */
7066  sprintf(qbuf, query, encoding);
7067  res = PQexec(conn, qbuf);
7068 
7069  if (res == NULL)
7070  return -1;
7072  status = -1;
7073  else
7074  {
7075  /*
7076  * We rely on the backend to report the parameter value, and we'll
7077  * change state at that time.
7078  */
7079  status = 0; /* everything is ok */
7080  }
7081  PQclear(res);
7082  return status;
7083 }
#define pg_encoding_to_char
Definition: pg_wchar.h:569
int pg_get_encoding_from_locale(const char *ctype, bool write_message)
Definition: chklocale.c:428

References conn, CONNECTION_OK, encoding, pg_encoding_to_char, pg_get_encoding_from_locale(), PGRES_COMMAND_OK, PQclear(), PQexec(), res, pg_result::resultStatus, sprintf, and pg_conn::status.

Referenced by dblink_connect(), dblink_get_conn(), exec_command_encoding(), main(), and setup_connection().

◆ PQsetdbLogin()

PGconn* PQsetdbLogin ( const char *  pghost,
const char *  pgport,
const char *  pgoptions,
const char *  pgtty,
const char *  dbName,
const char *  login,
const char *  pwd 
)

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

1860 {
1861  PGconn *conn;
1862 
1863  /*
1864  * Allocate memory for the conn structure. Note that we also expect this
1865  * to initialize conn->errorMessage to empty. All subsequent steps during
1866  * connection initialization will only append to that buffer.
1867  */
1868  conn = pqMakeEmptyPGconn();
1869  if (conn == NULL)
1870  return NULL;
1871 
1872  /*
1873  * If the dbName parameter contains what looks like a connection string,
1874  * parse it into conn struct using connectOptions1.
1875  */
1877  {
1878  if (!connectOptions1(conn, dbName))
1879  return conn;
1880  }
1881  else
1882  {
1883  /*
1884  * Old-style path: first, parse an empty conninfo string in order to
1885  * set up the same defaults that PQconnectdb() would use.
1886  */
1887  if (!connectOptions1(conn, ""))
1888  return conn;
1889 
1890  /* Insert dbName parameter value into struct */
1891  if (dbName && dbName[0] != '\0')
1892  {
1893  free(conn->dbName);
1894  conn->dbName = strdup(dbName);
1895  if (!conn->dbName)
1896  goto oom_error;
1897  }
1898  }
1899 
1900  /*
1901  * Insert remaining parameters into struct, overriding defaults (as well
1902  * as any conflicting data from dbName taken as a conninfo).
1903  */
1904  if (pghost && pghost[0] != '\0')
1905  {
1906  free(conn->pghost);
1907  conn->pghost = strdup(pghost);
1908  if (!conn->pghost)
1909  goto oom_error;
1910  }
1911 
1912  if (pgport && pgport[0] != '\0')
1913  {
1914  free(conn->pgport);
1915  conn->pgport = strdup(pgport);
1916  if (!conn->pgport)
1917  goto oom_error;
1918  }
1919 
1920  if (pgoptions && pgoptions[0] != '\0')
1921  {
1922  free(conn->pgoptions);
1923  conn->pgoptions = strdup(pgoptions);
1924  if (!conn->pgoptions)
1925  goto oom_error;
1926  }
1927 
1928  if (login && login[0] != '\0')
1929  {
1930  free(conn->pguser);
1931  conn->pguser = strdup(login);
1932  if (!conn->pguser)
1933  goto oom_error;
1934  }
1935 
1936  if (pwd && pwd[0] != '\0')
1937  {
1938  free(conn->pgpass);
1939  conn->pgpass = strdup(pwd);
1940  if (!conn->pgpass)
1941  goto oom_error;
1942  }
1943 
1944  /*
1945  * Compute derived options
1946  */
1947  if (!pqConnectOptions2(conn))
1948  return conn;
1949 
1950  /*
1951  * Connect to the database
1952  */
1953  if (pqConnectDBStart(conn))
1954  (void) pqConnectDBComplete(conn);
1955 
1956  return conn;
1957 
1958 oom_error:
1960  libpq_append_conn_error(conn, "out of memory");
1961  return conn;
1962 }
static bool recognized_connection_string(const char *connstr)
Definition: fe-connect.c:5633
const char * pghost
Definition: pgbench.c:294
const char * pgport
Definition: pgbench.c:295
const char * dbName
Definition: pgbench.c:297
char * pghost
Definition: libpq-int.h:361
char * pguser
Definition: libpq-int.h:379
char * pgport
Definition: libpq-int.h:369

References conn, CONNECTION_BAD, connectOptions1(), dbName, pg_conn::dbName, free, libpq_append_conn_error(), pghost, pg_conn::pghost, pg_conn::pgoptions, pg_conn::pgpass, pgport, pg_conn::pgport, pg_conn::pguser, pqConnectDBComplete(), pqConnectDBStart(), pqConnectOptions2(), pqMakeEmptyPGconn(), recognized_connection_string(), and pg_conn::status.

◆ PQsetErrorContextVisibility()

PGContextVisibility PQsetErrorContextVisibility ( PGconn conn,
PGContextVisibility  show_context 
)

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

7099 {
7100  PGContextVisibility old;
7101 
7102  if (!conn)
7103  return PQSHOW_CONTEXT_ERRORS;
7104  old = conn->show_context;
7105  conn->show_context = show_context;
7106  return old;
7107 }
PGContextVisibility show_context
Definition: libpq-int.h:506

References conn, PQSHOW_CONTEXT_ERRORS, and pg_conn::show_context.

Referenced by show_context_hook(), and SyncVariables().

◆ PQsetErrorVerbosity()

PGVerbosity PQsetErrorVerbosity ( PGconn conn,
PGVerbosity  verbosity 
)

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

7087 {
7088  PGVerbosity old;
7089 
7090  if (!conn)
7091  return PQERRORS_DEFAULT;
7092  old = conn->verbosity;
7093  conn->verbosity = verbosity;
7094  return old;
7095 }
PGVerbosity verbosity
Definition: libpq-int.h:505

References conn, PQERRORS_DEFAULT, and pg_conn::verbosity.

Referenced by main(), SyncVariables(), and verbosity_hook().

◆ PQsetnonblocking()

int PQsetnonblocking ( PGconn conn,
int  arg 
)

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

3905 {
3906  bool barg;
3907 
3908  if (!conn || conn->status == CONNECTION_BAD)
3909  return -1;
3910 
3911  barg = (arg ? true : false);
3912 
3913  /* early out if the socket is already in the state requested */
3914  if (barg == conn->nonblocking)
3915  return 0;
3916 
3917  /*
3918  * to guarantee constancy for flushing/query/result-polling behavior we
3919  * need to flush the send queue at this point in order to guarantee proper
3920  * behavior. this is ok because either they are making a transition _from_
3921  * or _to_ blocking mode, either way we can block them.
3922  *
3923  * Clear error state in case pqFlush adds to it, unless we're actively
3924  * pipelining, in which case it seems best not to.
3925  */
3926  if (conn->cmd_queue_head == NULL)
3928 
3929  /* if we are going from blocking to non-blocking flush here */
3930  if (pqFlush(conn))
3931  return -1;
3932 
3933  conn->nonblocking = barg;
3934 
3935  return 0;
3936 }
return true
Definition: isn.c:126
void * arg
bool nonblocking
Definition: libpq-int.h:434

References arg, pg_conn::cmd_queue_head, conn, CONNECTION_BAD, pg_conn::nonblocking, pqClearConnErrorState, pqFlush(), pg_conn::status, and true.

Referenced by test_cancel(), test_pipelined_insert(), and test_uniqviol().

◆ PQsetNoticeProcessor()

PQnoticeProcessor PQsetNoticeProcessor ( PGconn conn,
PQnoticeProcessor  proc,
void *  arg 
)

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

7128 {
7129  PQnoticeProcessor old;
7130 
7131  if (conn == NULL)
7132  return NULL;
7133 
7134  old = conn->noticeHooks.noticeProc;
7135  if (proc)
7136  {
7137  conn->noticeHooks.noticeProc = proc;
7139  }
7140  return old;
7141 }
void(* PQnoticeProcessor)(void *arg, const char *message)
Definition: libpq-fe.h:206

References arg, conn, pg_conn::noticeHooks, PGNoticeHooks::noticeProc, and PGNoticeHooks::noticeProcArg.

Referenced by ConnectDatabase(), do_connect(), main(), and test_pipeline_idle().

◆ PQsetNoticeReceiver()

PQnoticeReceiver PQsetNoticeReceiver ( PGconn conn,
PQnoticeReceiver  proc,
void *  arg 
)

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

7111 {
7112  PQnoticeReceiver old;
7113 
7114  if (conn == NULL)
7115  return NULL;
7116 
7117  old = conn->noticeHooks.noticeRec;
7118  if (proc)
7119  {
7120  conn->noticeHooks.noticeRec = proc;
7122  }
7123  return old;
7124 }
void(* PQnoticeReceiver)(void *arg, const PGresult *res)
Definition: libpq-fe.h:205

References arg, conn, pg_conn::noticeHooks, PGNoticeHooks::noticeRec, and PGNoticeHooks::noticeRecArg.

Referenced by ECPGconnect().

◆ PQsetResultAttrs()

int PQsetResultAttrs ( PGresult res,
int  numAttributes,
PGresAttDesc attDescs 
)

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

248 {
249  int i;
250 
251  /* Fail if argument is NULL or OOM_result */
252  if (!res || (const PGresult *) res == &OOM_result)
253  return false;
254 
255  /* If attrs already exist, they cannot be overwritten. */
256  if (res->numAttributes > 0)
257  return false;
258 
259  /* ignore no-op request */
260  if (numAttributes <= 0 || !attDescs)
261  return true;
262 
263  res->attDescs = (PGresAttDesc *)
264  PQresultAlloc(res, numAttributes * sizeof(PGresAttDesc));
265 
266  if (!res->attDescs)
267  return false;
268 
269  res->numAttributes = numAttributes;
270  memcpy(res->attDescs, attDescs, numAttributes * sizeof(PGresAttDesc));
271 
272  /* deep-copy the attribute names, and determine format */
273  res->binary = 1;
274  for (i = 0; i < res->numAttributes; i++)
275  {
276  if (res->attDescs[i].name)
278  else
280 
281  if (!res->attDescs[i].name)
282  return false;
283 
284  if (res->attDescs[i].format == 0)
285  res->binary = 0;
286  }
287 
288  return true;
289 }
char * pqResultStrdup(PGresult *res, const char *str)
Definition: fe-exec.c:673
void * PQresultAlloc(PGresult *res, size_t nBytes)
Definition: fe-exec.c:541

References pg_result::attDescs, pg_result::binary, pgresAttDesc::format, i, pgresAttDesc::name, pg_result::null_field, pg_result::numAttributes, OOM_result, PQresultAlloc(), pqResultStrdup(), and res.

Referenced by PQcopyResult().

◆ PQsetSingleRowMode()

int PQsetSingleRowMode ( PGconn conn)

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

1933 {
1934  /*
1935  * Only allow setting the flag when we have launched a query and not yet
1936  * received any results.
1937  */
1938  if (!conn)
1939  return 0;
1940  if (conn->asyncStatus != PGASYNC_BUSY)
1941  return 0;
1942  if (!conn->cmd_queue_head ||
1945  return 0;
1947  return 0;
1948 
1949  /* OK, set flag */
1950  conn->singleRowMode = true;
1951  return 1;
1952 }
@ PGQUERY_EXTENDED
Definition: libpq-int.h:321
bool singleRowMode
Definition: libpq-int.h:437

References pg_conn::asyncStatus, pg_conn::cmd_queue_head, conn, PGASYNC_BUSY, pgHavePendingResult, PGQUERY_EXTENDED, PGQUERY_SIMPLE, PGcmdQueueEntry::queryclass, and pg_conn::singleRowMode.

Referenced by process_queued_fetch_requests(), storeQueryResult(), test_pipeline_abort(), and test_singlerowmode().

◆ PQsetSSLKeyPassHook_OpenSSL()

void PQsetSSLKeyPassHook_OpenSSL ( PQsslKeyPassHook_OpenSSL_type  hook)

Definition at line 2009 of file fe-secure-openssl.c.

2010 {
2011  PQsslKeyPassHook = hook;
2012 }

References PQsslKeyPassHook.

◆ PQsetTraceFlags()

void PQsetTraceFlags ( PGconn conn,
int  flags 
)

Definition at line 64 of file fe-trace.c.

65 {
66  if (conn == NULL)
67  return;
68  /* If PQtrace() failed, do nothing. */
69  if (conn->Pfdebug == NULL)
70  return;
71  conn->traceFlags = flags;
72 }
FILE * Pfdebug
Definition: libpq-int.h:417
int traceFlags
Definition: libpq-int.h:418

References conn, pg_conn::Pfdebug, and pg_conn::traceFlags.

Referenced by main().

◆ PQsetvalue()

int PQsetvalue ( PGresult res,
int  tup_num,
int  field_num,
char *  value,
int  len 
)

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

451 {
452  PGresAttValue *attval;
453  const char *errmsg = NULL;
454 
455  /* Fail if argument is NULL or OOM_result */
456  if (!res || (const PGresult *) res == &OOM_result)
457  return false;
458 
459  /* Invalid field_num? */
460  if (!check_field_number(res, field_num))
461  return false;
462 
463  /* Invalid tup_num, must be <= ntups */
464  if (tup_num < 0 || tup_num > res->ntups)
465  {
467  "row number %d is out of range 0..%d",
468  tup_num, res->ntups);
469  return false;
470  }
471 
472  /* need to allocate a new tuple? */
473  if (tup_num == res->ntups)
474  {
475  PGresAttValue *tup;
476  int i;
477 
478  tup = (PGresAttValue *)
480  true);
481 
482  if (!tup)
483  goto fail;
484 
485  /* initialize each column to NULL */
486  for (i = 0; i < res->numAttributes; i++)
487  {
488  tup[i].len = NULL_LEN;
489  tup[i].value = res->null_field;
490  }
491 
492  /* add it to the array */
493  if (!pqAddTuple(res, tup, &errmsg))
494  goto fail;
495  }
496 
497  attval = &res->tuples[tup_num][field_num];
498 
499  /* treat either NULL_LEN or NULL value pointer as a NULL field */
500  if (len == NULL_LEN || value == NULL)
501  {
502  attval->len = NULL_LEN;
503  attval->value = res->null_field;
504  }
505  else if (len <= 0)
506  {
507  attval->len = 0;
508  attval->value = res->null_field;
509  }
510  else
511  {
512  attval->value = (char *) pqResultAlloc(res, len + 1, true);
513  if (!attval->value)
514  goto fail;
515  attval->len = len;
516  memcpy(attval->value, value, len);
517  attval->value[len] = '\0';
518  }
519 
520  return true;
521 
522  /*
523  * Report failure via pqInternalNotice. If preceding code didn't provide
524  * an error message, assume "out of memory" was meant.
525  */
526 fail:
527  if (!errmsg)
528  errmsg = libpq_gettext("out of memory");
530 
531  return false;
532 }
static bool pqAddTuple(PGresult *res, PGresAttValue *tup, const char **errmsgp)
Definition: fe-exec.c:991
static struct @150 value

References check_field_number(), errmsg(), i, pgresAttValue::len, len, libpq_gettext, pg_result::noticeHooks, pg_result::ntups, pg_result::null_field, NULL_LEN, pg_result::numAttributes, OOM_result, pqAddTuple(), pqInternalNotice(), pqResultAlloc(), res, pg_result::tuples, value, and pgresAttValue::value.

Referenced by PQcopyResult().

◆ PQsocket()

◆ PQsslAttribute()

const char* PQsslAttribute ( PGconn conn,
const char *  attribute_name 
)

Definition at line 1774 of file fe-secure-openssl.c.

1775 {
1776  if (!conn)
1777  {
1778  /* PQsslAttribute(NULL, "library") reports the default SSL library */
1779  if (strcmp(attribute_name, "library") == 0)
1780  return "OpenSSL";
1781  return NULL;
1782  }
1783 
1784  /* All attributes read as NULL for a non-encrypted connection */
1785  if (conn->ssl == NULL)
1786  return NULL;
1787 
1788  if (strcmp(attribute_name, "library") == 0)
1789  return "OpenSSL";
1790 
1791  if (strcmp(attribute_name, "key_bits") == 0)
1792  {
1793  static char sslbits_str[12];
1794  int sslbits;
1795 
1796  SSL_get_cipher_bits(conn->ssl, &sslbits);
1797  snprintf(sslbits_str, sizeof(sslbits_str), "%d", sslbits);
1798  return sslbits_str;
1799  }
1800 
1801  if (strcmp(attribute_name, "cipher") == 0)
1802  return SSL_get_cipher(conn->ssl);
1803 
1804  if (strcmp(attribute_name, "compression") == 0)
1805  return SSL_get_current_compression(conn->ssl) ? "on" : "off";
1806 
1807  if (strcmp(attribute_name, "protocol") == 0)
1808  return SSL_get_version(conn->ssl);
1809 
1810  return NULL; /* unknown attribute */
1811 }

References conn, and snprintf.

Referenced by print_ssl_library(), and printSSLInfo().

◆ PQsslAttributeNames()

const char* const* PQsslAttributeNames ( PGconn conn)

Definition at line 1748 of file fe-secure-openssl.c.

1749 {
1750  static const char *const openssl_attrs[] = {
1751  "library",
1752  "key_bits",
1753  "cipher",
1754  "compression",
1755  "protocol",
1756  NULL
1757  };
1758  static const char *const empty_attrs[] = {NULL};
1759 
1760  if (!conn)
1761  {
1762  /* Return attributes of default SSL library */
1763  return openssl_attrs;
1764  }
1765 
1766  /* No attrs for unencrypted connection */
1767  if (conn->ssl == NULL)
1768  return empty_attrs;
1769 
1770  return openssl_attrs;
1771 }

References conn.

◆ PQsslInUse()

int PQsslInUse ( PGconn conn)

Definition at line 103 of file fe-secure.c.

104 {
105  if (!conn)
106  return 0;
107  return conn->ssl_in_use;
108 }

References conn, and pg_conn::ssl_in_use.

Referenced by printSSLInfo().

◆ PQsslStruct()

void* PQsslStruct ( PGconn conn,
const char *  struct_name 
)

Definition at line 1738 of file fe-secure-openssl.c.

1739 {
1740  if (!conn)
1741  return NULL;
1742  if (strcmp(struct_name, "OpenSSL") == 0)
1743  return conn->ssl;
1744  return NULL;
1745 }

References conn.

◆ PQstatus()

◆ PQtrace()

void PQtrace ( PGconn conn,
FILE *  debug_port 
)

Definition at line 35 of file fe-trace.c.

36 {
37  if (conn == NULL)
38  return;
39  PQuntrace(conn);
40  if (debug_port == NULL)
41  return;
42 
43  conn->Pfdebug = debug_port;
44  conn->traceFlags = 0;
45 }
void PQuntrace(PGconn *conn)
Definition: fe-trace.c:49

References conn, pg_conn::Pfdebug, PQuntrace(), and pg_conn::traceFlags.

Referenced by main().

◆ PQtransactionStatus()

◆ PQtty()

char* PQtty ( const PGconn conn)

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

6880 {
6881  if (!conn)
6882  return NULL;
6883  return "";
6884 }

References conn.

◆ PQunescapeBytea()

unsigned char* PQunescapeBytea ( const unsigned char *  strtext,
size_t *  retbuflen 
)

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

4455 {
4456  size_t strtextlen,
4457  buflen;
4458  unsigned char *buffer,
4459  *tmpbuf;
4460  size_t i,
4461  j;
4462 
4463  if (strtext == NULL)
4464  return NULL;
4465 
4466  strtextlen = strlen((const char *) strtext);
4467 
4468  if (strtext[0] == '\\' && strtext[1] == 'x')
4469  {
4470  const unsigned char *s;
4471  unsigned char *p;
4472 
4473  buflen = (strtextlen - 2) / 2;
4474  /* Avoid unportable malloc(0) */
4475  buffer = (unsigned char *) malloc(buflen > 0 ? buflen : 1);
4476  if (buffer == NULL)
4477  return NULL;
4478 
4479  s = strtext + 2;
4480  p = buffer;
4481  while (*s)
4482  {
4483  char v1,
4484  v2;
4485 
4486  /*
4487  * Bad input is silently ignored. Note that this includes
4488  * whitespace between hex pairs, which is allowed by byteain.
4489  */
4490  v1 = get_hex(*s++);
4491  if (!*s || v1 == (char) -1)
4492  continue;
4493  v2 = get_hex(*s++);
4494  if (v2 != (char) -1)
4495  *p++ = (v1 << 4) | v2;
4496  }
4497 
4498  buflen = p - buffer;
4499  }
4500  else
4501  {
4502  /*
4503  * Length of input is max length of output, but add one to avoid
4504  * unportable malloc(0) if input is zero-length.
4505  */
4506  buffer = (unsigned char *) malloc(strtextlen + 1);
4507  if (buffer == NULL)
4508  return NULL;
4509 
4510  for (i = j = 0; i < strtextlen;)
4511  {
4512  switch (strtext[i])
4513  {
4514  case '\\':
4515  i++;
4516  if (strtext[i] == '\\')
4517  buffer[j++] = strtext[i++];
4518  else
4519  {
4520  if ((ISFIRSTOCTDIGIT(strtext[i])) &&
4521  (ISOCTDIGIT(strtext[i + 1])) &&
4522  (ISOCTDIGIT(strtext[i + 2])))
4523  {
4524  int byte;
4525 
4526  byte = OCTVAL(strtext[i++]);
4527  byte = (byte << 3) + OCTVAL(strtext[i++]);
4528  byte = (byte << 3) + OCTVAL(strtext[i++]);
4529  buffer[j++] = byte;
4530  }
4531  }
4532 
4533  /*
4534  * Note: if we see '\' followed by something that isn't a
4535  * recognized escape sequence, we loop around having done
4536  * nothing except advance i. Therefore the something will
4537  * be emitted as ordinary data on the next cycle. Corner
4538  * case: '\' at end of string will just be discarded.
4539  */
4540  break;
4541 
4542  default:
4543  buffer[j++] = strtext[i++];
4544  break;
4545  }
4546  }
4547  buflen = j; /* buflen is the length of the dequoted data */
4548  }
4549 
4550  /* Shrink the buffer to be no larger than necessary */
4551  /* +1 avoids unportable behavior when buflen==0 */
4552  tmpbuf = realloc(buffer, buflen + 1);
4553 
4554  /* It would only be a very brain-dead realloc that could fail, but... */
4555  if (!tmpbuf)
4556  {
4557  free(buffer);
4558  return NULL;
4559  }
4560 
4561  *retbuflen = buflen;
4562  return tmpbuf;
4563 }
static char get_hex(char c)
Definition: fe-exec.c:4290
#define ISOCTDIGIT(CH)
Definition: fe-exec.c:4438
#define OCTVAL(CH)
Definition: fe-exec.c:4439
#define ISFIRSTOCTDIGIT(CH)
Definition: fe-exec.c:4437
#define realloc(a, b)
Definition: header.h:60
static StringInfoData tmpbuf
Definition: walsender.c:170

References free, get_hex(), i, ISFIRSTOCTDIGIT, ISOCTDIGIT, j, malloc, OCTVAL, realloc, and tmpbuf.

◆ PQuntrace()

void PQuntrace ( PGconn conn)

Definition at line 49 of file fe-trace.c.

50 {
51  if (conn == NULL)
52  return;
53  if (conn->Pfdebug)
54  {
56  conn->Pfdebug = NULL;
57  }
58 
59  conn->traceFlags = 0;
60 }

References conn, fflush(), pg_conn::Pfdebug, and pg_conn::traceFlags.

Referenced by PQtrace().

◆ PQuser()

char* PQuser ( const PGconn conn)

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

6803 {
6804  if (!conn)
6805  return NULL;
6806  return conn->pguser;
6807 }

References conn, and pg_conn::pguser.

Referenced by do_connect(), exec_command_conninfo(), get_prompt(), main(), session_username(), and SyncVariables().