PostgreSQL Source Code git master
All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros Pages
libpq-fe.h File Reference
#include <stdint.h>
#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
 
struct  _PGpromptOAuthDevice
 
struct  PGoauthBearerRequest
 

Macros

#define LIBPQ_HAS_PIPELINING   1
 
#define LIBPQ_HAS_TRACE_FLAGS   1
 
#define LIBPQ_HAS_SSL_LIBRARY_DETECTION   1
 
#define LIBPQ_HAS_ASYNC_CANCEL   1
 
#define LIBPQ_HAS_CHANGE_PASSWORD   1
 
#define LIBPQ_HAS_CHUNK_MODE   1
 
#define LIBPQ_HAS_CLOSE_PREPARED   1
 
#define LIBPQ_HAS_SEND_PIPELINE_SYNC   1
 
#define LIBPQ_HAS_SOCKET_POLL   1
 
#define LIBPQ_HAS_FULL_PROTOCOL_VERSION   1
 
#define LIBPQ_HAS_PROMPT_OAUTH_DEVICE   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"
 
#define SOCKTYPE   int
 

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 int64_t pg_int64
 
typedef int64_t pg_usec_time_t
 
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 struct _PGpromptOAuthDevice PGpromptOAuthDevice
 
typedef struct PGoauthBearerRequest PGoauthBearerRequest
 
typedef int(* PQauthDataHook_type) (PGauthData type, PGconn *conn, void *data)
 
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 , CONNECTION_AUTHENTICATING
}
 
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 ,
  PGRES_TUPLES_CHUNK
}
 
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 }
 
enum  PGauthData { PQAUTHDATA_PROMPT_OAUTH_DEVICE , PQAUTHDATA_OAUTH_BEARER_TOKEN }
 

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 * PQservice (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 PQfullProtocolVersion (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)
 
int PQsetChunkedRowsMode (PGconn *conn, int chunkSize)
 
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)
 
int64_t lo_lseek64 (PGconn *conn, int fd, int64_t offset, int whence)
 
Oid lo_creat (PGconn *conn, int mode)
 
Oid lo_create (PGconn *conn, Oid lobjId)
 
int lo_tell (PGconn *conn, int fd)
 
int64_t lo_tell64 (PGconn *conn, int fd)
 
int lo_truncate (PGconn *conn, int fd, size_t len)
 
