PostgreSQL Source Code git master
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_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 * 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 507 of file libpq-fe.h.

◆ PQfreeNotify

#define PQfreeNotify (   ptr)    PQfreemem(ptr)

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

◆ PQnoPasswordSupplied

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

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

◆ PQTRACE_REGRESS_MODE

#define PQTRACE_REGRESS_MODE   (1<<1)

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

◆ PQTRACE_SUPPRESS_TIMESTAMPS

#define PQTRACE_SUPPRESS_TIMESTAMPS   (1<<0)

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

◆ SOCKTYPE

#define SOCKTYPE   int

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

Typedef Documentation

◆ pg_usec_time_t

typedef int64_t pg_usec_time_t

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

◆ PQauthDataHook_type

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

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

◆ pqbool

typedef char pqbool

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

◆ PQconninfoOption

◆ PQnoticeProcessor

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

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

◆ PQnoticeReceiver

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

Definition at line 241 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 821 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}
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:2997
static int lo_initialize(PGconn *conn)
Definition: fe-lobj.c:843
#define PQclear
Definition: libpq-be-fe.h:245
#define PQresultStatus
Definition: libpq-be-fe.h:247
static int fd(const char *x, int i)
Definition: preproc-init.c:105
PGconn * conn
Definition: streamutil.c:52
union PQArgBlock::@196 u
int isint
Definition: libpq-fe.h:293
int integer
Definition: libpq-fe.h:297
Oid fn_lo_close
Definition: libpq-int.h:281
PGlobjfuncs * lobjfuncs
Definition: libpq-int.h:562

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:56
#define InvalidOid
Definition: postgres_ext.h:37
unsigned int Oid
Definition: postgres_ext.h:32
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: oauth-utils.c:95
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:1261
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:923
static char * filename
Definition: pg_dumpall.c:120
static char * buf
Definition: pg_test_fsync.c:72
#define PG_STRERROR_R_BUFLEN
Definition: port.h:278
#define strerror_r
Definition: port.h:277

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:538
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:296
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:1233
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:790
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 3514 of file fe-exec.c.

3515{
3516 if (!res)
3517 return 0;
3518 return res->binary;
3519}
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 548 of file fe-cancel.c.

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

191{
193 return 0;
194 return pqConnectDBComplete(&cancelConn->conn);
195}
static PGcancel *volatile cancelConn
Definition: cancel.c:43
int PQcancelStart(PGcancelConn *cancelConn)
Definition: fe-cancel.c:204
int pqConnectDBComplete(PGconn *conn)
Definition: fe-connect.c:2796

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 (cancelConn->be_cancel_key == NULL)
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 cancelConn->connhost[0].type = originalHost.type;
141 if (originalHost.host)
142 {
143 cancelConn->connhost[0].host = strdup(originalHost.host);
144 if (!cancelConn->connhost[0].host)
145 goto oom_error;
146 }
147 if (originalHost.hostaddr)
148 {
149 cancelConn->connhost[0].hostaddr = strdup(originalHost.hostaddr);
150 if (!cancelConn->connhost[0].hostaddr)
151 goto oom_error;
152 }
153 if (originalHost.port)
154 {
155 cancelConn->connhost[0].port = strdup(originalHost.port);
156 if (!cancelConn->connhost[0].port)
157 goto oom_error;
158 }
159 if (originalHost.password)
160 {
161 cancelConn->connhost[0].password = strdup(originalHost.password);
162 if (!cancelConn->connhost[0].password)
163 goto oom_error;
164 }
165
166 cancelConn->addr = calloc(cancelConn->naddr, sizeof(AddrInfo));
167 if (!cancelConn->addr)
168 goto oom_error;
169
170 cancelConn->addr[0].addr = conn->raddr;
171 cancelConn->addr[0].family = conn->raddr.addr.ss_family;
172
174 return (PGcancelConn *) cancelConn;
175
176oom_error:
177 cancelConn->status = CONNECTION_BAD;
178 libpq_append_conn_error(cancelConn, "out of memory");
179 return (PGcancelConn *) cancelConn;
180}
bool pqConnectOptions2(PGconn *conn)
Definition: fe-connect.c:1252
void pqReleaseConnHosts(PGconn *conn)
Definition: fe-connect.c:5152
PGconn * pqMakeEmptyPGconn(void)
Definition: fe-connect.c:4954
bool pqCopyPGconn(PGconn *srcConn, PGconn *dstConn)
Definition: fe-connect.c:1037
#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:362
char * port
Definition: libpq-int.h:360
char * hostaddr
Definition: libpq-int.h:359
pg_conn_host_type type
Definition: libpq-int.h:357
uint8 * be_cancel_key
Definition: libpq-int.h:554
pgsocket sock
Definition: libpq-int.h:499
ProtocolVersion pversion
Definition: libpq-int.h:503
SockAddr raddr
Definition: libpq-int.h:502
int be_cancel_key_len
Definition: libpq-int.h:553
int whichhost
Definition: libpq-int.h:481
pg_conn_host * connhost
Definition: libpq-int.h:482

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, pg_conn_host::type, and pg_conn::whichhost.

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

◆ PQcancelErrorMessage()

char * PQcancelErrorMessage ( const PGcancelConn cancelConn)

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

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

References cancelConn, and PQerrorMessage().

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

◆ PQcancelFinish()

void PQcancelFinish ( PGcancelConn cancelConn)

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

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

References cancelConn, and PQfinish().

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

◆ PQcancelPoll()

PostgresPollingStatusType PQcancelPoll ( PGcancelConn cancelConn)

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

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

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 337 of file fe-cancel.c.

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

References cancelConn, CONNECTION_ALLOCATED, and pqClosePGconn().

Referenced by test_cancel().

◆ PQcancelSocket()

int PQcancelSocket ( const PGcancelConn cancelConn)

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

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

References cancelConn, and PQsocket().

Referenced by libpqsrv_cancel(), and test_cancel().

◆ PQcancelStart()

int PQcancelStart ( PGcancelConn cancelConn)

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

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

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 302 of file fe-cancel.c.

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

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:4049
char * PQescapeLiteral(PGconn *conn, const char *str, size_t len)
Definition: fe-exec.c:4399
PGresult * PQexec(PGconn *conn, const char *query)
Definition: fe-exec.c:2279
char * PQescapeIdentifier(PGconn *conn, const char *str, size_t len)
Definition: fe-exec.c:4405
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 727 of file fe-exec.c.

728{
729 PGresult_data *block;
730 int i;
731
732 /* As a convenience, do nothing for a NULL pointer */
733 if (!res)
734 return;
735 /* Also, do nothing if the argument is OOM_result */
736 if ((const PGresult *) res == &OOM_result)
737 return;
738
739 /* Close down any events we may have */
740 for (i = 0; i < res->nEvents; i++)
741 {
742 /* only send DESTROY to successfully-initialized event procs */
743 if (res->events[i].resultInitialized)
744 {
746
747 evt.result = res;
748 (void) res->events[i].proc(PGEVT_RESULTDESTROY, &evt,
749 res->events[i].passThrough);
750 }
751 free(res->events[i].name);
752 }
753
754 free(res->events);
755
756 /* Free all the subsidiary blocks */
757 while ((block = res->curBlock) != NULL)
758 {
759 res->curBlock = block->next;
760 free(block);
761 }
762
763 /* Free the top-level tuple pointer array */
764 free(res->tuples);
765
766 /* zero out the pointer fields to catch programming errors */
767 res->attDescs = NULL;
768 res->tuples = NULL;
769 res->paramDescs = NULL;
770 res->errFields = NULL;
771 res->events = NULL;
772 res->nEvents = 0;
773 /* res->curBlock was zeroed out earlier */
774
775 /* Free the PGresult structure itself */
776 free(res);
777}
static const PGresult OOM_result
Definition: fe-exec.c:50
#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 pqClearAsyncResult(), PQcopyResult(), PQexecFinish(), PQexecStart(), pqInternalNotice(), and PQmakeEmptyPGresult().

◆ PQclientEncoding()

◆ PQclosePortal()

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

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

2557{
2558 if (!PQexecStart(conn))
2559 return NULL;
2560 if (!PQsendTypedCommand(conn, PqMsg_Close, 'P', portal))
2561 return NULL;
2562 return PQexecFinish(conn);
2563}
static PGresult * PQexecFinish(PGconn *conn)
Definition: fe-exec.c:2427
static int PQsendTypedCommand(PGconn *conn, char command, char type, const char *target)
Definition: fe-exec.c:2606
static bool PQexecStart(PGconn *conn)
Definition: fe-exec.c:2361
#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 2538 of file fe-exec.c.

2539{
2540 if (!PQexecStart(conn))
2541 return NULL;
2543 return NULL;
2544 return PQexecFinish(conn);
2545}
#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 3769 of file fe-exec.c.

3770{
3771 if (!res)
3772 return NULL;
3773 return res->cmdStatus;
3774}
char cmdStatus[CMDSTATUS_LEN]
Definition: libpq-int.h:175

References pg_result::cmdStatus.

◆ PQcmdTuples()

char * PQcmdTuples ( PGresult res)

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

3840{
3841 char *p,
3842 *c;
3843
3844 if (!res)
3845 return "";
3846
3847 if (strncmp(res->cmdStatus, "INSERT ", 7) == 0)
3848 {
3849 p = res->cmdStatus + 7;
3850 /* INSERT: skip oid and space */
3851 while (*p && *p != ' ')
3852 p++;
3853 if (*p == 0)
3854 goto interpret_error; /* no space? */
3855 p++;
3856 }
3857 else if (strncmp(res->cmdStatus, "SELECT ", 7) == 0 ||
3858 strncmp(res->cmdStatus, "DELETE ", 7) == 0 ||
3859 strncmp(res->cmdStatus, "UPDATE ", 7) == 0)
3860 p = res->cmdStatus + 7;
3861 else if (strncmp(res->cmdStatus, "FETCH ", 6) == 0 ||
3862 strncmp(res->cmdStatus, "MERGE ", 6) == 0)
3863 p = res->cmdStatus + 6;
3864 else if (strncmp(res->cmdStatus, "MOVE ", 5) == 0 ||
3865 strncmp(res->cmdStatus, "COPY ", 5) == 0)
3866 p = res->cmdStatus + 5;
3867 else
3868 return "";
3869
3870 /* check that we have an integer (at least one digit, nothing else) */
3871 for (c = p; *c; c++)
3872 {
3873 if (!isdigit((unsigned char) *c))
3874 goto interpret_error;
3875 }
3876 if (c == p)
3877 goto interpret_error;
3878
3879 return p;
3880
3881interpret_error:
3883 "could not interpret result from server: %s",
3884 res->cmdStatus);
3885 return "";
3886}
void pqInternalNotice(const PGNoticeHooks *hooks, const char *fmt,...)
Definition: fe-exec.c:944
char * c
PGNoticeHooks noticeHooks
Definition: libpq-int.h:183

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