int lo_truncate64 (PGconn *conn, int fd, int64_t 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 PQsocketPoll (int sock, int forRead, int forWrite, pg_usec_time_t end_time)
 
pg_usec_time_t PQgetCurrentTimeUSec (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)
 
void PQsetAuthDataHook (PQauthDataHook_type hook)
 
PQauthDataHook_type PQgetAuthDataHook (void)
 
int PQdefaultAuthDataHook (PGauthData type, PGconn *conn, void *data)
 
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_ASYNC_CANCEL

#define LIBPQ_HAS_ASYNC_CANCEL   1

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

◆ LIBPQ_HAS_CHANGE_PASSWORD

#define LIBPQ_HAS_CHANGE_PASSWORD   1

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

◆ LIBPQ_HAS_CHUNK_MODE

#define LIBPQ_HAS_CHUNK_MODE   1

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

◆ LIBPQ_HAS_CLOSE_PREPARED

#define LIBPQ_HAS_CLOSE_PREPARED   1

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

◆ LIBPQ_HAS_FULL_PROTOCOL_VERSION

#define LIBPQ_HAS_FULL_PROTOCOL_VERSION   1

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

◆ LIBPQ_HAS_PIPELINING

#define LIBPQ_HAS_PIPELINING   1

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

◆ LIBPQ_HAS_PROMPT_OAUTH_DEVICE

#define LIBPQ_HAS_PROMPT_OAUTH_DEVICE   1

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

◆ LIBPQ_HAS_SEND_PIPELINE_SYNC

#define LIBPQ_HAS_SEND_PIPELINE_SYNC   1

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

◆ LIBPQ_HAS_SOCKET_POLL

#define LIBPQ_HAS_SOCKET_POLL   1

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

◆ LIBPQ_HAS_SSL_LIBRARY_DETECTION

#define LIBPQ_HAS_SSL_LIBRARY_DETECTION   1

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

◆ LIBPQ_HAS_TRACE_FLAGS

#define LIBPQ_HAS_TRACE_FLAGS   1

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

◆ PG_COPYRES_ATTRS

#define PG_COPYRES_ATTRS   0x01

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

◆ PG_COPYRES_EVENTS

#define PG_COPYRES_EVENTS   0x04

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

◆ PG_COPYRES_NOTICEHOOKS

#define PG_COPYRES_NOTICEHOOKS   0x08

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

◆ PG_COPYRES_TUPLES

#define PG_COPYRES_TUPLES   0x02 /* Implies PG_COPYRES_ATTRS */

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

◆ PQ_QUERY_PARAM_MAX_LIMIT

#define PQ_QUERY_PARAM_MAX_LIMIT   65535

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

◆ PQfreeNotify

#define PQfreeNotify (   ptr)    PQfreemem(ptr)

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

◆ PQnoPasswordSupplied

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

Definition at line 637 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 342 of file libpq-fe.h.

◆ PQTRACE_REGRESS_MODE

#define PQTRACE_REGRESS_MODE   (1<<1)

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

◆ PQTRACE_SUPPRESS_TIMESTAMPS

#define PQTRACE_SUPPRESS_TIMESTAMPS   (1<<0)

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

◆ SOCKTYPE

#define SOCKTYPE   int

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

Typedef Documentation

◆ pg_int64

typedef int64_t pg_int64

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

◆ pg_usec_time_t

typedef int64_t pg_usec_time_t

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

◆ PGcancel

typedef struct pg_cancel PGcancel

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

◆ PGcancelConn

typedef struct pg_cancel_conn PGcancelConn

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

◆ PGconn

typedef struct pg_conn PGconn

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

◆ PGnotify

typedef struct pgNotify PGnotify

◆ PGoauthBearerRequest

◆ PGpromptOAuthDevice

◆ PGresAttDesc

typedef struct pgresAttDesc PGresAttDesc

◆ PGresult

typedef struct pg_result PGresult

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

◆ pgthreadlock_t

typedef void(* pgthreadlock_t) (int acquire)

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

◆ PQauthDataHook_type

typedef int(* PQauthDataHook_type) (PGauthData type, PGconn *conn, void *data)

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

◆ pqbool

typedef char pqbool

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

◆ PQconninfoOption

◆ PQnoticeProcessor

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

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

◆ PQnoticeReceiver

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

Definition at line 244 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 825 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 
CONNECTION_AUTHENTICATING 

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

83{
86 /* Non-blocking mode only below here */
87
88 /*
89 * The existence of these should never be relied upon - they should only
90 * be used for user feedback or similar purposes.
91 */
92 CONNECTION_STARTED, /* Waiting for connection to be made. */
93 CONNECTION_MADE, /* Connection OK; waiting to send. */
94 CONNECTION_AWAITING_RESPONSE, /* Waiting for a response from the
95 * postmaster. */
96 CONNECTION_AUTH_OK, /* Received authentication; waiting for
97 * backend startup. */
98 CONNECTION_SETENV, /* This state is no longer used. */
99 CONNECTION_SSL_STARTUP, /* Performing SSL handshake. */
100 CONNECTION_NEEDED, /* Internal state: connect() needed. */
101 CONNECTION_CHECK_WRITABLE, /* Checking if session is read-write. */
102 CONNECTION_CONSUME, /* Consuming any extra messages. */
103 CONNECTION_GSS_STARTUP, /* Negotiating GSSAPI. */
104 CONNECTION_CHECK_TARGET, /* Internal state: checking target server
105 * properties. */
106 CONNECTION_CHECK_STANDBY, /* Checking if server is in standby mode. */
107 CONNECTION_ALLOCATED, /* Waiting for connection attempt to be
108 * started. */
109 CONNECTION_AUTHENTICATING, /* Authentication is in progress with some
110 * external system. */
ConnStatusType
Definition: libpq-fe.h:83
@ CONNECTION_CONSUME
Definition: libpq-fe.h:102
@ CONNECTION_AUTHENTICATING
Definition: libpq-fe.h:109
@ CONNECTION_CHECK_STANDBY
Definition: libpq-fe.h:106
@ CONNECTION_STARTED
Definition: libpq-fe.h:92
@ CONNECTION_AWAITING_RESPONSE
Definition: libpq-fe.h:94
@ CONNECTION_MADE
Definition: libpq-fe.h:93
@ CONNECTION_CHECK_WRITABLE
Definition: libpq-fe.h:101
@ CONNECTION_BAD
Definition: libpq-fe.h:85
@ CONNECTION_OK
Definition: libpq-fe.h:84
@ CONNECTION_GSS_STARTUP
Definition: libpq-fe.h:103
@ CONNECTION_ALLOCATED
Definition: libpq-fe.h:107
@ CONNECTION_SSL_STARTUP
Definition: libpq-fe.h:99
@ CONNECTION_AUTH_OK
Definition: libpq-fe.h:96
@ CONNECTION_CHECK_TARGET
Definition: libpq-fe.h:104
@ CONNECTION_NEEDED
Definition: libpq-fe.h:100
@ CONNECTION_SETENV
Definition: libpq-fe.h:98

◆ 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 
PGRES_TUPLES_CHUNK 

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

123{
124 PGRES_EMPTY_QUERY = 0, /* empty query string was executed */
125 PGRES_COMMAND_OK, /* a query command that doesn't return
126 * anything was executed properly by the
127 * backend */
128 PGRES_TUPLES_OK, /* a query command that returns tuples was
129 * executed properly by the backend, PGresult
130 * contains the result tuples */
131 PGRES_COPY_OUT, /* Copy Out data transfer in progress */
132 PGRES_COPY_IN, /* Copy In data transfer in progress */
133 PGRES_BAD_RESPONSE, /* an unexpected response was recv'd from the
134 * backend */
135 PGRES_NONFATAL_ERROR, /* notice or warning message */
136 PGRES_FATAL_ERROR, /* query failed */
137 PGRES_COPY_BOTH, /* Copy In/Out data transfer in progress */
138 PGRES_SINGLE_TUPLE, /* single tuple from larger resultset */
139 PGRES_PIPELINE_SYNC, /* pipeline synchronization point */
140 PGRES_PIPELINE_ABORTED, /* Command didn't run because of an abort
141 * earlier in a pipeline */
142 PGRES_TUPLES_CHUNK /* chunk of tuples from larger resultset */
ExecStatusType
Definition: libpq-fe.h:123
@ PGRES_COPY_IN
Definition: libpq-fe.h:132
@ PGRES_COPY_BOTH
Definition: libpq-fe.h:137
@ PGRES_COMMAND_OK
Definition: libpq-fe.h:125
@ PGRES_TUPLES_CHUNK
Definition: libpq-fe.h:142
@ PGRES_FATAL_ERROR
Definition: libpq-fe.h:136
@ PGRES_SINGLE_TUPLE
Definition: libpq-fe.h:138
@ PGRES_COPY_OUT
Definition: libpq-fe.h:131
@ PGRES_EMPTY_QUERY
Definition: libpq-fe.h:124
@ PGRES_PIPELINE_SYNC
Definition: libpq-fe.h:139
@ PGRES_BAD_RESPONSE
Definition: libpq-fe.h:133
@ PGRES_PIPELINE_ABORTED
Definition: libpq-fe.h:140
@ PGRES_NONFATAL_ERROR
Definition: libpq-fe.h:135
@ PGRES_TUPLES_OK
Definition: libpq-fe.h:128

◆ PGauthData

enum PGauthData
Enumerator
PQAUTHDATA_PROMPT_OAUTH_DEVICE 
PQAUTHDATA_OAUTH_BEARER_TOKEN 

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

193{
194 PQAUTHDATA_PROMPT_OAUTH_DEVICE, /* user must visit a device-authorization
195 * URL */
196 PQAUTHDATA_OAUTH_BEARER_TOKEN, /* server requests an OAuth Bearer token */
197} PGauthData;
PGauthData
Definition: libpq-fe.h:193
@ PQAUTHDATA_PROMPT_OAUTH_DEVICE
Definition: libpq-fe.h:194
@ PQAUTHDATA_OAUTH_BEARER_TOKEN
Definition: libpq-fe.h:196

◆ PGContextVisibility

Enumerator
PQSHOW_CONTEXT_NEVER 
PQSHOW_CONTEXT_ERRORS 
PQSHOW_CONTEXT_ALWAYS 

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

163{
164 PQSHOW_CONTEXT_NEVER, /* never show CONTEXT field */
165 PQSHOW_CONTEXT_ERRORS, /* show CONTEXT for errors only (default) */
166 PQSHOW_CONTEXT_ALWAYS /* always show CONTEXT field */
PGContextVisibility
Definition: libpq-fe.h:163
@ PQSHOW_CONTEXT_NEVER
Definition: libpq-fe.h:164
@ PQSHOW_CONTEXT_ALWAYS
Definition: libpq-fe.h:166
@ PQSHOW_CONTEXT_ERRORS
Definition: libpq-fe.h:165

◆ PGPing

enum PGPing
Enumerator
PQPING_OK 
PQPING_REJECT 
PQPING_NO_RESPONSE 
PQPING_NO_ATTEMPT 

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

175{
176 PQPING_OK, /* server is accepting connections */
177 PQPING_REJECT, /* server is alive but rejecting connections */
178 PQPING_NO_RESPONSE, /* could not establish connection */
179 PQPING_NO_ATTEMPT /* connection not attempted (bad params) */
180} PGPing;
PGPing
Definition: libpq-fe.h:175
@ PQPING_OK
Definition: libpq-fe.h:176
@ PQPING_REJECT
Definition: libpq-fe.h:177
@ PQPING_NO_RESPONSE
Definition: libpq-fe.h:178
@ PQPING_NO_ATTEMPT
Definition: libpq-fe.h:179

◆ PGpipelineStatus

Enumerator
PQ_PIPELINE_OFF 
PQ_PIPELINE_ON 
PQ_PIPELINE_ABORTED 

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

186{
PGpipelineStatus
Definition: libpq-fe.h:186
@ PQ_PIPELINE_OFF
Definition: libpq-fe.h:187
@ PQ_PIPELINE_ABORTED
Definition: libpq-fe.h:189
@ PQ_PIPELINE_ON
Definition: libpq-fe.h:188

◆ PGTransactionStatusType

Enumerator
PQTRANS_IDLE 
PQTRANS_ACTIVE 
PQTRANS_INTRANS 
PQTRANS_INERROR 
PQTRANS_UNKNOWN 

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

146{
147 PQTRANS_IDLE, /* connection idle */
148 PQTRANS_ACTIVE, /* command in progress */
149 PQTRANS_INTRANS, /* idle, within transaction block */
150 PQTRANS_INERROR, /* idle, within failed transaction */
151 PQTRANS_UNKNOWN /* cannot determine status */
PGTransactionStatusType
Definition: libpq-fe.h:146
@ PQTRANS_INTRANS
Definition: libpq-fe.h:149
@ PQTRANS_IDLE
Definition: libpq-fe.h:147
@ PQTRANS_ACTIVE
Definition: libpq-fe.h:148
@ PQTRANS_UNKNOWN
Definition: libpq-fe.h:151
@ PQTRANS_INERROR
Definition: libpq-fe.h:150

◆ PGVerbosity

Enumerator
PQERRORS_TERSE 
PQERRORS_DEFAULT 
PQERRORS_VERBOSE 
PQERRORS_SQLSTATE 

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

155{
156 PQERRORS_TERSE, /* single-line error messages */
157 PQERRORS_DEFAULT, /* recommended style */
158 PQERRORS_VERBOSE, /* all the facts, ma'am */
159 PQERRORS_SQLSTATE /* only error severity and SQLSTATE code */
PGVerbosity
Definition: libpq-fe.h:155
@ PQERRORS_VERBOSE
Definition: libpq-fe.h:158
@ PQERRORS_DEFAULT
Definition: libpq-fe.h:157
@ PQERRORS_TERSE
Definition: libpq-fe.h:156
@ PQERRORS_SQLSTATE
Definition: libpq-fe.h:159

◆ PostgresPollingStatusType

Enumerator
PGRES_POLLING_FAILED 
PGRES_POLLING_READING 
PGRES_POLLING_WRITING 
PGRES_POLLING_OK 
PGRES_POLLING_ACTIVE 

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

114{
116 PGRES_POLLING_READING, /* These two indicate that one may */
117 PGRES_POLLING_WRITING, /* use select before polling again. */
119 PGRES_POLLING_ACTIVE /* unused; keep for backwards compatibility */
PostgresPollingStatusType
Definition: libpq-fe.h:114
@ PGRES_POLLING_ACTIVE
Definition: libpq-fe.h:119
@ PGRES_POLLING_OK
Definition: libpq-fe.h:118
@ PGRES_POLLING_READING
Definition: libpq-fe.h:116
@ PGRES_POLLING_WRITING
Definition: libpq-fe.h:117
@ PGRES_POLLING_FAILED
Definition: libpq-fe.h:115

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}
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:3411
void PQclear(PGresult *res)
Definition: fe-exec.c:721
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:2980
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:52
int isint
Definition: libpq-fe.h:296
int integer
Definition: libpq-fe.h:300
union PQArgBlock::@189 u
Oid fn_lo_close
Definition: libpq-int.h:281
PGlobjfuncs * lobjfuncs
Definition: libpq-int.h:559

References conn, fd(), pgLobjfuncs::fn_lo_close, PQArgBlock::integer, PQArgBlock::isint, PQArgBlock::len, lo_initialize(), pg_conn::lobjfuncs, PGRES_COMMAND_OK, PQclear(), PQfn(), PQresultStatus(), 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:55
#define InvalidOid
Definition: postgres_ext.h:35
unsigned int Oid
Definition: postgres_ext.h:30
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(), 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:1381
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(), 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:1244
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:911
static char * filename
Definition: pg_dumpall.c:123
static char * buf
Definition: pg_test_fsync.c:72
#define PG_STRERROR_R_BUFLEN
Definition: port.h:257
#define strerror_r
Definition: port.h:256

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(), and PQArgBlock::u.

Referenced by overwrite(), and pickout().

◆ lo_lseek64()

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

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

386{
387 PQArgBlock argv[3];
388 PGresult *res;
389 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}
int64_t int64
Definition: c.h:499
static int64_t lo_ntoh64(int64_t net64)
Definition: fe-lobj.c:1048
static int64_t lo_hton64(int64_t host64)
Definition: fe-lobj.c:1023
int * ptr
Definition: libpq-fe.h:299
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, 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(), 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(), 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(), and PQArgBlock::u.

◆ lo_tell64()

int64_t lo_tell64 ( PGconn conn,
int  fd 
)

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

549{
550 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(), 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(), and PQArgBlock::u.

◆ lo_truncate64()

int lo_truncate64 ( PGconn conn,
int  fd,
int64_t  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
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, 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(), 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:1216
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, 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
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:759
static char * clean_encoding_name(const char *key, char *newkey)
Definition: encnames.c:524
static const pg_encname pg_encname_tbl[]
Definition: encnames.c:39
#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 {
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(PointerIsAligned(start, uint64))
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)

◆ PQbinaryTuples()

int PQbinaryTuples ( const PGresult res)

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

3498{
3499 if (!res)
3500 return 0;
3501 return res->binary;
3502}
int binary
Definition: libpq-int.h:176

References pg_result::binary.

Referenced by HandleCopyResult().

◆ PQcancel()

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

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

531{
532 int save_errno = SOCK_ERRNO;
533 pgsocket tmpsock = PGINVALID_SOCKET;
534 int maxlen;
535 char recvbuf;
536 int cancel_pkt_len;
537
538 if (!cancel)
539 {
540 strlcpy(errbuf, "PQcancel() -- no cancel object supplied", errbufsize);
541 /* strlcpy probably doesn't change errno, but be paranoid */
542 SOCK_ERRNO_SET(save_errno);
543 return false;
544 }
545
546 /*
547 * We need to open a temporary connection to the postmaster. Do this with
548 * only kernel calls.
549 */
550 if ((tmpsock = socket(cancel->raddr.addr.ss_family, SOCK_STREAM, 0)) == PGINVALID_SOCKET)
551 {
552 strlcpy(errbuf, "PQcancel() -- socket() failed: ", errbufsize);
553 goto cancel_errReturn;
554 }
555
556 /*
557 * Since this connection will only be used to send a single packet of
558 * data, we don't need NODELAY. We also don't set the socket to
559 * nonblocking mode, because the API definition of PQcancel requires the
560 * cancel to be sent in a blocking way.
561 *
562 * We do set socket options related to keepalives and other TCP timeouts.
563 * This ensures that this function does not block indefinitely when
564 * reasonable keepalive and timeout settings have been provided.
565 */
566 if (cancel->raddr.addr.ss_family != AF_UNIX &&
567 cancel->keepalives != 0)
568 {
569#ifndef WIN32
570 if (!optional_setsockopt(tmpsock, SOL_SOCKET, SO_KEEPALIVE, 1))
571 {
572 strlcpy(errbuf, "PQcancel() -- setsockopt(SO_KEEPALIVE) failed: ", errbufsize);
573 goto cancel_errReturn;
574 }
575
576#ifdef PG_TCP_KEEPALIVE_IDLE
577 if (!optional_setsockopt(tmpsock, IPPROTO_TCP, PG_TCP_KEEPALIVE_IDLE,
578 cancel->keepalives_idle))
579 {
580 strlcpy(errbuf, "PQcancel() -- setsockopt(" PG_TCP_KEEPALIVE_IDLE_STR ") failed: ", errbufsize);
581 goto cancel_errReturn;
582 }
583#endif
584
585#ifdef TCP_KEEPINTVL
586 if (!optional_setsockopt(tmpsock, IPPROTO_TCP, TCP_KEEPINTVL,
587 cancel->keepalives_interval))
588 {
589 strlcpy(errbuf, "PQcancel() -- setsockopt(TCP_KEEPINTVL) failed: ", errbufsize);
590 goto cancel_errReturn;
591 }
592#endif
593
594#ifdef TCP_KEEPCNT
595 if (!optional_setsockopt(tmpsock, IPPROTO_TCP, TCP_KEEPCNT,
596 cancel->keepalives_count))
597 {
598 strlcpy(errbuf, "PQcancel() -- setsockopt(TCP_KEEPCNT) failed: ", errbufsize);
599 goto cancel_errReturn;
600 }
601#endif
602
603#else /* WIN32 */
604
605#ifdef SIO_KEEPALIVE_VALS
606 if (!pqSetKeepalivesWin32(tmpsock,
607 cancel->keepalives_idle,
608 cancel->keepalives_interval))
609 {
610 strlcpy(errbuf, "PQcancel() -- WSAIoctl(SIO_KEEPALIVE_VALS) failed: ", errbufsize);
611 goto cancel_errReturn;
612 }
613#endif /* SIO_KEEPALIVE_VALS */
614#endif /* WIN32 */
615
616 /* TCP_USER_TIMEOUT works the same way on Unix and Windows */
617#ifdef TCP_USER_TIMEOUT
618 if (!optional_setsockopt(tmpsock, IPPROTO_TCP, TCP_USER_TIMEOUT,
619 cancel->pgtcp_user_timeout))
620 {
621 strlcpy(errbuf, "PQcancel() -- setsockopt(TCP_USER_TIMEOUT) failed: ", errbufsize);
622 goto cancel_errReturn;
623 }
624#endif
625 }
626
627retry3:
628 if (connect(tmpsock, (struct sockaddr *) &cancel->raddr.addr,
629 cancel->raddr.salen) < 0)
630 {
631 if (SOCK_ERRNO == EINTR)
632 /* Interrupted system call - we'll just try again */
633 goto retry3;
634 strlcpy(errbuf, "PQcancel() -- connect() failed: ", errbufsize);
635 goto cancel_errReturn;
636 }
637
638 cancel_pkt_len = pg_ntoh32(cancel->cancel_pkt_len);
639
640retry4:
641
642 /*
643 * Send the cancel request packet. It starts with the message length at
644 * cancel_pkt_len, followed by the actual packet.
645 */
646 if (send(tmpsock, (char *) &cancel->cancel_pkt_len, cancel_pkt_len, 0) != cancel_pkt_len)
647 {
648 if (SOCK_ERRNO == EINTR)
649 /* Interrupted system call - we'll just try again */
650 goto retry4;
651 strlcpy(errbuf, "PQcancel() -- send() failed: ", errbufsize);
652 goto cancel_errReturn;
653 }
654
655 /*
656 * Wait for the postmaster to close the connection, which indicates that
657 * it's processed the request. Without this delay, we might issue another
658 * command only to find that our cancel zaps that command instead of the
659 * one we thought we were canceling. Note we don't actually expect this
660 * read to obtain any data, we are just waiting for EOF to be signaled.
661 */
662retry5:
663 if (recv(tmpsock, &recvbuf, 1, 0) < 0)
664 {
665 if (SOCK_ERRNO == EINTR)
666 /* Interrupted system call - we'll just try again */
667 goto retry5;
668 /* we ignore other error conditions */
669 }
670
671 /* All done */
672 closesocket(tmpsock);
673 SOCK_ERRNO_SET(save_errno);
674 return true;
675
676cancel_errReturn:
677
678 /*
679 * Make sure we don't overflow the error buffer. Leave space for the \n at
680 * the end, and for the terminating zero.
681 */
682 maxlen = errbufsize - strlen(errbuf) - 2;
683 if (maxlen >= 0)
684 {
685 /*
686 * We can't invoke strerror here, since it's not signal-safe. Settle
687 * for printing the decimal value of errno. Even that has to be done
688 * the hard way.
689 */
690 int val = SOCK_ERRNO;
691 char buf[32];
692 char *bufp;
693
694 bufp = buf + sizeof(buf) - 1;
695 *bufp = '\0';
696 do
697 {
698 *(--bufp) = (val % 10) + '0';
699 val /= 10;
700 } while (val > 0);
701 bufp -= 6;
702 memcpy(bufp, "error ", 6);
703 strncat(errbuf, bufp, maxlen);
704 strcat(errbuf, "\n");
705 }
706 if (tmpsock != PGINVALID_SOCKET)
707 closesocket(tmpsock);
708 SOCK_ERRNO_SET(save_errno);
709 return false;
710}
static bool optional_setsockopt(int fd, int protoid, int optid, int value)
Definition: fe-cancel.c:498
long val
Definition: informix.c:689
#define SOCK_ERRNO
Definition: libpq-int.h:959
#define SOCK_ERRNO_SET(e)
Definition: libpq-int.h:961
#define pg_ntoh32(x)
Definition: pg_bswap.h:125
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:377
struct sockaddr_storage addr
Definition: pqcomm.h:32
socklen_t salen
Definition: pqcomm.h:33
int pgtcp_user_timeout
Definition: fe-cancel.c:44
int32 cancel_pkt_len
Definition: fe-cancel.c:53
int keepalives_interval
Definition: fe-cancel.c:47
int keepalives_idle
Definition: fe-cancel.c:46
int keepalives_count
Definition: fe-cancel.c:49
SockAddr raddr
Definition: fe-cancel.c:42
int keepalives
Definition: fe-cancel.c:45
#define EINTR
Definition: win32_port.h:364
#define recv(s, buf, len, flags)
Definition: win32_port.h:504
#define send(s, buf, len, flags)
Definition: win32_port.h:505
#define socket(af, type, protocol)
Definition: win32_port.h:498
#define connect(s, name, namelen)
Definition: win32_port.h:502

References SockAddr::addr, buf, pg_cancel::cancel_pkt_len, closesocket, connect, EINTR, pg_cancel::keepalives, pg_cancel::keepalives_count, pg_cancel::keepalives_idle, pg_cancel::keepalives_interval, optional_setsockopt(), pg_ntoh32, 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(), PQrequestCancel(), ShutdownWorkersHard(), sigTermHandler(), and test_cancel().

◆ PQcancelBlocking()

int PQcancelBlocking ( PGcancelConn cancelConn)

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

190{
192 return 0;
193 return pqConnectDBComplete(&cancelConn->conn);
194}
static PGcancel *volatile cancelConn
Definition: cancel.c:43
int PQcancelStart(PGcancelConn *cancelConn)
Definition: fe-cancel.c:203
int pqConnectDBComplete(PGconn *conn)
Definition: fe-connect.c:2779

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

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

◆ PQcancelCreate()

PGcancelConn * PQcancelCreate ( PGconn conn)

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

69{
71 pg_conn_host originalHost;
72
73 if (cancelConn == NULL)
74 return NULL;
75
76 /* Check we have an open connection */
77 if (!conn)
78 {
79 libpq_append_conn_error(cancelConn, "connection pointer is NULL");
80 return (PGcancelConn *) cancelConn;
81 }
82
84 {
85 libpq_append_conn_error(cancelConn, "connection not open");
86 return (PGcancelConn *) cancelConn;
87 }
88
89 /* Check that we have received a cancellation key */
90 if (conn->be_cancel_key_len == 0)
91 {
92 libpq_append_conn_error(cancelConn, "no cancellation key received");
93 return (PGcancelConn *) cancelConn;
94 }
95
96 /*
97 * Indicate that this connection is used to send a cancellation
98 */
99 cancelConn->cancelRequest = true;
100
102 return (PGcancelConn *) cancelConn;
103
104 /*
105 * Compute derived options
106 */
108 return (PGcancelConn *) cancelConn;
109
110 /*
111 * Copy cancellation token data from the original connection
112 */
114 if (conn->be_cancel_key != NULL)
115 {
116 cancelConn->be_cancel_key = malloc(conn->be_cancel_key_len);
117 if (!conn->be_cancel_key)
118 goto oom_error;
119 memcpy(cancelConn->be_cancel_key, conn->be_cancel_key, conn->be_cancel_key_len);
120 }
121 cancelConn->be_cancel_key_len = conn->be_cancel_key_len;
122 cancelConn->pversion = conn->pversion;
123
124 /*
125 * Cancel requests should not iterate over all possible hosts. The request
126 * needs to be sent to the exact host and address that the original
127 * connection used. So we manually create the host and address arrays with
128 * a single element after freeing the host array that we generated from
129 * the connection options.
130 */
132 cancelConn->nconnhost = 1;
133 cancelConn->naddr = 1;
134
135 cancelConn->connhost = calloc(cancelConn->nconnhost, sizeof(pg_conn_host));
136 if (!cancelConn->connhost)
137 goto oom_error;
138
139 originalHost = conn->connhost[conn->whichhost];
140 if (originalHost.host)
141 {
142 cancelConn->connhost[0].host = strdup(originalHost.host);
143 if (!cancelConn->connhost[0].host)
144 goto oom_error;
145 }
146 if (originalHost.hostaddr)
147 {
148 cancelConn->connhost[0].hostaddr = strdup(originalHost.hostaddr);
149 if (!cancelConn->connhost[0].hostaddr)
150 goto oom_error;
151 }
152 if (originalHost.port)
153 {
154 cancelConn->connhost[0].port = strdup(originalHost.port);
155 if (!cancelConn->connhost[0].port)
156 goto oom_error;
157 }
158 if (originalHost.password)
159 {
160 cancelConn->connhost[0].password = strdup(originalHost.password);
161 if (!cancelConn->connhost[0].password)
162 goto oom_error;
163 }
164
165 cancelConn->addr = calloc(cancelConn->naddr, sizeof(AddrInfo));
166 if (!cancelConn->addr)
167 goto oom_error;
168
169 cancelConn->addr[0].addr = conn->raddr;
170 cancelConn->addr[0].family = conn->raddr.addr.ss_family;
171
173 return (PGcancelConn *) cancelConn;
174
175oom_error:
176 cancelConn->status = CONNECTION_BAD;
177 libpq_append_conn_error(cancelConn, "out of memory");
178 return (PGcancelConn *) cancelConn;
179}
bool pqConnectOptions2(PGconn *conn)
Definition: fe-connect.c:1240
void pqReleaseConnHosts(PGconn *conn)
Definition: fe-connect.c:5127
PGconn * pqMakeEmptyPGconn(void)
Definition: fe-connect.c:4937
bool pqCopyPGconn(PGconn *srcConn, PGconn *dstConn)
Definition: fe-connect.c:1025
#define calloc(a, b)
Definition: header.h:55
#define malloc(a)
Definition: header.h:50
int be_pid
Definition: fe-cancel.c:43
char * host
Definition: libpq-int.h:358
char * password
Definition: libpq-int.h:361
char * port
Definition: libpq-int.h:360
char * hostaddr
Definition: libpq-int.h:359
char * be_cancel_key
Definition: libpq-int.h:550
pgsocket sock
Definition: libpq-int.h:496
ProtocolVersion pversion
Definition: libpq-int.h:500
SockAddr raddr
Definition: libpq-int.h:499
uint16 be_cancel_key_len
Definition: libpq-int.h:551
int whichhost
Definition: libpq-int.h:478
pg_conn_host * connhost
Definition: libpq-int.h:479

References SockAddr::addr, pg_conn::be_cancel_key, pg_conn::be_cancel_key_len, 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(), malloc, pg_conn_host::password, PGINVALID_SOCKET, pg_conn_host::port, pqConnectOptions2(), pqCopyPGconn(), pqMakeEmptyPGconn(), pqReleaseConnHosts(), pg_conn::pversion, pg_conn::raddr, pg_conn::sock, and pg_conn::whichhost.

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

◆ PQcancelErrorMessage()

char * PQcancelErrorMessage ( const PGcancelConn cancelConn)

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

325{
326 return PQerrorMessage(&cancelConn->conn);
327}
char * PQerrorMessage(const PGconn *conn)
Definition: fe-connect.c:7619

References cancelConn, and PQerrorMessage().

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

◆ PQcancelFinish()

void PQcancelFinish ( PGcancelConn cancelConn)

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

353{
354 PQfinish(&cancelConn->conn);
355}
void PQfinish(PGconn *conn)
Definition: fe-connect.c:5290

References cancelConn, and PQfinish().

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

◆ PQcancelPoll()

PostgresPollingStatusType PQcancelPoll ( PGcancelConn cancelConn)

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

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

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 libpqsrv_cancel(), pqConnectDBComplete(), and test_cancel().

◆ PQcancelReset()

void PQcancelReset ( PGcancelConn cancelConn)

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

337{
339 cancelConn->conn.status = CONNECTION_ALLOCATED;
340 cancelConn->conn.whichhost = 0;
341 cancelConn->conn.whichaddr = 0;
342 cancelConn->conn.try_next_host = false;
343 cancelConn->conn.try_next_addr = false;
344}
void pqClosePGconn(PGconn *conn)
Definition: fe-connect.c:5243

References cancelConn, CONNECTION_ALLOCATED, and pqClosePGconn().

Referenced by test_cancel().

◆ PQcancelSocket()

int PQcancelSocket ( const PGcancelConn cancelConn)

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

313{
314 return PQsocket(&cancelConn->conn);
315}
int PQsocket(const PGconn *conn)
Definition: fe-connect.c:7645

References cancelConn, and PQsocket().

Referenced by libpqsrv_cancel(), and test_cancel().

◆ PQcancelStart()

int PQcancelStart ( PGcancelConn cancelConn)

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

204{
205 if (!cancelConn || cancelConn->conn.status == CONNECTION_BAD)
206 return 0;
207
208 if (cancelConn->conn.status != CONNECTION_ALLOCATED)
209 {
211 "cancel request is already being sent on this connection");
212 cancelConn->conn.status = CONNECTION_BAD;
213 return 0;
214 }
215
216 return pqConnectDBStart(&cancelConn->conn);
217}
int pqConnectDBStart(PGconn *conn)
Definition: fe-connect.c:2701

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

Referenced by libpqsrv_cancel(), PQcancelBlocking(), and test_cancel().

◆ PQcancelStatus()

ConnStatusType PQcancelStatus ( const PGcancelConn cancelConn)

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

302{
303 return PQstatus(&cancelConn->conn);
304}
ConnStatusType PQstatus(const PGconn *conn)
Definition: fe-connect.c:7556

References cancelConn, and PQstatus().

Referenced by test_cancel().

◆ PQchangePassword()

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

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

1532{
1533 char *encrypted_password = PQencryptPasswordConn(conn, passwd,
1534 user, NULL);
1535
1536 if (!encrypted_password)
1537 {
1538 /* PQencryptPasswordConn() already registered the error */
1539 return NULL;
1540 }
1541 else
1542 {
1543 char *fmtpw = PQescapeLiteral(conn, encrypted_password,
1544 strlen(encrypted_password));
1545
1546 /* no longer needed, so clean up now */
1547 PQfreemem(encrypted_password);
1548
1549 if (!fmtpw)
1550 {
1551 /* PQescapeLiteral() already registered the error */
1552 return NULL;
1553 }
1554 else
1555 {
1556 char *fmtuser = PQescapeIdentifier(conn, user, strlen(user));
1557
1558 if (!fmtuser)
1559 {
1560 /* PQescapeIdentifier() already registered the error */
1561 PQfreemem(fmtpw);
1562 return NULL;
1563 }
1564 else
1565 {
1567 PGresult *res;
1568
1570 printfPQExpBuffer(&buf, "ALTER USER %s PASSWORD %s",
1571 fmtuser, fmtpw);
1572
1573 res = PQexec(conn, buf.data);
1574
1575 /* clean up */
1577 PQfreemem(fmtuser);
1578 PQfreemem(fmtpw);
1579
1580 return res;
1581 }
1582 }
1583 }
1584}
char * PQencryptPasswordConn(PGconn *conn, const char *passwd, const char *user, const char *algorithm)
Definition: fe-auth.c:1406
void PQfreemem(void *ptr)
Definition: fe-exec.c:4032
char * PQescapeLiteral(PGconn *conn, const char *str, size_t len)
Definition: fe-exec.c:4363
PGresult * PQexec(PGconn *conn, const char *query)
Definition: fe-exec.c:2262
char * PQescapeIdentifier(PGconn *conn, const char *str, size_t len)
Definition: fe-exec.c:4369
static char * user
Definition: pg_regress.c:119
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(), termPQExpBuffer(), and user.

Referenced by exec_command_password().

◆ PQclear()

void PQclear ( PGresult res)

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

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

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, PGEventResultDestroy::result, PGEvent::resultInitialized, and pg_result::tuples.

Referenced by _check_database_version(), _doSetSessionAuth(), _printTableAccessMethodNoStorage(), _selectOutputSchema(), _selectTableAccessMethod(), _selectTablespace(), add_tablespace_footer(), addFooterToPublicationDesc(), advanceConnectionState(), append_depends_on_extension(), appendQualifiedRelation(), BaseBackup(), binary_upgrade_set_type_oids_by_type_oid(), buildMatViewRefreshDependencies(), buildShSecLabels(), check_and_drop_existing_subscriptions(), check_and_drop_publications(), check_for_connection_status(), check_for_pg_role_prefix(), check_for_prepared_transactions(), check_is_install_user(), check_loadable_libraries(), check_new_cluster_logical_replication_slots(), check_new_cluster_subscription_configuration(), check_old_cluster_subscription_state(), check_prepare_conn(), check_publisher(), check_subscriber(), ClearOrSaveResult(), close_cursor(), cluster_all_databases(), collectBinaryUpgradeClassOids(), collectComments(), collectRoleNames(), collectSecLabels(), collectSequences(), compile_database_list(), compile_relation_list_one_db(), confirm_query_canceled_impl(), connect_database(), ConnectDatabase(), connectDatabase(), ConnectDatabaseAhx(), connectToServer(), convertTSFunction(), create_cursor(), create_logical_replication_slot(), create_logical_replication_slots(), create_new_objects(), create_publication(), create_subscription(), CreateReplicationSlot(), createViewAsClause(), dblink_close(), dblink_exec(), dblink_fetch(), dblink_open(), dblink_res_error(), dblink_res_internalerror(), deallocate_one(), deallocate_query(), describeAccessMethods(), describeAggregates(), describeConfigurationParameters(), describeFunctions(), describeOneTableDetails(), describeOneTSConfig(), describeOneTSParser(), describeOperators(), describePublications(), DescribeQuery(), describeRoleGrants(), describeRoles(), describeSubscriptions(), describeTableDetails(), describeTablespaces(), describeTypes(), descriptor_free(), discardAbortedPipelineResults(), discardUntilSync(), do_lo_import(), do_sql_command_end(), drop_existing_subscriptions(), drop_failover_replication_slots(), drop_publication(), drop_replication_slot(), dropDBs(), DropReplicationSlot(), dropRoles(), dropTablespaces(), dumpAgg(), dumpBaseType(), dumpCollation(), dumpCompositeType(), dumpConversion(), dumpDatabase(), dumpDatabaseConfig(), dumpDatabases(), dumpDomain(), dumpEnumType(), dumpForeignServer(), dumpFunc(), dumpOpclass(), dumpOpfamily(), dumpOpr(), dumpRangeType(), dumpRelationStats_dumper(), dumpRoleGUCPrivs(), dumpRoleMembership(), dumpRoles(), dumpRule(), dumpSearchPath(), dumpSequence(), dumpSequenceData(), dumpStatisticsExt(), dumpTable(), dumpTableAttach(), dumpTableData_copy(), dumpTableData_insert(), dumpTableSchema(), dumpTablespaces(), dumpTSConfig(), dumpTSDictionary(), dumpUserConfig(), dumpUserMappings(), ecpg_autostart_transaction(), ecpg_check_PQresult(), ecpg_is_type_an_array(), ecpg_process_output(), ECPGdescribe(), ECPGsetcommit(), ECPGtrans(), enable_subscription(), EndDBCopyMode(), exec_command_password(), execute_foreign_modify(), executeCommand(), executeMaintenanceCommand(), executeQueryOrDie(), ExecuteSqlCommand(), ExecuteSqlStatement(), executeStatement(), expand_dbname_patterns(), expand_extension_name_patterns(), expand_foreign_server_name_patterns(), expand_schema_name_patterns(), expand_table_name_patterns(), fail_lo_xact(), fetch_more_data(), finish_lo_xact(), generate_object_name(), get_create_object_cmd(), get_db_infos(), get_dbnames_list_to_restore(), get_language_name(), get_loadable_libraries(), get_next_possible_free_pg_type_oid(), get_parallel_tabidx_list(), get_parallel_tables_list(), get_primary_sysid(), get_publisher_databases(), get_remote_estimate(), get_returning_data(), get_subscription_count(), get_synchronized_snapshot(), get_table_relkind(), get_tablespace_paths(), get_template0_info(), getAccessMethods(), getAdditionalACLs(), getAggregates(), getCasts(), getCollations(), GetConnection(), getConstraints(), getConversions(), getCopyStart(), getDefaultACLs(), getDependencies(), getDomainConstraints(), getEventTriggers(), getExtendedStatistics(), getExtensionMembership(), getExtensions(), getForeignDataWrappers(), getForeignServers(), getFormattedTypeName(), getFuncs(), getIndexes(), getInherits(), getLOs(), getNamespaces(), getOpclasses(), getOperators(), getOpfamilies(), getParamDescriptions(), getPartitioningInfo(), getPolicies(), getProcLangs(), getPublicationNamespaces(), getPublications(), getPublicationTables(), getRowDescriptions(), getRules(), GetSlotInformation(), getSubscriptions(), getSubscriptionTables(), getTableAttrs(), GetTableInfo(), getTables(), getTransforms(), getTriggers(), getTSConfigurations(), getTSDictionaries(), getTSParsers(), getTSTemplates(), getTypes(), handleCopyIn(), 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_readtimelinehistoryfile(), libpqrcv_receive(), libpqrcv_startstreaming(), libpqsrv_get_result_last(), listAllDbs(), listCasts(), listCollations(), listConversions(), listDbRoleSettings(), listDefaultACLs(), listDomains(), listEventTriggers(), listExtendedStats(), listExtensionContents(), listExtensions(), listForeignDataWrappers(), listForeignServers(), listForeignTables(), listLanguages(), listLargeObjects(), listOneExtensionContents(), listOperatorClasses(), listOperatorFamilies(), listOpFamilyFunctions(), listOpFamilyOperators(), listPartitionedTables(), listPublications(), listSchemas(), listTables(), listTSConfigs(), listTSConfigsVerbose(), listTSDictionaries(), listTSParsers(), listTSParsersVerbose(), listTSTemplates(), listUserMappings(), lo_close(), lo_creat(), lo_create(), lo_initialize(), lo_lseek(), lo_lseek64(), lo_open(), lo_read(), lo_tell(), lo_tell64(), lo_truncate(), lo_truncate64(), lo_unlink(), lo_write(), lockTableForWorker(), lookup_object_oid(), main(), materializeResult(), objectDescription(), old_9_6_invalidate_hash_indexes(), permissionsList(), pgfdw_cancel_query_end(), pgfdw_exec_cleanup_query_end(), pgfdw_finish_pre_commit_cleanup(), pgfdw_get_cleanup_result(), pgfdw_report_error(), pgfdw_xact_callback(), postgresAcquireSampleRowsFunc(), postgresAnalyzeForeignTable(), postgresEndDirectModify(), postgresGetAnalyzeInfoForForeignTable(), postgresImportForeignSchema(), postgresReScanForeignScan(), pqClearAsyncResult(), PQconnectPoll(), PQcopyResult(), PQencryptPasswordConn(), pqEndcopy3(), PQexecFinish(), PQexecStart(), pqGetErrorNotice3(), pqInternalNotice(), PQmakeEmptyPGresult(), PQsetClientEncoding(), prepare_common(), prepare_foreign_modify(), prepareCommand(), process_global_sql_commands(), process_query_result(), process_queued_fetch_requests(), process_result(), processExtensionTables(), processQueryResult(), readCommandResponse(), ReceiveCopyData(), ReceiveXlogStream(), reindex_all_databases(), retrieve_objects(), RetrieveDataDirCreatePerm(), RetrieveWalSegSize(), run_permutation(), run_simple_command(), run_simple_query(), RunIdentifySystem(), SendQuery(), server_is_in_recovery(), set_frozenxids(), set_locale_and_encoding(), set_replication_progress(), set_restrict_relation_kind(), setup_connection(), setup_publisher(), sql_conn(), sql_exec(), start_lo_xact(), store_returning_result(), storeQueryResult(), StreamLogicalLog(), TableCommandResultHandler(), test_multi_pipelines(), test_nosync(), test_pipeline_abort(), test_pipeline_idle(), test_pipelined_insert(), test_prepared(), test_simple_pipeline(), test_singlerowmode(), test_transaction(), try_complete_step(), tryExecuteStatement(), unicode_version_changed(), vacuum_all_databases(), vacuumlo(), and wait_for_connection_state().

◆ PQclientEncoding()

◆ PQclosePortal()

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

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

2540{
2541 if (!PQexecStart(conn))
2542 return NULL;
2543 if (!PQsendTypedCommand(conn, PqMsg_Close, 'P', portal))
2544 return NULL;
2545 return PQexecFinish(conn);
2546}
static PGresult * PQexecFinish(PGconn *conn)
Definition: fe-exec.c:2410
static int PQsendTypedCommand(PGconn *conn, char command, char type, const char *target)
Definition: fe-exec.c:2589
static bool PQexecStart(PGconn *conn)
Definition: fe-exec.c:2344
#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 2521 of file fe-exec.c.

2522{
2523 if (!PQexecStart(conn))
2524 return NULL;
2526 return NULL;
2527 return PQexecFinish(conn);
2528}
#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 3752 of file fe-exec.c.

3753{
3754 if (!res)
3755 return NULL;
3756 return res->cmdStatus;
3757}
char cmdStatus[CMDSTATUS_LEN]
Definition: libpq-int.h:175

References pg_result::cmdStatus.

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

◆ PQcmdTuples()

char * PQcmdTuples ( PGresult res)

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

3823{
3824 char *p,
3825 *c;
3826
3827 if (!res)
3828 return "";
3829
3830 if (strncmp(res->cmdStatus, "INSERT ", 7) == 0)
3831 {
3832 p = res->cmdStatus + 7;
3833 /* INSERT: skip oid and space */
3834 while (*p && *p != ' ')
3835 p++;
3836 if (*p == 0)
3837 goto interpret_error; /* no space? */
3838 p++;
3839 }
3840 else if (strncmp(res->cmdStatus, "SELECT ", 7) == 0 ||
3841 strncmp(res->cmdStatus, "DELETE ", 7) == 0 ||
3842 strncmp(res->cmdStatus, "UPDATE ", 7) == 0)
3843 p = res->cmdStatus + 7;
3844 else if (strncmp(res->cmdStatus, "FETCH ", 6) == 0 ||
3845 strncmp(res->cmdStatus, "MERGE ", 6) == 0)
3846 p = res->cmdStatus + 6;
3847 else if (strncmp(res->cmdStatus, "MOVE ", 5) == 0 ||
3848 strncmp(res->cmdStatus, "COPY ", 5) == 0)
3849 p = res->cmdStatus + 5;
3850 else
3851 return "";
3852
3853 /* check that we have an integer (at least one digit, nothing else) */
3854 for (c = p; *c; c++)
3855 {
3856 if (!isdigit((unsigned char) *c))
3857 goto interpret_error;
3858 }
3859 if (c == p)
3860 goto interpret_error;
3861
3862 return p;
3863
3864interpret_error:
3866 "could not interpret result from server: %s",
3867 res->cmdStatus);
3868 return "";
3869}
void pqInternalNotice(const PGNoticeHooks *hooks, const char *fmt,...)
Definition: fe-exec.c:938
char * c
PGNoticeHooks noticeHooks
Definition: libpq-int.h:183

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

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

◆ PQconndefaults()

PQconninfoOption * PQconndefaults ( void  )

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

2191{
2192 PQExpBufferData errorBuf;
2193 PQconninfoOption *connOptions;
2194
2195 /* We don't actually report any errors here, but callees want a buffer */
2196 initPQExpBuffer(&errorBuf);
2197 if (PQExpBufferDataBroken(errorBuf))
2198 return NULL; /* out of memory already :-( */
2199
2200 connOptions = conninfo_init(&errorBuf);
2201 if (connOptions != NULL)
2202 {
2203 /* pass NULL errorBuf to ignore errors */
2204 if (!conninfo_add_defaults(connOptions, NULL))
2205 {
2206 PQconninfoFree(connOptions);
2207 connOptions = NULL;
2208 }
2209 }
2210
2211 termPQExpBuffer(&errorBuf);
2212 return connOptions;
2213}
static PQconninfoOption * conninfo_init(PQExpBuffer errorMessage)
Definition: fe-connect.c:6172
static bool conninfo_add_defaults(PQconninfoOption *options, PQExpBuffer errorMessage)
Definition: fe-connect.c:6599
void PQconninfoFree(PQconninfoOption *connOptions)
Definition: fe-connect.c:7434
#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(), GetDbnameFromConnectionOptions(), InitPgFdwOptions(), and main().

◆ PQconnectdb()

PGconn * PQconnectdb ( const char *  conninfo)

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

814{
815 PGconn *conn = PQconnectStart(conninfo);
816
817 if (conn && conn->status != CONNECTION_BAD)
819
820 return conn;
821}
PGconn * PQconnectStart(const char *conninfo)
Definition: fe-connect.c:941

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

Referenced by connect_database(), get_db_conn(), and main().

◆ PQconnectdbParams()

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

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

761{
762 PGconn *conn = PQconnectStartParams(keywords, values, expand_dbname);
763
764 if (conn && conn->status != CONNECTION_BAD)
766
767 return conn;
768}
static Datum values[MAXATTR]
Definition: bootstrap.c:151
PGconn * PQconnectStartParams(const char *const *keywords, const char *const *values, int expand_dbname)
Definition: fe-connect.c:860
static const JsonPathKeyword keywords[]

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

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

◆ PQconnectionNeedsPassword()

int PQconnectionNeedsPassword ( const PGconn conn)

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

7673{
7674 char *password;
7675
7676 if (!conn)
7677 return false;
7678 password = PQpass(conn);
7679 if (conn->password_needed &&
7680 (password == NULL || password[0] == '\0'))
7681 return true;
7682 else
7683 return false;
7684}
char * PQpass(const PGconn *conn)
Definition: fe-connect.c:7471
static char * password
Definition: streamutil.c:51
bool password_needed
Definition: libpq-int.h:505

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 7698 of file fe-connect.c.

7699{
7700 if (!conn)
7701 return false;
7702 if (conn->gssapi_used)
7703 return true;
7704 else
7705 return false;
7706}
bool gssapi_used
Definition: libpq-int.h:506

References conn, and pg_conn::gssapi_used.

Referenced by dblink_security_check(), exec_command_conninfo(), and pgfdw_security_check().

◆ PQconnectionUsedPassword()

int PQconnectionUsedPassword ( const PGconn conn)

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

7688{
7689 if (!conn)
7690 return false;
7691 if (conn->password_needed)
7692 return true;
7693 else
7694 return false;
7695}

References conn, and pg_conn::password_needed.

Referenced by ConnectDatabaseAhx(), dblink_security_check(), exec_command_conninfo(), libpqrcv_connect(), and pgfdw_security_check().

◆ PQconnectPoll()

PostgresPollingStatusType PQconnectPoll ( PGconn conn)

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

2906{
2907 bool reset_connection_state_machine = false;
2908 bool need_new_connection = false;
2909 PGresult *res;
2910 char sebuf[PG_STRERROR_R_BUFLEN];
2911 int optval;
2912
2913 if (conn == NULL)
2914 return PGRES_POLLING_FAILED;
2915
2916 /* Get the new data */
2917 switch (conn->status)
2918 {
2919 /*
2920 * We really shouldn't have been polled in these two cases, but we
2921 * can handle it.
2922 */
2923 case CONNECTION_BAD:
2924 return PGRES_POLLING_FAILED;
2925 case CONNECTION_OK:
2926 return PGRES_POLLING_OK;
2927
2928 /* These are reading states */
2930 case CONNECTION_AUTH_OK:
2932 case CONNECTION_CONSUME:
2934 {
2935 /* Load waiting data */
2936 int n = pqReadData(conn);
2937
2938 if (n < 0)
2939 goto error_return;
2940 if (n == 0)
2941 return PGRES_POLLING_READING;
2942
2943 break;
2944 }
2945
2946 /* These are writing states, so we just proceed. */
2947 case CONNECTION_STARTED:
2948 case CONNECTION_MADE:
2949 break;
2950
2951 /* Special cases: proceed without waiting. */
2953 case CONNECTION_NEEDED:
2957 break;
2958
2959 default:
2960 libpq_append_conn_error(conn, "invalid connection state, probably indicative of memory corruption");
2961 goto error_return;
2962 }
2963
2964
2965keep_going: /* We will come back to here until there is
2966 * nothing left to do. */
2967
2968 /* Time to advance to next address, or next host if no more addresses? */
2969 if (conn->try_next_addr)
2970 {
2971 if (conn->whichaddr < conn->naddr)
2972 {
2973 conn->whichaddr++;
2974 reset_connection_state_machine = true;
2975 }
2976 else
2977 conn->try_next_host = true;
2978 conn->try_next_addr = false;
2979 }
2980
2981 /* Time to advance to next connhost[] entry? */
2982 if (conn->try_next_host)
2983 {
2984 pg_conn_host *ch;
2985 struct addrinfo hint;
2986 struct addrinfo *addrlist;
2987 int thisport;
2988 int ret;
2989 char portstr[MAXPGPATH];
2990
2991 if (conn->whichhost + 1 < conn->nconnhost)
2992 conn->whichhost++;
2993 else
2994 {
2995 /*
2996 * Oops, no more hosts.
2997 *
2998 * If we are trying to connect in "prefer-standby" mode, then drop
2999 * the standby requirement and start over. Don't do this for
3000 * cancel requests though, since we are certain the list of
3001 * servers won't change as the target_server_type option is not
3002 * applicable to those connections.
3003 *
3004 * Otherwise, an appropriate error message is already set up, so
3005 * we just need to set the right status.
3006 */
3008 conn->nconnhost > 0 &&
3010 {
3012 conn->whichhost = 0;
3013 }
3014 else
3015 goto error_return;
3016 }
3017
3018 /* Drop any address info for previous host */
3020
3021 /*
3022 * Look up info for the new host. On failure, log the problem in
3023 * conn->errorMessage, then loop around to try the next host. (Note
3024 * we don't clear try_next_host until we've succeeded.)
3025 */
3026 ch = &conn->connhost[conn->whichhost];
3027
3028 /* Initialize hint structure */
3029 MemSet(&hint, 0, sizeof(hint));
3030 hint.ai_socktype = SOCK_STREAM;
3031 hint.ai_family = AF_UNSPEC;
3032
3033 /* Figure out the port number we're going to use. */
3034 if (ch->port == NULL || ch->port[0] == '\0')
3035 thisport = DEF_PGPORT;
3036 else
3037 {
3038 if (!pqParseIntParam(ch->port, &thisport, conn, "port"))
3039 goto error_return;
3040
3041 if (thisport < 1 || thisport > 65535)
3042 {
3043 libpq_append_conn_error(conn, "invalid port number: \"%s\"", ch->port);
3044 goto keep_going;
3045 }
3046 }
3047 snprintf(portstr, sizeof(portstr), "%d", thisport);
3048
3049 /* Use pg_getaddrinfo_all() to resolve the address */
3050 switch (ch->type)
3051 {
3052 case CHT_HOST_NAME:
3053 ret = pg_getaddrinfo_all(ch->host, portstr, &hint,
3054 &addrlist);
3055 if (ret || !addrlist)
3056 {
3057 libpq_append_conn_error(conn, "could not translate host name \"%s\" to address: %s",
3058 ch->host, gai_strerror(ret));
3059 goto keep_going;
3060 }
3061 break;
3062
3063 case CHT_HOST_ADDRESS:
3064 hint.ai_flags = AI_NUMERICHOST;
3065 ret = pg_getaddrinfo_all(ch->hostaddr, portstr, &hint,
3066 &addrlist);
3067 if (ret || !addrlist)
3068 {
3069 libpq_append_conn_error(conn, "could not parse network address \"%s\": %s",
3070 ch->hostaddr, gai_strerror(ret));
3071 goto keep_going;
3072 }
3073 break;
3074
3075 case CHT_UNIX_SOCKET:
3076 hint.ai_family = AF_UNIX;
3077 UNIXSOCK_PATH(portstr, thisport, ch->host);
3078 if (strlen(portstr) >= UNIXSOCK_PATH_BUFLEN)
3079 {
3080 libpq_append_conn_error(conn, "Unix-domain socket path \"%s\" is too long (maximum %d bytes)",
3081 portstr,
3082 (int) (UNIXSOCK_PATH_BUFLEN - 1));
3083 goto keep_going;
3084 }
3085
3086 /*
3087 * NULL hostname tells pg_getaddrinfo_all to parse the service
3088 * name as a Unix-domain socket path.
3089 */
3090 ret = pg_getaddrinfo_all(NULL, portstr, &hint,
3091 &addrlist);
3092 if (ret || !addrlist)
3093 {
3094 libpq_append_conn_error(conn, "could not translate Unix-domain socket path \"%s\" to address: %s",
3095 portstr, gai_strerror(ret));
3096 goto keep_going;
3097 }
3098 break;
3099 }
3100
3101 /*
3102 * Store a copy of the addrlist in private memory so we can perform
3103 * randomization for load balancing.
3104 */
3105 ret = store_conn_addrinfo(conn, addrlist);
3106 pg_freeaddrinfo_all(hint.ai_family, addrlist);
3107 if (ret)
3108 goto error_return; /* message already logged */
3109
3110 /*
3111 * If random load balancing is enabled we shuffle the addresses.
3112 */
3114 {
3115 /*
3116 * This is the "inside-out" variant of the Fisher-Yates shuffle
3117 * algorithm. Notionally, we append each new value to the array
3118 * and then swap it with a randomly-chosen array element (possibly
3119 * including itself, else we fail to generate permutations with
3120 * the last integer last). The swap step can be optimized by
3121 * combining it with the insertion.
3122 *
3123 * We don't need to initialize conn->prng_state here, because that
3124 * already happened in pqConnectOptions2.
3125 */
3126 for (int i = 1; i < conn->naddr; i++)
3127 {
3128 int j = pg_prng_uint64_range(&conn->prng_state, 0, i);
3129 AddrInfo temp = conn->addr[j];
3130
3131 conn->addr[j] = conn->addr[i];
3132 conn->addr[i] = temp;
3133 }
3134 }
3135
3136 reset_connection_state_machine = true;
3137 conn->try_next_host = false;
3138 }
3139
3140 /* Reset connection state machine? */
3141 if (reset_connection_state_machine)
3142 {
3143 /*
3144 * (Re) initialize our connection control variables for a set of
3145 * connection attempts to a single server address. These variables
3146 * must persist across individual connection attempts, but we must
3147 * reset them when we start to consider a new server.
3148 */
3150 conn->send_appname = true;
3154 reset_connection_state_machine = false;
3155 need_new_connection = true;
3156 }
3157
3158 /* Force a new connection (perhaps to the same server as before)? */
3159 if (need_new_connection)
3160 {
3161 /* Drop any existing connection */
3162 pqDropConnection(conn, true);
3163
3164 /* Reset all state obtained from old server */
3166
3167 /* Drop any PGresult we might have, too */
3172
3173 /* Reset conn->status to put the state machine in the right state */
3175
3176 need_new_connection = false;
3177 }
3178
3179 /*
3180 * Decide what to do next, if server rejects SSL or GSS negotiation, but
3181 * the connection is still valid. If there are no options left, error out
3182 * with 'msg'.
3183 */
3184#define ENCRYPTION_NEGOTIATION_FAILED(msg) \
3185 do { \
3186 switch (encryption_negotiation_failed(conn)) \
3187 { \
3188 case 0: \
3189 libpq_append_conn_error(conn, (msg)); \
3190 goto error_return; \
3191 case 1: \
3192 conn->status = CONNECTION_MADE; \
3193 return PGRES_POLLING_WRITING; \
3194 case 2: \
3195 need_new_connection = true; \
3196 goto keep_going; \
3197 } \
3198 } while(0);
3199
3200 /*
3201 * Decide what to do next, if connection fails. If there are no options
3202 * left, return with an error. The error message has already been written
3203 * to the connection's error buffer.
3204 */
3205#define CONNECTION_FAILED() \
3206 do { \
3207 if (connection_failed(conn)) \
3208 { \
3209 need_new_connection = true; \
3210 goto keep_going; \
3211 } \
3212 else \
3213 goto error_return; \
3214 } while(0);
3215
3216 /* Now try to advance the state machine for this connection */
3217 switch (conn->status)
3218 {
3219 case CONNECTION_NEEDED:
3220 {
3221 /*
3222 * Try to initiate a connection to one of the addresses
3223 * returned by pg_getaddrinfo_all(). conn->whichaddr is the
3224 * next one to try.
3225 *
3226 * The extra level of braces here is historical. It's not
3227 * worth reindenting this whole switch case to remove 'em.
3228 */
3229 {
3230 char host_addr[NI_MAXHOST];
3231 int sock_type;
3232 AddrInfo *addr_cur;
3233
3234 /*
3235 * Advance to next possible host, if we've tried all of
3236 * the addresses for the current host.
3237 */
3238 if (conn->whichaddr == conn->naddr)
3239 {
3240 conn->try_next_host = true;
3241 goto keep_going;
3242 }
3243 addr_cur = &conn->addr[conn->whichaddr];
3244
3245 /* Remember current address for possible use later */
3246 memcpy(&conn->raddr, &addr_cur->addr, sizeof(SockAddr));
3247
3248#ifdef ENABLE_GSS
3249
3250 /*
3251 * Before establishing the connection, check if it's
3252 * doomed to fail because gssencmode='require' but GSSAPI
3253 * is not available.
3254 */
3255 if (conn->gssencmode[0] == 'r')
3256 {
3257 if (conn->raddr.addr.ss_family == AF_UNIX)
3258 {
3260 "GSSAPI encryption required but it is not supported over a local socket");
3261 goto error_return;
3262 }
3263 if (conn->gcred == GSS_C_NO_CREDENTIAL)
3264 {
3265 if (!pg_GSS_have_cred_cache(&conn->gcred))
3266 {
3268 "GSSAPI encryption required but no credential cache");
3269 goto error_return;
3270 }
3271 }
3272 }
3273#endif
3274
3275 /*
3276 * Choose the encryption method to try first. Do this
3277 * before establishing the connection, so that if none of
3278 * the modes allowed by the connections options are
3279 * available, we can error out before establishing the
3280 * connection.
3281 */
3283 goto error_return;
3284
3285 /*
3286 * Set connip, too. Note we purposely ignore strdup
3287 * failure; not a big problem if it fails.
3288 */
3289 if (conn->connip != NULL)
3290 {
3291 free(conn->connip);
3292 conn->connip = NULL;
3293 }
3294 getHostaddr(conn, host_addr, NI_MAXHOST);
3295 if (host_addr[0])
3296 conn->connip = strdup(host_addr);
3297
3298 /* Try to create the socket */
3299 sock_type = SOCK_STREAM;
3300#ifdef SOCK_CLOEXEC
3301
3302 /*
3303 * Atomically mark close-on-exec, if possible on this
3304 * platform, so that there isn't a window where a
3305 * subprogram executed by another thread inherits the
3306 * socket. See fallback code below.
3307 */
3308 sock_type |= SOCK_CLOEXEC;
3309#endif
3310#ifdef SOCK_NONBLOCK
3311
3312 /*
3313 * We might as well skip a system call for nonblocking
3314 * mode too, if we can.
3315 */
3316 sock_type |= SOCK_NONBLOCK;
3317#endif
3318 conn->sock = socket(addr_cur->family, sock_type, 0);
3319 if (conn->sock == PGINVALID_SOCKET)
3320 {
3321 int errorno = SOCK_ERRNO;
3322
3323 /*
3324 * Silently ignore socket() failure if we have more
3325 * addresses to try; this reduces useless chatter in
3326 * cases where the address list includes both IPv4 and
3327 * IPv6 but kernel only accepts one family.
3328 */
3329 if (conn->whichaddr < conn->naddr ||
3330 conn->whichhost + 1 < conn->nconnhost)
3331 {
3332 conn->try_next_addr = true;
3333 goto keep_going;
3334 }
3335 emitHostIdentityInfo(conn, host_addr);
3336 libpq_append_conn_error(conn, "could not create socket: %s",
3337 SOCK_STRERROR(errorno, sebuf, sizeof(sebuf)));
3338 goto error_return;
3339 }
3340
3341 /*
3342 * Once we've identified a target address, all errors
3343 * except the preceding socket()-failure case should be
3344 * prefixed with host-identity information. (If the
3345 * connection succeeds, the contents of conn->errorMessage
3346 * won't matter, so this is harmless.)
3347 */
3348 emitHostIdentityInfo(conn, host_addr);
3349
3350 /*
3351 * Select socket options: no delay of outgoing data for
3352 * TCP sockets, nonblock mode, close-on-exec. Try the
3353 * next address if any of this fails.
3354 */
3355 if (addr_cur->family != AF_UNIX)
3356 {
3357 if (!connectNoDelay(conn))
3358 {
3359 /* error message already created */
3360 conn->try_next_addr = true;
3361 goto keep_going;
3362 }
3363 }
3364#ifndef SOCK_NONBLOCK
3365 if (!pg_set_noblock(conn->sock))
3366 {
3367 libpq_append_conn_error(conn, "could not set socket to nonblocking mode: %s",
3368 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
3369 conn->try_next_addr = true;
3370 goto keep_going;
3371 }
3372#endif
3373
3374#ifndef SOCK_CLOEXEC
3375#ifdef F_SETFD
3376 if (fcntl(conn->sock, F_SETFD, FD_CLOEXEC) == -1)
3377 {
3378 libpq_append_conn_error(conn, "could not set socket to close-on-exec mode: %s",
3379 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
3380 conn->try_next_addr = true;
3381 goto keep_going;
3382 }
3383#endif /* F_SETFD */
3384#endif
3385
3386 if (addr_cur->family != AF_UNIX)
3387 {
3388#ifndef WIN32
3389 int on = 1;
3390#endif
3391 int usekeepalives = useKeepalives(conn);
3392 int err = 0;
3393
3394 if (usekeepalives < 0)
3395 {
3396 /* error is already reported */
3397 err = 1;
3398 }
3399 else if (usekeepalives == 0)
3400 {
3401 /* Do nothing */
3402 }
3403#ifndef WIN32
3404 else if (setsockopt(conn->sock,
3405 SOL_SOCKET, SO_KEEPALIVE,
3406 (char *) &on, sizeof(on)) < 0)
3407 {
3408 libpq_append_conn_error(conn, "%s(%s) failed: %s",
3409 "setsockopt",
3410 "SO_KEEPALIVE",
3411 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
3412 err = 1;
3413 }
3414 else if (!setKeepalivesIdle(conn)
3417 err = 1;
3418#else /* WIN32 */
3419#ifdef SIO_KEEPALIVE_VALS
3420 else if (!prepKeepalivesWin32(conn))
3421 err = 1;
3422#endif /* SIO_KEEPALIVE_VALS */
3423#endif /* WIN32 */
3424 else if (!setTCPUserTimeout(conn))
3425 err = 1;
3426
3427 if (err)
3428 {
3429 conn->try_next_addr = true;
3430 goto keep_going;
3431 }
3432 }
3433
3434 /*----------
3435 * We have three methods of blocking SIGPIPE during
3436 * send() calls to this socket:
3437 *
3438 * - setsockopt(sock, SO_NOSIGPIPE)
3439 * - send(sock, ..., MSG_NOSIGNAL)
3440 * - setting the signal mask to SIG_IGN during send()
3441 *
3442 * The third method requires three syscalls per send,
3443 * so we prefer either of the first two, but they are
3444 * less portable. The state is tracked in the following
3445 * members of PGconn:
3446 *
3447 * conn->sigpipe_so - we have set up SO_NOSIGPIPE
3448 * conn->sigpipe_flag - we're specifying MSG_NOSIGNAL
3449 *
3450 * If we can use SO_NOSIGPIPE, then set sigpipe_so here
3451 * and we're done. Otherwise, set sigpipe_flag so that
3452 * we will try MSG_NOSIGNAL on sends. If we get an error
3453 * with MSG_NOSIGNAL, we'll clear that flag and revert to
3454 * signal masking.
3455 *----------
3456 */
3457 conn->sigpipe_so = false;
3458#ifdef MSG_NOSIGNAL
3459 conn->sigpipe_flag = true;
3460#else
3461 conn->sigpipe_flag = false;
3462#endif /* MSG_NOSIGNAL */
3463
3464#ifdef SO_NOSIGPIPE
3465 optval = 1;
3466 if (setsockopt(conn->sock, SOL_SOCKET, SO_NOSIGPIPE,
3467 (char *) &optval, sizeof(optval)) == 0)
3468 {
3469 conn->sigpipe_so = true;
3470 conn->sigpipe_flag = false;
3471 }
3472#endif /* SO_NOSIGPIPE */
3473
3474 /*
3475 * Start/make connection. This should not block, since we
3476 * are in nonblock mode. If it does, well, too bad.
3477 */
3478 if (connect(conn->sock, (struct sockaddr *) &addr_cur->addr.addr,
3479 addr_cur->addr.salen) < 0)
3480 {
3481 if (SOCK_ERRNO == EINPROGRESS ||
3482#ifdef WIN32
3484#endif
3485 SOCK_ERRNO == EINTR)
3486 {
3487 /*
3488 * This is fine - we're in non-blocking mode, and
3489 * the connection is in progress. Tell caller to
3490 * wait for write-ready on socket.
3491 */
3493 return PGRES_POLLING_WRITING;
3494 }
3495 /* otherwise, trouble */
3496 }
3497 else
3498 {
3499 /*
3500 * Hm, we're connected already --- seems the "nonblock
3501 * connection" wasn't. Advance the state machine and
3502 * go do the next stuff.
3503 */
3505 goto keep_going;
3506 }
3507
3508 /*
3509 * This connection failed. Add the error report to
3510 * conn->errorMessage, then try the next address if any.
3511 */
3513 conn->try_next_addr = true;
3514 goto keep_going;
3515 }
3516 }
3517
3518 case CONNECTION_STARTED:
3519 {
3520 socklen_t optlen = sizeof(optval);
3521
3522 /*
3523 * Write ready, since we've made it here, so the connection
3524 * has been made ... or has failed.
3525 */
3526
3527 /*
3528 * Now check (using getsockopt) that there is not an error
3529 * state waiting for us on the socket.
3530 */
3531
3532 if (getsockopt(conn->sock, SOL_SOCKET, SO_ERROR,
3533 (char *) &optval, &optlen) == -1)
3534 {
3535 libpq_append_conn_error(conn, "could not get socket error status: %s",
3536 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
3537 goto error_return;
3538 }
3539 else if (optval != 0)
3540 {
3541 /*
3542 * When using a nonblocking connect, we will typically see
3543 * connect failures at this point, so provide a friendly
3544 * error message.
3545 */
3546 connectFailureMessage(conn, optval);
3547
3548 /*
3549 * Try the next address if any, just as in the case where
3550 * connect() returned failure immediately.
3551 */
3552 conn->try_next_addr = true;
3553 goto keep_going;
3554 }
3555
3556 /* Fill in the client address */
3557 conn->laddr.salen = sizeof(conn->laddr.addr);
3558 if (getsockname(conn->sock,
3559 (struct sockaddr *) &conn->laddr.addr,
3560 &conn->laddr.salen) < 0)
3561 {
3562 libpq_append_conn_error(conn, "could not get client address from socket: %s",
3563 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
3564 goto error_return;
3565 }
3566
3567 /*
3568 * Implement requirepeer check, if requested and it's a
3569 * Unix-domain socket.
3570 */
3571 if (conn->requirepeer && conn->requirepeer[0] &&
3572 conn->raddr.addr.ss_family == AF_UNIX)
3573 {
3574#ifndef WIN32
3575 char *remote_username;
3576#endif
3577 uid_t uid;
3578 gid_t gid;
3579
3580 errno = 0;
3581 if (getpeereid(conn->sock, &uid, &gid) != 0)
3582 {
3583 /*
3584 * Provide special error message if getpeereid is a
3585 * stub
3586 */
3587 if (errno == ENOSYS)
3588 libpq_append_conn_error(conn, "requirepeer parameter is not supported on this platform");
3589 else
3590 libpq_append_conn_error(conn, "could not get peer credentials: %s",
3591 strerror_r(errno, sebuf, sizeof(sebuf)));
3592 goto error_return;
3593 }
3594
3595#ifndef WIN32
3596 remote_username = pg_fe_getusername(uid,
3597 &conn->errorMessage);
3598 if (remote_username == NULL)
3599 goto error_return; /* message already logged */
3600
3601 if (strcmp(remote_username, conn->requirepeer) != 0)
3602 {
3603 libpq_append_conn_error(conn, "requirepeer specifies \"%s\", but actual peer user name is \"%s\"",
3604 conn->requirepeer, remote_username);
3605 free(remote_username);
3606 goto error_return;
3607 }
3608 free(remote_username);
3609#else /* WIN32 */
3610 /* should have failed with ENOSYS above */
3611 Assert(false);
3612#endif /* WIN32 */
3613 }
3614
3615 /*
3616 * Make sure we can write before advancing to next step.
3617 */
3619 return PGRES_POLLING_WRITING;
3620 }
3621
3622 case CONNECTION_MADE:
3623 {
3624 char *startpacket;
3625 int packetlen;
3626
3627#ifdef ENABLE_GSS
3628
3629 /*
3630 * If GSSAPI encryption is enabled, send a packet to the
3631 * server asking for GSSAPI Encryption and proceed with GSSAPI
3632 * handshake. We will come back here after GSSAPI encryption
3633 * has been established, with conn->gctx set.
3634 */
3635 if (conn->current_enc_method == ENC_GSSAPI && !conn->gctx)
3636 {
3638
3639 if (pqPacketSend(conn, 0, &pv, sizeof(pv)) != STATUS_OK)
3640 {
3641 libpq_append_conn_error(conn, "could not send GSSAPI negotiation packet: %s",
3642 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
3643 goto error_return;
3644 }
3645
3646 /* Ok, wait for response */
3648 return PGRES_POLLING_READING;
3649 }
3650#endif
3651
3652#ifdef USE_SSL
3653
3654 /*
3655 * If SSL is enabled, start the SSL negotiation. We will come
3656 * back here after SSL encryption has been established, with
3657 * ssl_in_use set.
3658 */
3660 {
3661 /*
3662 * If traditional postgres SSL negotiation is used, send
3663 * the SSL request. In direct negotiation, jump straight
3664 * into the SSL handshake.
3665 */
3666 if (conn->sslnegotiation[0] == 'p')
3667 {
3668 ProtocolVersion pv;
3669
3670 /*
3671 * Send the SSL request packet.
3672 *
3673 * Theoretically, this could block, but it really
3674 * shouldn't since we only got here if the socket is
3675 * write-ready.
3676 */
3678 if (pqPacketSend(conn, 0, &pv, sizeof(pv)) != STATUS_OK)
3679 {
3680 libpq_append_conn_error(conn, "could not send SSL negotiation packet: %s",
3681 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
3682 goto error_return;
3683 }
3684 /* Ok, wait for response */
3686 return PGRES_POLLING_READING;
3687 }
3688 else
3689 {
3690 Assert(conn->sslnegotiation[0] == 'd');
3692 return PGRES_POLLING_WRITING;
3693 }
3694 }
3695#endif /* USE_SSL */
3696
3697 /*
3698 * For cancel requests this is as far as we need to go in the
3699 * connection establishment. Now we can actually send our
3700 * cancellation request.
3701 */
3702 if (conn->cancelRequest)
3703 {
3705 {
3706 libpq_append_conn_error(conn, "could not send cancel packet: %s",
3707 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
3708 goto error_return;
3709 }
3711 return PGRES_POLLING_READING;
3712 }
3713
3714 /*
3715 * We have now established encryption, or we are happy to
3716 * proceed without.
3717 */
3718
3719 /* Build the startup packet. */
3720 startpacket = pqBuildStartupPacket3(conn, &packetlen,
3722 if (!startpacket)
3723 {
3724 libpq_append_conn_error(conn, "out of memory");
3725 goto error_return;
3726 }
3727
3728 /*
3729 * Send the startup packet.
3730 *
3731 * Theoretically, this could block, but it really shouldn't
3732 * since we only got here if the socket is write-ready.
3733 */
3734 if (pqPacketSend(conn, 0, startpacket, packetlen) != STATUS_OK)
3735 {
3736 libpq_append_conn_error(conn, "could not send startup packet: %s",
3737 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
3738 free(startpacket);
3739 goto error_return;
3740 }
3741
3742 free(startpacket);
3743
3745 return PGRES_POLLING_READING;
3746 }
3747
3748 /*
3749 * Handle SSL negotiation: wait for postmaster messages and
3750 * respond as necessary.
3751 */
3753 {
3754#ifdef USE_SSL
3756
3757 /*
3758 * On first time through with traditional SSL negotiation, get
3759 * the postmaster's response to our SSLRequest packet. With
3760 * sslnegotiation='direct', go straight to initiating SSL.
3761 */
3762 if (!conn->ssl_in_use && conn->sslnegotiation[0] == 'p')
3763 {
3764 /*
3765 * We use pqReadData here since it has the logic to
3766 * distinguish no-data-yet from connection closure. Since
3767 * conn->ssl isn't set, a plain recv() will occur.
3768 */
3769 char SSLok;
3770 int rdresult;
3771
3772 rdresult = pqReadData(conn);
3773 if (rdresult < 0)
3774 {
3775 /* errorMessage is already filled in */
3776 goto error_return;
3777 }
3778 if (rdresult == 0)
3779 {
3780 /* caller failed to wait for data */
3781 return PGRES_POLLING_READING;
3782 }
3783 if (pqGetc(&SSLok, conn) < 0)
3784 {
3785 /* should not happen really */
3786 return PGRES_POLLING_READING;
3787 }
3788 if (SSLok == 'S')
3789 {
3790 if (conn->Pfdebug)
3791 pqTraceOutputCharResponse(conn, "SSLResponse",
3792 SSLok);
3793 /* mark byte consumed */
3795 }
3796 else if (SSLok == 'N')
3797 {
3798 if (conn->Pfdebug)
3799 pqTraceOutputCharResponse(conn, "SSLResponse",
3800 SSLok);
3801 /* mark byte consumed */
3803
3804 /*
3805 * The connection is still valid, so if it's OK to
3806 * continue without SSL, we can proceed using this
3807 * connection. Otherwise return with an error.
3808 */
3809 ENCRYPTION_NEGOTIATION_FAILED(libpq_gettext("server does not support SSL, but SSL was required"));
3810 }
3811 else if (SSLok == 'E')
3812 {
3813 /*
3814 * Server failure of some sort, such as failure to
3815 * fork a backend process. Don't bother retrieving
3816 * the error message; we should not trust it as the
3817 * server has not been authenticated yet.
3818 */
3819 libpq_append_conn_error(conn, "server sent an error response during SSL exchange");
3820 goto error_return;
3821 }
3822 else
3823 {
3824 libpq_append_conn_error(conn, "received invalid response to SSL negotiation: %c",
3825 SSLok);
3826 goto error_return;
3827 }
3828 }
3829
3830 /*
3831 * Begin or continue the SSL negotiation process.
3832 */
3833 pollres = pqsecure_open_client(conn);
3834 if (pollres == PGRES_POLLING_OK)
3835 {
3836 /*
3837 * At this point we should have no data already buffered.
3838 * If we do, it was received before we performed the SSL
3839 * handshake, so it wasn't encrypted and indeed may have
3840 * been injected by a man-in-the-middle.
3841 */
3842 if (conn->inCursor != conn->inEnd)
3843 {
3844 libpq_append_conn_error(conn, "received unencrypted data after SSL response");
3845 goto error_return;
3846 }
3847
3848 /* SSL handshake done, ready to send startup packet */
3850 return PGRES_POLLING_WRITING;
3851 }
3852 if (pollres == PGRES_POLLING_FAILED)
3853 {
3854 /*
3855 * SSL handshake failed. We will retry with a plaintext
3856 * connection, if permitted by sslmode.
3857 */
3859 }
3860 /* Else, return POLLING_READING or POLLING_WRITING status */
3861 return pollres;
3862#else /* !USE_SSL */
3863 /* can't get here */
3864 goto error_return;
3865#endif /* USE_SSL */
3866 }
3867
3869 {
3870#ifdef ENABLE_GSS
3872
3873 /*
3874 * If we haven't yet, get the postmaster's response to our
3875 * negotiation packet
3876 */
3877 if (!conn->gctx)
3878 {
3879 char gss_ok;
3880 int rdresult = pqReadData(conn);
3881
3882 if (rdresult < 0)
3883 /* pqReadData fills in error message */
3884 goto error_return;
3885 else if (rdresult == 0)
3886 /* caller failed to wait for data */
3887 return PGRES_POLLING_READING;
3888 if (pqGetc(&gss_ok, conn) < 0)
3889 /* shouldn't happen... */
3890 return PGRES_POLLING_READING;
3891
3892 if (gss_ok == 'E')
3893 {
3894 /*
3895 * Server failure of some sort, possibly protocol
3896 * version support failure. Don't bother retrieving
3897 * the error message; we should not trust it anyway as
3898 * the server has not authenticated yet.
3899 *
3900 * Note that unlike on an error response to
3901 * SSLRequest, we allow falling back to SSL or
3902 * plaintext connection here. GSS support was
3903 * introduced in PostgreSQL version 12, so an error
3904 * response might mean that we are connecting to a
3905 * pre-v12 server.
3906 */
3907 libpq_append_conn_error(conn, "server sent an error response during GSS encryption exchange");
3909 }
3910
3911 /* mark byte consumed */
3913
3914 if (gss_ok == 'N')
3915 {
3916 if (conn->Pfdebug)
3917 pqTraceOutputCharResponse(conn, "GSSENCResponse",
3918 gss_ok);
3919
3920 /*
3921 * The connection is still valid, so if it's OK to
3922 * continue without GSS, we can proceed using this
3923 * connection. Otherwise return with an error.
3924 */
3925 ENCRYPTION_NEGOTIATION_FAILED(libpq_gettext("server doesn't support GSSAPI encryption, but it was required"));
3926 }
3927 else if (gss_ok != 'G')
3928 {
3929 libpq_append_conn_error(conn, "received invalid response to GSSAPI negotiation: %c",
3930 gss_ok);
3931 goto error_return;
3932 }
3933
3934 if (conn->Pfdebug)
3935 pqTraceOutputCharResponse(conn, "GSSENCResponse",
3936 gss_ok);
3937 }
3938
3939 /* Begin or continue GSSAPI negotiation */
3940 pollres = pqsecure_open_gss(conn);
3941 if (pollres == PGRES_POLLING_OK)
3942 {
3943 /*
3944 * At this point we should have no data already buffered.
3945 * If we do, it was received before we performed the GSS
3946 * handshake, so it wasn't encrypted and indeed may have
3947 * been injected by a man-in-the-middle.
3948 */
3949 if (conn->inCursor != conn->inEnd)
3950 {
3951 libpq_append_conn_error(conn, "received unencrypted data after GSSAPI encryption response");
3952 goto error_return;
3953 }
3954
3955 /* All set for startup packet */
3957 return PGRES_POLLING_WRITING;
3958 }
3959 else if (pollres == PGRES_POLLING_FAILED)
3960 {
3961 /*
3962 * GSS handshake failed. We will retry with an SSL or
3963 * plaintext connection, if permitted by the options.
3964 */
3966 }
3967 /* Else, return POLLING_READING or POLLING_WRITING status */
3968 return pollres;
3969#else /* !ENABLE_GSS */
3970 /* unreachable */
3971 goto error_return;
3972#endif /* ENABLE_GSS */
3973 }
3974
3975 /*
3976 * Handle authentication exchange: wait for postmaster messages
3977 * and respond as necessary.
3978 */
3980 {
3981 char beresp;
3982 int msgLength;
3983 int avail;
3984 AuthRequest areq;
3985 int res;
3986 bool async;
3987
3988 /*
3989 * Scan the message from current point (note that if we find
3990 * the message is incomplete, we will return without advancing
3991 * inStart, and resume here next time).
3992 */
3994
3995 /* Read type byte */
3996 if (pqGetc(&beresp, conn))
3997 {
3998 /* We'll come back when there is more data */
3999 return PGRES_POLLING_READING;
4000 }
4001
4002 /*
4003 * Validate message type: we expect only an authentication
4004 * request, NegotiateProtocolVersion, or an error here.
4005 * Anything else probably means it's not Postgres on the other
4006 * end at all.
4007 */
4008 if (beresp != PqMsg_AuthenticationRequest &&
4009 beresp != PqMsg_ErrorResponse &&
4011 {
4012 libpq_append_conn_error(conn, "expected authentication request from server, but received %c",
4013 beresp);
4014 goto error_return;
4015 }
4016
4017 /* Read message length word */
4018 if (pqGetInt(&msgLength, 4, conn))
4019 {
4020 /* We'll come back when there is more data */
4021 return PGRES_POLLING_READING;
4022 }
4023
4024 /*
4025 * Try to validate message length before using it.
4026 *
4027 * Authentication requests can't be very large, although GSS
4028 * auth requests may not be that small. Same for
4029 * NegotiateProtocolVersion.
4030 *
4031 * Errors can be a little larger, but not huge. If we see a
4032 * large apparent length in an error, it means we're really
4033 * talking to a pre-3.0-protocol server; cope. (Before
4034 * version 14, the server also used the old protocol for
4035 * errors that happened before processing the startup packet.)
4036 */
4037 if (beresp == PqMsg_AuthenticationRequest &&
4038 (msgLength < 8 || msgLength > 2000))
4039 {
4040 libpq_append_conn_error(conn, "received invalid authentication request");
4041 goto error_return;
4042 }
4043 if (beresp == PqMsg_NegotiateProtocolVersion &&
4044 (msgLength < 8 || msgLength > 2000))
4045 {
4046 libpq_append_conn_error(conn, "received invalid protocol negotiation message");
4047 goto error_return;
4048 }
4049
4050#define MAX_ERRLEN 30000
4051 if (beresp == PqMsg_ErrorResponse &&
4052 (msgLength < 8 || msgLength > MAX_ERRLEN))
4053 {
4054 /* Handle error from a pre-3.0 server */
4055 conn->inCursor = conn->inStart + 1; /* reread data */
4057 {
4058 /*
4059 * We may not have authenticated the server yet, so
4060 * don't let the buffer grow forever.
4061 */
4062 avail = conn->inEnd - conn->inCursor;
4063 if (avail > MAX_ERRLEN)
4064 {
4065 libpq_append_conn_error(conn, "received invalid error message");
4066 goto error_return;
4067 }
4068
4069 /* We'll come back when there is more data */
4070 return PGRES_POLLING_READING;
4071 }
4072 /* OK, we read the message; mark data consumed */
4074
4075 /*
4076 * Before 7.2, the postmaster didn't always end its
4077 * messages with a newline, so add one if needed to
4078 * conform to libpq conventions.
4079 */
4080 if (conn->errorMessage.len == 0 ||
4081 conn->errorMessage.data[conn->errorMessage.len - 1] != '\n')
4082 {
4084 }
4085
4086 goto error_return;
4087 }
4088#undef MAX_ERRLEN
4089
4090 /*
4091 * Can't process if message body isn't all here yet.
4092 *
4093 * After this check passes, any further EOF during parsing
4094 * implies that the server sent a bad/truncated message.
4095 * Reading more bytes won't help in that case, so don't return
4096 * PGRES_POLLING_READING after this point.
4097 */
4098 msgLength -= 4;
4099 avail = conn->inEnd - conn->inCursor;
4100 if (avail < msgLength)
4101 {
4102 /*
4103 * Before returning, try to enlarge the input buffer if
4104 * needed to hold the whole message; see notes in
4105 * pqParseInput3.
4106 */
4107 if (pqCheckInBufferSpace(conn->inCursor + (size_t) msgLength,
4108 conn))
4109 goto error_return;
4110 /* We'll come back when there is more data */
4111 return PGRES_POLLING_READING;
4112 }
4113
4114 /* Handle errors. */
4115 if (beresp == PqMsg_ErrorResponse)
4116 {
4117 if (pqGetErrorNotice3(conn, true))
4118 {
4119 libpq_append_conn_error(conn, "received invalid error message");
4120 goto error_return;
4121 }
4122 /* OK, we read the message; mark data consumed */
4124
4125 /*
4126 * If error is "cannot connect now", try the next host if
4127 * any (but we don't want to consider additional addresses
4128 * for this host, nor is there much point in changing SSL
4129 * or GSS mode). This is helpful when dealing with
4130 * standby servers that might not be in hot-standby state.
4131 */
4132 if (strcmp(conn->last_sqlstate,
4134 {
4135 conn->try_next_host = true;
4136 goto keep_going;
4137 }
4138
4139 /* Check to see if we should mention pgpassfile */
4141
4143 }
4144 /* Handle NegotiateProtocolVersion */
4145 else if (beresp == PqMsg_NegotiateProtocolVersion)
4146 {
4148 {
4149 libpq_append_conn_error(conn, "received duplicate protocol negotiation message");
4150 goto error_return;
4151 }
4153 {
4154 /* pqGetNegotiateProtocolVersion3 set error already */
4155 goto error_return;
4156 }
4157 conn->pversion_negotiated = true;
4158
4159 /* OK, we read the message; mark data consumed */
4161
4162 goto keep_going;
4163 }
4164
4165 /* It is an authentication request. */
4166 conn->auth_req_received = true;
4167
4168 /* Get the type of request. */
4169 if (pqGetInt((int *) &areq, 4, conn))
4170 {
4171 /* can't happen because we checked the length already */
4172 libpq_append_conn_error(conn, "received invalid authentication request");
4173 goto error_return;
4174 }
4175 msgLength -= 4;
4176
4177 /*
4178 * Process the rest of the authentication request message, and
4179 * respond to it if necessary.
4180 *
4181 * Note that conn->pghost must be non-NULL if we are going to
4182 * avoid the Kerberos code doing a hostname look-up.
4183 */
4184 res = pg_fe_sendauth(areq, msgLength, conn, &async);
4185
4186 if (async && (res == STATUS_OK))
4187 {
4188 /*
4189 * We'll come back later once we're ready to respond.
4190 * Don't consume the request yet.
4191 */
4193 goto keep_going;
4194 }
4195
4196 /*
4197 * OK, we have processed the message; mark data consumed. We
4198 * don't call pqParseDone here because we already traced this
4199 * message inside pg_fe_sendauth.
4200 */
4202
4203 if (res != STATUS_OK)
4204 {
4205 /*
4206 * OAuth connections may perform two-step discovery, where
4207 * the first connection is a dummy.
4208 */
4210 {
4211 need_new_connection = true;
4212 goto keep_going;
4213 }
4214
4215 goto error_return;
4216 }
4217
4218 /*
4219 * Just make sure that any data sent by pg_fe_sendauth is
4220 * flushed out. Although this theoretically could block, it
4221 * really shouldn't since we don't send large auth responses.
4222 */
4223 if (pqFlush(conn))
4224 goto error_return;
4225
4226 if (areq == AUTH_REQ_OK)
4227 {
4228 /* We are done with authentication exchange */
4230
4231 /*
4232 * Set asyncStatus so that PQgetResult will think that
4233 * what comes back next is the result of a query. See
4234 * below.
4235 */
4237 }
4238
4239 /* Look to see if we have more data yet. */
4240 goto keep_going;
4241 }
4242
4244 {
4246
4248 {
4249 /* programmer error; should not happen */
4251 "internal error: async authentication has no handler");
4252 goto error_return;
4253 }
4254
4255 /* Drive some external authentication work. */
4256 status = conn->async_auth(conn);
4257
4258 if (status == PGRES_POLLING_FAILED)
4259 goto error_return;
4260
4261 if (status == PGRES_POLLING_OK)
4262 {
4263 /* Done. Tear down the async implementation. */
4265 conn->cleanup_async_auth = NULL;
4266
4267 /*
4268 * Cleanup must unset altsock, both as an indication that
4269 * it's been released, and to stop pqSocketCheck from
4270 * looking at the wrong socket after async auth is done.
4271 */
4273 {
4274 Assert(false);
4276 "internal error: async cleanup did not release polling socket");
4277 goto error_return;
4278 }
4279
4280 /*
4281 * Reenter the authentication exchange with the server. We
4282 * didn't consume the message that started external
4283 * authentication, so it'll be reprocessed as if we just
4284 * received it.
4285 */
4287
4288 goto keep_going;
4289 }
4290
4291 /*
4292 * Caller needs to poll some more. conn->async_auth() should
4293 * have assigned an altsock to poll on.
4294 */
4296 {
4297 Assert(false);
4299 "internal error: async authentication did not set a socket for polling");
4300 goto error_return;
4301 }
4302
4303 return status;
4304 }
4305
4306 case CONNECTION_AUTH_OK:
4307 {
4308 /*
4309 * Now we expect to hear from the backend. A ReadyForQuery
4310 * message indicates that startup is successful, but we might
4311 * also get an Error message indicating failure. (Notice
4312 * messages indicating nonfatal warnings are also allowed by
4313 * the protocol, as are ParameterStatus and BackendKeyData
4314 * messages.) Easiest way to handle this is to let
4315 * PQgetResult() read the messages. We just have to fake it
4316 * out about the state of the connection, by setting
4317 * asyncStatus = PGASYNC_BUSY (done above).
4318 */
4319
4320 if (PQisBusy(conn))
4321 return PGRES_POLLING_READING;
4322
4323 res = PQgetResult(conn);
4324
4325 /*
4326 * NULL return indicating we have gone to IDLE state is
4327 * expected
4328 */
4329 if (res)
4330 {
4331 if (res->resultStatus != PGRES_FATAL_ERROR)
4332 libpq_append_conn_error(conn, "unexpected message from server during startup");
4333 else if (conn->send_appname &&
4334 (conn->appname || conn->fbappname))
4335 {
4336 /*
4337 * If we tried to send application_name, check to see
4338 * if the error is about that --- pre-9.0 servers will
4339 * reject it at this stage of the process. If so,
4340 * close the connection and retry without sending
4341 * application_name. We could possibly get a false
4342 * SQLSTATE match here and retry uselessly, but there
4343 * seems no great harm in that; we'll just get the
4344 * same error again if it's unrelated.
4345 */
4346 const char *sqlstate;
4347
4348 sqlstate = PQresultErrorField(res, PG_DIAG_SQLSTATE);
4349 if (sqlstate &&
4350 strcmp(sqlstate, ERRCODE_APPNAME_UNKNOWN) == 0)
4351 {
4352 PQclear(res);
4353 conn->send_appname = false;
4354 need_new_connection = true;
4355 goto keep_going;
4356 }
4357 }
4358
4359 /*
4360 * if the resultStatus is FATAL, then conn->errorMessage
4361 * already has a copy of the error; needn't copy it back.
4362 * But add a newline if it's not there already, since
4363 * postmaster error messages may not have one.
4364 */
4365 if (conn->errorMessage.len <= 0 ||
4366 conn->errorMessage.data[conn->errorMessage.len - 1] != '\n')
4368 PQclear(res);
4369 goto error_return;
4370 }
4371
4372 /* Almost there now ... */
4374 goto keep_going;
4375 }
4376
4378 {
4379 /*
4380 * If a read-write, read-only, primary, or standby connection
4381 * is required, see if we have one.
4382 */
4385 {
4386 bool read_only_server;
4387
4388 /*
4389 * If the server didn't report
4390 * "default_transaction_read_only" or "in_hot_standby" at
4391 * startup, we must determine its state by sending the
4392 * query "SHOW transaction_read_only". This GUC exists in
4393 * all server versions that support 3.0 protocol.
4394 */
4397 {
4398 /*
4399 * We use PQsendQueryContinue so that
4400 * conn->errorMessage does not get cleared. We need
4401 * to preserve any error messages related to previous
4402 * hosts we have tried and failed to connect to.
4403 */
4406 "SHOW transaction_read_only"))
4407 goto error_return;
4408 /* We'll return to this state when we have the answer */
4410 return PGRES_POLLING_READING;
4411 }
4412
4413 /* OK, we can make the test */
4414 read_only_server =
4417
4419 read_only_server : !read_only_server)
4420 {
4421 /* Wrong server state, reject and try the next host */
4423 libpq_append_conn_error(conn, "session is read-only");
4424 else
4425 libpq_append_conn_error(conn, "session is not read-only");
4426
4427 /* Close connection politely. */
4430
4431 /*
4432 * Try next host if any, but we don't want to consider
4433 * additional addresses for this host.
4434 */
4435 conn->try_next_host = true;
4436 goto keep_going;
4437 }
4438 }
4442 {
4443 /*
4444 * If the server didn't report "in_hot_standby" at
4445 * startup, we must determine its state by sending the
4446 * query "SELECT pg_catalog.pg_is_in_recovery()". Servers
4447 * before 9.0 don't have that function, but by the same
4448 * token they don't have any standby mode, so we may just
4449 * assume the result.
4450 */
4451 if (conn->sversion < 90000)
4453
4455 {
4456 /*
4457 * We use PQsendQueryContinue so that
4458 * conn->errorMessage does not get cleared. We need
4459 * to preserve any error messages related to previous
4460 * hosts we have tried and failed to connect to.
4461 */
4464 "SELECT pg_catalog.pg_is_in_recovery()"))
4465 goto error_return;
4466 /* We'll return to this state when we have the answer */
4468 return PGRES_POLLING_READING;
4469 }
4470
4471 /* OK, we can make the test */
4475 {
4476 /* Wrong server state, reject and try the next host */
4478 libpq_append_conn_error(conn, "server is in hot standby mode");
4479 else
4480 libpq_append_conn_error(conn, "server is not in hot standby mode");
4481
4482 /* Close connection politely. */
4485
4486 /*
4487 * Try next host if any, but we don't want to consider
4488 * additional addresses for this host.
4489 */
4490 conn->try_next_host = true;
4491 goto keep_going;
4492 }
4493 }
4494
4495 /* Don't hold onto any OAuth tokens longer than necessary. */
4497
4498 /*
4499 * For non cancel requests we can release the address list
4500 * now. For cancel requests we never actually resolve
4501 * addresses and instead the addrinfo exists for the lifetime
4502 * of the connection.
4503 */
4504 if (!conn->cancelRequest)
4506
4507 /*
4508 * Contents of conn->errorMessage are no longer interesting
4509 * (and it seems some clients expect it to be empty after a
4510 * successful connection).
4511 */
4513
4514 /* We are open for business! */
4516 return PGRES_POLLING_OK;
4517 }
4518
4519 case CONNECTION_CONSUME:
4520 {
4521 /*
4522 * This state just makes sure the connection is idle after
4523 * we've obtained the result of a SHOW or SELECT query. Once
4524 * we're clear, return to CONNECTION_CHECK_TARGET state to
4525 * decide what to do next. We must transiently set status =
4526 * CONNECTION_OK in order to use the result-consuming
4527 * subroutines.
4528 */
4530 if (!PQconsumeInput(conn))
4531 goto error_return;
4532
4533 if (PQisBusy(conn))
4534 {
4536 return PGRES_POLLING_READING;
4537 }
4538
4539 /* Call PQgetResult() again until we get a NULL result */
4540 res = PQgetResult(conn);
4541 if (res != NULL)
4542 {
4543 PQclear(res);
4545 return PGRES_POLLING_READING;
4546 }
4547
4549 goto keep_going;
4550 }
4551
4553 {
4554 /*
4555 * Waiting for result of "SHOW transaction_read_only". We
4556 * must transiently set status = CONNECTION_OK in order to use
4557 * the result-consuming subroutines.
4558 */
4560 if (!PQconsumeInput(conn))
4561 goto error_return;
4562
4563 if (PQisBusy(conn))
4564 {
4566 return PGRES_POLLING_READING;
4567 }
4568
4569 res = PQgetResult(conn);
4570 if (res && PQresultStatus(res) == PGRES_TUPLES_OK &&
4571 PQntuples(res) == 1)
4572 {
4573 char *val = PQgetvalue(res, 0, 0);
4574
4575 /*
4576 * "transaction_read_only = on" proves that at least one
4577 * of default_transaction_read_only and in_hot_standby is
4578 * on, but we don't actually know which. We don't care
4579 * though for the purpose of identifying a read-only
4580 * session, so satisfy the CONNECTION_CHECK_TARGET code by
4581 * claiming they are both on. On the other hand, if it's
4582 * a read-write session, they are certainly both off.
4583 */
4584 if (strncmp(val, "on", 2) == 0)
4585 {
4588 }
4589 else
4590 {
4593 }
4594 PQclear(res);
4595
4596 /* Finish reading messages before continuing */
4598 goto keep_going;
4599 }
4600
4601 /* Something went wrong with "SHOW transaction_read_only". */
4602 PQclear(res);
4603
4604 /* Append error report to conn->errorMessage. */
4605 libpq_append_conn_error(conn, "\"%s\" failed",
4606 "SHOW transaction_read_only");
4607
4608 /* Close connection politely. */
4611
4612 /* Try next host. */
4613 conn->try_next_host = true;
4614 goto keep_going;
4615 }
4616
4618 {
4619 /*
4620 * Waiting for result of "SELECT pg_is_in_recovery()". We
4621 * must transiently set status = CONNECTION_OK in order to use
4622 * the result-consuming subroutines.
4623 */
4625 if (!PQconsumeInput(conn))
4626 goto error_return;
4627
4628 if (PQisBusy(conn))
4629 {
4631 return PGRES_POLLING_READING;
4632 }
4633
4634 res = PQgetResult(conn);
4635 if (res && PQresultStatus(res) == PGRES_TUPLES_OK &&
4636 PQntuples(res) == 1)
4637 {
4638 char *val = PQgetvalue(res, 0, 0);
4639
4640 if (strncmp(val, "t", 1) == 0)
4642 else
4644 PQclear(res);
4645
4646 /* Finish reading messages before continuing */
4648 goto keep_going;
4649 }
4650
4651 /* Something went wrong with "SELECT pg_is_in_recovery()". */
4652 PQclear(res);
4653
4654 /* Append error report to conn->errorMessage. */
4655 libpq_append_conn_error(conn, "\"%s\" failed",
4656 "SELECT pg_is_in_recovery()");
4657
4658 /* Close connection politely. */
4661
4662 /* Try next host. */
4663 conn->try_next_host = true;
4664 goto keep_going;
4665 }
4666
4667 default:
4669 "invalid connection state %d, probably indicative of memory corruption",
4670 conn->status);
4671 goto error_return;
4672 }
4673
4674 /* Unreachable */
4675
4676error_return:
4677
4678 /*
4679 * We used to close the socket at this point, but that makes it awkward
4680 * for those above us if they wish to remove this socket from their own
4681 * records (an fd_set for example). We'll just have this socket closed
4682 * when PQfinish is called (which is compulsory even after an error, since
4683 * the connection structure must be freed).
4684 */
4686 return PGRES_POLLING_FAILED;
4687}
#define STATUS_OK
Definition: c.h:1140
#define MemSet(start, val, len)
Definition: c.h:991
void err(int eval, const char *fmt,...)
Definition: err.c:43
const pg_fe_sasl_mech pg_oauth_mech
Definition: fe-auth-oauth.c:35
void pqClearOAuthToken(PGconn *conn)
int pg_fe_sendauth(AuthRequest areq, int payloadlen, PGconn *conn, bool *async)
Definition: fe-auth.c:1066
char * pg_fe_getusername(uid_t user_id, PQExpBuffer errorMessage)
Definition: fe-auth.c:1286
int PQsendCancelRequest(PGconn *cancelConn)
Definition: fe-cancel.c:454
#define MAX_ERRLEN
void pqDropConnection(PGconn *conn, bool flushInput)
Definition: fe-connect.c:520
static const PQEnvironmentOption EnvironmentOptions[]
Definition: fe-connect.c:413
#define CONNECTION_FAILED()
static void sendTerminateConn(PGconn *conn)
Definition: fe-connect.c:5209
static int setKeepalivesCount(PGconn *conn)
Definition: fe-connect.c:2565
static int useKeepalives(PGconn *conn)
Definition: fe-connect.c:2478
static int store_conn_addrinfo(PGconn *conn, struct addrinfo *addrlist)
Definition: fe-connect.c:5156
static void connectFailureMessage(PGconn *conn, int errorno)
Definition: fe-connect.c:2458
static void release_conn_addrinfo(PGconn *conn)
Definition: fe-connect.c:5195
#define ERRCODE_APPNAME_UNKNOWN
Definition: fe-connect.c:89
static int setKeepalivesInterval(PGconn *conn)
Definition: fe-connect.c:2530
static int setKeepalivesIdle(PGconn *conn)
Definition: fe-connect.c:2496
bool pqParseIntParam(const char *value, int *result, PGconn *conn, const char *context)
Definition: fe-connect.c:8177
static void pgpassfileWarning(PGconn *conn)
Definition: fe-connect.c:8034
static void emitHostIdentityInfo(PGconn *conn, const char *host_addr)
Definition: fe-connect.c:2402
static int setTCPUserTimeout(PGconn *conn)
Definition: fe-connect.c:2662
static void pqDropServerData(PGconn *conn)
Definition: fe-connect.c:646
static int connectNoDelay(PGconn *conn)
Definition: fe-connect.c:2343
static void getHostaddr(PGconn *conn, char *host_addr, int host_addr_len)
Definition: fe-connect.c:2369
#define ERRCODE_CANNOT_CONNECT_NOW
Definition: fe-connect.c:94
#define ENCRYPTION_NEGOTIATION_FAILED(msg)
static bool init_allowed_encryption_methods(PGconn *conn)
Definition: fe-connect.c:4693
int pqPacketSend(PGconn *conn, char pack_type, const void *buf, size_t buf_len)
Definition: fe-connect.c:5398
int PQsendQueryContinue(PGconn *conn, const char *query)
Definition: fe-exec.c:1422
char * PQgetvalue(const PGresult *res, int tup_num, int field_num)
Definition: fe-exec.c:3876
PGresult * PQgetResult(PGconn *conn)
Definition: fe-exec.c:2062
int PQntuples(const PGresult *res)
Definition: fe-exec.c:3481
int PQconsumeInput(PGconn *conn)
Definition: fe-exec.c:1984
void pqClearAsyncResult(PGconn *conn)
Definition: fe-exec.c:779
char * PQresultErrorField(const PGresult *res, int fieldcode)
Definition: fe-exec.c:3466
int PQisBusy(PGconn *conn)
Definition: fe-exec.c:2031
bool pg_GSS_have_cred_cache(gss_cred_id_t *cred_out)
int pqFlush(PGconn *conn)
Definition: fe-misc.c:968
void pqParseDone(PGconn *conn, int newInStart)
Definition: fe-misc.c:443
int pqGetc(char *result, PGconn *conn)
Definition: fe-misc.c:77
int pqGetInt(int *result, size_t bytes, PGconn *conn)
Definition: fe-misc.c:216
int pqCheckInBufferSpace(size_t bytes_needed, PGconn *conn)
Definition: fe-misc.c:351
int pqGets_append(PQExpBuffer buf, PGconn *conn)
Definition: fe-misc.c:142
char * pqBuildStartupPacket3(PGconn *conn, int *packetlen, const PQEnvironmentOption *options)
int pqGetNegotiateProtocolVersion3(PGconn *conn)
int pqGetErrorNotice3(PGconn *conn, bool isError)
Definition: fe-protocol3.c:878
PostgresPollingStatusType pqsecure_open_gss(PGconn *conn)
PostgresPollingStatusType pqsecure_open_client(PGconn *conn)
Definition: fe-secure.c:138
void pqTraceOutputCharResponse(PGconn *conn, const char *responseType, char response)
Definition: fe-trace.c:915
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:78
@ PGASYNC_IDLE
Definition: libpq-int.h:215
@ PGASYNC_BUSY
Definition: libpq-int.h:216
#define libpq_gettext(x)
Definition: libpq-int.h:938
@ LOAD_BALANCE_RANDOM
Definition: libpq-int.h:250
#define SOCK_STRERROR
Definition: libpq-int.h:960
#define ENC_GSSAPI
Definition: libpq-int.h:231
#define ENC_SSL
Definition: libpq-int.h:232
@ 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 pg_hton32(x)
Definition: pg_bswap.h:121
#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:116
bool pg_set_noblock(pgsocket sock)
Definition: noblock.c:25
#define snprintf
Definition: port.h:239
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:52
#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:173
#define NEGOTIATE_SSL_CODE
Definition: pqcomm.h:172
uint32 ProtocolVersion
Definition: pqcomm.h:99
uint32 AuthRequest
Definition: pqcomm.h:121
void appendPQExpBufferChar(PQExpBuffer str, char ch)
Definition: pqexpbuffer.c:378
#define AUTH_REQ_OK
Definition: protocol.h:74
#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
pg_conn_host_type type
Definition: libpq-int.h:357
SockAddr laddr
Definition: libpq-int.h:498
bool try_next_host
Definition: libpq-int.h:535
AddrInfo * addr
Definition: libpq-int.h:538
uint8 failed_enc_methods
Definition: libpq-int.h:604
char * sslnegotiation
Definition: libpq-int.h:404
bool sigpipe_flag
Definition: libpq-int.h:508
int nconnhost
Definition: libpq-int.h:477
bool send_appname
Definition: libpq-int.h:540
PGTransactionStatusType xactStatus
Definition: libpq-int.h:461
const pg_fe_sasl_mech * sasl
Definition: libpq-int.h:599
bool cancelRequest
Definition: libpq-int.h:431
int inCursor
Definition: libpq-int.h:567
PGTernaryBool in_hot_standby
Definition: libpq-int.h:556
void(* cleanup_async_auth)(PGconn *conn)
Definition: libpq-int.h:526
int inEnd
Definition: libpq-int.h:568
char * fbappname
Definition: libpq-int.h:388
uint8 current_enc_method
Definition: libpq-int.h:605
int naddr
Definition: libpq-int.h:536
int inStart
Definition: libpq-int.h:566
char * connip
Definition: libpq-int.h:480
int sversion
Definition: libpq-int.h:501
bool auth_req_received
Definition: libpq-int.h:504
bool pversion_negotiated
Definition: libpq-int.h:502
bool oauth_want_retry
Definition: libpq-int.h:444
PGTernaryBool default_transaction_read_only
Definition: libpq-int.h:555
bool sigpipe_so
Definition: libpq-int.h:507
int whichaddr
Definition: libpq-int.h:537
char * appname
Definition: libpq-int.h:387
pg_prng_state prng_state
Definition: libpq-int.h:560
char * gssencmode
Definition: libpq-int.h:415
pgsocket altsock
Definition: libpq-int.h:527
ProtocolVersion max_pversion
Definition: libpq-int.h:546
PostgresPollingStatusType(* async_auth)(PGconn *conn)
Definition: libpq-int.h:525
char last_sqlstate[6]
Definition: libpq-int.h:462
PGAsyncStatusType asyncStatus
Definition: libpq-int.h:460
PGLoadBalanceType load_balance_type
Definition: libpq-int.h:532
PGpipelineStatus pipelineStatus
Definition: libpq-int.h:466
uint8 allowed_enc_methods
Definition: libpq-int.h:603
PGTargetServerType target_server_type
Definition: libpq-int.h:531
FILE * Pfdebug
Definition: libpq-int.h:447
bool try_next_addr
Definition: libpq-int.h:534
char * requirepeer
Definition: libpq-int.h:414
bool ssl_in_use
Definition: libpq-int.h:608
#define EWOULDBLOCK
Definition: win32_port.h:370
#define EINPROGRESS
Definition: win32_port.h:376
int gid_t
Definition: win32_port.h:235
int uid_t
Definition: win32_port.h:234

References SockAddr::addr, AddrInfo::addr, pg_conn::addr, pg_conn::allowed_enc_methods, pg_conn::altsock, appendPQExpBufferChar(), pg_conn::appname, Assert(), pg_conn::async_auth, pg_conn::asyncStatus, AUTH_REQ_OK, pg_conn::auth_req_received, pg_conn::cancelRequest, CHT_HOST_ADDRESS, CHT_HOST_NAME, CHT_UNIX_SOCKET, pg_conn::cleanup_async_auth, conn, connect, connectFailureMessage(), CONNECTION_AUTH_OK, CONNECTION_AUTHENTICATING, CONNECTION_AWAITING_RESPONSE, CONNECTION_BAD, CONNECTION_CHECK_STANDBY, CONNECTION_CHECK_TARGET, CONNECTION_CHECK_WRITABLE, CONNECTION_CONSUME, CONNECTION_FAILED, CONNECTION_GSS_STARTUP, CONNECTION_MADE, CONNECTION_NEEDED, CONNECTION_OK, CONNECTION_SSL_STARTUP, CONNECTION_STARTED, connectNoDelay(), pg_conn::connhost, pg_conn::connip, pg_conn::current_enc_method, PQExpBufferData::data, pg_conn::default_transaction_read_only, EINPROGRESS, EINTR, emitHostIdentityInfo(), ENC_GSSAPI, ENC_SSL, ENCRYPTION_NEGOTIATION_FAILED, EnvironmentOptions, err(), ERRCODE_APPNAME_UNKNOWN, ERRCODE_CANNOT_CONNECT_NOW, pg_conn::errorMessage, EWOULDBLOCK, pg_conn::failed_enc_methods, 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, init_allowed_encryption_methods(), pg_conn::inStart, j, pg_conn::laddr, pg_conn::last_sqlstate, PQExpBufferData::len, libpq_append_conn_error(), libpq_gettext, LOAD_BALANCE_RANDOM, pg_conn::load_balance_type, MAX_ERRLEN, pg_conn::max_pversion, MAXPGPATH, MemSet, pg_conn::naddr, pg_conn::nconnhost, NEGOTIATE_GSS_CODE, NEGOTIATE_SSL_CODE, pg_conn::oauth_want_retry, pg_conn::Pfdebug, 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_oauth_mech, pg_prng_uint64_range(), 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, pqClearOAuthToken(), PQconsumeInput(), pqDropConnection(), pqDropServerData(), pqFlush(), pqGetc(), pqGetErrorNotice3(), pqGetInt(), pqGetNegotiateProtocolVersion3(), PQgetResult(), pqGets_append(), PQgetvalue(), PQisBusy(), PqMsg_AuthenticationRequest, PqMsg_ErrorResponse, PqMsg_NegotiateProtocolVersion, PQntuples(), pqPacketSend(), pqParseDone(), pqParseIntParam(), pqReadData(), PQresultErrorField(), PQresultStatus(), pqsecure_open_client(), pqsecure_open_gss(), PQsendCancelRequest(), PQsendQueryContinue(), pqTraceOutputCharResponse(), PQTRANS_IDLE, pg_conn::prng_state, pg_conn::pversion, pg_conn::pversion_negotiated, pg_conn::raddr, release_conn_addrinfo(), pg_conn::requirepeer, pg_result::resultStatus, SockAddr::salen, pg_conn::sasl, 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::sslnegotiation, 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 libpqsrv_connect_internal(), main(), PQcancelPoll(), pqConnectDBComplete(), pqConnectDBStart(), PQresetPoll(), process_slot(), and wait_until_connected().

◆ PQconnectStart()

PGconn * PQconnectStart ( const char *  conninfo)

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

942{
943 PGconn *conn;
944
945 /*
946 * Allocate memory for the conn structure. Note that we also expect this
947 * to initialize conn->errorMessage to empty. All subsequent steps during
948 * connection initialization will only append to that buffer.
949 */
951 if (conn == NULL)
952 return NULL;
953
954 /*
955 * Parse the conninfo string
956 */
957 if (!connectOptions1(conn, conninfo))
958 return conn;
959
960 /*
961 * Compute derived options
962 */
964 return conn;
965
966 /*
967 * Connect to the database
968 */
970 {
971 /* Just in case we failed to set it in pqConnectDBStart */
973 }
974
975 return conn;
976}
static bool connectOptions1(PGconn *conn, const char *conninfo)
Definition: fe-connect.c:1066

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

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

◆ PQconnectStartParams()

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

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

863{
864 PGconn *conn;
865 PQconninfoOption *connOptions;
866
867 /*
868 * Allocate memory for the conn structure. Note that we also expect this
869 * to initialize conn->errorMessage to empty. All subsequent steps during
870 * connection initialization will only append to that buffer.
871 */
873 if (conn == NULL)
874 return NULL;
875
876 /*
877 * Parse the conninfo arrays
878 */
879 connOptions = conninfo_array_parse(keywords, values,
881 true, expand_dbname);
882 if (connOptions == NULL)
883 {
885 /* errorMessage is already set */
886 return conn;
887 }
888
889 /*
890 * Move option values into conn structure
891 */
892 if (!fillPGconn(conn, connOptions))
893 {
894 PQconninfoFree(connOptions);
895 return conn;
896 }
897
898 /*
899 * Free the option info - all is in conn now
900 */
901 PQconninfoFree(connOptions);
902
903 /*
904 * Compute derived options
905 */
907 return conn;
908
909 /*
910 * Connect to the database
911 */
913 {
914 /* Just in case we failed to set it in pqConnectDBStart */
916 }
917
918 return conn;
919}
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:6441
static bool fillPGconn(PGconn *conn, PQconninfoOption *connOptions)
Definition: fe-connect.c:987

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

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

◆ PQconninfo()

PQconninfoOption * PQconninfo ( PGconn conn)

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

7391{
7392 PQExpBufferData errorBuf;
7393 PQconninfoOption *connOptions;
7394
7395 if (conn == NULL)
7396 return NULL;
7397
7398 /*
7399 * We don't actually report any errors here, but callees want a buffer,
7400 * and we prefer not to trash the conn's errorMessage.
7401 */
7402 initPQExpBuffer(&errorBuf);
7403 if (PQExpBufferDataBroken(errorBuf))
7404 return NULL; /* out of memory already :-( */
7405
7406 connOptions = conninfo_init(&errorBuf);
7407
7408 if (connOptions != NULL)
7409 {
7411
7412 for (option = PQconninfoOptions; option->keyword; option++)
7413 {
7414 char **connmember;
7415
7416 if (option->connofs < 0)
7417 continue;
7418
7419 connmember = (char **) ((char *) conn + option->connofs);
7420
7421 if (*connmember)
7422 conninfo_storeval(connOptions, option->keyword, *connmember,
7423 &errorBuf, true, false);
7424 }
7425 }
7426
7427 termPQExpBuffer(&errorBuf);
7428
7429 return connOptions;
7430}
static PQconninfoOption * conninfo_storeval(PQconninfoOption *connOptions, const char *keyword, const char *value, PQExpBuffer errorMessage, bool ignoreMissing, bool uri_decode)
Definition: fe-connect.c:7308
static const internalPQconninfoOption PQconninfoOptions[]
Definition: fe-connect.c:193

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

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

◆ PQconninfoFree()

◆ PQconninfoParse()

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

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

6151{
6152 PQExpBufferData errorBuf;
6153 PQconninfoOption *connOptions;
6154
6155 if (errmsg)
6156 *errmsg = NULL; /* default */
6157 initPQExpBuffer(&errorBuf);
6158 if (PQExpBufferDataBroken(errorBuf))
6159 return NULL; /* out of memory already :-( */
6160 connOptions = parse_connection_string(conninfo, &errorBuf, false);
6161 if (connOptions == NULL && errmsg)
6162 *errmsg = errorBuf.data;
6163 else
6164 termPQExpBuffer(&errorBuf);
6165 return connOptions;
6166}
int errmsg(const char *fmt,...)
Definition: elog.c:1071
static PQconninfoOption * parse_connection_string(const char *connstr, PQExpBuffer errorMessage, bool use_defaults)
Definition: fe-connect.c:6211

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

Referenced by ConnectDatabase(), dblink_connstr_has_pw(), dblink_connstr_has_required_scram_options(), do_connect(), get_base_conninfo(), GetConnection(), GetDbnameFromConnectionOptions(), libpqrcv_check_conninfo(), libpqrcv_get_dbname_from_conninfo(), and main().

◆ PQconsumeInput()

int PQconsumeInput ( PGconn conn)

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

1985{
1986 if (!conn)
1987 return 0;
1988
1989 /*
1990 * for non-blocking connections try to flush the send-queue, otherwise we
1991 * may never get a response for something that may not have already been
1992 * sent because it's in our write buffer!
1993 */
1994 if (pqIsnonblocking(conn))
1995 {
1996 if (pqFlush(conn) < 0)
1997 return 0;
1998 }
1999
2000 /*
2001 * Load more data, if available. We do this no matter what state we are
2002 * in, since we are probably getting called because the application wants
2003 * to get rid of a read-select condition. Note that we will NOT block
2004 * waiting for more input.
2005 */
2006 if (pqReadData(conn) < 0)
2007 return 0;
2008
2009 /* Parsing of the data waits till later. */
2010 return 1;
2011}
#define pqIsnonblocking(conn)
Definition: libpq-int.h:927

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_receive(), libpqsrv_get_result(), main(), pgfdw_cancel_query_end(), pgfdw_exec_cleanup_query_end(), pgfdw_get_cleanup_result(), postgresForeignAsyncNotify(), PQconnectPoll(), PrintNotifications(), process_slot(), 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 318 of file fe-exec.c.

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

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

◆ PQdefaultAuthDataHook()

int PQdefaultAuthDataHook ( PGauthData  type,
PGconn conn,
void *  data 
)

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

1602{
1603 return 0; /* handle nothing */
1604}

Referenced by PQsetAuthDataHook().

◆ PQdefaultSSLKeyPassHook_OpenSSL()

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

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

1901{
1902 if (conn && conn->sslpassword)
1903 {
1904 if (strlen(conn->sslpassword) + 1 > size)
1905 fprintf(stderr, libpq_gettext("WARNING: sslpassword truncated\n"));
1906 strncpy(buf, conn->sslpassword, size);
1907 buf[size - 1] = '\0';
1908 return strlen(buf);
1909 }
1910 else
1911 {
1912 buf[0] = '\0';
1913 return 0;
1914 }
1915}
#define fprintf(file, fmt, msg)
Definition: cubescan.l:21
char * sslpassword
Definition: libpq-int.h:408

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

Referenced by PQssl_passwd_cb().

◆ PQdescribePortal()

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

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

2475{
2476 if (!PQexecStart(conn))
2477 return NULL;
2478 if (!PQsendTypedCommand(conn, PqMsg_Describe, 'P', portal))
2479 return NULL;
2480 return PQexecFinish(conn);
2481}
#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 2455 of file fe-exec.c.

2456{
2457 if (!PQexecStart(conn))
2458 return NULL;
2460 return NULL;
2461 return PQexecFinish(conn);
2462}

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:3887
char * PQfname(const PGresult *res, int field_num)
Definition: fe-exec.c:3567
int PQnfields(const PGresult *res)
Definition: fe-exec.c:3489
static void fill(int length, int max, char filler, FILE *fp)
Definition: fe-print.c:755
#define DEFAULT_FIELD_SEP

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

◆ PQdsplen()

int PQdsplen ( const char *  s,
int  encoding 
)

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

1254{
1255 return pg_encoding_dsplen(encoding, s);
1256}
int pg_encoding_dsplen(int encoding, const char *mbstr)
Definition: wchar.c:2137

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 1363 of file fe-auth.c.

1364{
1365 char *crypt_pwd;
1366 const char *errstr = NULL;
1367
1368 crypt_pwd = malloc(MD5_PASSWD_LEN + 1);
1369 if (!crypt_pwd)
1370 return NULL;
1371
1372 if (!pg_md5_encrypt(passwd, user, strlen(user), crypt_pwd, &errstr))
1373 {
1374 free(crypt_pwd);
1375 return NULL;
1376 }
1377
1378 return crypt_pwd;
1379}
#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 1406 of file fe-auth.c.

1408{
1409#define MAX_ALGORITHM_NAME_LEN 50
1410 char algobuf[MAX_ALGORITHM_NAME_LEN + 1];
1411 char *crypt_pwd = NULL;
1412
1413 if (!conn)
1414 return NULL;
1415
1417
1418 /* If no algorithm was given, ask the server. */
1419 if (algorithm == NULL)
1420 {
1421 PGresult *res;
1422 char *val;
1423
1424 res = PQexec(conn, "show password_encryption");
1425 if (res == NULL)
1426 {
1427 /* PQexec() should've set conn->errorMessage already */
1428 return NULL;
1429 }
1430 if (PQresultStatus(res) != PGRES_TUPLES_OK)
1431 {
1432 /* PQexec() should've set conn->errorMessage already */
1433 PQclear(res);
1434 return NULL;
1435 }
1436 if (PQntuples(res) != 1 || PQnfields(res) != 1)
1437 {
1438 PQclear(res);
1439 libpq_append_conn_error(conn, "unexpected shape of result set returned for SHOW");
1440 return NULL;
1441 }
1442 val = PQgetvalue(res, 0, 0);
1443
1444 if (strlen(val) > MAX_ALGORITHM_NAME_LEN)
1445 {
1446 PQclear(res);
1447 libpq_append_conn_error(conn, "\"password_encryption\" value too long");
1448 return NULL;
1449 }
1450 strcpy(algobuf, val);
1451 PQclear(res);
1452
1453 algorithm = algobuf;
1454 }
1455
1456 /*
1457 * Also accept "on" and "off" as aliases for "md5", because
1458 * password_encryption was a boolean before PostgreSQL 10. We refuse to
1459 * send the password in plaintext even if it was "off".
1460 */
1461 if (strcmp(algorithm, "on") == 0 ||
1462 strcmp(algorithm, "off") == 0)
1463 algorithm = "md5";
1464
1465 /*
1466 * Ok, now we know what algorithm to use
1467 */
1468 if (strcmp(algorithm, "scram-sha-256") == 0)
1469 {
1470 const char *errstr = NULL;
1471
1472 crypt_pwd = pg_fe_scram_build_secret(passwd,
1474 &errstr);
1475 if (!crypt_pwd)
1476 libpq_append_conn_error(conn, "could not encrypt password: %s", errstr);
1477 }
1478 else if (strcmp(algorithm, "md5") == 0)
1479 {
1480 crypt_pwd = malloc(MD5_PASSWD_LEN + 1);
1481 if (crypt_pwd)
1482 {
1483 const char *errstr = NULL;
1484
1485 if (!pg_md5_encrypt(passwd, user, strlen(user), crypt_pwd, &errstr))
1486 {
1487 libpq_append_conn_error(conn, "could not encrypt password: %s", errstr);
1488 free(crypt_pwd);
1489 crypt_pwd = NULL;
1490 }
1491 }
1492 else
1493 libpq_append_conn_error(conn, "out of memory");
1494 }
1495 else
1496 {
1497 libpq_append_conn_error(conn, "unrecognized password encryption algorithm \"%s\"",
1498 algorithm);
1499 return NULL;
1500 }
1501
1502 return crypt_pwd;
1503}
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:601

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(), pg_conn::scram_sha_256_iterations, user, and val.

Referenced by main(), and PQchangePassword().

◆ PQendcopy()

int PQendcopy ( PGconn conn)

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

2950{
2951 if (!conn)
2952 return 0;
2953
2954 return pqEndcopy3(conn);
2955}
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 3042 of file fe-exec.c.

3043{
3044 if (!conn)
3045 return 0;
3046
3047 /* succeed with no action if already in pipeline mode */
3049 return 1;
3050
3052 {
3053 libpq_append_conn_error(conn, "cannot enter pipeline mode, connection not idle");
3054 return 0;
3055 }
3056
3058
3059 return 1;
3060}

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

Referenced by ExecQueryAndProcessResults(), 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 1262 of file fe-misc.c.

1263{
1264 char *str;
1265 int encoding = PG_SQL_ASCII;
1266
1267 str = getenv("PGCLIENTENCODING");
1268 if (str && *str != '\0')
1269 {
1271 if (encoding < 0)
1273 }
1274 return encoding;
1275}
const char * str
@ PG_SQL_ASCII
Definition: pg_wchar.h:226
#define pg_char_to_encoding
Definition: pg_wchar.h:629

References encoding, pg_char_to_encoding, PG_SQL_ASCII, and str.

Referenced by main().

◆ PQerrorMessage()

char * PQerrorMessage ( const PGconn conn)

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

7620{
7621 if (!conn)
7622 return libpq_gettext("connection pointer is NULL\n");
7623
7624 /*
7625 * The errorMessage buffer might be marked "broken" due to having
7626 * previously failed to allocate enough memory for the message. In that
7627 * case, tell the application we ran out of memory.
7628 */
7630 return libpq_gettext("out of memory\n");
7631
7632 return conn->errorMessage.data;
7633}
#define PQExpBufferBroken(str)
Definition: pqexpbuffer.h:59

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

Referenced by _doSetSessionAuth(), _printTableAccessMethodNoStorage(), _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_database(), connect_pg_server(), ConnectDatabase(), connectDatabase(), connectToServer(), copy_connection(), CopyStreamPoll(), CopyStreamReceive(), CreateReplicationSlot(), dblink_connect(), dblink_error_message(), dblink_get_conn(), dblink_res_error(), dblink_res_internalerror(), 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(), escape_identifier(), escape_literal(), escape_string_conn(), exec_command_password(), ExecQueryAndProcessResults(), executeCommand(), executeQuery(), executeQueryOrDie(), ExecuteSqlCommand(), ExecuteSqlCommandBuf(), executeStatement(), get_table_relkind(), 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_global_sql_commands(), process_query_result(), process_queued_fetch_requests(), process_result(), process_slot(), 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_one_vector(), test_pipeline_abort(), test_pipeline_idle(), test_pipelined_insert(), test_prepared(), test_protocol_version(), 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 4528 of file fe-exec.c.

4529{
4530 return PQescapeByteaInternal(NULL, from, from_length, to_length,
4532 false /* can't use hex */ );
4533}
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:4416
static bool static_std_strings
Definition: fe-exec.c:60

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

4515{
4516 if (!conn)
4517 return NULL;
4518
4519 if (conn->cmd_queue_head == NULL)
4521
4522 return PQescapeByteaInternal(conn, from, from_length, to_length,
4524 (conn->sversion >= 90000));
4525}
bool std_strings
Definition: libpq-int.h:554
PGcmdQueueEntry * cmd_queue_head
Definition: libpq-int.h:486

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

4370{
4371 return PQescapeInternal(conn, str, len, true);
4372}
static char * PQescapeInternal(PGconn *conn, const char *str, size_t len, bool as_ident)
Definition: fe-exec.c:4213

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

Referenced by create_publication(), create_subscription(), drop_publication(), enable_subscription(), escape_identifier(), initCreatePKeys(), initCreateTables(), main(), PQchangePassword(), psql_get_variable(), stringlist_to_identifierstr(), and vacuumlo().

◆ PQescapeLiteral()

◆ PQescapeString()

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

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

4199{
4200 return PQescapeStringInternal(NULL, to, from, length, NULL,
4203}
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:4071
static int static_client_encoding
Definition: fe-exec.c:59

References PQescapeStringInternal(), static_client_encoding, and static_std_strings.

Referenced by escape_string(), 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 4176 of file fe-exec.c.

4179{
4180 if (!conn)
4181 {
4182 /* force empty-string result */
4183 *to = '\0';
4184 if (error)
4185 *error = 1;
4186 return 0;
4187 }
4188
4189 if (conn->cmd_queue_head == NULL)
4191
4192 return PQescapeStringInternal(conn, to, from, length, error,
4194 conn->std_strings);
4195}
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(), do_lo_import(), and escape_string_conn().

◆ PQexec()

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

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

2263{
2264 if (!PQexecStart(conn))
2265 return NULL;
2266 if (!PQsendQuery(conn, query))
2267 return NULL;
2268 return PQexecFinish(conn);
2269}
int PQsendQuery(PGconn *conn, const char *query)
Definition: fe-exec.c:1416

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

Referenced by _doSetSessionAuth(), _printTableAccessMethodNoStorage(), _selectOutputSchema(), _selectTableAccessMethod(), _selectTablespace(), check_and_drop_existing_subscriptions(), check_and_drop_publications(), check_loadable_libraries(), check_prepare_conn(), check_publisher(), check_subscriber(), connect_database(), create_logical_replication_slot(), create_publication(), create_subscription(), CreateReplicationSlot(), deallocate_one(), DescribeQuery(), drop_existing_subscriptions(), drop_failover_replication_slots(), drop_publication(), drop_replication_slot(), DropReplicationSlot(), ecpg_autostart_transaction(), ecpg_execute(), ecpg_is_type_an_array(), ECPGsetcommit(), ECPGtrans(), enable_subscription(), executeCommand(), executeMaintenanceCommand(), executeQuery(), executeQueryOrDie(), ExecuteSqlCommand(), ExecuteSqlQuery(), ExecuteSqlStatement(), executeStatement(), generate_object_name(), get_create_object_cmd(), get_primary_sysid(), get_publisher_databases(), GetConnection(), GetSlotInformation(), GetTableInfo(), init_libpq_conn(), initPopulateTable(), libpq_traverse_files(), lo_initialize(), lockTableForWorker(), lookup_object_oid(), main(), PQchangePassword(), PQencryptPasswordConn(), PQsetClientEncoding(), process_global_sql_commands(), PSQLexec(), ReceiveXlogStream(), RetrieveDataDirCreatePerm(), RetrieveWalSegSize(), run_permutation(), run_simple_command(), run_simple_query(), RunIdentifySystem(), SendQuery(), server_is_in_recovery(), set_replication_progress(), setup_publisher(), 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 2276 of file fe-exec.c.

2284{
2285 if (!PQexecStart(conn))
2286 return NULL;
2287 if (!PQsendQueryParams(conn, command,
2288 nParams, paramTypes, paramValues, paramLengths,
2289 paramFormats, resultFormat))
2290 return NULL;
2291 return PQexecFinish(conn);
2292}
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:1492

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

Referenced by ecpg_execute(), get_table_relkind(), 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 2323 of file fe-exec.c.

2330{
2331 if (!PQexecStart(conn))
2332 return NULL;
2333 if (!PQsendQueryPrepared(conn, stmtName,
2334 nParams, paramValues, paramLengths,
2335 paramFormats, resultFormat))
2336 return NULL;
2337 return PQexecFinish(conn);
2338}
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:1633

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

Referenced by ecpg_execute(), and try_complete_step().

◆ PQexitPipelineMode()

int PQexitPipelineMode ( PGconn conn)

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

3074{
3075 if (!conn)
3076 return 0;
3077
3081 conn->cmd_queue_head == NULL)
3082 return 1;
3083
3084 switch (conn->asyncStatus)
3085 {
3086 case PGASYNC_READY:
3087 case PGASYNC_READY_MORE:
3088 /* there are some uncollected results */
3089 libpq_append_conn_error(conn, "cannot exit pipeline mode with uncollected results");
3090 return 0;
3091
3092 case PGASYNC_BUSY:
3093 libpq_append_conn_error(conn, "cannot exit pipeline mode while busy");
3094 return 0;
3095
3096 case PGASYNC_IDLE:
3098 /* OK */
3099 break;
3100
3101 case PGASYNC_COPY_IN:
3102 case PGASYNC_COPY_OUT:
3103 case PGASYNC_COPY_BOTH:
3104 libpq_append_conn_error(conn, "cannot exit pipeline mode while in COPY");
3105 }
3106
3107 /* still work to process */
3108 if (conn->cmd_queue_head != NULL)
3109 {
3110 libpq_append_conn_error(conn, "cannot exit pipeline mode with uncollected results");
3111 return 0;
3112 }
3113
3116
3117 /* Flush any pending data in out buffer */
3118 if (pqFlush(conn) < 0)
3119 return 0; /* error message is setup already */
3120 return 1;
3121}
@ PGASYNC_COPY_OUT
Definition: libpq-int.h:223
@ PGASYNC_READY_MORE
Definition: libpq-int.h:219
@ PGASYNC_READY
Definition: libpq-int.h:217
@ PGASYNC_COPY_BOTH
Definition: libpq-int.h:224
@ PGASYNC_COPY_IN
Definition: libpq-int.h:222
@ PGASYNC_PIPELINE_IDLE
Definition: libpq-int.h:225

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(), ExecQueryAndProcessResults(), 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 3708 of file fe-exec.c.

3709{
3710 if (!check_field_number(res, field_num))
3711 return 0;
3712 if (res->attDescs)
3713 return res->attDescs[field_num].format;
3714 else
3715 return 0;
3716}
static int check_field_number(const PGresult *res, int field_num)
Definition: fe-exec.c:3510

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

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

◆ PQfinish()

void PQfinish ( PGconn conn)

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

5291{
5292 if (conn)
5293 {
5296 }
5297}
static void freePGconn(PGconn *conn)
Definition: fe-connect.c:5037

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

Referenced by appendQualifiedRelation(), BaseBackup(), check_for_connection_status(), check_for_pg_role_prefix(), check_for_prepared_transactions(), check_is_install_user(), check_loadable_libraries(), check_new_cluster_logical_replication_slots(), check_new_cluster_subscription_configuration(), check_old_cluster_subscription_state(), CheckConnection(), cluster_all_databases(), cluster_one_database(), connect_database(), ConnectDatabase(), connectDatabase(), connectToServer(), create_logical_replication_slots(), create_new_objects(), disconnect_atexit(), disconnect_database(), DisconnectDatabase(), disconnectDatabase(), do_connect(), doConnect(), dumpRoleGUCPrivs(), dumpRoleMembership(), dumpTablespaces(), ecpg_finish(), executeCommand(), executeQuery(), executeQueryOrDie(), exit_nicely(), expand_dbname_patterns(), finishCon(), get_db_infos(), get_dbnames_list_to_restore(), get_subscription_count(), get_tablespace_paths(), get_template0_info(), GetConnection(), libpqsrv_connect_internal(), libpqsrv_disconnect(), LogStreamerMain(), main(), old_9_6_invalidate_hash_indexes(), PQcancelFinish(), PQping(), PQpingParams(), process_slot(), ReconnectToServer(), reindex_all_databases(), reindex_one_database(), restore_all_databases(), runInitSteps(), set_frozenxids(), set_locale_and_encoding(), sql_conn(), sql_exec(), start_postmaster(), StreamLog(), StreamLogicalLog(), test_protocol_version(), unicode_version_changed(), vacuum_all_databases(), vacuum_one_database(), and vacuumlo().

◆ PQflush()

◆ PQfmod()

int PQfmod ( const PGresult res,
int  field_num 
)

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

3742{
3743 if (!check_field_number(res, field_num))
3744 return 0;
3745 if (res->attDescs)
3746 return res->attDescs[field_num].atttypmod;
3747 else
3748 return 0;
3749}
int atttypmod
Definition: libpq-fe.h:316

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

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

2987{
2988 *result_len = 0;
2989
2990 if (!conn)
2991 return NULL;
2992
2993 /*
2994 * Since this is the beginning of a query cycle, reset the error state.
2995 * However, in pipeline mode with something already queued, the error
2996 * buffer belongs to that command and we shouldn't clear it.
2997 */
2998 if (conn->cmd_queue_head == NULL)
3000
3002 {
3003 libpq_append_conn_error(conn, "%s not allowed in pipeline mode", "PQfn");
3004 return NULL;
3005 }
3006
3009 {
3010 libpq_append_conn_error(conn, "connection in wrong state");
3011 return NULL;
3012 }
3013
3014 return pqFunctionCall3(conn, fnid,
3015 result_buf, result_len,
3016 result_is_int,
3017 args, nargs);
3018}
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:920

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

3590{
3591 char *field_case;
3592 bool in_quotes;
3593 bool all_lower = true;
3594 const char *iptr;
3595 char *optr;
3596 int i;
3597
3598 if (!res)
3599 return -1;
3600
3601 /*
3602 * Note: it is correct to reject a zero-length input string; the proper
3603 * input to match a zero-length field name would be "".
3604 */
3605 if (field_name == NULL ||
3606 field_name[0] == '\0' ||
3607 res->attDescs == NULL)
3608 return -1;
3609
3610 /*
3611 * Check if we can avoid the strdup() and related work because the
3612 * passed-in string wouldn't be changed before we do the check anyway.
3613 */
3614 for (iptr = field_name; *iptr; iptr++)
3615 {
3616 char c = *iptr;
3617
3618 if (c == '"' || c != pg_tolower((unsigned char) c))
3619 {
3620 all_lower = false;
3621 break;
3622 }
3623 }
3624
3625 if (all_lower)
3626 for (i = 0; i < res->numAttributes; i++)
3627 if (strcmp(field_name, res->attDescs[i].name) == 0)
3628 return i;
3629
3630 /* Fall through to the normal check if that didn't work out. */
3631
3632 /*
3633 * Note: this code will not reject partially quoted strings, eg
3634 * foo"BAR"foo will become fooBARfoo when it probably ought to be an error
3635 * condition.
3636 */
3637 field_case = strdup(field_name);
3638 if (field_case == NULL)
3639 return -1; /* grotty */
3640
3641 in_quotes = false;
3642 optr = field_case;
3643 for (iptr = field_case; *iptr; iptr++)
3644 {
3645 char c = *iptr;
3646
3647 if (in_quotes)
3648 {
3649 if (c == '"')
3650 {
3651 if (iptr[1] == '"')
3652 {
3653 /* doubled quotes become a single quote */
3654 *optr++ = '"';
3655 iptr++;
3656 }
3657 else
3658 in_quotes = false;
3659 }
3660 else
3661 *optr++ = c;
3662 }
3663 else if (c == '"')
3664 in_quotes = true;
3665 else
3666 {
3667 c = pg_tolower((unsigned char) c);
3668 *optr++ = c;
3669 }
3670 }
3671 *optr = '\0';
3672
3673 for (i = 0; i < res->numAttributes; i++)
3674 {
3675 if (strcmp(field_case, res->attDescs[i].name) == 0)
3676 {
3677 free(field_case);
3678 return i;
3679 }
3680 }
3681 free(field_case);
3682 return -1;
3683}
unsigned char pg_tolower(unsigned char ch)
Definition: pgstrcasecmp.c:122

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

Referenced by append_depends_on_extension(), binary_upgrade_set_type_oids_by_type_oid(), buildMatViewRefreshDependencies(), check_for_connection_status(), check_for_pg_role_prefix(), collectComments(), collectSecLabels(), describeOneTableDetails(), dropRoles(), dumpAgg(), dumpBaseType(), dumpCollation(), dumpCompositeType(), dumpCompositeTypeColComments(), dumpConversion(), dumpDatabase(), dumpDomain(), dumpEnumType(), dumpFunc(), dumpOpclass(), dumpOpfamily(), dumpOpr(), dumpRangeType(), dumpRelationStats_dumper(), dumpRoleMembership(), dumpRoles(), dumpTableSchema(), dumpTSConfig(), dumpUserMappings(), get_db_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(), process_data_type_check(), process_extension_updates(), process_incompat_polymorphics(), process_isn_and_int8_passing_mismatch(), process_old_cluster_logical_slot_infos(), process_old_sub_state_check(), process_rel_infos(), process_unicode_update(), process_user_defined_encoding_conversions(), process_user_defined_postfix_ops(), process_with_oids_check(), processExtensionTables(), set_frozenxids(), and show_binary_results().

◆ PQfreeCancel()

void PQfreeCancel ( PGcancel cancel)

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

485{
486 free(cancel);
487}

References free.

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

◆ PQfreemem()

◆ PQfsize()

int PQfsize ( const PGresult res,
int  field_num 
)

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

3731{
3732 if (!check_field_number(res, field_num))
3733 return 0;
3734 if (res->attDescs)
3735 return res->attDescs[field_num].typlen;
3736 else
3737 return 0;
3738}

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

Referenced by ecpg_build_compat_sqlda(), and ECPGget_desc().

◆ PQftable()

Oid PQftable ( const PGresult res,
int  field_num 
)

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

3687{
3688 if (!check_field_number(res, field_num))
3689 return InvalidOid;
3690 if (res->attDescs)
3691 return res->attDescs[field_num].tableid;
3692 else
3693 return InvalidOid;
3694}

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

◆ PQftablecol()

int PQftablecol ( const PGresult res,
int  field_num 
)

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

3698{
3699 if (!check_field_number(res, field_num))
3700 return 0;
3701 if (res->attDescs)
3702 return res->attDescs[field_num].columnid;
3703 else
3704 return 0;
3705}
int columnid
Definition: libpq-fe.h:312

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

◆ PQftype()

Oid PQftype ( const PGresult res,
int  field_num 
)

◆ PQfullProtocolVersion()

int PQfullProtocolVersion ( const PGconn conn)

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

7600{
7601 if (!conn)
7602 return 0;
7603 if (conn->status == CONNECTION_BAD)
7604 return 0;
7606}
#define PG_PROTOCOL_FULL(v)
Definition: pqcomm.h:89

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

Referenced by test_protocol_version().

◆ PQgetAuthDataHook()

PQauthDataHook_type PQgetAuthDataHook ( void  )

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

1590{
1591 return PQauthDataHook;
1592}
PQauthDataHook_type PQauthDataHook
Definition: fe-auth.c:1586

References PQauthDataHook.

◆ PQgetCancel()

PGcancel * PQgetCancel ( PGconn conn)

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

368{
369 PGcancel *cancel;
370 int cancel_req_len;
372
373 if (!conn)
374 return NULL;
375
376 if (conn->sock == PGINVALID_SOCKET)
377 return NULL;
378
379 /* Check that we have received a cancellation key */
380 if (conn->be_cancel_key_len == 0)
381 return NULL;
382
383 cancel_req_len = offsetof(CancelRequestPacket, cancelAuthCode) + conn->be_cancel_key_len;
384 cancel = malloc(offsetof(PGcancel, cancel_req) + cancel_req_len);
385 if (cancel == NULL)
386 return NULL;
387
388 memcpy(&cancel->raddr, &conn->raddr, sizeof(SockAddr));
389
390 /* We use -1 to indicate an unset connection option */
391 cancel->pgtcp_user_timeout = -1;
392 cancel->keepalives = -1;
393 cancel->keepalives_idle = -1;
394 cancel->keepalives_interval = -1;
395 cancel->keepalives_count = -1;
396 if (conn->pgtcp_user_timeout != NULL)
397 {
399 &cancel->pgtcp_user_timeout,
400 conn, "tcp_user_timeout"))
401 goto fail;
402 }
403 if (conn->keepalives != NULL)
404 {
406 &cancel->keepalives,
407 conn, "keepalives"))
408 goto fail;
409 }
410 if (conn->keepalives_idle != NULL)
411 {
413 &cancel->keepalives_idle,
414 conn, "keepalives_idle"))
415 goto fail;
416 }
417 if (conn->keepalives_interval != NULL)
418 {
420 &cancel->keepalives_interval,
421 conn, "keepalives_interval"))
422 goto fail;
423 }
424 if (conn->keepalives_count != NULL)
425 {
427 &cancel->keepalives_count,
428 conn, "keepalives_count"))
429 goto fail;
430 }
431
432 req = (CancelRequestPacket *) &cancel->cancel_req;
436 /* include the length field itself in the length */
437 cancel->cancel_pkt_len = pg_hton32(cancel_req_len + 4);
438
439 return cancel;
440
441fail:
442 free(cancel);
443 return NULL;
444}
#define CANCEL_REQUEST_CODE
Definition: pqcomm.h:137
ProtocolVersion MsgType
Definition: pqcomm.h:101
MsgType cancelRequestCode
Definition: pqcomm.h:142
uint32 backendPID
Definition: pqcomm.h:143
char cancelAuthCode[FLEXIBLE_ARRAY_MEMBER]
Definition: pqcomm.h:144
char cancel_req[FLEXIBLE_ARRAY_MEMBER]
Definition: fe-cancel.c:54
char * keepalives_idle
Definition: libpq-int.h:398
char * keepalives
Definition: libpq-int.h:397
char * keepalives_interval
Definition: libpq-int.h:399
char * pgtcp_user_timeout
Definition: libpq-int.h:384
char * keepalives_count
Definition: libpq-int.h:401

References CancelRequestPacket::backendPID, pg_conn::be_cancel_key, pg_conn::be_cancel_key_len, pg_conn::be_pid, pg_cancel::cancel_pkt_len, pg_cancel::cancel_req, CANCEL_REQUEST_CODE, CancelRequestPacket::cancelAuthCode, CancelRequestPacket::cancelRequestCode, 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, pg_hton32, 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 PQrequestCancel(), set_archive_cancel_info(), SetCancelConn(), and test_cancel().

◆ PQgetCopyData()

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

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

2817{
2818 *buffer = NULL; /* for all failure cases */
2819 if (!conn)
2820 return -2;
2823 {
2824 libpq_append_conn_error(conn, "no COPY in progress");
2825 return -2;
2826 }
2827 return pqGetCopyData3(conn, buffer, async);
2828}
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().

◆ PQgetCurrentTimeUSec()

pg_usec_time_t PQgetCurrentTimeUSec ( void  )

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

1210{
1211 struct timeval tval;
1212
1213 gettimeofday(&tval, NULL);
1214 return (pg_usec_time_t) tval.tv_sec * 1000000 + tval.tv_usec;
1215}
int64_t pg_usec_time_t
Definition: libpq-fe.h:241
int gettimeofday(struct timeval *tp, void *tzp)