◆ PQconndefaults()

PQconninfoOption * PQconndefaults ( void  )

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

2208{
2209 PQExpBufferData errorBuf;
2210 PQconninfoOption *connOptions;
2211
2212 /* We don't actually report any errors here, but callees want a buffer */
2213 initPQExpBuffer(&errorBuf);
2214 if (PQExpBufferDataBroken(errorBuf))
2215 return NULL; /* out of memory already :-( */
2216
2217 connOptions = conninfo_init(&errorBuf);
2218 if (connOptions != NULL)
2219 {
2220 /* pass NULL errorBuf to ignore errors */
2221 if (!conninfo_add_defaults(connOptions, NULL))
2222 {
2223 PQconninfoFree(connOptions);
2224 connOptions = NULL;
2225 }
2226 }
2227
2228 termPQExpBuffer(&errorBuf);
2229 return connOptions;
2230}
static PQconninfoOption * conninfo_init(PQExpBuffer errorMessage)
Definition: fe-connect.c:6263
static bool conninfo_add_defaults(PQconninfoOption *options, PQExpBuffer errorMessage)
Definition: fe-connect.c:6690
void PQconninfoFree(PQconninfoOption *connOptions)
Definition: fe-connect.c:7525
#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 825 of file fe-connect.c.

826{
827 PGconn *conn = PQconnectStart(conninfo);
828
829 if (conn && conn->status != CONNECTION_BAD)
831
832 return conn;
833}
PGconn * PQconnectStart(const char *conninfo)
Definition: fe-connect.c:953

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

773{
774 PGconn *conn = PQconnectStartParams(keywords, values, expand_dbname);
775
776 if (conn && conn->status != CONNECTION_BAD)
778
779 return conn;
780}
static Datum values[MAXATTR]
Definition: bootstrap.c:153
PGconn * PQconnectStartParams(const char *const *keywords, const char *const *values, int expand_dbname)
Definition: fe-connect.c:872
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 7757 of file fe-connect.c.

7758{
7759 char *password;
7760
7761 if (!conn)
7762 return false;
7763 password = PQpass(conn);
7764 if (conn->password_needed &&
7765 (password == NULL || password[0] == '\0'))
7766 return true;
7767 else
7768 return false;
7769}
char * PQpass(const PGconn *conn)
Definition: fe-connect.c:7554
static char * password
Definition: streamutil.c:51
bool password_needed
Definition: libpq-int.h:508

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

7784{
7785 if (!conn)
7786 return false;
7787 if (conn->gssapi_used)
7788 return true;
7789 else
7790 return false;
7791}
bool gssapi_used
Definition: libpq-int.h:509

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

7773{
7774 if (!conn)
7775 return false;
7776 if (conn->password_needed)
7777 return true;
7778 else
7779 return false;
7780}

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

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

954{
955 PGconn *conn;
956
957 /*
958 * Allocate memory for the conn structure. Note that we also expect this
959 * to initialize conn->errorMessage to empty. All subsequent steps during
960 * connection initialization will only append to that buffer.
961 */
963 if (conn == NULL)
964 return NULL;
965
966 /*
967 * Parse the conninfo string
968 */
969 if (!connectOptions1(conn, conninfo))
970 return conn;
971
972 /*
973 * Compute derived options
974 */
976 return conn;
977
978 /*
979 * Connect to the database
980 */
982 {
983 /* Just in case we failed to set it in pqConnectDBStart */
985 }
986
987 return conn;
988}
static bool connectOptions1(PGconn *conn, const char *conninfo)
Definition: fe-connect.c:1078

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

875{
876 PGconn *conn;
877 PQconninfoOption *connOptions;
878
879 /*
880 * Allocate memory for the conn structure. Note that we also expect this
881 * to initialize conn->errorMessage to empty. All subsequent steps during
882 * connection initialization will only append to that buffer.
883 */
885 if (conn == NULL)
886 return NULL;
887
888 /*
889 * Parse the conninfo arrays
890 */
891 connOptions = conninfo_array_parse(keywords, values,
893 true, expand_dbname);
894 if (connOptions == NULL)
895 {
897 /* errorMessage is already set */
898 return conn;
899 }
900
901 /*
902 * Move option values into conn structure
903 */
904 if (!fillPGconn(conn, connOptions))
905 {
906 PQconninfoFree(connOptions);
907 return conn;
908 }
909
910 /*
911 * Free the option info - all is in conn now
912 */
913 PQconninfoFree(connOptions);
914
915 /*
916 * Compute derived options
917 */
919 return conn;
920
921 /*
922 * Connect to the database
923 */
925 {
926 /* Just in case we failed to set it in pqConnectDBStart */
928 }
929
930 return conn;
931}
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:6532
static bool fillPGconn(PGconn *conn, PQconninfoOption *connOptions)
Definition: fe-connect.c:999

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

7482{
7483 PQExpBufferData errorBuf;
7484 PQconninfoOption *connOptions;
7485
7486 if (conn == NULL)
7487 return NULL;
7488
7489 /*
7490 * We don't actually report any errors here, but callees want a buffer,
7491 * and we prefer not to trash the conn's errorMessage.
7492 */
7493 initPQExpBuffer(&errorBuf);
7494 if (PQExpBufferDataBroken(errorBuf))
7495 return NULL; /* out of memory already :-( */
7496
7497 connOptions = conninfo_init(&errorBuf);
7498
7499 if (connOptions != NULL)
7500 {
7502
7503 for (option = PQconninfoOptions; option->keyword; option++)
7504 {
7505 char **connmember;
7506
7507 if (option->connofs < 0)
7508 continue;
7509
7510 connmember = (char **) ((char *) conn + option->connofs);
7511
7512 if (*connmember)
7513 conninfo_storeval(connOptions, option->keyword, *connmember,
7514 &errorBuf, true, false);
7515 }
7516 }
7517
7518 termPQExpBuffer(&errorBuf);
7519
7520 return connOptions;
7521}
static PQconninfoOption * conninfo_storeval(PQconninfoOption *connOptions, const char *keyword, const char *value, PQExpBuffer errorMessage, bool ignoreMissing, bool uri_decode)
Definition: fe-connect.c:7399
static const internalPQconninfoOption PQconninfoOptions[]
Definition: fe-connect.c:200

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

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

◆ PQconninfoFree()

◆ PQconninfoParse()

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

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

6242{
6243 PQExpBufferData errorBuf;
6244 PQconninfoOption *connOptions;
6245
6246 if (errmsg)
6247 *errmsg = NULL; /* default */
6248 initPQExpBuffer(&errorBuf);
6249 if (PQExpBufferDataBroken(errorBuf))
6250 return NULL; /* out of memory already :-( */
6251 connOptions = parse_connection_string(conninfo, &errorBuf, false);
6252 if (connOptions == NULL && errmsg)
6253 *errmsg = errorBuf.data;
6254 else
6255 termPQExpBuffer(&errorBuf);
6256 return connOptions;
6257}
int errmsg(const char *fmt,...)
Definition: elog.c:1080
static PQconninfoOption * parse_connection_string(const char *connstr, PQExpBuffer errorMessage, bool use_defaults)
Definition: fe-connect.c:6302

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

2002{
2003 if (!conn)
2004 return 0;
2005
2006 /*
2007 * for non-blocking connections try to flush the send-queue, otherwise we
2008 * may never get a response for something that may not have already been
2009 * sent because it's in our write buffer!
2010 */
2011 if (pqIsnonblocking(conn))
2012 {
2013 if (pqFlush(conn) < 0)
2014 return 0;
2015 }
2016
2017 /*
2018 * Load more data, if available. We do this no matter what state we are
2019 * in, since we are probably getting called because the application wants
2020 * to get rid of a read-select condition. Note that we will NOT block
2021 * waiting for more input.
2022 */
2023 if (pqReadData(conn) < 0)
2024 return 0;
2025
2026 /* Parsing of the data waits till later. */
2027 return 1;
2028}
#define pqIsnonblocking(conn)
Definition: libpq-int.h:939

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

Referenced by advanceConnectionState(), consume_query_cancel_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 319 of file fe-exec.c.

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

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

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

2492{
2493 if (!PQexecStart(conn))
2494 return NULL;
2495 if (!PQsendTypedCommand(conn, PqMsg_Describe, 'P', portal))
2496 return NULL;
2497 return PQexecFinish(conn);
2498}
#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 2472 of file fe-exec.c.

2473{
2474 if (!PQexecStart(conn))
2475 return NULL;
2477 return NULL;
2478 return PQexecFinish(conn);
2479}

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 605 of file fe-print.c.