References gettimeofday().

Referenced by pqConnectDBComplete(), PQsocketPoll(), and wait_until_connected().

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

3902{
3903 if (!check_tuple_field_number(res, tup_num, field_num))
3904 return 1; /* pretend it is null */
3905 if (res->tuples[tup_num][field_num].len == NULL_LEN)
3906 return 1;
3907 else
3908 return 0;
3909}
static int check_tuple_field_number(const PGresult *res, int tup_num, int field_num)
Definition: fe-exec.c:3525
#define NULL_LEN
Definition: libpq-int.h:130

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

Referenced by addFooterToPublicationDesc(), BaseBackup(), compile_database_list(), compile_relation_list_one_db(), describeOneTableDetails(), determineNotNullFlags(), dumpAgg(), dumpBaseType(), dumpCollation(), dumpDatabase(), dumpDomain(), dumpFunc(), dumpRangeType(), dumpRelationStats_dumper(), dumpRoleMembership(), 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(), getIndexes(), 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(), retrieve_objects(), run_simple_query(), RunIdentifySystem(), sqlda_common_total_size(), StoreQueryTuple(), storeRow(), and verify_heap_slot_handler().

◆ PQgetlength()

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

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

3888{
3889 if (!check_tuple_field_number(res, tup_num, field_num))
3890 return 0;
3891 if (res->tuples[tup_num][field_num].len != NULL_LEN)
3892 return res->tuples[tup_num][field_num].len;
3893 else
3894 return 0;
3895}

References check_tuple_field_number(), pgresAttValue::len, NULL_LEN, 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 2854 of file fe-exec.c.

2855{
2856 if (!buffer || length <= 0)
2857 return EOF;
2858 *buffer = '\0';
2859 /* length must be at least 3 to hold the \. terminator! */
2860 if (length < 3)
2861 return EOF;
2862
2863 if (!conn)
2864 return EOF;
2865
2866 return pqGetline3(conn, buffer, length);
2867}
int pqGetline3(PGconn *conn, char *s, int maxlen)

References conn, and pqGetline3().

◆ PQgetlineAsync()

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

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

2902{
2903 if (!conn)
2904 return -1;
2905
2906 return pqGetlineAsync3(conn, buffer, bufsize);
2907}
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 2062 of file fe-exec.c.

2063{
2064 PGresult *res;
2065
2066 if (!conn)
2067 return NULL;
2068
2069 /* Parse any available data, if our state permits. */
2071
2072 /* If not ready to return something, block until we are. */
2073 while (conn->asyncStatus == PGASYNC_BUSY)
2074 {
2075 int flushResult;
2076
2077 /*
2078 * If data remains unsent, send it. Else we might be waiting for the
2079 * result of a command the backend hasn't even got yet.
2080 */
2081 while ((flushResult = pqFlush(conn)) > 0)
2082 {
2083 if (pqWait(false, true, conn))
2084 {
2085 flushResult = -1;
2086 break;
2087 }
2088 }
2089
2090 /*
2091 * Wait for some more data, and load it. (Note: if the connection has
2092 * been lost, pqWait should return immediately because the socket
2093 * should be read-ready, either with the last server data or with an
2094 * EOF indication. We expect therefore that this won't result in any
2095 * undue delay in reporting a previous write failure.)
2096 */
2097 if (flushResult ||
2098 pqWait(true, false, conn) ||
2099 pqReadData(conn) < 0)
2100 {
2101 /* Report the error saved by pqWait or pqReadData */
2104 return pqPrepareAsyncResult(conn);
2105 }
2106
2107 /* Parse it. */
2109
2110 /*
2111 * If we had a write error, but nothing above obtained a query result
2112 * or detected a read error, report the write error.
2113 */
2115 {
2118 return pqPrepareAsyncResult(conn);
2119 }
2120 }
2121
2122 /* Return the appropriate thing. */
2123 switch (conn->asyncStatus)
2124 {
2125 case PGASYNC_IDLE:
2126 res = NULL; /* query is complete */
2127 break;
2130
2131 /*
2132 * We're about to return the NULL that terminates the round of
2133 * results from the current query; prepare to send the results of
2134 * the next query, if any, when we're called next. If there's no
2135 * next element in the command queue, this gets us in IDLE state.
2136 */
2138 res = NULL; /* query is complete */
2139 break;
2140
2141 case PGASYNC_READY:
2143
2144 /*
2145 * Normally pqPrepareAsyncResult will have left conn->result
2146 * empty. Otherwise, "res" must be a not-full PGRES_TUPLES_CHUNK
2147 * result, which we want to return to the caller while staying in
2148 * PGASYNC_READY state. Then the next call here will return the
2149 * empty PGRES_TUPLES_OK result that was restored from
2150 * saved_result, after which we can proceed.
2151 */
2152 if (conn->result)
2153 {
2155 break;
2156 }
2157
2158 /* Advance the queue as appropriate */
2161
2163 {
2164 /*
2165 * We're about to send the results of the current query. Set
2166 * us idle now, and ...
2167 */
2169
2170 /*
2171 * ... in cases when we're sending a pipeline-sync result,
2172 * move queue processing forwards immediately, so that next
2173 * time we're called, we're prepared to return the next result
2174 * received from the server. In all other cases, leave the
2175 * queue state change for next time, so that a terminating
2176 * NULL result is sent.
2177 *
2178 * (In other words: we don't return a NULL after a pipeline
2179 * sync.)
2180 */
2183 }
2184 else
2185 {
2186 /* Set the state back to BUSY, allowing parsing to proceed. */
2188 }
2189 break;
2190 case PGASYNC_READY_MORE:
2192 /* Set the state back to BUSY, allowing parsing to proceed. */
2194 break;
2195 case PGASYNC_COPY_IN:
2197 break;
2198 case PGASYNC_COPY_OUT:
2200 break;
2201 case PGASYNC_COPY_BOTH:
2203 break;
2204 default:
2205 libpq_append_conn_error(conn, "unexpected asyncStatus: %d", (int) conn->asyncStatus);
2207 conn->asyncStatus = PGASYNC_IDLE; /* try to restore valid state */
2209 break;
2210 }
2211
2212 /* Time to fire PGEVT_RESULTCREATE events, if there are any */
2213 if (res && res->nEvents > 0)
2214 (void) PQfireResultCreateEvents(conn, res);
2215
2216 return res;
2217}
PGresult * pqPrepareAsyncResult(PGconn *conn)
Definition: fe-exec.c:851
static void pqSaveWriteError(PGconn *conn)
Definition: fe-exec.c:820
void pqCommandQueueAdvance(PGconn *conn, bool isReadyForQuery, bool gotSync)
Definition: fe-exec.c:3142
void pqSaveErrorResult(PGconn *conn)
Definition: fe-exec.c:803
static PGresult * getCopyResult(PGconn *conn, ExecStatusType copytype)
Definition: fe-exec.c:2224
static void parseInput(PGconn *conn)
Definition: fe-exec.c:2020
static void pqPipelineProcessQueue(PGconn *conn)
Definition: fe-exec.c:3180
int pqWait(int forRead, int forWrite, PGconn *conn)
Definition: fe-misc.c:993
int PQfireResultCreateEvents(PGconn *conn, PGresult *res)
Definition: libpq-events.c:185
bool write_failed
Definition: libpq-int.h:509
PGresult * result
Definition: libpq-int.h:594
ExecStatusType resultStatus
Definition: libpq-int.h:174

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, PGRES_TUPLES_CHUNK, pg_conn::pipelineStatus, PQ_PIPELINE_OFF, pqCommandQueueAdvance(), PQfireResultCreateEvents(), pqFlush(), pqPipelineProcessQueue(), pqPrepareAsyncResult(), pqReadData(), pqSaveErrorResult(), pqSaveWriteError(), pqWait(), pg_conn::result, pg_result::resultStatus, and pg_conn::write_failed.