612{
613#define DEFAULT_FIELD_SEP " "
614
615 int i,
616 j;
617 int nFields;
618 int nTuples;
619 int *fLength = NULL;
620
621 if (fieldSep == NULL)
622 fieldSep = DEFAULT_FIELD_SEP;
623
624 /* Get some useful info about the results */
625 nFields = PQnfields(res);
626 nTuples = PQntuples(res);
627
628 if (fp == NULL)
629 fp = stdout;
630
631 /* Figure the field lengths to align to */
632 /* will be somewhat time consuming for very large results */
633 if (fillAlign)
634 {
635 fLength = (int *) malloc(nFields * sizeof(int));
636 if (!fLength)
637 {
638 fprintf(stderr, libpq_gettext("out of memory\n"));
639 return;
640 }
641
642 for (j = 0; j < nFields; j++)
643 {
644 fLength[j] = strlen(PQfname(res, j));
645 for (i = 0; i < nTuples; i++)
646 {
647 int flen = PQgetlength(res, i, j);
648
649 if (flen > fLength[j])
650 fLength[j] = flen;
651 }
652 }
653 }
654
655 if (printHeader)
656 {
657 /* first, print out the attribute names */
658 for (i = 0; i < nFields; i++)
659 {
660 fputs(PQfname(res, i), fp);
661 if (fillAlign)
662 fill(strlen(PQfname(res, i)), fLength[i], ' ', fp);
663 fputs(fieldSep, fp);
664 }
665 fprintf(fp, "\n");
666
667 /* Underline the attribute names */
668 for (i = 0; i < nFields; i++)
669 {
670 if (fillAlign)
671 fill(0, fLength[i], '-', fp);
672 fputs(fieldSep, fp);
673 }
674 fprintf(fp, "\n");
675 }
676
677 /* next, print out the instances */
678 for (i = 0; i < nTuples; i++)
679 {
680 for (j = 0; j < nFields; j++)
681 {
682 fprintf(fp, "%s", PQgetvalue(res, i, j));
683 if (fillAlign)
684 fill(strlen(PQgetvalue(res, i, j)), fLength[j], ' ', fp);
685 fputs(fieldSep, fp);
686 }
687 fprintf(fp, "\n");
688 }
689
690 if (!quiet)
691 fprintf(fp, "\nQuery returned %d row%s.\n", PQntuples(res),
692 (PQntuples(res) == 1) ? "" : "s");
693
694 fflush(fp);
695
696 free(fLength);
697}
static void fill(int length, int max, char filler, FILE *fp)
Definition: fe-print.c:786
#define DEFAULT_FIELD_SEP
#define PQgetlength
Definition: libpq-be-fe.h:254
#define PQnfields
Definition: libpq-be-fe.h:252
#define PQfname
Definition: libpq-be-fe.h:256

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 1276 of file fe-misc.c.

1277{
1278 return pg_encoding_dsplen(encoding, s);
1279}
int pg_encoding_dsplen(int encoding, const char *mbstr)
Definition: wchar.c:2176

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, (uint8 *) user, strlen(user), crypt_pwd, &errstr))
1373 {
1374 free(crypt_pwd);
1375 return NULL;
1376 }
1377
1378 return crypt_pwd;
1379}
uint8_t uint8
Definition: c.h:539
#define MD5_PASSWD_LEN
Definition: md5.h:26
bool pg_md5_encrypt(const char *passwd, const uint8 *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, (uint8 *) 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:613

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

2967{
2968 if (!conn)
2969 return 0;
2970
2971 return pqEndcopy3(conn);
2972}
int pqEndcopy3(PGconn *conn)

References conn, and pqEndcopy3().

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

◆ PQenterPipelineMode()

int PQenterPipelineMode ( PGconn conn)

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

3060{
3061 if (!conn)
3062 return 0;
3063
3064 /* succeed with no action if already in pipeline mode */
3066 return 1;
3067
3069 {
3070 libpq_append_conn_error(conn, "cannot enter pipeline mode, connection not idle");
3071 return 0;
3072 }
3073
3075
3076 return 1;
3077}

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 1285 of file fe-misc.c.

1286{
1287 char *str;
1288 int encoding = PG_SQL_ASCII;
1289
1290 str = getenv("PGCLIENTENCODING");
1291 if (str && *str != '\0')
1292 {
1294 if (encoding < 0)
1296 }
1297 return encoding;
1298}
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 7704 of file fe-connect.c.

7705{
7706 if (!conn)
7707 return libpq_gettext("connection pointer is NULL\n");
7708
7709 /*
7710 * The errorMessage buffer might be marked "broken" due to having
7711 * previously failed to allocate enough memory for the message. In that
7712 * case, tell the application we ran out of memory.
7713 */
7715 return libpq_gettext("out of memory\n");
7716
7717 return conn->errorMessage.data;
7718}
#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_result_status_impl(), connect_database(), connect_pg_server(), ConnectDatabase(), connectDatabase(), connectToServer(), consume_null_result_impl(), consume_query_cancel_impl(), 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_internal(), pickout(), PQcancelErrorMessage(), prepareCommand(), process_query_result(), process_queued_fetch_requests(), process_result(), process_slot(), ProcessWALDataMsg(), psql_get_variable(), 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 4592 of file fe-exec.c.

4593{
4594 return PQescapeByteaInternal(NULL, from, from_length, to_length,
4596 false /* can't use hex */ );
4597}
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:4452
static bool static_std_strings
Definition: fe-exec.c:61

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

4579{
4580 if (!conn)
4581 return NULL;
4582
4583 if (conn->cmd_queue_head == NULL)
4585
4586 return PQescapeByteaInternal(conn, from, from_length, to_length,
4588 (conn->sversion >= 90000));
4589}
bool std_strings
Definition: libpq-int.h:557
PGcmdQueueEntry * cmd_queue_head
Definition: libpq-int.h:489

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

4406{
4407 return PQescapeInternal(conn, str, len, true);
4408}
static char * PQescapeInternal(PGconn *conn, const char *str, size_t len, bool as_ident)
Definition: fe-exec.c:4231

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

4217{
4218 return PQescapeStringInternal(NULL, to, from, length, NULL,
4221}
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:4088
static int static_client_encoding
Definition: fe-exec.c:60

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

4197{
4198 if (!conn)
4199 {
4200 /* force empty-string result */
4201 *to = '\0';
4202 if (error)
4203 *error = 1;
4204 return 0;
4205 }
4206
4207 if (conn->cmd_queue_head == NULL)
4209
4210 return PQescapeStringInternal(conn, to, from, length, error,
4212 conn->std_strings);
4213}
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 2279 of file fe-exec.c.

2280{
2281 if (!PQexecStart(conn))
2282 return NULL;
2283 if (!PQsendQuery(conn, query))
2284 return NULL;
2285 return PQexecFinish(conn);
2286}
int PQsendQuery(PGconn *conn, const char *query)
Definition: fe-exec.c:1433

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

2301{
2302 if (!PQexecStart(conn))
2303 return NULL;
2304 if (!PQsendQueryParams(conn, command,
2305 nParams, paramTypes, paramValues, paramLengths,
2306 paramFormats, resultFormat))
2307 return NULL;
2308 return PQexecFinish(conn);
2309}
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:1509

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

2347{
2348 if (!PQexecStart(conn))
2349 return NULL;
2350 if (!PQsendQueryPrepared(conn, stmtName,
2351 nParams, paramValues, paramLengths,
2352 paramFormats, resultFormat))
2353 return NULL;
2354 return PQexecFinish(conn);
2355}
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:1650

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

Referenced by ecpg_execute(), and try_complete_step().

◆ PQexitPipelineMode()

int PQexitPipelineMode ( PGconn conn)

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

3091{
3092 if (!conn)
3093 return 0;
3094
3098 conn->cmd_queue_head == NULL)
3099 return 1;
3100
3101 switch (conn->asyncStatus)
3102 {
3103 case PGASYNC_READY:
3104 case PGASYNC_READY_MORE:
3105 /* there are some uncollected results */
3106 libpq_append_conn_error(conn, "cannot exit pipeline mode with uncollected results");
3107 return 0;
3108
3109 case PGASYNC_BUSY:
3110 libpq_append_conn_error(conn, "cannot exit pipeline mode while busy");
3111 return 0;
3112
3113 case PGASYNC_IDLE:
3115 /* OK */
3116 break;
3117
3118 case PGASYNC_COPY_IN:
3119 case PGASYNC_COPY_OUT:
3120 case PGASYNC_COPY_BOTH:
3121 libpq_append_conn_error(conn, "cannot exit pipeline mode while in COPY");
3122 }
3123
3124 /* still work to process */
3125 if (conn->cmd_queue_head != NULL)
3126 {
3127 libpq_append_conn_error(conn, "cannot exit pipeline mode with uncollected results");
3128 return 0;
3129 }
3130
3133
3134 /* Flush any pending data in out buffer */
3135 if (pqFlush(conn) < 0)
3136 return 0; /* error message is setup already */
3137 return 1;
3138}
@ 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 3725 of file fe-exec.c.

3726{
3727 if (!check_field_number(res, field_num))
3728 return 0;
3729 if (res->attDescs)
3730 return res->attDescs[field_num].format;
3731 else
3732 return 0;
3733}
static int check_field_number(const PGresult *res, int field_num)
Definition: fe-exec.c:3527

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

5317{
5318 if (conn)
5319 {
5322 }
5323}
static void freePGconn(PGconn *conn)
Definition: fe-connect.c:5054

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_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_conflict_detection_slot(), 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_subscription_info(), 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(), runInitSteps(), set_frozenxids(), set_locale_and_encoding(), sql_conn(), sql_exec(), start_postmaster(), StreamLog(), StreamLogicalLog(), test_cancel(), 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 3758 of file fe-exec.c.

3759{
3760 if (!check_field_number(res, field_num))
3761 return 0;
3762 if (res->attDescs)
3763 return res->attDescs[field_num].atttypmod;
3764 else
3765 return 0;
3766}
int atttypmod
Definition: libpq-fe.h:313

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

3004{
3005 *result_len = 0;
3006
3007 if (!conn)
3008 return NULL;
3009
3010 /*
3011 * Since this is the beginning of a query cycle, reset the error state.
3012 * However, in pipeline mode with something already queued, the error
3013 * buffer belongs to that command and we shouldn't clear it.
3014 */
3015 if (conn->cmd_queue_head == NULL)
3017
3019 {
3020 libpq_append_conn_error(conn, "%s not allowed in pipeline mode", "PQfn");
3021 return NULL;
3022 }
3023
3026 {
3027 libpq_append_conn_error(conn, "connection in wrong state");
3028 return NULL;
3029 }
3030
3031 return pqFunctionCall3(conn, fnid,
3032 result_buf, result_len,
3033 result_is_int,
3034 args, nargs);
3035}
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:932

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 
)

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

3585{
3586 if (!check_field_number(res, field_num))
3587 return NULL;
3588 if (res->attDescs)
3589 return res->attDescs[field_num].name;
3590 else
3591 return NULL;
3592}
char * name
Definition: libpq-fe.h:307

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

◆ PQfnumber()

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

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

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

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(), check_new_cluster_replication_slots(), 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_subscription_info(), 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(), getSubscriptionRelations(), getSubscriptions(), 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_inconsistent_notnull(), 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 502 of file fe-cancel.c.

503{
504 free(cancel);
505}

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