Referenced by advanceConnectionState(), BaseBackup(), ClearOrSaveAllResults(), confirm_query_canceled_impl(), consumeQueryResult(), discardAbortedPipelineResults(), discardUntilSync(), dumpTableData_copy(), ecpg_process_output(), EndDBCopyMode(), ExecQueryAndProcessResults(), handleCopyIn(), handleCopyOut(), HandleEndOfCopyStream(), libpqsrv_get_result(), pgfdw_finish_pre_commit_cleanup(), pgfdw_get_cleanup_result(), PQconnectPoll(), pqEndcopy3(), PQexecFinish(), PQexecStart(), process_query_result(), 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 1622 of file fe-secure-openssl.c.

1623{
1624 if (!conn)
1625 return NULL;
1626 return conn->ssl;
1627}

References conn.

◆ PQgetSSLKeyPassHook_OpenSSL()

PQsslKeyPassHook_OpenSSL_type PQgetSSLKeyPassHook_OpenSSL ( void  )

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

1919{
1920 return PQsslKeyPassHook;
1921}
static PQsslKeyPassHook_OpenSSL_type PQsslKeyPassHook

References PQsslKeyPassHook.

◆ PQgetvalue()

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

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

3877{
3878 if (!check_tuple_field_number(res, tup_num, field_num))
3879 return NULL;
3880 return res->tuples[tup_num][field_num].value;
3881}

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

Referenced by _check_database_version(), add_tablespace_footer(), addFooterToPublicationDesc(), append_depends_on_extension(), appendQualifiedRelation(), BaseBackup(), binary_upgrade_set_type_oids_by_type_oid(), buildMatViewRefreshDependencies(), check_and_drop_existing_subscriptions(), check_and_drop_publications(), check_for_connection_status(), check_for_pg_role_prefix(), check_is_install_user(), check_new_cluster_logical_replication_slots(), check_new_cluster_subscription_configuration(), check_old_cluster_subscription_state(), check_publisher(), check_subscriber(), cluster_all_databases(), collectBinaryUpgradeClassOids(), collectComments(), collectRoleNames(), collectSecLabels(), collectSequences(), compile_database_list(), compile_relation_list_one_db(), convertTSFunction(), create_logical_replication_slot(), createViewAsClause(), describeOneTableDetails(), describePublications(), describeRoles(), describeTableDetails(), determineNotNullFlags(), do_field(), drop_failover_replication_slots(), dropDBs(), dropRoles(), dropTablespaces(), dumpAgg(), dumpBaseType(), dumpCollation(), dumpCompositeType(), dumpCompositeTypeColComments(), dumpConversion(), dumpDatabase(), dumpDatabaseConfig(), dumpDatabases(), dumpDomain(), dumpEnumType(), dumpForeignServer(), dumpFunc(), dumpOpclass(), dumpOpfamily(), dumpOpr(), dumpRangeType(), dumpRelationStats_dumper(), dumpRoleGUCPrivs(), dumpRoleMembership(), dumpRoles(), dumpRule(), dumpSearchPath(), dumpSequence(), dumpSequenceData(), dumpStatisticsExt(), dumpTable(), dumpTableAttach(), dumpTableData_insert(), dumpTableSchema(), dumpTablespaces(), dumpTSConfig(), dumpTSDictionary(), dumpUserConfig(), dumpUserMappings(), ecpg_get_data(), ecpg_is_type_an_array(), 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(), generate_object_name(), get_create_object_cmd(), get_db_infos(), get_language_name(), get_loadable_libraries(), get_next_possible_free_pg_type_oid(), get_parallel_tabidx_list(), get_parallel_tables_list(), get_primary_sysid(), get_publisher_databases(), get_remote_estimate(), get_subscription_count(), get_synchronized_snapshot(), get_table_relkind(), 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_data_type_check(), process_extension_updates(), process_incompat_polymorphics(), process_isn_and_int8_passing_mismatch(), process_old_cluster_logical_slot_infos(), process_old_sub_state_check(), process_queued_fetch_requests(), process_rel_infos(), process_result(), process_unicode_update(), process_user_defined_encoding_conversions(), process_user_defined_postfix_ops(), process_with_oids_check(), processExtensionTables(), readCommandResponse(), ReadEndOfStreamingResult(), ReceiveXlogStream(), reindex_all_databases(), retrieve_objects(), RetrieveDataDirCreatePerm(), RetrieveWalSegSize(), run_simple_query(), RunIdentifySystem(), server_is_in_recovery(), set_frozenxids(), set_replication_progress(), show_binary_results(), sql_exec(), sqlda_common_total_size(), StoreQueryTuple(), storeRow(), test_pipeline_abort(), test_singlerowmode(), test_transaction(), try_complete_step(), unicode_version_changed(), vacuum_all_databases(), 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 7488 of file fe-connect.c.

7489{
7490 if (!conn)
7491 return NULL;
7492
7493 if (conn->connhost != NULL)
7494 {
7495 /*
7496 * Return the verbatim host value provided by user, or hostaddr in its
7497 * lack.
7498 */
7499 if (conn->connhost[conn->whichhost].host != NULL &&
7500 conn->connhost[conn->whichhost].host[0] != '\0')
7501 return conn->connhost[conn->whichhost].host;
7502 else if (conn->connhost[conn->whichhost].hostaddr != NULL &&
7503 conn->connhost[conn->whichhost].hostaddr[0] != '\0')
7505 }
7506
7507 return "";
7508}

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 7511 of file fe-connect.c.

7512{
7513 if (!conn)
7514 return NULL;
7515
7516 /* Return the parsed IP address */
7517 if (conn->connhost != NULL && conn->connip != NULL)
7518 return conn->connip;
7519
7520 return "";
7521}

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 129 of file fe-secure.c.

130{
131 /* no-op */
132}

◆ PQinitSSL()

void PQinitSSL ( int  do_init)

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

118{
119 /* no-op */
120}

◆ PQisBusy()

int PQisBusy ( PGconn conn)

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

2032{
2033 if (!conn)
2034 return false;
2035
2036 /* Parse any available data, if our state permits. */
2038
2039 /*
2040 * PQgetResult will return immediately in all states except BUSY. Also,
2041 * if we've detected read EOF and dropped the connection, we can expect
2042 * that PQgetResult will fail immediately. Note that we do *not* check
2043 * conn->write_failed here --- once that's become set, we know we have
2044 * trouble, but we need to keep trying to read until we have a complete
2045 * server message or detect read EOF.
2046 */
2048}

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

Referenced by advanceConnectionState(), confirm_query_canceled_impl(), dblink_is_busy(), libpqsrv_get_result(), pgfdw_get_cleanup_result(), PQconnectPoll(), pqEndcopy3(), process_slot(), 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 3983 of file fe-exec.c.

3984{
3985 if (!conn || conn->status == CONNECTION_BAD)
3986 return false;
3987 return pqIsnonblocking(conn);
3988}

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

3993{
3994 return true;
3995}

◆ PQlibVersion()

int PQlibVersion ( void  )

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

64{
65 return PG_VERSION_NUM;
66}

◆ PQmakeEmptyPGresult()

PGresult * PQmakeEmptyPGresult ( PGconn conn,
ExecStatusType  status 
)

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

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

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_CHUNK, 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 1233 of file fe-misc.c.

1234{
1235 return pg_encoding_mblen(encoding, s);
1236}
int pg_encoding_mblen(int encoding, const char *mbstr)
Definition: wchar.c:2116

References encoding, and pg_encoding_mblen().

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

◆ PQmblenBounded()

int PQmblenBounded ( const char *  s,
int  encoding 
)

◆ PQnfields()

◆ PQnotifies()

PGnotify * PQnotifies ( PGconn conn)

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

2668{
2669 PGnotify *event;
2670
2671 if (!conn)
2672 return NULL;
2673
2674 /* Parse any available data to see if we can extract NOTIFY messages. */
2676
2677 event = conn->notifyHead;
2678 if (event)
2679 {
2680 conn->notifyHead = event->next;
2681 if (!conn->notifyHead)
2682 conn->notifyTail = NULL;
2683 event->next = NULL; /* don't let app see the internal state */
2684 }
2685 return event;
2686}
struct pgNotify * next
Definition: libpq-fe.h:234
PGnotify * notifyHead
Definition: libpq-int.h:473
PGnotify * notifyTail
Definition: libpq-int.h:474

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

3916{
3917 if (!res)
3918 return 0;
3919 return res->numParameters;
3920}

References pg_result::numParameters.

◆ PQntuples()

int PQntuples ( const PGresult res)

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

3482{
3483 if (!res)
3484 return 0;
3485 return res->ntups;
3486}

References pg_result::ntups.

Referenced by add_tablespace_footer(), addFooterToPublicationDesc(), append_depends_on_extension(), appendQualifiedRelation(), BaseBackup(), buildMatViewRefreshDependencies(), check_and_drop_existing_subscriptions(), check_and_drop_publications(), check_for_connection_status(), check_for_pg_role_prefix(), check_for_prepared_transactions(), check_is_install_user(), check_new_cluster_logical_replication_slots(), check_new_cluster_subscription_configuration(), check_old_cluster_subscription_state(), cluster_all_databases(), collectBinaryUpgradeClassOids(), collectComments(), collectRoleNames(), collectSecLabels(), collectSequences(), compile_database_list(), compile_relation_list_one_db(), create_publication(), CreateReplicationSlot(), createViewAsClause(), describeOneTableDetails(), describePublications(), describeRoles(), describeTableDetails(), drop_failover_replication_slots(), dropDBs(), DropReplicationSlot(), dropRoles(), dropTablespaces(), dumpCompositeType(), dumpCompositeTypeColComments(), dumpDatabase(), dumpDatabaseConfig(), dumpDatabases(), dumpEnumType(), dumpOpclass(), dumpOpfamily(), dumpRelationStats_dumper(), dumpRoleGUCPrivs(), dumpRoleMembership(), dumpRoles(), dumpRule(), dumpSequence(), dumpSequenceData(), dumpTable(), dumpTableData_insert(), dumpTablespaces(), dumpTSConfig(), dumpUserConfig(), dumpUserMappings(), ecpg_is_type_an_array(), ecpg_process_output(), ecpg_store_result(), ECPGget_desc(), emitShSecLabels(), ExecQueryAndProcessResults(), ExecQueryTuples(), 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(), generate_object_name(), get_create_object_cmd(), get_db_infos(), get_dbnames_list_to_restore(), get_loadable_libraries(), get_parallel_tabidx_list(), get_parallel_tables_list(), get_primary_sysid(), get_publisher_databases(), 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_data_type_check(), process_extension_updates(), process_incompat_polymorphics(), process_isn_and_int8_passing_mismatch(), process_loadable_libraries(), process_old_cluster_logical_slot_infos(), process_old_sub_state_check(), process_queued_fetch_requests(), process_rel_infos(), process_unicode_update(), process_user_defined_encoding_conversions(), process_user_defined_postfix_ops(), process_with_oids_check(), processExtensionTables(), readCommandResponse(), ReadEndOfStreamingResult(), ReceiveXlogStream(), reindex_all_databases(), retrieve_objects(), RetrieveDataDirCreatePerm(), RetrieveWalSegSize(), run_simple_query(), RunIdentifySystem(), set_frozenxids(), set_replication_progress(), show_binary_results(), sql_exec(), StoreQueryTuple(), storeRow(), test_pipeline_abort(), test_singlerowmode(), test_transaction(), try_complete_step(), vacuum_all_databases(), vacuumlo(), verify_btree_slot_handler(), verify_heap_slot_handler(), and wait_for_connection_state().

◆ PQoidStatus()

char * PQoidStatus ( const PGresult res)

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

3766{
3767 /*
3768 * This must be enough to hold the result. Don't laugh, this is better
3769 * than what this function used to do.
3770 */
3771 static char buf[24];
3772
3773 size_t len;
3774
3775 if (!res || strncmp(res->cmdStatus, "INSERT ", 7) != 0)
3776 return "";
3777
3778 len = strspn(res->cmdStatus + 7, "0123456789");
3779 if (len > sizeof(buf) - 1)
3780 len = sizeof(buf) - 1;
3781 memcpy(buf, res->cmdStatus + 7, len);
3782 buf[len] = '\0';
3783
3784 return buf;
3785}

References buf, pg_result::cmdStatus, and len.

◆ PQoidValue()

Oid PQoidValue ( const PGresult res)

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

3794{
3795 char *endptr = NULL;
3796 unsigned long result;
3797
3798 if (!res ||
3799 strncmp(res->cmdStatus, "INSERT ", 7) != 0 ||
3800 res->cmdStatus[7] < '0' ||
3801 res->cmdStatus[7] > '9')
3802 return InvalidOid;
3803
3804 result = strtoul(res->cmdStatus + 7, &endptr, 10);
3805
3806 if (!endptr || (*endptr != ' ' && *endptr != '\0'))
3807 return InvalidOid;
3808 else
3809 return (Oid) result;
3810}

References pg_result::cmdStatus, and InvalidOid.

Referenced by ecpg_process_output(), and PrintQueryStatus().

◆ PQoptions()

char * PQoptions ( const PGconn conn)

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

7549{
7550 if (!conn)
7551 return NULL;
7552 return conn->pgoptions;
7553}
char * pgoptions
Definition: libpq-int.h:386

References conn, and pg_conn::pgoptions.

Referenced by exec_command_conninfo().

◆ PQparameterStatus()

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

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

7575{
7576 const pgParameterStatus *pstatus;
7577
7578 if (!conn || !paramName)
7579 return NULL;
7580 for (pstatus = conn->pstatus; pstatus != NULL; pstatus = pstatus->next)
7581 {
7582 if (strcmp(pstatus->name, paramName) == 0)
7583 return pstatus->value;
7584 }
7585 return NULL;
7586}
struct pgParameterStatus * next
Definition: libpq-int.h:271
pgParameterStatus * pstatus
Definition: libpq-int.h:552

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(), exec_command_conninfo(), 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 3926 of file fe-exec.c.

3927{
3928 if (!check_param_number(res, param_num))
3929 return InvalidOid;
3930 if (res->paramDescs)
3931 return res->paramDescs[param_num].typid;
3932 else
3933 return InvalidOid;
3934}
static int check_param_number(const PGresult *res, int param_num)
Definition: fe-exec.c:3548

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

◆ PQpass()

char * PQpass ( const PGconn conn)

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

7472{
7473 char *password = NULL;
7474
7475 if (!conn)
7476 return NULL;
7477 if (conn->connhost != NULL)
7479 if (password == NULL)
7480 password = conn->pgpass;
7481 /* Historically we've returned "" not NULL for no password specified */
7482 if (password == NULL)
7483 password = "";
7484 return password;
7485}
char * pgpass
Definition: libpq-int.h:393

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

Referenced by ConnectDatabaseAhx(), and PQconnectionNeedsPassword().

◆ PQping()

PGPing PQping ( const char *  conninfo)

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

830{
831 PGconn *conn = PQconnectStart(conninfo);
832 PGPing ret;
833
834 ret = internal_ping(conn);
835 PQfinish(conn);
836
837 return ret;
838}
static PGPing internal_ping(PGconn *conn)
Definition: fe-connect.c:4873

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

◆ PQpingParams()

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

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

779{
780 PGconn *conn = PQconnectStartParams(keywords, values, expand_dbname);
781 PGPing ret;
782
783 ret = internal_ping(conn);
784 PQfinish(conn);
785
786 return ret;
787}

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

Referenced by main(), and regression_main().

◆ PQpipelineStatus()

◆ PQpipelineSync()

int PQpipelineSync ( PGconn conn)

◆ PQport()

char * PQport ( const PGconn conn)

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

7525{
7526 if (!conn)
7527 return NULL;
7528
7529 if (conn->connhost != NULL)
7530 return conn->connhost[conn->whichhost].port;
7531
7532 return "";
7533}

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

2309{
2310 if (!PQexecStart(conn))
2311 return NULL;
2312 if (!PQsendPrepare(conn, stmtName, query, nParams, paramTypes))
2313 return NULL;
2314 return PQexecFinish(conn);
2315}
int PQsendPrepare(PGconn *conn, const char *stmtName, const char *query, int nParams, const Oid *paramTypes)
Definition: fe-exec.c:1536

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
299exit:
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:554
int pq_block_sigpipe(sigset_t *osigset, bool *sigpipe_pending)
Definition: fe-secure.c:504
pqbool align
Definition: libpq-fe.h:253
pqbool pager
Definition: libpq-fe.h:257
pqbool standard
Definition: libpq-fe.h:254
pqbool html3
Definition: libpq-fe.h:255
char * caption
Definition: libpq-fe.h:260
pqbool header
Definition: libpq-fe.h:252
pqbool expanded
Definition: libpq-fe.h:256
char * fieldSep
Definition: libpq-fe.h:258
char ** fieldName
Definition: libpq-fe.h:261
char * tableOpt
Definition: libpq-fe.h:259

References _PQprintOpt::align, calloc, _PQprintOpt::caption, do_field(), do_header(), _PQprintOpt::expanded, _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(), _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:241

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

◆ PQprotocolVersion()

int PQprotocolVersion ( const PGconn conn)

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

7590{
7591 if (!conn)
7592 return 0;
7593 if (conn->status == CONNECTION_BAD)
7594 return 0;
7596}
#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 exec_command_conninfo(), and handleCopyIn().

◆ PQputCopyData()

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

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

2696{
2697 if (!conn)
2698 return -1;
2701 {
2702 libpq_append_conn_error(conn, "no COPY in progress");
2703 return -1;
2704 }
2705
2706 /*
2707 * Process any NOTICE or NOTIFY messages that might be pending in the
2708 * input buffer. Since the server might generate many notices during the
2709 * COPY, we want to clean those out reasonably promptly to prevent
2710 * indefinite expansion of the input buffer. (Note: the actual read of
2711 * input data into the input buffer happens down inside pqSendSome, but
2712 * it's not authorized to get rid of the data again.)
2713 */
2715
2716 if (nbytes > 0)
2717 {
2718 /*
2719 * Try to flush any previously sent data in preference to growing the
2720 * output buffer. If we can't enlarge the buffer enough to hold the
2721 * data, return 0 in the nonblock case, else hard error. (For
2722 * simplicity, always assume 5 bytes of overhead.)
2723 */
2724 if ((conn->outBufSize - conn->outCount - 5) < nbytes)
2725 {
2726 if (pqFlush(conn) < 0)
2727 return -1;
2728 if (pqCheckOutBufferSpace(conn->outCount + 5 + (size_t) nbytes,
2729 conn))
2730 return pqIsnonblocking(conn) ? 0 : -1;
2731 }
2732 /* Send the data (too simple to delegate to fe-protocol files) */
2733 if (pqPutMsgStart(PqMsg_CopyData, conn) < 0 ||
2734 pqPutnchar(buffer, nbytes, conn) < 0 ||
2735 pqPutMsgEnd(conn) < 0)
2736 return -1;
2737 }
2738 return 1;
2739}
int pqCheckOutBufferSpace(size_t bytes_needed, PGconn *conn)
Definition: fe-misc.c:287
int pqPutMsgStart(char msg_type, PGconn *conn)
Definition: fe-misc.c:473
int pqPutnchar(const char *s, size_t len, PGconn *conn)
Definition: fe-misc.c:202
int pqPutMsgEnd(PGconn *conn)
Definition: fe-misc.c:532
#define PqMsg_CopyData
Definition: protocol.h:65
int outBufSize
Definition: libpq-int.h:572
int outCount
Definition: libpq-int.h:573

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