3748{
3749 if (!check_field_number(res, field_num))
3750 return 0;
3751 if (res->attDescs)
3752 return res->attDescs[field_num].typlen;
3753 else
3754 return 0;
3755}

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

3704{
3705 if (!check_field_number(res, field_num))
3706 return InvalidOid;
3707 if (res->attDescs)
3708 return res->attDescs[field_num].tableid;
3709 else
3710 return InvalidOid;
3711}

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

◆ PQftablecol()

int PQftablecol ( const PGresult res,
int  field_num 
)

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

3715{
3716 if (!check_field_number(res, field_num))
3717 return 0;
3718 if (res->attDescs)
3719 return res->attDescs[field_num].columnid;
3720 else
3721 return 0;
3722}
int columnid
Definition: libpq-fe.h:309

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

7685{
7686 if (!conn)
7687 return 0;
7688 if (conn->status == CONNECTION_BAD)
7689 return 0;
7691}
#define PG_PROTOCOL_FULL(v)
Definition: pqcomm.h:88

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

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

Referenced by prompt_user().

◆ PQgetCancel()

PGcancel * PQgetCancel ( PGconn conn)

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

369{
370 PGcancel *cancel;
371 int cancel_req_len;
373
374 if (!conn)
375 return NULL;
376
377 if (conn->sock == PGINVALID_SOCKET)
378 return NULL;
379
380 /* Check that we have received a cancellation key */
381 if (conn->be_cancel_key_len == 0)
382 {
383 /*
384 * In case there is no cancel key, return an all-zero PGcancel object.
385 * Actually calling PQcancel on this will fail, but we allow creating
386 * the PGcancel object anyway. Arguably it would be better return NULL
387 * to indicate that cancellation is not possible, but there'd be no
388 * way for the caller to distinguish "out of memory" from "server did
389 * not send a cancel key". Also, this is how PGgetCancel() has always
390 * behaved, and if we changed it, some clients would stop working
391 * altogether with servers that don't support cancellation. (The
392 * modern PQcancelCreate() function returns a failed connection object
393 * instead.)
394 *
395 * The returned dummy object has cancel_pkt_len == 0; we check for
396 * that in PQcancel() to identify it as a dummy.
397 */
398 return calloc(1, sizeof(PGcancel));
399 }
400
401 cancel_req_len = offsetof(CancelRequestPacket, cancelAuthCode) + conn->be_cancel_key_len;
402 cancel = malloc(offsetof(PGcancel, cancel_req) + cancel_req_len);
403 if (cancel == NULL)
404 return NULL;
405
406 memcpy(&cancel->raddr, &conn->raddr, sizeof(SockAddr));
407
408 /* We use -1 to indicate an unset connection option */
409 cancel->pgtcp_user_timeout = -1;
410 cancel->keepalives = -1;
411 cancel->keepalives_idle = -1;
412 cancel->keepalives_interval = -1;
413 cancel->keepalives_count = -1;
414 if (conn->pgtcp_user_timeout != NULL)
415 {
417 &cancel->pgtcp_user_timeout,
418 conn, "tcp_user_timeout"))
419 goto fail;
420 }
421 if (conn->keepalives != NULL)
422 {
424 &cancel->keepalives,
425 conn, "keepalives"))
426 goto fail;
427 }
428 if (conn->keepalives_idle != NULL)
429 {
431 &cancel->keepalives_idle,
432 conn, "keepalives_idle"))
433 goto fail;
434 }
435 if (conn->keepalives_interval != NULL)
436 {
438 &cancel->keepalives_interval,
439 conn, "keepalives_interval"))
440 goto fail;
441 }
442 if (conn->keepalives_count != NULL)
443 {
445 &cancel->keepalives_count,
446 conn, "keepalives_count"))
447 goto fail;
448 }
449
450 req = (CancelRequestPacket *) &cancel->cancel_req;
454 /* include the length field itself in the length */
455 cancel->cancel_pkt_len = pg_hton32(cancel_req_len + 4);
456
457 return cancel;
458
459fail:
460 free(cancel);
461 return NULL;
462}
#define CANCEL_REQUEST_CODE
Definition: pqcomm.h:106
ProtocolVersion MsgType
Definition: pqcomm.h:117
MsgType cancelRequestCode
Definition: pqcomm.h:149
uint32 backendPID
Definition: pqcomm.h:150
uint8 cancelAuthCode[FLEXIBLE_ARRAY_MEMBER]
Definition: pqcomm.h:151
char cancel_req[FLEXIBLE_ARRAY_MEMBER]
Definition: fe-cancel.c:54
char * keepalives_idle
Definition: libpq-int.h:401
char * keepalives
Definition: libpq-int.h:400
char * keepalives_interval
Definition: libpq-int.h:402
char * pgtcp_user_timeout
Definition: libpq-int.h:385
char * keepalives_count
Definition: libpq-int.h:404

References CancelRequestPacket::backendPID, pg_conn::be_cancel_key, pg_conn::be_cancel_key_len, pg_conn::be_pid, calloc, 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 2833 of file fe-exec.c.

2834{
2835 *buffer = NULL; /* for all failure cases */
2836 if (!conn)
2837 return -2;
2840 {
2841 libpq_append_conn_error(conn, "no COPY in progress");
2842 return -2;
2843 }
2844 return pqGetCopyData3(conn, buffer, async);
2845}
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 1235 of file fe-misc.c.

1236{
1237 struct timeval tval;
1238
1239 gettimeofday(&tval, NULL);
1240 return (pg_usec_time_t) tval.tv_sec * 1000000 + tval.tv_usec;
1241}
int64_t pg_usec_time_t
Definition: libpq-fe.h:238
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 759 of file fe-secure-gssapi.c.

760{
761 if (!conn)
762 return NULL;
763
764 return conn->gctx;
765}

References conn.

◆ PQgetisnull()

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

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

3919{
3920 if (!check_tuple_field_number(res, tup_num, field_num))
3921 return 1; /* pretend it is null */
3922 if (res->tuples[tup_num][field_num].len == NULL_LEN)
3923 return 1;
3924 else
3925 return 0;
3926}
static int check_tuple_field_number(const PGresult *res, int tup_num, int field_num)
Definition: fe-exec.c:3542
#define NULL_LEN
Definition: libpq-int.h:130

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

◆ PQgetlength()

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

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

3905{
3906 if (!check_tuple_field_number(res, tup_num, field_num))
3907 return 0;
3908 if (res->tuples[tup_num][field_num].len != NULL_LEN)
3909 return res->tuples[tup_num][field_num].len;
3910 else
3911 return 0;
3912}

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

◆ PQgetline()

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

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

2872{
2873 if (!buffer || length <= 0)
2874 return EOF;
2875 *buffer = '\0';
2876 /* length must be at least 3 to hold the \. terminator! */
2877 if (length < 3)
2878 return EOF;
2879
2880 if (!conn)
2881 return EOF;
2882
2883 return pqGetline3(conn, buffer, length);
2884}
int pqGetline3(PGconn *conn, char *s, int maxlen)

References conn, and pqGetline3().

◆ PQgetlineAsync()

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

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

2919{
2920 if (!conn)
2921 return -1;
2922
2923 return pqGetlineAsync3(conn, buffer, bufsize);
2924}
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 2079 of file fe-exec.c.

2080{
2081 PGresult *res;
2082
2083 if (!conn)
2084 return NULL;
2085
2086 /* Parse any available data, if our state permits. */
2088
2089 /* If not ready to return something, block until we are. */
2090 while (conn->asyncStatus == PGASYNC_BUSY)
2091 {
2092 int flushResult;
2093
2094 /*
2095 * If data remains unsent, send it. Else we might be waiting for the
2096 * result of a command the backend hasn't even got yet.
2097 */
2098 while ((flushResult = pqFlush(conn)) > 0)
2099 {
2100 if (pqWait(false, true, conn))
2101 {
2102 flushResult = -1;
2103 break;
2104 }
2105 }
2106
2107 /*
2108 * Wait for some more data, and load it. (Note: if the connection has
2109 * been lost, pqWait should return immediately because the socket
2110 * should be read-ready, either with the last server data or with an
2111 * EOF indication. We expect therefore that this won't result in any
2112 * undue delay in reporting a previous write failure.)
2113 */
2114 if (flushResult ||
2115 pqWait(true, false, conn) ||
2116 pqReadData(conn) < 0)
2117 {
2118 /* Report the error saved by pqWait or pqReadData */
2121 return pqPrepareAsyncResult(conn);
2122 }
2123
2124 /* Parse it. */
2126
2127 /*
2128 * If we had a write error, but nothing above obtained a query result
2129 * or detected a read error, report the write error.
2130 */
2132 {
2135 return pqPrepareAsyncResult(conn);
2136 }
2137 }
2138
2139 /* Return the appropriate thing. */
2140 switch (conn->asyncStatus)
2141 {
2142 case PGASYNC_IDLE:
2143 res = NULL; /* query is complete */
2144 break;
2147
2148 /*
2149 * We're about to return the NULL that terminates the round of
2150 * results from the current query; prepare to send the results of
2151 * the next query, if any, when we're called next. If there's no
2152 * next element in the command queue, this gets us in IDLE state.
2153 */
2155 res = NULL; /* query is complete */
2156 break;
2157
2158 case PGASYNC_READY:
2160
2161 /*
2162 * Normally pqPrepareAsyncResult will have left conn->result
2163 * empty. Otherwise, "res" must be a not-full PGRES_TUPLES_CHUNK
2164 * result, which we want to return to the caller while staying in
2165 * PGASYNC_READY state. Then the next call here will return the
2166 * empty PGRES_TUPLES_OK result that was restored from
2167 * saved_result, after which we can proceed.
2168 */
2169 if (conn->result)
2170 {
2172 break;
2173 }
2174
2175 /* Advance the queue as appropriate */
2178
2180 {
2181 /*
2182 * We're about to send the results of the current query. Set
2183 * us idle now, and ...
2184 */
2186
2187 /*
2188 * ... in cases when we're sending a pipeline-sync result,
2189 * move queue processing forwards immediately, so that next
2190 * time we're called, we're prepared to return the next result
2191 * received from the server. In all other cases, leave the
2192 * queue state change for next time, so that a terminating
2193 * NULL result is sent.
2194 *
2195 * (In other words: we don't return a NULL after a pipeline
2196 * sync.)
2197 */
2200 }
2201 else
2202 {
2203 /* Set the state back to BUSY, allowing parsing to proceed. */
2205 }
2206 break;
2207 case PGASYNC_READY_MORE:
2209 /* Set the state back to BUSY, allowing parsing to proceed. */
2211 break;
2212 case PGASYNC_COPY_IN:
2214 break;
2215 case PGASYNC_COPY_OUT:
2217 break;
2218 case PGASYNC_COPY_BOTH:
2220 break;
2221 default:
2222 libpq_append_conn_error(conn, "unexpected asyncStatus: %d", (int) conn->asyncStatus);
2224 conn->asyncStatus = PGASYNC_IDLE; /* try to restore valid state */
2226 break;
2227 }
2228
2229 /* Time to fire PGEVT_RESULTCREATE events, if there are any */
2230 if (res && res->nEvents > 0)
2231 (void) PQfireResultCreateEvents(conn, res);
2232
2233 return res;
2234}
PGresult * pqPrepareAsyncResult(PGconn *conn)
Definition: fe-exec.c:857
static void pqSaveWriteError(PGconn *conn)
Definition: fe-exec.c:826
void pqCommandQueueAdvance(PGconn *conn, bool isReadyForQuery, bool gotSync)
Definition: fe-exec.c:3159
void pqSaveErrorResult(PGconn *conn)
Definition: fe-exec.c:809
static PGresult * getCopyResult(PGconn *conn, ExecStatusType copytype)
Definition: fe-exec.c:2241
static void parseInput(PGconn *conn)
Definition: fe-exec.c:2037
static void pqPipelineProcessQueue(PGconn *conn)
Definition: fe-exec.c:3197
int pqWait(int forRead, int forWrite, PGconn *conn)
Definition: fe-misc.c:1019
int PQfireResultCreateEvents(PGconn *conn, PGresult *res)
Definition: libpq-events.c:185
bool write_failed
Definition: libpq-int.h:512
PGresult * result
Definition: libpq-int.h:606
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 PQexecFinish(), and PQexecStart().

◆ PQgetssl()

void * PQgetssl ( PGconn conn)

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

1627{
1628 if (!conn)
1629 return NULL;
1630 return conn->ssl;
1631}

References conn.

◆ PQgetSSLKeyPassHook_OpenSSL()

PQsslKeyPassHook_OpenSSL_type PQgetSSLKeyPassHook_OpenSSL ( void  )

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

1923{
1924 return PQsslKeyPassHook;
1925}
static PQsslKeyPassHook_OpenSSL_type PQsslKeyPassHook

References PQsslKeyPassHook.

◆ PQgetvalue()

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

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

3894{
3895 if (!check_tuple_field_number(res, tup_num, field_num))
3896 return NULL;
3897 return res->tuples[tup_num][field_num].value;
3898}

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

◆ PQgssEncInUse()

int PQgssEncInUse ( PGconn conn)

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

772{
773 if (!conn || !conn->gctx)
774 return 0;
775
776 return conn->gssenc;
777}

References conn.

Referenced by printGSSInfo().

◆ PQhost()

char * PQhost ( const PGconn conn)

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

7572{
7573 if (!conn)
7574 return NULL;
7575
7576 if (conn->connhost != NULL)
7577 {
7578 /*
7579 * Return the verbatim host value provided by user, or hostaddr in its
7580 * lack.
7581 */
7582 if (conn->connhost[conn->whichhost].host != NULL &&
7583 conn->connhost[conn->whichhost].host[0] != '\0')
7584 return conn->connhost[conn->whichhost].host;
7585 else if (conn->connhost[conn->whichhost].hostaddr != NULL &&
7586 conn->connhost[conn->whichhost].hostaddr[0] != '\0')
7588 }
7589
7590 return "";
7591}

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

7595{
7596 if (!conn)
7597 return NULL;
7598
7599 /* Return the parsed IP address */
7600 if (conn->connhost != NULL && conn->connip != NULL)
7601 return conn->connip;
7602
7603 return "";
7604}

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

2049{
2050 if (!conn)
2051 return false;
2052
2053 /* Parse any available data, if our state permits. */
2055
2056 /*
2057 * PQgetResult will return immediately in all states except BUSY. Also,
2058 * if we've detected read EOF and dropped the connection, we can expect
2059 * that PQgetResult will fail immediately. Note that we do *not* check
2060 * conn->write_failed here --- once that's become set, we know we have
2061 * trouble, but we need to keep trying to read until we have a complete
2062 * server message or detect read EOF.
2063 */
2065}

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

Referenced by advanceConnectionState(), consume_query_cancel_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 4000 of file fe-exec.c.

4001{
4002 if (!conn || conn->status == CONNECTION_BAD)
4003 return false;
4004 return pqIsnonblocking(conn);
4005}

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

4010{
4011 return true;
4012}

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

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

1256{
1257 return pg_encoding_mblen(encoding, s);
1258}
int pg_encoding_mblen(int encoding, const char *mbstr)
Definition: wchar.c:2135

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

int PQnfields ( const PGresult res)

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

3507{
3508 if (!res)
3509 return 0;
3510 return res->numAttributes;
3511}

References pg_result::numAttributes.

◆ PQnotifies()

PGnotify * PQnotifies ( PGconn conn)

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

2685{
2686 PGnotify *event;
2687
2688 if (!conn)
2689 return NULL;
2690
2691 /* Parse any available data to see if we can extract NOTIFY messages. */
2693
2694 event = conn->notifyHead;
2695 if (event)
2696 {
2697 conn->notifyHead = event->next;
2698 if (!conn->notifyHead)
2699 conn->notifyTail = NULL;
2700 event->next = NULL; /* don't let app see the internal state */
2701 }
2702 return event;
2703}
struct pgNotify * next
Definition: libpq-fe.h:234
PGnotify * notifyHead
Definition: libpq-int.h:476
PGnotify * notifyTail
Definition: libpq-int.h:477

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

3933{
3934 if (!res)
3935 return 0;
3936 return res->numParameters;
3937}

References pg_result::numParameters.

◆ PQntuples()

int PQntuples ( const PGresult res)

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

3499{
3500 if (!res)
3501 return 0;
3502 return res->ntups;
3503}

References pg_result::ntups.

◆ PQoidStatus()

char * PQoidStatus ( const PGresult res)

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

3783{
3784 /*
3785 * This must be enough to hold the result. Don't laugh, this is better
3786 * than what this function used to do.
3787 */
3788 static char buf[24];
3789
3790 size_t len;
3791
3792 if (!res || strncmp(res->cmdStatus, "INSERT ", 7) != 0)
3793 return "";
3794
3795 len = strspn(res->cmdStatus + 7, "0123456789");
3796 if (len > sizeof(buf) - 1)
3797 len = sizeof(buf) - 1;
3798 memcpy(buf, res->cmdStatus + 7, len);
3799 buf[len] = '\0';
3800
3801 return buf;
3802}

References buf, pg_result::cmdStatus, and len.

◆ PQoidValue()

Oid PQoidValue ( const PGresult res)

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

3811{
3812 char *endptr = NULL;
3813 unsigned long result;
3814
3815 if (!res ||
3816 strncmp(res->cmdStatus, "INSERT ", 7) != 0 ||
3817 res->cmdStatus[7] < '0' ||
3818 res->cmdStatus[7] > '9')
3819 return InvalidOid;
3820
3821 result = strtoul(res->cmdStatus + 7, &endptr, 10);
3822
3823 if (!endptr || (*endptr != ' ' && *endptr != '\0'))
3824 return InvalidOid;
3825 else
3826 return (Oid) result;
3827}

References pg_result::cmdStatus, and InvalidOid.

Referenced by ecpg_process_output(), and PrintQueryStatus().

◆ PQoptions()

char * PQoptions ( const PGconn conn)

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

7634{
7635 if (!conn)
7636 return NULL;
7637 return conn->pgoptions;
7638}
char * pgoptions
Definition: libpq-int.h:387

References conn, and pg_conn::pgoptions.

Referenced by exec_command_conninfo().

◆ PQparameterStatus()

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

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

7660{
7661 const pgParameterStatus *pstatus;
7662
7663 if (!conn || !paramName)
7664 return NULL;
7665 for (pstatus = conn->pstatus; pstatus != NULL; pstatus = pstatus->next)
7666 {
7667 if (strcmp(pstatus->name, paramName) == 0)
7668 return pstatus->value;
7669 }
7670 return NULL;
7671}
struct pgParameterStatus * next
Definition: libpq-int.h:271
pgParameterStatus * pstatus
Definition: libpq-int.h:555

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

3944{
3945 if (!check_param_number(res, param_num))
3946 return InvalidOid;
3947 if (res->paramDescs)
3948 return res->paramDescs[param_num].typid;
3949 else
3950 return InvalidOid;
3951}
static int check_param_number(const PGresult *res, int param_num)
Definition: fe-exec.c:3565

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

◆ PQpass()

char * PQpass ( const PGconn conn)

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

7555{
7556 char *password = NULL;
7557
7558 if (!conn)
7559 return NULL;
7560 if (conn->connhost != NULL)
7562 if (password == NULL)
7563 password = conn->pgpass;
7564 /* Historically we've returned "" not NULL for no password specified */
7565 if (password == NULL)
7566 password = "";
7567 return password;
7568}
char * pgpass
Definition: libpq-int.h:396

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

842{
843 PGconn *conn = PQconnectStart(conninfo);
844 PGPing ret;
845
846 ret = internal_ping(conn);
847 PQfinish(conn);
848
849 return ret;
850}
static PGPing internal_ping(PGconn *conn)
Definition: fe-connect.c:4890

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

◆ PQpingParams()

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

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

791{
792 PGconn *conn = PQconnectStartParams(keywords, values, expand_dbname);
793 PGPing ret;
794
795 ret = internal_ping(conn);
796 PQfinish(conn);
797
798 return ret;
799}

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

7608{
7609 if (!conn)
7610 return NULL;
7611
7612 if (conn->connhost != NULL &&
7613 conn->connhost[conn->whichhost].port != NULL &&
7614 conn->connhost[conn->whichhost].port[0] != '\0')
7615 return conn->connhost[conn->whichhost].port;
7616
7617 return DEF_PGPORT_STR;
7618}

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