2750{
2751 if (!conn)
2752 return -1;
2755 {
2756 libpq_append_conn_error(conn, "no COPY in progress");
2757 return -1;
2758 }
2759
2760 /*
2761 * Send the COPY END indicator. This is simple enough that we don't
2762 * bother delegating it to the fe-protocol files.
2763 */
2764 if (errormsg)
2765 {
2766 /* Send COPY FAIL */
2767 if (pqPutMsgStart(PqMsg_CopyFail, conn) < 0 ||
2768 pqPuts(errormsg, conn) < 0 ||
2769 pqPutMsgEnd(conn) < 0)
2770 return -1;
2771 }
2772 else
2773 {
2774 /* Send COPY DONE */
2775 if (pqPutMsgStart(PqMsg_CopyDone, conn) < 0 ||
2776 pqPutMsgEnd(conn) < 0)
2777 return -1;
2778 }
2779
2780 /*
2781 * If we sent the COPY command in extended-query mode, we must issue a
2782 * Sync as well.
2783 */
2784 if (conn->cmd_queue_head &&
2786 {
2787 if (pqPutMsgStart(PqMsg_Sync, conn) < 0 ||
2788 pqPutMsgEnd(conn) < 0)
2789 return -1;
2790 }
2791
2792 /* Return to active duty */
2795 else
2797
2798 /* Try to flush data */
2799 if (pqFlush(conn) < 0)
2800 return -1;
2801
2802 return 1;
2803}
int pqPuts(const char *s, PGconn *conn)
Definition: fe-misc.c:152
@ 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:345

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

2919{
2920 return PQputnbytes(conn, string, strlen(string));
2921}
int PQputnbytes(PGconn *conn, const char *buffer, int nbytes)
Definition: fe-exec.c:2928

References conn, and PQputnbytes().

Referenced by initPopulateTable().

◆ PQputnbytes()

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

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

2929{
2930 if (PQputCopyData(conn, buffer, nbytes) > 0)
2931 return 0;
2932 else
2933 return EOF;
2934}
int PQputCopyData(PGconn *conn, const char *buffer, int nbytes)
Definition: fe-exec.c:2695

References conn, and PQputCopyData().

Referenced by PQputline().

◆ PQregisterThreadLock()

pgthreadlock_t PQregisterThreadLock ( pgthreadlock_t  newhandler)

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

8278{
8280
8281 if (newhandler)
8282 pg_g_threadlock = newhandler;
8283 else
8285
8286 return prev;
8287}
static void default_threadlock(int acquire)
Definition: fe-connect.c:8260
pgthreadlock_t pg_g_threadlock
Definition: fe-connect.c:504
void(* pgthreadlock_t)(int acquire)
Definition: libpq-fe.h:472

References default_threadlock(), and pg_g_threadlock.

◆ PQrequestCancel()

int PQrequestCancel ( PGconn conn)

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

726{
727 int r;
728 PGcancel *cancel;
729
730 /* Check we have an open connection */
731 if (!conn)
732 return false;
733
734 if (conn->sock == PGINVALID_SOCKET)
735 {
737 "PQrequestCancel() -- connection is not open\n",
740 conn->errorReported = 0;
741
742 return false;
743 }
744
745 cancel = PQgetCancel(conn);
746 if (cancel)
747 {
748 r = PQcancel(cancel, conn->errorMessage.data,
750 PQfreeCancel(cancel);
751 }
752 else
753 {
754 strlcpy(conn->errorMessage.data, "out of memory",
756 r = false;
757 }
758
759 if (!r)
760 {
762 conn->errorReported = 0;
763 }
764
765 return r;
766}
PGcancel * PQgetCancel(PGconn *conn)
Definition: fe-cancel.c:367
int PQcancel(PGcancel *cancel, char *errbuf, int errbufsize)
Definition: fe-cancel.c:530
void PQfreeCancel(PGcancel *cancel)
Definition: fe-cancel.c:484
int errorReported
Definition: libpq-int.h:672

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 5304 of file fe-connect.c.

5305{
5306 if (conn)
5307 {
5309
5311 {
5312 /*
5313 * Notify event procs of successful reset.
5314 */
5315 int i;
5316
5317 for (i = 0; i < conn->nEvents; i++)
5318 {
5319 PGEventConnReset evt;
5320
5321 evt.conn = conn;
5322 (void) conn->events[i].proc(PGEVT_CONNRESET, &evt,
5324 }
5325 }
5326 }
5327}
@ 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 5356 of file fe-connect.c.

5357{
5358 if (conn)
5359 {
5361
5362 if (status == PGRES_POLLING_OK)
5363 {
5364 /*
5365 * Notify event procs of successful reset.
5366 */
5367 int i;
5368
5369 for (i = 0; i < conn->nEvents; i++)
5370 {
5371 PGEventConnReset evt;
5372
5373 evt.conn = conn;
5374 (void) conn->events[i].proc(PGEVT_CONNRESET, &evt,
5376 }
5377 }
5378
5379 return status;
5380 }
5381
5382 return PGRES_POLLING_FAILED;
5383}

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 5337 of file fe-connect.c.

5338{
5339 if (conn)
5340 {
5342
5343 return pqConnectDBStart(conn);
5344 }
5345
5346 return 0;
5347}

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

◆ PQresStatus()

char * PQresStatus ( ExecStatusType  status)

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

3420{
3421 if ((unsigned int) status >= lengthof(pgresStatus))
3422 return libpq_gettext("invalid ExecStatusType code");
3423 return pgresStatus[status];
3424}
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 543 of file fe-exec.c.

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

References OOM_result, and pqResultAlloc().

Referenced by PQsetResultAttrs().

◆ PQresultErrorField()

char * PQresultErrorField ( const PGresult res,
int  fieldcode 
)

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

3467{
3468 PGMessageField *pfield;
3469
3470 if (!res)
3471 return NULL;
3472 for (pfield = res->errFields; pfield != NULL; pfield = pfield->next)
3473 {
3474 if (pfield->code == fieldcode)
3475 return pfield->contents;
3476 }
3477 return NULL;
3478}
struct pgMessageField * next
Definition: libpq-int.h:141
char contents[FLEXIBLE_ARRAY_MEMBER]
Definition: libpq-int.h:143

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

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

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

References pg_result::memorySize.

◆ PQresultStatus()

ExecStatusType PQresultStatus ( const PGresult res)

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

3412{
3413 if (!res)
3414 return PGRES_FATAL_ERROR;
3415 return res->resultStatus;
3416}

References PGRES_FATAL_ERROR, and pg_result::resultStatus.

Referenced by _doSetSessionAuth(), _printTableAccessMethodNoStorage(), _selectOutputSchema(), _selectTableAccessMethod(), _selectTablespace(), AcceptResult(), advanceConnectionState(), BaseBackup(), check_and_drop_existing_subscriptions(), check_and_drop_publications(), check_loadable_libraries(), check_prepare_conn(), check_publisher(), check_subscriber(), ClearOrSaveResult(), close_cursor(), compile_database_list(), compile_relation_list_one_db(), confirm_query_canceled_impl(), connect_database(), create_cursor(), create_logical_replication_slot(), create_publication(), create_subscription(), CreateReplicationSlot(), dblink_close(), dblink_exec(), dblink_fetch(), dblink_open(), dblink_record_internal(), deallocate_query(), DescribeQuery(), discardAbortedPipelineResults(), discardUntilSync(), do_sql_command_end(), drop_existing_subscriptions(), drop_failover_replication_slots(), drop_publication(), drop_replication_slot(), DropReplicationSlot(), dumpTableData_copy(), ecpg_check_PQresult(), ecpg_is_type_an_array(), ecpg_process_output(), enable_subscription(), EndDBCopyMode(), exec_command_password(), ExecQueryAndProcessResults(), execute_dml_stmt(), execute_foreign_modify(), executeCommand(), executeMaintenanceCommand(), executeQuery(), executeQueryOrDie(), ExecuteSqlCommand(), ExecuteSqlQuery(), ExecuteSqlStatement(), executeStatement(), fetch_more_data(), generate_object_name(), get_create_object_cmd(), get_dbnames_list_to_restore(), get_primary_sysid(), get_publisher_databases(), get_remote_estimate(), get_table_relkind(), 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_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(), PrintQueryStatus(), PrintResultInCrosstab(), process_global_sql_commands(), process_query_result(), process_queued_fetch_requests(), process_result(), readCommandResponse(), ReceiveCopyData(), ReceiveXlogStream(), RetrieveDataDirCreatePerm(), RetrieveWalSegSize(), run_permutation(), run_simple_command(), run_simple_query(), RunIdentifySystem(), SendQuery(), server_is_in_recovery(), set_replication_progress(), setup_publisher(), 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 3435 of file fe-exec.c.

3438{
3439 PQExpBufferData workBuf;
3440
3441 /*
3442 * Because the caller is expected to free the result string, we must
3443 * strdup any constant result. We use plain strdup and document that
3444 * callers should expect NULL if out-of-memory.
3445 */
3446 if (!res ||
3449 return strdup(libpq_gettext("PGresult is not an error result\n"));
3450
3451 initPQExpBuffer(&workBuf);
3452
3453 pqBuildErrorMessage3(&workBuf, res, verbosity, show_context);
3454
3455 /* If insufficient memory to format the message, fail cleanly */
3456 if (PQExpBufferDataBroken(workBuf))
3457 {
3458 termPQExpBuffer(&workBuf);
3459 return strdup(libpq_gettext("out of memory\n"));
3460 }
3461
3462 return workBuf.data;
3463}
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, pg_result::resultStatus, and termPQExpBuffer().

Referenced by exec_command_errverbose().

◆ PQsendClosePortal()

int PQsendClosePortal ( PGconn conn,
const char *  portal 
)

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

2570{
2571 return PQsendTypedCommand(conn, PqMsg_Close, 'P', portal);
2572}

References conn, PqMsg_Close, and PQsendTypedCommand().

Referenced by test_prepared().

◆ PQsendClosePrepared()

int PQsendClosePrepared ( PGconn conn,
const char *  stmt 
)

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

2557{
2558 return PQsendTypedCommand(conn, PqMsg_Close, 'S', stmt);
2559}

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

Referenced by ExecQueryAndProcessResults(), and test_prepared().

◆ PQsendDescribePortal()

int PQsendDescribePortal ( PGconn conn,
const char *  portal 
)

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

2505{
2506 return PQsendTypedCommand(conn, PqMsg_Describe, 'P', portal);
2507}

References conn, PqMsg_Describe, and PQsendTypedCommand().

Referenced by test_prepared().

◆ PQsendDescribePrepared()

int PQsendDescribePrepared ( PGconn conn,
const char *  stmt 
)

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

2492{
2494}

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

Referenced by test_prepared().

◆ PQsendFlushRequest()

int PQsendFlushRequest ( PGconn conn)

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

3372{
3373 if (!conn)
3374 return 0;
3375
3376 /* Don't try to send if we know there's no live connection. */
3377 if (conn->status != CONNECTION_OK)
3378 {
3379 libpq_append_conn_error(conn, "no connection to the server");
3380 return 0;
3381 }
3382
3383 /* Can't send while already busy, either, unless enqueuing for later */
3384 if (conn->asyncStatus != PGASYNC_IDLE &&
3386 {
3387 libpq_append_conn_error(conn, "another command is already in progress");
3388 return 0;
3389 }
3390
3391 if (pqPutMsgStart(PqMsg_Flush, conn) < 0 ||
3392 pqPutMsgEnd(conn) < 0)
3393 {
3394 return 0;
3395 }
3396
3397 /*
3398 * Give the data a push (in pipeline mode, only if we're past the size
3399 * threshold). In nonblock mode, don't complain if we're unable to send
3400 * it all; PQgetResult() will do any additional flushing needed.
3401 */
3402 if (pqPipelineFlush(conn) < 0)
3403 return 0;
3404
3405 return 1;
3406}
static int pqPipelineFlush(PGconn *conn)
Definition: fe-exec.c:4016
#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 ExecQueryAndProcessResults(), test_nosync(), test_pipeline_idle(), test_singlerowmode(), and test_uniqviol().

◆ PQsendPipelineSync()

int PQsendPipelineSync ( PGconn conn)

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

3283{
3284 return pqPipelineSyncInternal(conn, false);
3285}

References conn, and pqPipelineSyncInternal().

Referenced by ExecQueryAndProcessResults(), executeMetaCommand(), and test_multi_pipelines().

◆ PQsendPrepare()

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

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

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

1500{
1501 if (!PQsendQueryStart(conn, true))
1502 return 0;
1503
1504 /* check the arguments */
1505 if (!command)
1506 {
1507 libpq_append_conn_error(conn, "command string is a null pointer");
1508 return 0;
1509 }
1510 if (nParams < 0 || nParams > PQ_QUERY_PARAM_MAX_LIMIT)
1511 {
1512 libpq_append_conn_error(conn, "number of parameters must be between 0 and %d",
1514 return 0;
1515 }
1516
1517 return PQsendQueryGuts(conn,
1518 command,
1519 "", /* use unnamed statement */
1520 nParams,
1521 paramTypes,
1522 paramValues,
1523 paramLengths,
1524 paramFormats,
1525 resultFormat);
1526}
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:1757

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

1640{
1641 if (!PQsendQueryStart(conn, true))
1642 return 0;
1643
1644 /* check the arguments */
1645 if (!stmtName)
1646 {
1647 libpq_append_conn_error(conn, "statement name is a null pointer");
1648 return 0;
1649 }
1650 if (nParams < 0 || nParams > PQ_QUERY_PARAM_MAX_LIMIT)
1651 {
1652 libpq_append_conn_error(conn, "number of parameters must be between 0 and %d",
1654 return 0;
1655 }
1656
1657 return PQsendQueryGuts(conn,
1658 NULL, /* no command to parse */
1659 stmtName,
1660 nParams,
1661 NULL, /* no param types */
1662 paramValues,
1663 paramLengths,
1664 paramFormats,
1665 resultFormat);
1666}

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

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

◆ PQserverVersion()

◆ PQservice()

char * PQservice ( const PGconn conn)

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

7456{
7457 if (!conn)
7458 return NULL;
7459 return conn->pgservice;
7460}
char * pgservice
Definition: libpq-int.h:391

References conn, and pg_conn::pgservice.

Referenced by get_prompt(), and SyncVariables().

◆ PQsetAuthDataHook()

void PQsetAuthDataHook ( PQauthDataHook_type  hook)

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

1596{
1597 PQauthDataHook = hook ? hook : PQdefaultAuthDataHook;
1598}
int PQdefaultAuthDataHook(PGauthData type, PGconn *conn, void *data)
Definition: fe-auth.c:1601

References PQauthDataHook, and PQdefaultAuthDataHook().

Referenced by main().

◆ PQsetChunkedRowsMode()

int PQsetChunkedRowsMode ( PGconn conn,
int  chunkSize 
)

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

1966{
1967 if (chunkSize > 0 && canChangeResultMode(conn))
1968 {
1969 conn->partialResMode = true;
1970 conn->singleRowMode = false;
1971 conn->maxChunkSize = chunkSize;
1972 return 1;
1973 }
1974 else
1975 return 0;
1976}
static bool canChangeResultMode(PGconn *conn)
Definition: fe-exec.c:1925
int maxChunkSize
Definition: libpq-int.h:469
bool singleRowMode
Definition: libpq-int.h:468
bool partialResMode
Definition: libpq-int.h:467

References canChangeResultMode(), conn, pg_conn::maxChunkSize, pg_conn::partialResMode, and pg_conn::singleRowMode.

Referenced by ExecQueryAndProcessResults(), and test_singlerowmode().

◆ PQsetClientEncoding()

int PQsetClientEncoding ( PGconn conn,
const char *  encoding 
)

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

7718{
7719 char qbuf[128];
7720 static const char query[] = "set client_encoding to '%s'";
7721 PGresult *res;
7722 int status;
7723
7724 if (!conn || conn->status != CONNECTION_OK)
7725 return -1;
7726
7727 if (!encoding)
7728 return -1;
7729
7730 /* Resolve special "auto" value from the locale */
7731 if (strcmp(encoding, "auto") == 0)
7733
7734 /* check query buffer overflow */
7735 if (sizeof(qbuf) < (sizeof(query) + strlen(encoding)))
7736 return -1;
7737
7738 /* ok, now send a query */
7739 sprintf(qbuf, query, encoding);
7740 res = PQexec(conn, qbuf);
7741
7742 if (res == NULL)
7743 return -1;
7744 if (res->resultStatus != PGRES_COMMAND_OK)
7745 status = -1;
7746 else
7747 {
7748 /*
7749 * We rely on the backend to report the parameter value, and we'll
7750 * change state at that time.
7751 */
7752 status = 0; /* everything is ok */
7753 }
7754 PQclear(res);
7755 return status;
7756}
#define pg_encoding_to_char
Definition: pg_wchar.h:630
int pg_get_encoding_from_locale(const char *ctype, bool write_message)
Definition: chklocale.c:301

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

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

◆ 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 2228 of file fe-connect.c.

2231{
2232 PGconn *conn;
2233
2234 /*
2235 * Allocate memory for the conn structure. Note that we also expect this
2236 * to initialize conn->errorMessage to empty. All subsequent steps during
2237 * connection initialization will only append to that buffer.
2238 */
2240 if (conn == NULL)
2241 return NULL;
2242
2243 /*
2244 * If the dbName parameter contains what looks like a connection string,
2245 * parse it into conn struct using connectOptions1.
2246 */
2248 {
2250 return conn;
2251 }
2252 else
2253 {
2254 /*
2255 * Old-style path: first, parse an empty conninfo string in order to
2256 * set up the same defaults that PQconnectdb() would use.
2257 */
2258 if (!connectOptions1(conn, ""))
2259 return conn;
2260
2261 /* Insert dbName parameter value into struct */
2262 if (dbName && dbName[0] != '\0')
2263 {
2264 free(conn->dbName);
2265 conn->dbName = strdup(dbName);
2266 if (!conn->dbName)
2267 goto oom_error;
2268 }
2269 }
2270
2271 /*
2272 * Insert remaining parameters into struct, overriding defaults (as well
2273 * as any conflicting data from dbName taken as a conninfo).
2274 */
2275 if (pghost && pghost[0] != '\0')
2276 {
2277 free(conn->pghost);
2278 conn->pghost = strdup(pghost);
2279 if (!conn->pghost)
2280 goto oom_error;
2281 }
2282
2283 if (pgport && pgport[0] != '\0')
2284 {
2285 free(conn->pgport);
2286 conn->pgport = strdup(pgport);
2287 if (!conn->pgport)
2288 goto oom_error;
2289 }
2290
2291 if (pgoptions && pgoptions[0] != '\0')
2292 {
2294 conn->pgoptions = strdup(pgoptions);
2295 if (!conn->pgoptions)
2296 goto oom_error;
2297 }
2298
2299 if (login && login[0] != '\0')
2300 {
2301 free(conn->pguser);
2302 conn->pguser = strdup(login);
2303 if (!conn->pguser)
2304 goto oom_error;
2305 }
2306
2307 if (pwd && pwd[0] != '\0')
2308 {
2309 free(conn->pgpass);
2310 conn->pgpass = strdup(pwd);
2311 if (!conn->pgpass)
2312 goto oom_error;
2313 }
2314
2315 /*
2316 * Compute derived options
2317 */
2318 if (!pqConnectOptions2(conn))
2319 return conn;
2320
2321 /*
2322 * Connect to the database
2323 */
2325 (void) pqConnectDBComplete(conn);
2326
2327 return conn;
2328
2329oom_error:
2331 libpq_append_conn_error(conn, "out of memory");
2332 return conn;
2333}
static bool recognized_connection_string(const char *connstr)
Definition: fe-connect.c:6254
static const char * pghost
Definition: pgbench.c:295
static const char * pgport
Definition: pgbench.c:296
static const char * dbName
Definition: pgbench.c:298
char * pghost
Definition: libpq-int.h:373
char * pguser
Definition: libpq-int.h:392
char * pgport
Definition: libpq-int.h:381

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 7771 of file fe-connect.c.

7772{
7774
7775 if (!conn)
7776 return PQSHOW_CONTEXT_ERRORS;
7777 old = conn->show_context;
7778 conn->show_context = show_context;
7779 return old;
7780}
PGContextVisibility show_context
Definition: libpq-int.h:558

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 7759 of file fe-connect.c.

7760{
7761 PGVerbosity old;
7762
7763 if (!conn)
7764 return PQERRORS_DEFAULT;
7765 old = conn->verbosity;
7766 conn->verbosity = verbosity;
7767 return old;
7768}
PGVerbosity verbosity
Definition: libpq-int.h:557

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

3945{
3946 bool barg;
3947
3948 if (!conn || conn->status == CONNECTION_BAD)
3949 return -1;
3950
3951 barg = (arg ? true : false);
3952
3953 /* early out if the socket is already in the state requested */
3954 if (barg == conn->nonblocking)
3955 return 0;
3956
3957 /*
3958 * to guarantee constancy for flushing/query/result-polling behavior we
3959 * need to flush the send queue at this point in order to guarantee proper
3960 * behavior. this is ok because either they are making a transition _from_
3961 * or _to_ blocking mode, either way we can block them.
3962 *
3963 * Clear error state in case pqFlush adds to it, unless we're actively
3964 * pipelining, in which case it seems best not to.
3965 */
3966 if (conn->cmd_queue_head == NULL)
3968
3969 /* if we are going from blocking to non-blocking flush here */
3970 if (pqFlush(conn))
3971 return -1;
3972
3973 conn->nonblocking = barg;
3974
3975 return 0;
3976}
return true
Definition: isn.c:130
void * arg
bool nonblocking
Definition: libpq-int.h:464

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 7800 of file fe-connect.c.

7801{
7803
7804 if (conn == NULL)
7805 return NULL;
7806
7808 if (proc)
7809 {
7810 conn->noticeHooks.noticeProc = proc;
7812 }
7813 return old;
7814}
void(* PQnoticeProcessor)(void *arg, const char *message)
Definition: libpq-fe.h:245

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

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

◆ PQsetNoticeReceiver()

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

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

7784{
7785 PQnoticeReceiver old;
7786
7787 if (conn == NULL)
7788 return NULL;
7789
7790 old = conn->noticeHooks.noticeRec;
7791 if (proc)
7792 {
7793 conn->noticeHooks.noticeRec = proc;
7795 }
7796 return old;
7797}
void(* PQnoticeReceiver)(void *arg, const PGresult *res)
Definition: libpq-fe.h:244

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

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

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

Referenced by PQcopyResult().

◆ PQsetSingleRowMode()

int PQsetSingleRowMode ( PGconn conn)

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

1949{
1951 {
1952 conn->partialResMode = true;
1953 conn->singleRowMode = true;
1954 conn->maxChunkSize = 1;
1955 return 1;
1956 }
1957 else
1958 return 0;
1959}

References canChangeResultMode(), conn, pg_conn::maxChunkSize, pg_conn::partialResMode, 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 1924 of file fe-secure-openssl.c.

1925{
1926 PQsslKeyPassHook = hook;
1927}

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}
int traceFlags
Definition: libpq-int.h:448

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

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

Referenced by PQcopyResult().

◆ PQsocket()

◆ PQsocketPoll()

int PQsocketPoll ( int  sock,
int  forRead,
int  forWrite,
pg_usec_time_t  end_time 
)

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

1116{
1117 /* We use poll(2) if available, otherwise select(2) */
1118#ifdef HAVE_POLL
1119 struct pollfd input_fd;
1120 int timeout_ms;
1121
1122 if (!forRead && !forWrite)
1123 return 0;
1124
1125 input_fd.fd = sock;
1126 input_fd.events = POLLERR;
1127 input_fd.revents = 0;
1128
1129 if (forRead)
1130 input_fd.events |= POLLIN;
1131 if (forWrite)
1132 input_fd.events |= POLLOUT;
1133
1134 /* Compute appropriate timeout interval */
1135 if (end_time == -1)
1136 timeout_ms = -1;
1137 else if (end_time == 0)
1138 timeout_ms = 0;
1139 else
1140 {
1142
1143 if (end_time > now)
1144 timeout_ms = (end_time - now) / 1000;
1145 else
1146 timeout_ms = 0;
1147 }
1148
1149 return poll(&input_fd, 1, timeout_ms);
1150#else /* !HAVE_POLL */
1151
1152 fd_set input_mask;
1153 fd_set output_mask;
1154 fd_set except_mask;
1155 struct timeval timeout;
1156 struct timeval *ptr_timeout;
1157
1158 if (!forRead && !forWrite)
1159 return 0;
1160
1161 FD_ZERO(&input_mask);
1162 FD_ZERO(&output_mask);
1163 FD_ZERO(&except_mask);
1164 if (forRead)
1165 FD_SET(sock, &input_mask);
1166
1167 if (forWrite)
1168 FD_SET(sock, &output_mask);
1169 FD_SET(sock, &except_mask);
1170
1171 /* Compute appropriate timeout interval */
1172 if (end_time == -1)
1173 ptr_timeout = NULL;
1174 else if (end_time == 0)
1175 {
1176 timeout.tv_sec = 0;
1177 timeout.tv_usec = 0;
1178 ptr_timeout = &timeout;
1179 }
1180 else
1181 {
1183
1184 if (end_time > now)
1185 {
1186 timeout.tv_sec = (end_time - now) / 1000000;
1187 timeout.tv_usec = (end_time - now) % 1000000;
1188 }
1189 else
1190 {
1191 timeout.tv_sec = 0;
1192 timeout.tv_usec = 0;
1193 }
1194 ptr_timeout = &timeout;
1195 }
1196
1197 return select(sock + 1, &input_mask, &output_mask,
1198 &except_mask, ptr_timeout);
1199#endif /* HAVE_POLL */
1200}
Datum now(PG_FUNCTION_ARGS)
Definition: timestamp.c:1609
pg_usec_time_t PQgetCurrentTimeUSec(void)
Definition: fe-misc.c:1209
static int64 end_time
Definition: pgbench.c:176
#define select(n, r, w, e, timeout)
Definition: win32_port.h:503

References end_time, now(), PQgetCurrentTimeUSec(), and select.

Referenced by pqSocketCheck(), timer_expired(), and wait_until_connected().

◆ PQsslAttribute()

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

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

1668{
1669 if (!conn)
1670 {
1671 /* PQsslAttribute(NULL, "library") reports the default SSL library */
1672 if (strcmp(attribute_name, "library") == 0)
1673 return "OpenSSL";
1674 return NULL;
1675 }
1676
1677 /* All attributes read as NULL for a non-encrypted connection */
1678 if (conn->ssl == NULL)
1679 return NULL;
1680
1681 if (strcmp(attribute_name, "library") == 0)
1682 return "OpenSSL";
1683
1684 if (strcmp(attribute_name, "key_bits") == 0)
1685 {
1686 static char sslbits_str[12];
1687 int sslbits;
1688
1689 SSL_get_cipher_bits(conn->ssl, &sslbits);
1690 snprintf(sslbits_str, sizeof(sslbits_str), "%d", sslbits);
1691 return sslbits_str;
1692 }
1693
1694 if (strcmp(attribute_name, "cipher") == 0)
1695 return SSL_get_cipher(conn->ssl);
1696
1697 if (strcmp(attribute_name, "compression") == 0)
1698 return SSL_get_current_compression(conn->ssl) ? "on" : "off";
1699
1700 if (strcmp(attribute_name, "protocol") == 0)
1701 return SSL_get_version(conn->ssl);
1702
1703 if (strcmp(attribute_name, "alpn") == 0)
1704 {
1705 const unsigned char *data;
1706 unsigned int len;
1707 static char alpn_str[256]; /* alpn doesn't support longer than 255
1708 * bytes */
1709
1710 SSL_get0_alpn_selected(conn->ssl, &data, &len);
1711 if (data == NULL || len == 0 || len > sizeof(alpn_str) - 1)
1712 return "";
1713 memcpy(alpn_str, data, len);
1714 alpn_str[len] = 0;
1715 return alpn_str;
1716 }
1717
1718 return NULL; /* unknown attribute */
1719}
const void * data

References conn, data, len, and snprintf.

Referenced by exec_command_conninfo(), print_ssl_library(), and printSSLInfo().

◆ PQsslAttributeNames()

const char *const * PQsslAttributeNames ( PGconn conn)

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

1641{
1642 static const char *const openssl_attrs[] = {
1643 "library",
1644 "key_bits",
1645 "cipher",
1646 "compression",
1647 "protocol",
1648 "alpn",
1649 NULL
1650 };
1651 static const char *const empty_attrs[] = {NULL};
1652
1653 if (!conn)
1654 {
1655 /* Return attributes of default SSL library */
1656 return openssl_attrs;
1657 }
1658
1659 /* No attrs for unencrypted connection */
1660 if (conn->ssl == NULL)
1661 return empty_attrs;
1662
1663 return openssl_attrs;
1664}

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 exec_command_conninfo(), and printSSLInfo().

◆ PQsslStruct()

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

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

1631{
1632 if (!conn)
1633 return NULL;
1634 if (strcmp(struct_name, "OpenSSL") == 0)
1635 return conn->ssl;
1636 return NULL;
1637}

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;
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 7540 of file fe-connect.c.

7541{
7542 if (!conn)
7543 return NULL;
7544 return "";
7545}

References conn.

◆ PQunescapeBytea()

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

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

4554{
4555 size_t strtextlen,
4556 buflen;
4557 unsigned char *buffer,
4558 *tmpbuf;
4559 size_t i,
4560 j;
4561
4562 if (strtext == NULL)
4563 return NULL;
4564
4565 strtextlen = strlen((const char *) strtext);
4566
4567 if (strtext[0] == '\\' && strtext[1] == 'x')
4568 {
4569 const unsigned char *s;
4570 unsigned char *p;
4571
4572 buflen = (strtextlen - 2) / 2;
4573 /* Avoid unportable malloc(0) */
4574 buffer = (unsigned char *) malloc(buflen > 0 ? buflen : 1);
4575 if (buffer == NULL)
4576 return NULL;
4577
4578 s = strtext + 2;
4579 p = buffer;
4580 while (*s)
4581 {
4582 char v1,
4583 v2;
4584
4585 /*
4586 * Bad input is silently ignored. Note that this includes
4587 * whitespace between hex pairs, which is allowed by byteain.
4588 */
4589 v1 = get_hex(*s++);
4590 if (!*s || v1 == (char) -1)
4591 continue;
4592 v2 = get_hex(*s++);
4593 if (v2 != (char) -1)
4594 *p++ = (v1 << 4) | v2;
4595 }
4596
4597 buflen = p - buffer;
4598 }
4599 else
4600 {
4601 /*
4602 * Length of input is max length of output, but add one to avoid
4603 * unportable malloc(0) if input is zero-length.
4604 */
4605 buffer = (unsigned char *) malloc(strtextlen + 1);
4606 if (buffer == NULL)
4607 return NULL;
4608
4609 for (i = j = 0; i < strtextlen;)
4610 {
4611 switch (strtext[i])
4612 {
4613 case '\\':
4614 i++;
4615 if (strtext[i] == '\\')
4616 buffer[j++] = strtext[i++];
4617 else
4618 {
4619 if ((ISFIRSTOCTDIGIT(strtext[i])) &&
4620 (ISOCTDIGIT(strtext[i + 1])) &&
4621 (ISOCTDIGIT(strtext[i + 2])))
4622 {
4623 int byte;
4624
4625 byte = OCTVAL(strtext[i++]);
4626 byte = (byte << 3) + OCTVAL(strtext[i++]);
4627 byte = (byte << 3) + OCTVAL(strtext[i++]);
4628 buffer[j++] = byte;
4629 }
4630 }
4631
4632 /*
4633 * Note: if we see '\' followed by something that isn't a
4634 * recognized escape sequence, we loop around having done
4635 * nothing except advance i. Therefore the something will
4636 * be emitted as ordinary data on the next cycle. Corner
4637 * case: '\' at end of string will just be discarded.
4638 */
4639 break;
4640
4641 default:
4642 buffer[j++] = strtext[i++];
4643 break;
4644 }
4645 }
4646 buflen = j; /* buflen is the length of the dequoted data */
4647 }
4648
4649 /* Shrink the buffer to be no larger than necessary */
4650 /* +1 avoids unportable behavior when buflen==0 */
4651 tmpbuf = realloc(buffer, buflen + 1);
4652
4653 /* It would only be a very brain-dead realloc that could fail, but... */
4654 if (!tmpbuf)
4655 {
4656 free(buffer);
4657 return NULL;
4658 }
4659
4660 *retbuflen = buflen;
4661 return tmpbuf;
4662}
static char get_hex(char c)
Definition: fe-exec.c:4389
#define ISOCTDIGIT(CH)
Definition: fe-exec.c:4537
#define OCTVAL(CH)
Definition: fe-exec.c:4538
#define ISFIRSTOCTDIGIT(CH)
Definition: fe-exec.c:4536
#define realloc(a, b)
Definition: header.h:60
static StringInfoData tmpbuf
Definition: walsender.c:175

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 {
55 fflush(conn->Pfdebug);
56 conn->Pfdebug = NULL;
57 }
58
59 conn->traceFlags = 0;
60}

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

Referenced by PQtrace().

◆ PQuser()

char * PQuser ( const PGconn conn)

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

7464{
7465 if (!conn)
7466 return NULL;
7467 return conn->pguser;
7468}

References conn, and pg_conn::pguser.

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