2326{
2327 if (!PQexecStart(conn))
2328 return NULL;
2329 if (!PQsendPrepare(conn, stmtName, query, nParams, paramTypes))
2330 return NULL;
2331 return PQexecFinish(conn);
2332}
int PQsendPrepare(PGconn *conn, const char *stmtName, const char *query, int nParams, const Oid *paramTypes)
Definition: fe-exec.c:1553

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 69 of file fe-print.c.

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

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 702 of file fe-print.c.

708{
709 int nFields;
710 int nTups;
711 int i,
712 j;
713 char formatString[80];
714 char *tborder = NULL;
715
716 nFields = PQnfields(res);
717 nTups = PQntuples(res);
718
719 if (colWidth > 0)
720 sprintf(formatString, "%%s %%-%ds", colWidth);
721 else
722 sprintf(formatString, "%%s %%s");
723
724 if (nFields > 0)
725 { /* only print rows with at least 1 field. */
726
727 if (!TerseOutput)
728 {
729 int width;
730
731 width = nFields * 14;
732 tborder = (char *) malloc(width + 1);
733 if (!tborder)
734 {
735 fprintf(stderr, libpq_gettext("out of memory\n"));
736 return;
737 }
738 for (i = 0; i < width; i++)
739 tborder[i] = '-';
740 tborder[width] = '\0';
741 fprintf(fout, "%s\n", tborder);
742 }
743
744 for (i = 0; i < nFields; i++)
745 {
746 if (PrintAttNames)
747 {
748 fprintf(fout, formatString,
749 TerseOutput ? "" : "|",
750 PQfname(res, i));
751 }
752 }
753
754 if (PrintAttNames)
755 {
756 if (TerseOutput)
757 fprintf(fout, "\n");
758 else
759 fprintf(fout, "|\n%s\n", tborder);
760 }
761
762 for (i = 0; i < nTups; i++)
763 {
764 for (j = 0; j < nFields; j++)
765 {
766 const char *pval = PQgetvalue(res, i, j);
767
768 fprintf(fout, formatString,
769 TerseOutput ? "" : "|",
770 pval ? pval : "");
771 }
772 if (TerseOutput)
773 fprintf(fout, "\n");
774 else
775 fprintf(fout, "|\n%s\n", tborder);
776 }
777 }
778
779 free(tborder);
780}
#define sprintf
Definition: port.h:262

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

◆ PQprotocolVersion()

int PQprotocolVersion ( const PGconn conn)

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

7675{
7676 if (!conn)
7677 return 0;
7678 if (conn->status == CONNECTION_BAD)
7679 return 0;
7681}
#define PG_PROTOCOL_MAJOR(v)
Definition: pqcomm.h:86

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

Referenced by handleCopyIn().

◆ PQputCopyData()

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

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

2713{
2714 if (!conn)
2715 return -1;
2718 {
2719 libpq_append_conn_error(conn, "no COPY in progress");
2720 return -1;
2721 }
2722
2723 /*
2724 * Process any NOTICE or NOTIFY messages that might be pending in the
2725 * input buffer. Since the server might generate many notices during the
2726 * COPY, we want to clean those out reasonably promptly to prevent
2727 * indefinite expansion of the input buffer. (Note: the actual read of
2728 * input data into the input buffer happens down inside pqSendSome, but
2729 * it's not authorized to get rid of the data again.)
2730 */
2732
2733 if (nbytes > 0)
2734 {
2735 /*
2736 * Try to flush any previously sent data in preference to growing the
2737 * output buffer. If we can't enlarge the buffer enough to hold the
2738 * data, return 0 in the nonblock case, else hard error. (For
2739 * simplicity, always assume 5 bytes of overhead.)
2740 */
2741 if ((conn->outBufSize - conn->outCount - 5) < nbytes)
2742 {
2743 if (pqFlush(conn) < 0)
2744 return -1;
2745 if (pqCheckOutBufferSpace(conn->outCount + 5 + (size_t) nbytes,
2746 conn))
2747 return pqIsnonblocking(conn) ? 0 : -1;
2748 }
2749 /* Send the data (too simple to delegate to fe-protocol files) */
2750 if (pqPutMsgStart(PqMsg_CopyData, conn) < 0 ||
2751 pqPutnchar(buffer, nbytes, conn) < 0 ||
2752 pqPutMsgEnd(conn) < 0)
2753 return -1;
2754 }
2755 return 1;
2756}
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 void *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:584
int outCount
Definition: libpq-int.h:585

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

2767{
2768 if (!conn)
2769 return -1;
2772 {
2773 libpq_append_conn_error(conn, "no COPY in progress");
2774 return -1;
2775 }
2776
2777 /*
2778 * Send the COPY END indicator. This is simple enough that we don't
2779 * bother delegating it to the fe-protocol files.
2780 */
2781 if (errormsg)
2782 {
2783 /* Send COPY FAIL */
2784 if (pqPutMsgStart(PqMsg_CopyFail, conn) < 0 ||
2785 pqPuts(errormsg, conn) < 0 ||
2786 pqPutMsgEnd(conn) < 0)
2787 return -1;
2788 }
2789 else
2790 {
2791 /* Send COPY DONE */
2792 if (pqPutMsgStart(PqMsg_CopyDone, conn) < 0 ||
2793 pqPutMsgEnd(conn) < 0)
2794 return -1;
2795 }
2796
2797 /*
2798 * If we sent the COPY command in extended-query mode, we must issue a
2799 * Sync as well.
2800 */
2801 if (conn->cmd_queue_head &&
2803 {
2804 if (pqPutMsgStart(PqMsg_Sync, conn) < 0 ||
2805 pqPutMsgEnd(conn) < 0)
2806 return -1;
2807 }
2808
2809 /* Return to active duty */
2812 else
2814
2815 /* Try to flush data */
2816 if (pqFlush(conn) < 0)
2817 return -1;
2818
2819 return 1;
2820}
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 ProcessWALDataMsg().

◆ PQputline()

int PQputline ( PGconn conn,
const char *  string 
)

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

2936{
2937 return PQputnbytes(conn, string, strlen(string));
2938}
int PQputnbytes(PGconn *conn, const char *buffer, int nbytes)
Definition: fe-exec.c:2945

References conn, and PQputnbytes().

Referenced by initPopulateTable().

◆ PQputnbytes()

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

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

2946{
2947 if (PQputCopyData(conn, buffer, nbytes) > 0)
2948 return 0;
2949 else
2950 return EOF;
2951}
int PQputCopyData(PGconn *conn, const char *buffer, int nbytes)
Definition: fe-exec.c:2712

References conn, and PQputCopyData().

Referenced by PQputline().

◆ PQregisterThreadLock()

pgthreadlock_t PQregisterThreadLock ( pgthreadlock_t  newhandler)

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

8374{
8376
8377 if (newhandler)
8378 pg_g_threadlock = newhandler;
8379 else
8381
8382 return prev;
8383}
static void default_threadlock(int acquire)
Definition: fe-connect.c:8356
pgthreadlock_t pg_g_threadlock
Definition: fe-connect.c:516
void(* pgthreadlock_t)(int acquire)
Definition: libpq-fe.h:468

References default_threadlock(), and pg_g_threadlock.

◆ PQrequestCancel()

int PQrequestCancel ( PGconn conn)

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

753{
754 int r;
755 PGcancel *cancel;
756
757 /* Check we have an open connection */
758 if (!conn)
759 return false;
760
761 if (conn->sock == PGINVALID_SOCKET)
762 {
764 "PQrequestCancel() -- connection is not open\n",
767 conn->errorReported = 0;
768
769 return false;
770 }
771
772 cancel = PQgetCancel(conn);
773 if (cancel)
774 {
775 r = PQcancel(cancel, conn->errorMessage.data,
777 PQfreeCancel(cancel);
778 }
779 else
780 {
781 strlcpy(conn->errorMessage.data, "out of memory",
783 r = false;
784 }
785
786 if (!r)
787 {
789 conn->errorReported = 0;
790 }
791
792 return r;
793}
PGcancel * PQgetCancel(PGconn *conn)
Definition: fe-cancel.c:368
int PQcancel(PGcancel *cancel, char *errbuf, int errbufsize)
Definition: fe-cancel.c:548
void PQfreeCancel(PGcancel *cancel)
Definition: fe-cancel.c:502
int errorReported
Definition: libpq-int.h:684

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

5331{
5332 if (conn)
5333 {
5335
5337 {
5338 /*
5339 * Notify event procs of successful reset.
5340 */
5341 int i;
5342
5343 for (i = 0; i < conn->nEvents; i++)
5344 {
5345 PGEventConnReset evt;
5346
5347 evt.conn = conn;
5348 (void) conn->events[i].proc(PGEVT_CONNRESET, &evt,
5350 }
5351 }
5352 }
5353}
@ 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 5382 of file fe-connect.c.

5383{
5384 if (conn)
5385 {
5387
5388 if (status == PGRES_POLLING_OK)
5389 {
5390 /*
5391 * Notify event procs of successful reset.
5392 */
5393 int i;
5394
5395 for (i = 0; i < conn->nEvents; i++)
5396 {
5397 PGEventConnReset evt;
5398
5399 evt.conn = conn;
5400 (void) conn->events[i].proc(PGEVT_CONNRESET, &evt,
5402 }
5403 }
5404
5405 return status;
5406 }
5407
5408 return PGRES_POLLING_FAILED;
5409}

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

5364{
5365 if (conn)
5366 {
5368
5369 return pqConnectDBStart(conn);
5370 }
5371
5372 return 0;
5373}

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

◆ PQresStatus()

char * PQresStatus ( ExecStatusType  status)

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

3437{
3438 if ((unsigned int) status >= lengthof(pgresStatus))
3439 return libpq_gettext("invalid ExecStatusType code");
3440 return pgresStatus[status];
3441}
char *const pgresStatus[]
Definition: fe-exec.c:33

References lengthof, libpq_gettext, and pgresStatus.

Referenced by BaseBackup(), confirm_result_status_impl(), consume_null_result_impl(), process_result(), test_pipeline_abort(), test_pipelined_insert(), test_prepared(), test_singlerowmode(), test_transaction(), and try_complete_step().

◆ PQresultAlloc()

void * PQresultAlloc ( PGresult res,
size_t  nBytes 
)

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

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

References OOM_result, and pqResultAlloc().

Referenced by PQsetResultAttrs().

◆ PQresultErrorField()

char * PQresultErrorField ( const PGresult res,
int  fieldcode 
)

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

3484{
3485 PGMessageField *pfield;
3486
3487 if (!res)
3488 return NULL;
3489 for (pfield = res->errFields; pfield != NULL; pfield = pfield->next)
3490 {
3491 if (pfield->code == fieldcode)
3492 return pfield->contents;
3493 }
3494 return NULL;
3495}
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.

◆ PQresultErrorMessage()

char * PQresultErrorMessage ( const PGresult res)

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

3445{
3446 if (!res || !res->errMsg)
3447 return "";
3448 return res->errMsg;
3449}

References pg_result::errMsg.

◆ PQresultMemorySize()

size_t PQresultMemorySize ( const PGresult res)

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

670{
671 if (!res)
672 return 0;
673 return res->memorySize;
674}

References pg_result::memorySize.

◆ PQresultStatus()

ExecStatusType PQresultStatus ( const PGresult res)

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

3429{
3430 if (!res)
3431 return PGRES_FATAL_ERROR;
3432 return res->resultStatus;
3433}

References PGRES_FATAL_ERROR, and pg_result::resultStatus.

◆ PQresultVerboseErrorMessage()

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

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

3455{
3456 PQExpBufferData workBuf;
3457
3458 /*
3459 * Because the caller is expected to free the result string, we must
3460 * strdup any constant result. We use plain strdup and document that
3461 * callers should expect NULL if out-of-memory.
3462 */
3463 if (!res ||
3466 return strdup(libpq_gettext("PGresult is not an error result\n"));
3467
3468 initPQExpBuffer(&workBuf);
3469
3470 pqBuildErrorMessage3(&workBuf, res, verbosity, show_context);
3471
3472 /* If insufficient memory to format the message, fail cleanly */
3473 if (PQExpBufferDataBroken(workBuf))
3474 {
3475 termPQExpBuffer(&workBuf);
3476 return strdup(libpq_gettext("out of memory\n"));
3477 }
3478
3479 return workBuf.data;
3480}
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 2586 of file fe-exec.c.

2587{
2588 return PQsendTypedCommand(conn, PqMsg_Close, 'P', portal);
2589}

References conn, PqMsg_Close, and PQsendTypedCommand().

Referenced by test_prepared().

◆ PQsendClosePrepared()

int PQsendClosePrepared ( PGconn conn,
const char *  stmt 
)

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

2574{
2575 return PQsendTypedCommand(conn, PqMsg_Close, 'S', stmt);
2576}

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

Referenced by ExecQueryAndProcessResults(), and test_prepared().

◆ PQsendDescribePortal()

int PQsendDescribePortal ( PGconn conn,
const char *  portal 
)

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

2522{
2523 return PQsendTypedCommand(conn, PqMsg_Describe, 'P', portal);
2524}

References conn, PqMsg_Describe, and PQsendTypedCommand().

Referenced by test_prepared().

◆ PQsendDescribePrepared()

int PQsendDescribePrepared ( PGconn conn,
const char *  stmt 
)

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

2509{
2511}

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

Referenced by test_prepared().

◆ PQsendFlushRequest()

int PQsendFlushRequest ( PGconn conn)

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

3389{
3390 if (!conn)
3391 return 0;
3392
3393 /* Don't try to send if we know there's no live connection. */
3394 if (conn->status != CONNECTION_OK)
3395 {
3396 libpq_append_conn_error(conn, "no connection to the server");
3397 return 0;
3398 }
3399
3400 /* Can't send while already busy, either, unless enqueuing for later */
3401 if (conn->asyncStatus != PGASYNC_IDLE &&
3403 {
3404 libpq_append_conn_error(conn, "another command is already in progress");
3405 return 0;
3406 }
3407
3408 if (pqPutMsgStart(PqMsg_Flush, conn) < 0 ||
3409 pqPutMsgEnd(conn) < 0)
3410 {
3411 return 0;
3412 }
3413
3414 /*
3415 * Give the data a push (in pipeline mode, only if we're past the size
3416 * threshold). In nonblock mode, don't complain if we're unable to send
3417 * it all; PQgetResult() will do any additional flushing needed.
3418 */
3419 if (pqPipelineFlush(conn) < 0)
3420 return 0;
3421
3422 return 1;
3423}
static int pqPipelineFlush(PGconn *conn)
Definition: fe-exec.c:4033
#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 3299 of file fe-exec.c.

3300{
3301 return pqPipelineSyncInternal(conn, false);
3302}

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

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

1517{
1518 if (!PQsendQueryStart(conn, true))
1519 return 0;
1520
1521 /* check the arguments */
1522 if (!command)
1523 {
1524 libpq_append_conn_error(conn, "command string is a null pointer");
1525 return 0;
1526 }
1527 if (nParams < 0 || nParams > PQ_QUERY_PARAM_MAX_LIMIT)
1528 {
1529 libpq_append_conn_error(conn, "number of parameters must be between 0 and %d",
1531 return 0;
1532 }
1533
1534 return PQsendQueryGuts(conn,
1535 command,
1536 "", /* use unnamed statement */
1537 nParams,
1538 paramTypes,
1539 paramValues,
1540 paramLengths,
1541 paramFormats,
1542 resultFormat);
1543}
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:1774

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

1657{
1658 if (!PQsendQueryStart(conn, true))
1659 return 0;
1660
1661 /* check the arguments */
1662 if (!stmtName)
1663 {
1664 libpq_append_conn_error(conn, "statement name is a null pointer");
1665 return 0;
1666 }
1667 if (nParams < 0 || nParams > PQ_QUERY_PARAM_MAX_LIMIT)
1668 {
1669 libpq_append_conn_error(conn, "number of parameters must be between 0 and %d",
1671 return 0;
1672 }
1673
1674 return PQsendQueryGuts(conn,
1675 NULL, /* no command to parse */
1676 stmtName,
1677 nParams,
1678 NULL, /* no param types */
1679 paramValues,
1680 paramLengths,
1681 paramFormats,
1682 resultFormat);
1683}

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

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

1983{
1984 if (chunkSize > 0 && canChangeResultMode(conn))
1985 {
1986 conn->partialResMode = true;
1987 conn->singleRowMode = false;
1988 conn->maxChunkSize = chunkSize;
1989 return 1;
1990 }
1991 else
1992 return 0;
1993}
static bool canChangeResultMode(PGconn *conn)
Definition: fe-exec.c:1942
int maxChunkSize
Definition: libpq-int.h:472
bool singleRowMode
Definition: libpq-int.h:471
bool partialResMode
Definition: libpq-int.h:470

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

7803{
7804 char qbuf[128];
7805 static const char query[] = "set client_encoding to '%s'";
7806 PGresult *res;
7807 int status;
7808
7809 if (!conn || conn->status != CONNECTION_OK)
7810 return -1;
7811
7812 if (!encoding)
7813 return -1;
7814
7815 /* Resolve special "auto" value from the locale */
7816 if (strcmp(encoding, "auto") == 0)
7818
7819 /* check query buffer overflow */
7820 if (sizeof(qbuf) < (sizeof(query) + strlen(encoding)))
7821 return -1;
7822
7823 /* ok, now send a query */
7824 sprintf(qbuf, query, encoding);
7825 res = PQexec(conn, qbuf);
7826
7827 if (res == NULL)
7828 return -1;
7829 if (res->resultStatus != PGRES_COMMAND_OK)
7830 status = -1;
7831 else
7832 {
7833 /*
7834 * We rely on the backend to report the parameter value, and we'll
7835 * change state at that time.
7836 */
7837 status = 0; /* everything is ok */
7838 }
7839 PQclear(res);
7840 return status;
7841}
#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(), test_gb18030_page_multiple(), 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 2245 of file fe-connect.c.

2248{
2249 PGconn *conn;
2250
2251 /*
2252 * Allocate memory for the conn structure. Note that we also expect this
2253 * to initialize conn->errorMessage to empty. All subsequent steps during
2254 * connection initialization will only append to that buffer.
2255 */
2257 if (conn == NULL)
2258 return NULL;
2259
2260 /*
2261 * If the dbName parameter contains what looks like a connection string,
2262 * parse it into conn struct using connectOptions1.
2263 */
2265 {
2267 return conn;
2268 }
2269 else
2270 {
2271 /*
2272 * Old-style path: first, parse an empty conninfo string in order to
2273 * set up the same defaults that PQconnectdb() would use.
2274 */
2275 if (!connectOptions1(conn, ""))
2276 return conn;
2277
2278 /* Insert dbName parameter value into struct */
2279 if (dbName && dbName[0] != '\0')
2280 {
2281 free(conn->dbName);
2282 conn->dbName = strdup(dbName);
2283 if (!conn->dbName)
2284 goto oom_error;
2285 }
2286 }
2287
2288 /*
2289 * Insert remaining parameters into struct, overriding defaults (as well
2290 * as any conflicting data from dbName taken as a conninfo).
2291 */
2292 if (pghost && pghost[0] != '\0')
2293 {
2294 free(conn->pghost);
2295 conn->pghost = strdup(pghost);
2296 if (!conn->pghost)
2297 goto oom_error;
2298 }
2299
2300 if (pgport && pgport[0] != '\0')
2301 {
2302 free(conn->pgport);
2303 conn->pgport = strdup(pgport);
2304 if (!conn->pgport)
2305 goto oom_error;
2306 }
2307
2308 if (pgoptions && pgoptions[0] != '\0')
2309 {
2311 conn->pgoptions = strdup(pgoptions);
2312 if (!conn->pgoptions)
2313 goto oom_error;
2314 }
2315
2316 if (login && login[0] != '\0')
2317 {
2318 free(conn->pguser);
2319 conn->pguser = strdup(login);
2320 if (!conn->pguser)
2321 goto oom_error;
2322 }
2323
2324 if (pwd && pwd[0] != '\0')
2325 {
2326 free(conn->pgpass);
2327 conn->pgpass = strdup(pwd);
2328 if (!conn->pgpass)
2329 goto oom_error;
2330 }
2331
2332 /*
2333 * Compute derived options
2334 */
2335 if (!pqConnectOptions2(conn))
2336 return conn;
2337
2338 /*
2339 * Connect to the database
2340 */
2342 (void) pqConnectDBComplete(conn);
2343
2344 return conn;
2345
2346oom_error:
2348 libpq_append_conn_error(conn, "out of memory");
2349 return conn;
2350}
static bool recognized_connection_string(const char *connstr)
Definition: fe-connect.c:6345
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:374
char * pguser
Definition: libpq-int.h:395
char * pgport
Definition: libpq-int.h:382

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

7857{
7859
7860 if (!conn)
7861 return PQSHOW_CONTEXT_ERRORS;
7862 old = conn->show_context;
7863 conn->show_context = show_context;
7864 return old;
7865}
PGContextVisibility show_context
Definition: libpq-int.h:561

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

7845{
7846 PGVerbosity old;
7847
7848 if (!conn)
7849 return PQERRORS_DEFAULT;
7850 old = conn->verbosity;
7851 conn->verbosity = verbosity;
7852 return old;
7853}
PGVerbosity verbosity
Definition: libpq-int.h:560

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

3962{
3963 bool barg;
3964
3965 if (!conn || conn->status == CONNECTION_BAD)
3966 return -1;
3967
3968 barg = (arg ? true : false);
3969
3970 /* early out if the socket is already in the state requested */
3971 if (barg == conn->nonblocking)
3972 return 0;
3973
3974 /*
3975 * to guarantee constancy for flushing/query/result-polling behavior we
3976 * need to flush the send queue at this point in order to guarantee proper
3977 * behavior. this is ok because either they are making a transition _from_
3978 * or _to_ blocking mode, either way we can block them.
3979 *
3980 * Clear error state in case pqFlush adds to it, unless we're actively
3981 * pipelining, in which case it seems best not to.
3982 */
3983 if (conn->cmd_queue_head == NULL)
3985
3986 /* if we are going from blocking to non-blocking flush here */
3987 if (pqFlush(conn))
3988 return -1;
3989
3990 conn->nonblocking = barg;
3991
3992 return 0;
3993}
return true
Definition: isn.c:130
void * arg
bool nonblocking
Definition: libpq-int.h:467

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

7886{
7888
7889 if (conn == NULL)
7890 return NULL;
7891
7893 if (proc)
7894 {
7895 conn->noticeHooks.noticeProc = proc;
7897 }
7898 return old;
7899}
void(* PQnoticeProcessor)(void *arg, const char *message)
Definition: libpq-fe.h:242

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

7869{
7870 PQnoticeReceiver old;
7871
7872 if (conn == NULL)
7873 return NULL;
7874
7875 old = conn->noticeHooks.noticeRec;
7876 if (proc)
7877 {
7878 conn->noticeHooks.noticeRec = proc;
7880 }
7881 return old;
7882}
void(* PQnoticeReceiver)(void *arg, const PGresult *res)
Definition: libpq-fe.h:241

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

Referenced by connect_pg_server(), dblink_connect(), dblink_get_conn(), ECPGconnect(), and libpqrcv_connect().

◆ PQsetResultAttrs()

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

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

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

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

1966{
1968 {
1969 conn->partialResMode = true;
1970 conn->singleRowMode = true;
1971 conn->maxChunkSize = 1;
1972 return 1;
1973 }
1974 else
1975 return 0;
1976}

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

1929{
1930 PQsslKeyPassHook = hook;
1931}

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:451

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

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

1142{
1143 /* We use poll(2) if available, otherwise select(2) */
1144#ifdef HAVE_POLL
1145 struct pollfd input_fd;
1146 int timeout_ms;
1147
1148 if (!forRead && !forWrite)
1149 return 0;
1150
1151 input_fd.fd = sock;
1152 input_fd.events = POLLERR;
1153 input_fd.revents = 0;
1154
1155 if (forRead)
1156 input_fd.events |= POLLIN;
1157 if (forWrite)
1158 input_fd.events |= POLLOUT;
1159
1160 /* Compute appropriate timeout interval */
1161 if (end_time == -1)
1162 timeout_ms = -1;
1163 else if (end_time == 0)
1164 timeout_ms = 0;
1165 else
1166 {
1168
1169 if (end_time > now)
1170 timeout_ms = (end_time - now) / 1000;
1171 else
1172 timeout_ms = 0;
1173 }
1174
1175 return poll(&input_fd, 1, timeout_ms);
1176#else /* !HAVE_POLL */
1177
1178 fd_set input_mask;
1179 fd_set output_mask;
1180 fd_set except_mask;
1181 struct timeval timeout;
1182 struct timeval *ptr_timeout;
1183
1184 if (!forRead && !forWrite)
1185 return 0;
1186
1187 FD_ZERO(&input_mask);
1188 FD_ZERO(&output_mask);
1189 FD_ZERO(&except_mask);
1190 if (forRead)
1191 FD_SET(sock, &input_mask);
1192
1193 if (forWrite)
1194 FD_SET(sock, &output_mask);
1195 FD_SET(sock, &except_mask);
1196
1197 /* Compute appropriate timeout interval */
1198 if (end_time == -1)
1199 ptr_timeout = NULL;
1200 else if (end_time == 0)
1201 {
1202 timeout.tv_sec = 0;
1203 timeout.tv_usec = 0;
1204 ptr_timeout = &timeout;
1205 }
1206 else
1207 {
1209
1210 if (end_time > now)
1211 {
1212 timeout.tv_sec = (end_time - now) / 1000000;
1213 timeout.tv_usec = (end_time - now) % 1000000;
1214 }
1215 else
1216 {
1217 timeout.tv_sec = 0;
1218 timeout.tv_usec = 0;
1219 }
1220 ptr_timeout = &timeout;
1221 }
1222
1223 return select(sock + 1, &input_mask, &output_mask,
1224 &except_mask, ptr_timeout);
1225#endif /* HAVE_POLL */
1226}
Datum now(PG_FUNCTION_ARGS)
Definition: timestamp.c:1609
pg_usec_time_t PQgetCurrentTimeUSec(void)
Definition: fe-misc.c:1235
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 1671 of file fe-secure-openssl.c.

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

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

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

1635{
1636 if (!conn)
1637 return NULL;
1638 if (strcmp(struct_name, "OpenSSL") == 0)
1639 return conn->ssl;
1640 return NULL;
1641}

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

7626{
7627 if (!conn)
7628 return NULL;
7629 return "";
7630}

References conn.

◆ PQunescapeBytea()

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

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

4618{
4619 size_t strtextlen,
4620 buflen;
4621 unsigned char *buffer,
4622 *tmpbuf;
4623 size_t i,
4624 j;
4625
4626 if (strtext == NULL)
4627 return NULL;
4628
4629 strtextlen = strlen((const char *) strtext);
4630
4631 if (strtext[0] == '\\' && strtext[1] == 'x')
4632 {
4633 const unsigned char *s;
4634 unsigned char *p;
4635
4636 buflen = (strtextlen - 2) / 2;
4637 /* Avoid unportable malloc(0) */
4638 buffer = (unsigned char *) malloc(buflen > 0 ? buflen : 1);
4639 if (buffer == NULL)
4640 return NULL;
4641
4642 s = strtext + 2;
4643 p = buffer;
4644 while (*s)
4645 {
4646 char v1,
4647 v2;
4648
4649 /*
4650 * Bad input is silently ignored. Note that this includes
4651 * whitespace between hex pairs, which is allowed by byteain.
4652 */
4653 v1 = get_hex(*s++);
4654 if (!*s || v1 == (char) -1)
4655 continue;
4656 v2 = get_hex(*s++);
4657 if (v2 != (char) -1)
4658 *p++ = (v1 << 4) | v2;
4659 }
4660
4661 buflen = p - buffer;
4662 }
4663 else
4664 {
4665 /*
4666 * Length of input is max length of output, but add one to avoid
4667 * unportable malloc(0) if input is zero-length.
4668 */
4669 buffer = (unsigned char *) malloc(strtextlen + 1);
4670 if (buffer == NULL)
4671 return NULL;
4672
4673 for (i = j = 0; i < strtextlen;)
4674 {
4675 switch (strtext[i])
4676 {
4677 case '\\':
4678 i++;
4679 if (strtext[i] == '\\')
4680 buffer[j++] = strtext[i++];
4681 else
4682 {
4683 if ((ISFIRSTOCTDIGIT(strtext[i])) &&
4684 (ISOCTDIGIT(strtext[i + 1])) &&
4685 (ISOCTDIGIT(strtext[i + 2])))
4686 {
4687 int byte;
4688
4689 byte = OCTVAL(strtext[i++]);
4690 byte = (byte << 3) + OCTVAL(strtext[i++]);
4691 byte = (byte << 3) + OCTVAL(strtext[i++]);
4692 buffer[j++] = byte;
4693 }
4694 }
4695
4696 /*
4697 * Note: if we see '\' followed by something that isn't a
4698 * recognized escape sequence, we loop around having done
4699 * nothing except advance i. Therefore the something will
4700 * be emitted as ordinary data on the next cycle. Corner
4701 * case: '\' at end of string will just be discarded.
4702 */
4703 break;
4704
4705 default:
4706 buffer[j++] = strtext[i++];
4707 break;
4708 }
4709 }
4710 buflen = j; /* buflen is the length of the dequoted data */
4711 }
4712
4713 /* Shrink the buffer to be no larger than necessary */
4714 /* +1 avoids unportable behavior when buflen==0 */
4715 tmpbuf = realloc(buffer, buflen + 1);
4716
4717 /* It would only be a very brain-dead realloc that could fail, but... */
4718 if (!tmpbuf)
4719 {
4720 free(buffer);
4721 return NULL;
4722 }
4723
4724 *retbuflen = buflen;
4725 return tmpbuf;
4726}
static char get_hex(char c)
Definition: fe-exec.c:4425
#define ISOCTDIGIT(CH)
Definition: fe-exec.c:4601
#define OCTVAL(CH)
Definition: fe-exec.c:4602
#define ISFIRSTOCTDIGIT(CH)
Definition: fe-exec.c:4600
#define realloc(a, b)
Definition: header.h:60
static StringInfoData tmpbuf
Definition: walsender.c:178

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

7547{
7548 if (!conn)
7549 return NULL;
7550 return conn->pguser;
7551}

References conn, and pg_conn::pguser.

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