PostgreSQL Source Code  git master
libpq-fe.h File Reference
#include <stdio.h>
#include "postgres_ext.h"
Include dependency graph for libpq-fe.h:
This graph shows which files directly or indirectly include this file:

Go to the source code of this file.

Data Structures

struct  pgNotify
 
struct  _PQprintOpt
 
struct  _PQconninfoOption
 
struct  PQArgBlock
 
struct  pgresAttDesc
 

Macros

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

Typedefs

typedef struct pg_conn PGconn
 
typedef struct pg_result PGresult
 
typedef struct pg_cancel PGcancel
 
typedef struct pgNotify PGnotify
 
typedef void(* PQnoticeReceiver) (void *arg, const PGresult *res)
 
typedef void(* PQnoticeProcessor) (void *arg, const char *message)
 
typedef char pqbool
 
typedef struct _PQprintOpt PQprintOpt
 
typedef struct _PQconninfoOption PQconninfoOption
 
typedef struct pgresAttDesc PGresAttDesc
 
typedef void(* pgthreadlock_t) (int acquire)
 
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
}
 
enum  PostgresPollingStatusType {
  PGRES_POLLING_FAILED = 0, PGRES_POLLING_READING, PGRES_POLLING_WRITING, PGRES_POLLING_OK,
  PGRES_POLLING_ACTIVE
}
 
enum  ExecStatusType {
  PGRES_EMPTY_QUERY = 0, PGRES_COMMAND_OK, PGRES_TUPLES_OK, PGRES_COPY_OUT,
  PGRES_COPY_IN, PGRES_BAD_RESPONSE, PGRES_NONFATAL_ERROR, PGRES_FATAL_ERROR,
  PGRES_COPY_BOTH, PGRES_SINGLE_TUPLE
}
 
enum  PGTransactionStatusType {
  PQTRANS_IDLE, PQTRANS_ACTIVE, PQTRANS_INTRANS, PQTRANS_INERROR,
  PQTRANS_UNKNOWN
}
 
enum  PGVerbosity { PQERRORS_TERSE, PQERRORS_DEFAULT, PQERRORS_VERBOSE, 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 }
 

Functions

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

◆ PG_COPYRES_ATTRS

#define PG_COPYRES_ATTRS   0x01

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

Referenced by PQcopyResult(), and pqRowProcessor().

◆ PG_COPYRES_EVENTS

#define PG_COPYRES_EVENTS   0x04

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

Referenced by PQcopyResult(), and pqRowProcessor().

◆ PG_COPYRES_NOTICEHOOKS

#define PG_COPYRES_NOTICEHOOKS   0x08

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

Referenced by PQcopyResult(), and pqRowProcessor().

◆ PG_COPYRES_TUPLES

#define PG_COPYRES_TUPLES   0x02 /* Implies PG_COPYRES_ATTRS */

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

Referenced by PQcopyResult().

◆ PQfreeNotify

#define PQfreeNotify (   ptr)    PQfreemem(ptr)

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

◆ PQnoPasswordSupplied

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

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

Referenced by pg_fe_sendauth(), and pg_SASL_init().

◆ 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 272 of file libpq-fe.h.

Referenced by main().

Typedef Documentation

◆ PGcancel

typedef struct pg_cancel PGcancel

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

◆ PGconn

typedef struct pg_conn PGconn

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

◆ PGnotify

typedef struct pgNotify PGnotify

◆ PGresAttDesc

typedef struct pgresAttDesc PGresAttDesc

◆ PGresult

typedef struct pg_result PGresult

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

◆ pgthreadlock_t

typedef void(* pgthreadlock_t) (int acquire)

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

◆ pqbool

typedef char pqbool

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

◆ PQconninfoOption

◆ PQnoticeProcessor

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

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

◆ PQnoticeReceiver

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

Definition at line 174 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 623 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 

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

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

◆ 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 

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

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

◆ PGContextVisibility

Enumerator
PQSHOW_CONTEXT_NEVER 
PQSHOW_CONTEXT_ERRORS 
PQSHOW_CONTEXT_ALWAYS 

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

121 {
122  PQSHOW_CONTEXT_NEVER, /* never show CONTEXT field */
123  PQSHOW_CONTEXT_ERRORS, /* show CONTEXT for errors only (default) */
124  PQSHOW_CONTEXT_ALWAYS /* always show CONTEXT field */
PGContextVisibility
Definition: libpq-fe.h:120

◆ PGPing

enum PGPing
Enumerator
PQPING_OK 
PQPING_REJECT 
PQPING_NO_RESPONSE 
PQPING_NO_ATTEMPT 

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

133 {
134  PQPING_OK, /* server is accepting connections */
135  PQPING_REJECT, /* server is alive but rejecting connections */
136  PQPING_NO_RESPONSE, /* could not establish connection */
137  PQPING_NO_ATTEMPT /* connection not attempted (bad params) */
138 } PGPing;
PGPing
Definition: libpq-fe.h:132

◆ PGTransactionStatusType

Enumerator
PQTRANS_IDLE 
PQTRANS_ACTIVE 
PQTRANS_INTRANS 
PQTRANS_INERROR 
PQTRANS_UNKNOWN 

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

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

◆ PGVerbosity

Enumerator
PQERRORS_TERSE 
PQERRORS_DEFAULT 
PQERRORS_VERBOSE 
PQERRORS_SQLSTATE 

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

113 {
114  PQERRORS_TERSE, /* single-line error messages */
115  PQERRORS_DEFAULT, /* recommended style */
116  PQERRORS_VERBOSE, /* all the facts, ma'am */
117  PQERRORS_SQLSTATE /* only error severity and SQLSTATE code */
118 } PGVerbosity;
PGVerbosity
Definition: libpq-fe.h:112

◆ PostgresPollingStatusType

Enumerator
PGRES_POLLING_FAILED 
PGRES_POLLING_READING 
PGRES_POLLING_WRITING 
PGRES_POLLING_OK 
PGRES_POLLING_ACTIVE 

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

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

Function Documentation

◆ lo_close()

int lo_close ( PGconn conn,
int  fd 
)

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

References 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 dumpBlobs(), EndRestoreBlob(), exportFile(), importFile(), lo_export(), lo_import_internal(), my_truncate(), overwrite(), and pickout().

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;
109  res = PQfn(conn, conn->lobjfuncs->fn_lo_close,
110  &retval, &result_len, 1, argv, 1);
111  if (PQresultStatus(res) == PGRES_COMMAND_OK)
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:2609
static int fd(const char *x, int i)
Definition: preproc-init.c:105
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:2651
void PQclear(PGresult *res)
Definition: fe-exec.c:676
Oid fn_lo_close
Definition: libpq-int.h:271
union PQArgBlock::@162 u
int isint
Definition: libpq-fe.h:226
PGlobjfuncs * lobjfuncs
Definition: libpq-int.h:441
int integer
Definition: libpq-fe.h:230
static int lo_initialize(PGconn *conn)
Definition: fe-lobj.c:853

◆ lo_creat()

Oid lo_creat ( PGconn conn,
int  mode 
)

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

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

445 {
446  PQArgBlock argv[1];
447  PGresult *res;
448  int retval;
449  int result_len;
450 
451  if (lo_initialize(conn) < 0)
452  return InvalidOid;
453 
454  argv[0].isint = 1;
455  argv[0].len = 4;
456  argv[0].u.integer = mode;
457  res = PQfn(conn, conn->lobjfuncs->fn_lo_creat,
458  &retval, &result_len, 1, argv, 1);
459  if (PQresultStatus(res) == PGRES_COMMAND_OK)
460  {
461  PQclear(res);
462  return (Oid) retval;
463  }
464  else
465  {
466  PQclear(res);
467  return InvalidOid;
468  }
469 }
static PgChecksumMode mode
Definition: pg_checksums.c:61
unsigned int Oid
Definition: postgres_ext.h:31
PGresult * PQfn(PGconn *conn, int fnid, int *result_buf, int *result_len, int result_is_int, const PQArgBlock *args, int nargs)
Definition: fe-exec.c:2609
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:2651
#define InvalidOid
Definition: postgres_ext.h:36
void PQclear(PGresult *res)
Definition: fe-exec.c:676
Oid fn_lo_creat
Definition: libpq-int.h:272
union PQArgBlock::@162 u
int isint
Definition: libpq-fe.h:226
PGlobjfuncs * lobjfuncs
Definition: libpq-int.h:441
int integer
Definition: libpq-fe.h:230
static int lo_initialize(PGconn *conn)
Definition: fe-lobj.c:853

◆ lo_create()

Oid lo_create ( PGconn conn,
Oid  lobjId 
)

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

References appendPQExpBuffer(), pg_conn::errorMessage, pgLobjfuncs::fn_lo_create, PQArgBlock::integer, InvalidOid, PQArgBlock::isint, PQArgBlock::len, libpq_gettext, lo_initialize(), pg_conn::lobjfuncs, PGRES_COMMAND_OK, PQclear(), PQfn(), PQresultStatus(), and PQArgBlock::u.

Referenced by lo_import_internal(), and StartRestoreBlob().

481 {
482  PQArgBlock argv[1];
483  PGresult *res;
484  int retval;
485  int result_len;
486 
487  if (lo_initialize(conn) < 0)
488  return InvalidOid;
489 
490  /* Must check this on-the-fly because it's not there pre-8.1 */
491  if (conn->lobjfuncs->fn_lo_create == 0)
492  {
494  libpq_gettext("cannot determine OID of function %s\n"),
495  "lo_create");
496  return InvalidOid;
497  }
498 
499  argv[0].isint = 1;
500  argv[0].len = 4;
501  argv[0].u.integer = lobjId;
502  res = PQfn(conn, conn->lobjfuncs->fn_lo_create,
503  &retval, &result_len, 1, argv, 1);
504  if (PQresultStatus(res) == PGRES_COMMAND_OK)
505  {
506  PQclear(res);
507  return (Oid) retval;
508  }
509  else
510  {
511  PQclear(res);
512  return InvalidOid;
513  }
514 }
Oid fn_lo_create
Definition: libpq-int.h:273
unsigned int Oid
Definition: postgres_ext.h:31
PGresult * PQfn(PGconn *conn, int fnid, int *result_buf, int *result_len, int result_is_int, const PQArgBlock *args, int nargs)
Definition: fe-exec.c:2609
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:2651
void appendPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:267
PQExpBufferData errorMessage
Definition: libpq-int.h:530
#define InvalidOid
Definition: postgres_ext.h:36
void PQclear(PGresult *res)
Definition: fe-exec.c:676
union PQArgBlock::@162 u
int isint
Definition: libpq-fe.h:226
PGlobjfuncs * lobjfuncs
Definition: libpq-int.h:441
#define libpq_gettext(x)
Definition: libpq-int.h:809
int integer
Definition: libpq-fe.h:230
static int lo_initialize(PGconn *conn)
Definition: fe-lobj.c:853

◆ lo_export()

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

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

References appendPQExpBuffer(), buf, close, pg_conn::errorMessage, fd(), INV_READ, libpq_gettext, LO_BUFSIZE, lo_close(), lo_open(), lo_read(), PG_BINARY, PG_STRERROR_R_BUFLEN, printfPQExpBuffer(), strerror_r, and write.

Referenced by do_lo_export(), and main().

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

◆ lo_import()

Oid lo_import ( PGconn conn,
const char *  filename 
)

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

References InvalidOid, and lo_import_internal().

Referenced by do_lo_import(), and main().

635 {
636  return lo_import_internal(conn, filename, InvalidOid);
637 }
static Oid lo_import_internal(PGconn *conn, const char *filename, Oid oid)
Definition: fe-lobj.c:655
#define InvalidOid
Definition: postgres_ext.h:36
static char * filename
Definition: pg_dumpall.c:91

◆ lo_import_with_oid()

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

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

References lo_import_internal().

650 {
651  return lo_import_internal(conn, filename, lobjId);
652 }
static Oid lo_import_internal(PGconn *conn, const char *filename, Oid oid)
Definition: fe-lobj.c:655
static char * filename
Definition: pg_dumpall.c:91

◆ lo_lseek()

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

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

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

350 {
351  PQArgBlock argv[3];
352  PGresult *res;
353  int retval;
354  int result_len;
355 
356  if (lo_initialize(conn) < 0)
357  return -1;
358 
359  argv[0].isint = 1;
360  argv[0].len = 4;
361  argv[0].u.integer = fd;
362 
363  argv[1].isint = 1;
364  argv[1].len = 4;
365  argv[1].u.integer = offset;
366 
367  argv[2].isint = 1;
368  argv[2].len = 4;
369  argv[2].u.integer = whence;
370 
371  res = PQfn(conn, conn->lobjfuncs->fn_lo_lseek,
372  &retval, &result_len, 1, argv, 3);
373  if (PQresultStatus(res) == PGRES_COMMAND_OK)
374  {
375  PQclear(res);
376  return retval;
377  }
378  else
379  {
380  PQclear(res);
381  return -1;
382  }
383 }
Oid fn_lo_lseek
Definition: libpq-int.h:275
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:2609
static int fd(const char *x, int i)
Definition: preproc-init.c:105
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:2651
void PQclear(PGresult *res)
Definition: fe-exec.c:676
union PQArgBlock::@162 u
int isint
Definition: libpq-fe.h:226
PGlobjfuncs * lobjfuncs
Definition: libpq-int.h:441
int integer
Definition: libpq-fe.h:230
static int lo_initialize(PGconn *conn)
Definition: fe-lobj.c:853

◆ lo_lseek64()

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

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

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

Referenced by overwrite(), and pickout().

391 {
392  PQArgBlock argv[3];
393  PGresult *res;
394  pg_int64 retval;
395  int result_len;
396 
397  if (lo_initialize(conn) < 0)
398  return -1;
399 
400  if (conn->lobjfuncs->fn_lo_lseek64 == 0)
401  {
403  libpq_gettext("cannot determine OID of function %s\n"),
404  "lo_lseek64");
405  return -1;
406  }
407 
408  argv[0].isint = 1;
409  argv[0].len = 4;
410  argv[0].u.integer = fd;
411 
412  offset = lo_hton64(offset);
413  argv[1].isint = 0;
414  argv[1].len = 8;
415  argv[1].u.ptr = (int *) &offset;
416 
417  argv[2].isint = 1;
418  argv[2].len = 4;
419  argv[2].u.integer = whence;
420 
421  res = PQfn(conn, conn->lobjfuncs->fn_lo_lseek64,
422  (void *) &retval, &result_len, 0, argv, 3);
423  if (PQresultStatus(res) == PGRES_COMMAND_OK && result_len == 8)
424  {
425  PQclear(res);
426  return lo_ntoh64(retval);
427  }
428  else
429  {
430  PQclear(res);
431  return -1;
432  }
433 }
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:2609
static int fd(const char *x, int i)
Definition: preproc-init.c:105
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:2651
PG_INT64_TYPE pg_int64
Definition: postgres_ext.h:47
void appendPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:267
static pg_int64 lo_hton64(pg_int64 host64)
Definition: fe-lobj.c:1055
PQExpBufferData errorMessage
Definition: libpq-int.h:530
void PQclear(PGresult *res)
Definition: fe-exec.c:676
union PQArgBlock::@162 u
Oid fn_lo_lseek64
Definition: libpq-int.h:276
int isint
Definition: libpq-fe.h:226
PGlobjfuncs * lobjfuncs
Definition: libpq-int.h:441
int * ptr
Definition: libpq-fe.h:229
#define libpq_gettext(x)
Definition: libpq-int.h:809
int integer
Definition: libpq-fe.h:230
static pg_int64 lo_ntoh64(pg_int64 net64)
Definition: fe-lobj.c:1080
static int lo_initialize(PGconn *conn)
Definition: fe-lobj.c:853

◆ lo_open()

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

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

References 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 dumpBlobs(), exportFile(), importFile(), lo_export(), lo_import_internal(), my_truncate(), overwrite(), pickout(), and StartRestoreBlob().

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);
76  if (PQresultStatus(res) == PGRES_COMMAND_OK)
77  {
78  PQclear(res);
79  return fd;
80  }
81  else
82  {
83  PQclear(res);
84  return -1;
85  }
86 }
static PgChecksumMode mode
Definition: pg_checksums.c:61
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:2609
static int fd(const char *x, int i)
Definition: preproc-init.c:105
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:2651
Oid fn_lo_open
Definition: libpq-int.h:270
void PQclear(PGresult *res)
Definition: fe-exec.c:676
union PQArgBlock::@162 u
int isint
Definition: libpq-fe.h:226
PGlobjfuncs * lobjfuncs
Definition: libpq-int.h:441
int integer
Definition: libpq-fe.h:230
static int lo_initialize(PGconn *conn)
Definition: fe-lobj.c:853

◆ lo_read()

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

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

References appendPQExpBufferStr(), pg_conn::errorMessage, fd(), pgLobjfuncs::fn_lo_read, PQArgBlock::integer, PQArgBlock::isint, PQArgBlock::len, libpq_gettext, lo_initialize(), pg_conn::lobjfuncs, PGRES_COMMAND_OK, PQclear(), PQfn(), PQresultStatus(), and PQArgBlock::u.

Referenced by lo_export().

249 {
250  PQArgBlock argv[2];
251  PGresult *res;
252  int result_len;
253 
254  if (lo_initialize(conn) < 0)
255  return -1;
256 
257  /*
258  * Long ago, somebody thought it'd be a good idea to declare this function
259  * as taking size_t ... but the underlying backend function only accepts a
260  * signed int32 length. So throw error if the given value overflows
261  * int32.
262  */
263  if (len > (size_t) INT_MAX)
264  {
266  libpq_gettext("argument of lo_read exceeds integer range\n"));
267  return -1;
268  }
269 
270  argv[0].isint = 1;
271  argv[0].len = 4;
272  argv[0].u.integer = fd;
273 
274  argv[1].isint = 1;
275  argv[1].len = 4;
276  argv[1].u.integer = (int) len;
277 
278  res = PQfn(conn, conn->lobjfuncs->fn_lo_read,
279  (void *) buf, &result_len, 0, argv, 2);
280  if (PQresultStatus(res) == PGRES_COMMAND_OK)
281  {
282  PQclear(res);
283  return result_len;
284  }
285  else
286  {
287  PQclear(res);
288  return -1;
289  }
290 }
void appendPQExpBufferStr(PQExpBuffer str, const char *data)
Definition: pqexpbuffer.c:369
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:2609
static int fd(const char *x, int i)
Definition: preproc-init.c:105
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:2651
Oid fn_lo_read
Definition: libpq-int.h:281
static char * buf
Definition: pg_test_fsync.c:68
PQExpBufferData errorMessage
Definition: libpq-int.h:530
void PQclear(PGresult *res)
Definition: fe-exec.c:676
union PQArgBlock::@162 u
int isint
Definition: libpq-fe.h:226
PGlobjfuncs * lobjfuncs
Definition: libpq-int.h:441
#define libpq_gettext(x)
Definition: libpq-int.h:809
int integer
Definition: libpq-fe.h:230
static int lo_initialize(PGconn *conn)
Definition: fe-lobj.c:853

◆ lo_tell()

int lo_tell ( PGconn conn,
int  fd 
)

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

References 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.

523 {
524  int retval;
525  PQArgBlock argv[1];
526  PGresult *res;
527  int result_len;
528 
529  if (lo_initialize(conn) < 0)
530  return -1;
531 
532  argv[0].isint = 1;
533  argv[0].len = 4;
534  argv[0].u.integer = fd;
535 
536  res = PQfn(conn, conn->lobjfuncs->fn_lo_tell,
537  &retval, &result_len, 1, argv, 1);
538  if (PQresultStatus(res) == PGRES_COMMAND_OK)
539  {
540  PQclear(res);
541  return retval;
542  }
543  else
544  {
545  PQclear(res);
546  return -1;
547  }
548 }
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:2609
static int fd(const char *x, int i)
Definition: preproc-init.c:105
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:2651
Oid fn_lo_tell
Definition: libpq-int.h:277
void PQclear(PGresult *res)
Definition: fe-exec.c:676
union PQArgBlock::@162 u
int isint
Definition: libpq-fe.h:226
PGlobjfuncs * lobjfuncs
Definition: libpq-int.h:441
int integer
Definition: libpq-fe.h:230
static int lo_initialize(PGconn *conn)
Definition: fe-lobj.c:853

◆ lo_tell64()

pg_int64 lo_tell64 ( PGconn conn,
int  fd 
)

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

References appendPQExpBuffer(), pg_conn::errorMessage, fd(), pgLobjfuncs::fn_lo_tell64, PQArgBlock::integer, PQArgBlock::isint, PQArgBlock::len, libpq_gettext, lo_initialize(), lo_ntoh64(), pg_conn::lobjfuncs, PGRES_COMMAND_OK, PQclear(), PQfn(), PQresultStatus(), and PQArgBlock::u.

Referenced by pickout().

556 {
557  pg_int64 retval;
558  PQArgBlock argv[1];
559  PGresult *res;
560  int result_len;
561 
562  if (lo_initialize(conn) < 0)
563  return -1;
564 
565  if (conn->lobjfuncs->fn_lo_tell64 == 0)
566  {
568  libpq_gettext("cannot determine OID of function %s\n"),
569  "lo_tell64");
570  return -1;
571  }
572 
573  argv[0].isint = 1;
574  argv[0].len = 4;
575  argv[0].u.integer = fd;
576 
577  res = PQfn(conn, conn->lobjfuncs->fn_lo_tell64,
578  (void *) &retval, &result_len, 0, argv, 1);
579  if (PQresultStatus(res) == PGRES_COMMAND_OK && result_len == 8)
580  {
581  PQclear(res);
582  return lo_ntoh64(retval);
583  }
584  else
585  {
586  PQclear(res);
587  return -1;
588  }
589 }
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:2609
static int fd(const char *x, int i)
Definition: preproc-init.c:105
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:2651
PG_INT64_TYPE pg_int64
Definition: postgres_ext.h:47
void appendPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:267
Oid fn_lo_tell64
Definition: libpq-int.h:278
PQExpBufferData errorMessage
Definition: libpq-int.h:530
void PQclear(PGresult *res)
Definition: fe-exec.c:676
union PQArgBlock::@162 u
int isint
Definition: libpq-fe.h:226
PGlobjfuncs * lobjfuncs
Definition: libpq-int.h:441
#define libpq_gettext(x)
Definition: libpq-int.h:809
int integer
Definition: libpq-fe.h:230
static pg_int64 lo_ntoh64(pg_int64 net64)
Definition: fe-lobj.c:1080
static int lo_initialize(PGconn *conn)
Definition: fe-lobj.c:853

◆ lo_truncate()

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

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

References appendPQExpBuffer(), appendPQExpBufferStr(), pg_conn::errorMessage, fd(), pgLobjfuncs::fn_lo_truncate, PQArgBlock::integer, PQArgBlock::isint, PQArgBlock::len, libpq_gettext, lo_initialize(), pg_conn::lobjfuncs, PGRES_COMMAND_OK, PQclear(), PQfn(), PQresultStatus(), and PQArgBlock::u.

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  {
145  libpq_gettext("cannot determine OID of function %s\n"),
146  "lo_truncate");
147  return -1;
148  }
149 
150  /*
151  * Long ago, somebody thought it'd be a good idea to declare this function
152  * as taking size_t ... but the underlying backend function only accepts a
153  * signed int32 length. So throw error if the given value overflows
154  * int32. (A possible alternative is to automatically redirect the call
155  * to lo_truncate64; but if the caller wanted to rely on that backend
156  * function being available, he could have called lo_truncate64 for
157  * himself.)
158  */
159  if (len > (size_t) INT_MAX)
160  {
162  libpq_gettext("argument of lo_truncate exceeds integer range\n"));
163  return -1;
164  }
165 
166  argv[0].isint = 1;
167  argv[0].len = 4;
168  argv[0].u.integer = fd;
169 
170  argv[1].isint = 1;
171  argv[1].len = 4;
172  argv[1].u.integer = (int) len;
173 
174  res = PQfn(conn, conn->lobjfuncs->fn_lo_truncate,
175  &retval, &result_len, 1, argv, 2);
176 
177  if (PQresultStatus(res) == PGRES_COMMAND_OK)
178  {
179  PQclear(res);
180  return retval;
181  }
182  else
183  {
184  PQclear(res);
185  return -1;
186  }
187 }
void appendPQExpBufferStr(PQExpBuffer str, const char *data)
Definition: pqexpbuffer.c:369
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:2609
static int fd(const char *x, int i)
Definition: preproc-init.c:105
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:2651
Oid fn_lo_truncate
Definition: libpq-int.h:279
void appendPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:267
PQExpBufferData errorMessage
Definition: libpq-int.h:530
void PQclear(PGresult *res)
Definition: fe-exec.c:676
union PQArgBlock::@162 u
int isint
Definition: libpq-fe.h:226
PGlobjfuncs * lobjfuncs
Definition: libpq-int.h:441
#define libpq_gettext(x)
Definition: libpq-int.h:809
int integer
Definition: libpq-fe.h:230
static int lo_initialize(PGconn *conn)
Definition: fe-lobj.c:853

◆ lo_truncate64()

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

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

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

Referenced by my_truncate().

198 {
199  PQArgBlock argv[2];
200  PGresult *res;
201  int retval;
202  int result_len;
203 
204  if (lo_initialize(conn) < 0)
205  return -1;
206 
207  if (conn->lobjfuncs->fn_lo_truncate64 == 0)
208  {
210  libpq_gettext("cannot determine OID of function %s\n"),
211  "lo_truncate64");
212  return -1;
213  }
214 
215  argv[0].isint = 1;
216  argv[0].len = 4;
217  argv[0].u.integer = fd;
218 
219  len = lo_hton64(len);
220  argv[1].isint = 0;
221  argv[1].len = 8;
222  argv[1].u.ptr = (int *) &len;
223 
224  res = PQfn(conn, conn->lobjfuncs->fn_lo_truncate64,
225  &retval, &result_len, 1, argv, 2);
226 
227  if (PQresultStatus(res) == PGRES_COMMAND_OK)
228  {
229  PQclear(res);
230  return retval;
231  }
232  else
233  {
234  PQclear(res);
235  return -1;
236  }
237 }
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:2609
static int fd(const char *x, int i)
Definition: preproc-init.c:105
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:2651
void appendPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:267
static pg_int64 lo_hton64(pg_int64 host64)
Definition: fe-lobj.c:1055
Oid fn_lo_truncate64
Definition: libpq-int.h:280
PQExpBufferData errorMessage
Definition: libpq-int.h:530
void PQclear(PGresult *res)
Definition: fe-exec.c:676
union PQArgBlock::@162 u
int isint
Definition: libpq-fe.h:226
PGlobjfuncs * lobjfuncs
Definition: libpq-int.h:441
int * ptr
Definition: libpq-fe.h:229
#define libpq_gettext(x)
Definition: libpq-int.h:809
int integer
Definition: libpq-fe.h:230
static int lo_initialize(PGconn *conn)
Definition: fe-lobj.c:853

◆ lo_unlink()

int lo_unlink ( PGconn conn,
Oid  lobjId 
)

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

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

598 {
599  PQArgBlock argv[1];
600  PGresult *res;
601  int result_len;
602  int retval;
603 
604  if (lo_initialize(conn) < 0)
605  return -1;
606 
607  argv[0].isint = 1;
608  argv[0].len = 4;
609  argv[0].u.integer = lobjId;
610 
611  res = PQfn(conn, conn->lobjfuncs->fn_lo_unlink,
612  &retval, &result_len, 1, argv, 1);
613  if (PQresultStatus(res) == PGRES_COMMAND_OK)
614  {
615  PQclear(res);
616  return retval;
617  }
618  else
619  {
620  PQclear(res);
621  return -1;
622  }
623 }
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:2609
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:2651
void PQclear(PGresult *res)
Definition: fe-exec.c:676
union PQArgBlock::@162 u
Oid fn_lo_unlink
Definition: libpq-int.h:274
int isint
Definition: libpq-fe.h:226
PGlobjfuncs * lobjfuncs
Definition: libpq-int.h:441
int integer
Definition: libpq-fe.h:230
static int lo_initialize(PGconn *conn)
Definition: fe-lobj.c:853

◆ lo_write()

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

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

References appendPQExpBufferStr(), pg_conn::errorMessage, fd(), pgLobjfuncs::fn_lo_write, PQArgBlock::integer, PQArgBlock::isint, PQArgBlock::len, libpq_gettext, lo_initialize(), pg_conn::lobjfuncs, PGRES_COMMAND_OK, PQclear(), PQfn(), PQresultStatus(), PQArgBlock::ptr, PQArgBlock::u, and unconstify.

Referenced by lo_import_internal().

300 {
301  PQArgBlock argv[2];
302  PGresult *res;
303  int result_len;
304  int retval;
305 
306  if (lo_initialize(conn) < 0)
307  return -1;
308 
309  /*
310  * Long ago, somebody thought it'd be a good idea to declare this function
311  * as taking size_t ... but the underlying backend function only accepts a
312  * signed int32 length. So throw error if the given value overflows
313  * int32.
314  */
315  if (len > (size_t) INT_MAX)
316  {
318  libpq_gettext("argument of lo_write exceeds integer range\n"));
319  return -1;
320  }
321 
322  argv[0].isint = 1;
323  argv[0].len = 4;
324  argv[0].u.integer = fd;
325 
326  argv[1].isint = 0;
327  argv[1].len = (int) len;
328  argv[1].u.ptr = (int *) unconstify(char *, buf);
329 
330  res = PQfn(conn, conn->lobjfuncs->fn_lo_write,
331  &retval, &result_len, 1, argv, 2);
332  if (PQresultStatus(res) == PGRES_COMMAND_OK)
333  {
334  PQclear(res);
335  return retval;
336  }
337  else
338  {
339  PQclear(res);
340  return -1;
341  }
342 }
Oid fn_lo_write
Definition: libpq-int.h:282
void appendPQExpBufferStr(PQExpBuffer str, const char *data)
Definition: pqexpbuffer.c:369
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:2609
static int fd(const char *x, int i)
Definition: preproc-init.c:105
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:2651
static char * buf
Definition: pg_test_fsync.c:68
#define unconstify(underlying_type, expr)
Definition: c.h:1231
PQExpBufferData errorMessage
Definition: libpq-int.h:530
void PQclear(PGresult *res)
Definition: fe-exec.c:676
union PQArgBlock::@162 u
int isint
Definition: libpq-fe.h:226
PGlobjfuncs * lobjfuncs
Definition: libpq-int.h:441
int * ptr
Definition: libpq-fe.h:229
#define libpq_gettext(x)
Definition: libpq-int.h:809
int integer
Definition: libpq-fe.h:230
static int lo_initialize(PGconn *conn)
Definition: fe-lobj.c:853

◆ pg_char_to_encoding()

int pg_char_to_encoding ( const char *  name)

Definition at line 550 of file encnames.c.

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

Referenced by CreateConversionCommand(), length_in_encoding(), main(), PG_char_to_encoding(), pg_convert(), pg_get_utf8_id(), pg_valid_client_encoding(), pg_valid_server_encoding(), PQenv2encoding(), pqSaveParameterStatus(), ProcessCopyOptions(), processEncodingEntry(), and to_ascii_encname().

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

◆ pg_encoding_to_char()

◆ pg_valid_server_encoding_id()

int pg_valid_server_encoding_id ( int  encoding)

Definition at line 514 of file encnames.c.

References PG_VALID_BE_ENCODING.

Referenced by setup_locale_encoding().

515 {
517 }
#define PG_VALID_BE_ENCODING(_enc)
Definition: pg_wchar.h:295
int32 encoding
Definition: pg_database.h:41

◆ PQbackendPID()

int PQbackendPID ( const PGconn conn)

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

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

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

6652 {
6653  if (!conn || conn->status != CONNECTION_OK)
6654  return 0;
6655  return conn->be_pid;
6656 }
ConnStatusType status
Definition: libpq-int.h:388
int be_pid
Definition: libpq-int.h:434

◆ PQbinaryTuples()

int PQbinaryTuples ( const PGresult res)

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

References pg_result::binary.

Referenced by ProcessResult().

2745 {
2746  if (!res)
2747  return 0;
2748  return res->binary;
2749 }
int binary
Definition: libpq-int.h:179

◆ PQcancel()

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

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

References pg_cancel::be_key, pg_cancel::be_pid, internal_cancel(), pg_cancel::raddr, and strlcpy().

Referenced by dblink_cancel_query(), disconnectDatabase(), DisconnectDatabase(), handle_sigint(), pgfdw_cancel_query(), setup_cancel_handler(), ShutdownWorkersHard(), sigTermHandler(), and try_complete_step().

4397 {
4398  if (!cancel)
4399  {
4400  strlcpy(errbuf, "PQcancel() -- no cancel object supplied", errbufsize);
4401  return false;
4402  }
4403 
4404  return internal_cancel(&cancel->raddr, cancel->be_pid, cancel->be_key,
4405  errbuf, errbufsize);
4406 }
static int internal_cancel(SockAddr *raddr, int be_pid, int be_key, char *errbuf, int errbufsize)
Definition: fe-connect.c:4292
int be_pid
Definition: libpq-int.h:543
int be_key
Definition: libpq-int.h:544
size_t strlcpy(char *dst, const char *src, size_t siz)
Definition: strlcpy.c:45
SockAddr raddr
Definition: libpq-int.h:542

◆ PQclear()

void PQclear ( PGresult res)

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

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

Referenced by _check_database_version(), _doSetSessionAuth(), _selectOutputSchema(), _selectTableAccessMethod(), _selectTablespace(), add_tablespace_footer(), append_depends_on_extension(), appendQualifiedRelation(), BaseBackup(), binary_upgrade_set_pg_class_oids(), binary_upgrade_set_type_oids_by_rel_oid(), binary_upgrade_set_type_oids_by_type_oid(), buildMatViewRefreshDependencies(), buildShSecLabels(), check_for_data_type_usage(), check_for_isn_and_int8_passing_mismatch(), check_for_jsonb_9_4_usage(), check_for_pg_role_prefix(), check_for_prepared_transactions(), check_for_reg_data_type_usage(), check_for_tables_with_oids(), check_for_user_defined_postfix_ops(), check_is_install_user(), check_loadable_libraries(), check_prepare_conn(), check_proper_datallowconn(), ClearOrSaveResult(), close_cursor(), cluster_all_databases(), connectDatabase(), ConnectDatabase(), connectToServer(), convertTSFunction(), create_cursor(), CreateReplicationSlot(), createViewAsClause(), dblink_close(), dblink_exec(), dblink_fetch(), dblink_open(), dblink_res_error(), deallocate_one(), describeAccessMethods(), describeAggregates(), describeFunctions(), describeOneTableDetails(), describeOneTSConfig(), describeOneTSParser(), describeOperators(), describePublications(), DescribeQuery(), describeRoles(), describeSubscriptions(), describeTableDetails(), describeTablespaces(), describeTypes(), descriptor_free(), do_lo_import(), do_lo_list(), do_sql_command(), dropDBs(), DropReplicationSlot(), dropRoles(), dropTablespaces(), dumpAgg(), dumpBaseType(), dumpBlobs(), dumpCollation(), dumpCompositeType(), dumpCompositeTypeColComments(), dumpConversion(), dumpDatabase(), dumpDatabaseConfig(), dumpDatabases(), dumpDomain(), dumpEnumType(), dumpFunc(), dumpGroups(), dumpOpclass(), dumpOpfamily(), dumpOpr(), dumpRangeType(), dumpRoleMembership(), dumpRoles(), dumpRule(), dumpSearchPath(), dumpSequence(), dumpSequenceData(), dumpStatisticsExt(), dumpTable(), dumpTableData_copy(), dumpTableData_insert(), dumpTableSchema(), dumpTablespaces(), dumpTSConfig(), dumpTSDictionary(), dumpUserConfig(), dumpUserMappings(), ecpg_autostart_transaction(), ecpg_check_PQresult(), ecpg_is_type_an_array(), ecpg_process_output(), ECPGdescribe(), ECPGsetcommit(), ECPGtrans(), EndDBCopyMode(), exec_command_password(), ExecQueryUsingCursor(), execute_foreign_modify(), executeCommand(), executeMaintenanceCommand(), executeQueryOrDie(), ExecuteSqlCommand(), ExecuteSqlStatement(), executeStatement(), expand_dbname_patterns(), expand_foreign_server_name_patterns(), expand_schema_name_patterns(), expand_table_name_patterns(), fail_lo_xact(), fetch_more_data(), findLastBuiltinOid_V71(), finish_foreign_modify(), finish_lo_xact(), get_create_object_cmd(), get_db_infos(), get_language_name(), get_loadable_libraries(), get_next_possible_free_pg_type_oid(), get_parallel_object_list(), get_rel_infos(), get_remote_estimate(), get_returning_data(), get_synchronized_snapshot(), get_tablespace_paths(), getAccessMethods(), getAggregates(), getBlobs(), getCasts(), getCollations(), GetConnection(), getConstraints(), getConversions(), getCopyStart(), getDefaultACLs(), getDependencies(), getDomainConstraints(), getEventTriggers(), getExtendedStatistics(), getExtensionMembership(), getExtensions(), getForeignDataWrappers(), getForeignServers(), getFormattedTypeName(), getFuncs(), getIndexes(), getInherits(), getNamespaces(), getOpclasses(), getOperators(), getOpfamilies(), getParamDescriptions(), getPolicies(), getProcLangs(), getPublications(), getPublicationTables(), getRowDescriptions(), getRules(), getSubscriptions(), getTableAttrs(), GetTableInfo(), getTables(), getTransforms(), getTriggers(), getTSConfigurations(), getTSDictionaries(), getTSParsers(), getTSTemplates(), getTypes(), handleCopyIn(), HandleEndOfCopyStream(), init_libpq_conn(), initGenerateDataClientSide(), libpq_fetch_file(), libpq_traverse_files(), libpqrcv_connect(), libpqrcv_create_slot(), libpqrcv_endstreaming(), libpqrcv_exec(), libpqrcv_identify_system(), libpqrcv_PQexec(), libpqrcv_readtimelinehistoryfile(), libpqrcv_receive(), libpqrcv_startstreaming(), listAllDbs(), listCasts(), listCollations(), listConversions(), listDbRoleSettings(), listDefaultACLs(), listDomains(), listEventTriggers(), listExtensionContents(), listExtensions(), listForeignDataWrappers(), listForeignServers(), listForeignTables(), listLanguages(), listOneExtensionContents(), listOperatorClasses(), listOperatorFamilies(), listOpFamilyFunctions(), listOpFamilyOperators(), listPartitionedTables(), listPublications(), listSchemas(), listTables(), listTSConfigs(), listTSConfigsVerbose(), listTSDictionaries(), listTSParsers(), listTSParsersVerbose(), listTSTemplates(), listUserMappings(), lo_close(), lo_creat(), lo_create(), lo_initialize(), lo_lseek(), lo_lseek64(), lo_open(), lo_read(), lo_tell(), lo_tell64(), lo_truncate(), lo_truncate64(), lo_unlink(), lo_write(), lockTableForWorker(), lookup_object_oid(), main(), materializeResult(), new_9_0_populate_pg_largeobject_metadata(), objectDescription(), old_9_6_invalidate_hash_indexes(), permissionsList(), pg_attribute_noreturn(), pgfdw_cancel_query(), pgfdw_exec_cleanup_query(), pgfdw_get_cleanup_result(), pgfdw_get_result(), pgfdw_report_error(), pgfdw_xact_callback(), postgresAcquireSampleRowsFunc(), postgresAnalyzeForeignTable(), postgresEndDirectModify(), postgresImportForeignSchema(), postgresReScanForeignScan(), pqClearAsyncResult(), PQconnectPoll(), PQcopyResult(), PQencryptPasswordConn(), pqEndcopy2(), pqEndcopy3(), PQexecFinish(), PQexecStart(), pqGetErrorNotice2(), pqGetErrorNotice3(), pqInternalNotice(), PQmakeEmptyPGresult(), pqRowProcessor(), PQsetClientEncoding(), pqSetenvPoll(), prepare_common(), prepare_foreign_modify(), process_queued_fetch_requests(), processExtensionTables(), processQueryResult(), ProcessResult(), PSQLexecWatch(), readCommandResponse(), ReceiveCopyData(), ReceiveXlogStream(), reindex_all_databases(), RetrieveDataDirCreatePerm(), RetrieveWalSegSize(), run_permutation(), run_simple_command(), run_simple_query(), RunIdentifySystem(), sendCommand(), SendQuery(), set_frozenxids(), setup_connection(), sql_conn(), sql_exec(), start_lo_xact(), store_returning_result(), storeQueryResult(), StreamLogicalLog(), try_complete_step(), tryExecuteStatement(), vacuum_all_databases(), vacuum_one_database(), and vacuumlo().

677 {
678  PGresult_data *block;
679  int i;
680 
681  if (!res)
682  return;
683 
684  for (i = 0; i < res->nEvents; i++)
685  {
686  /* only send DESTROY to successfully-initialized event procs */
687  if (res->events[i].resultInitialized)
688  {
690 
691  evt.result = res;
692  (void) res->events[i].proc(PGEVT_RESULTDESTROY, &evt,
693  res->events[i].passThrough);
694  }
695  free(res->events[i].name);
696  }
697 
698  if (res->events)
699  free(res->events);
700 
701  /* Free all the subsidiary blocks */
702  while ((block = res->curBlock) != NULL)
703  {
704  res->curBlock = block->next;
705  free(block);
706  }
707 
708  /* Free the top-level tuple pointer array */
709  if (res->tuples)
710  free(res->tuples);
711 
712  /* zero out the pointer fields to catch programming errors */
713  res->attDescs = NULL;
714  res->tuples = NULL;
715  res->paramDescs = NULL;
716  res->errFields = NULL;
717  res->events = NULL;
718  res->nEvents = 0;
719  /* res->curBlock was zeroed out earlier */
720 
721  /* Free the PGresult structure itself */
722  free(res);
723 }
PGMessageField * errFields
Definition: libpq-int.h:197
bool resultInitialized
Definition: libpq-int.h:164
PGresult_data * next
Definition: libpq-int.h:105
int nEvents
Definition: libpq-int.h:188
PGresAttDesc * attDescs
Definition: libpq-int.h:171
PGresAttValue ** tuples
Definition: libpq-int.h:172
PGresult_data * curBlock
Definition: libpq-int.h:208
#define free(a)
Definition: header.h:65
PGresParamDesc * paramDescs
Definition: libpq-int.h:176
PGEventProc proc
Definition: libpq-int.h:160
int i
void * passThrough
Definition: libpq-int.h:162
PGEvent * events
Definition: libpq-int.h:187
char * name
Definition: libpq-int.h:161

◆ PQclientEncoding()

int PQclientEncoding ( const PGconn conn)

◆ PQcmdStatus()

char* PQcmdStatus ( PGresult res)

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

References pg_result::cmdStatus.

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

3000 {
3001  if (!res)
3002  return NULL;
3003  return res->cmdStatus;
3004 }
char cmdStatus[CMDSTATUS_LEN]
Definition: libpq-int.h:178

◆ PQcmdTuples()

char* PQcmdTuples ( PGresult res)

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

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

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

3070 {
3071  char *p,
3072  *c;
3073 
3074  if (!res)
3075  return "";
3076 
3077  if (strncmp(res->cmdStatus, "INSERT ", 7) == 0)
3078  {
3079  p = res->cmdStatus + 7;
3080  /* INSERT: skip oid and space */
3081  while (*p && *p != ' ')
3082  p++;
3083  if (*p == 0)
3084  goto interpret_error; /* no space? */
3085  p++;
3086  }
3087  else if (strncmp(res->cmdStatus, "SELECT ", 7) == 0 ||
3088  strncmp(res->cmdStatus, "DELETE ", 7) == 0 ||
3089  strncmp(res->cmdStatus, "UPDATE ", 7) == 0)
3090  p = res->cmdStatus + 7;
3091  else if (strncmp(res->cmdStatus, "FETCH ", 6) == 0)
3092  p = res->cmdStatus + 6;
3093  else if (strncmp(res->cmdStatus, "MOVE ", 5) == 0 ||
3094  strncmp(res->cmdStatus, "COPY ", 5) == 0)
3095  p = res->cmdStatus + 5;
3096  else
3097  return "";
3098 
3099  /* check that we have an integer (at least one digit, nothing else) */
3100  for (c = p; *c; c++)
3101  {
3102  if (!isdigit((unsigned char) *c))
3103  goto interpret_error;
3104  }
3105  if (c == p)
3106  goto interpret_error;
3107 
3108  return p;
3109 
3110 interpret_error:
3112  "could not interpret result from server: %s",
3113  res->cmdStatus);
3114  return "";
3115 }
PGNoticeHooks noticeHooks
Definition: libpq-int.h:186
char * c
void pqInternalNotice(const PGNoticeHooks *hooks, const char *fmt,...)
Definition: fe-exec.c:821
char cmdStatus[CMDSTATUS_LEN]
Definition: libpq-int.h:178

◆ PQconndefaults()

PQconninfoOption* PQconndefaults ( void  )

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

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

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

1450 {
1451  PQExpBufferData errorBuf;
1452  PQconninfoOption *connOptions;
1453 
1454  /* We don't actually report any errors here, but callees want a buffer */
1455  initPQExpBuffer(&errorBuf);
1456  if (PQExpBufferDataBroken(errorBuf))
1457  return NULL; /* out of memory already :-( */
1458 
1459  connOptions = conninfo_init(&errorBuf);
1460  if (connOptions != NULL)
1461  {
1462  /* pass NULL errorBuf to ignore errors */
1463  if (!conninfo_add_defaults(connOptions, NULL))
1464  {
1465  PQconninfoFree(connOptions);
1466  connOptions = NULL;
1467  }
1468  }
1469 
1470  termPQExpBuffer(&errorBuf);
1471  return connOptions;
1472 }
void termPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:131
static PQconninfoOption * conninfo_init(PQExpBuffer errorMessage)
Definition: fe-connect.c:5244
void PQconninfoFree(PQconninfoOption *connOptions)
Definition: fe-connect.c:6457
#define PQExpBufferDataBroken(buf)
Definition: pqexpbuffer.h:67
static bool conninfo_add_defaults(PQconninfoOption *options, PQExpBuffer errorMessage)
Definition: fe-connect.c:5680
void initPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:92

◆ PQconnectdb()

PGconn* PQconnectdb ( const char *  conninfo)

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

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

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

704 {
705  PGconn *conn = PQconnectStart(conninfo);
706 
707  if (conn && conn->status != CONNECTION_BAD)
708  (void) connectDBComplete(conn);
709 
710  return conn;
711 }
PGconn * conn
Definition: streamutil.c:54
static int connectDBComplete(PGconn *conn)
Definition: fe-connect.c:2088
PGconn * PQconnectStart(const char *conninfo)
Definition: fe-connect.c:831
ConnStatusType status
Definition: libpq-int.h:388

◆ PQconnectdbParams()

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

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

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

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

650 {
651  PGconn *conn = PQconnectStartParams(keywords, values, expand_dbname);
652 
653  if (conn && conn->status != CONNECTION_BAD)
654  (void) connectDBComplete(conn);
655 
656  return conn;
657 
658 }
PGconn * conn
Definition: streamutil.c:54
static int connectDBComplete(PGconn *conn)
Definition: fe-connect.c:2088
ConnStatusType status
Definition: libpq-int.h:388
static Datum values[MAXATTR]
Definition: bootstrap.c:165
PGconn * PQconnectStartParams(const char *const *keywords, const char *const *values, int expand_dbname)
Definition: fe-connect.c:750

◆ PQconnectionNeedsPassword()

int PQconnectionNeedsPassword ( const PGconn conn)

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

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

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

6660 {
6661  char *password;
6662 
6663  if (!conn)
6664  return false;
6665  password = PQpass(conn);
6666  if (conn->password_needed &&
6667  (password == NULL || password[0] == '\0'))
6668  return true;
6669  else
6670  return false;
6671 }
bool password_needed
Definition: libpq-int.h:417
char * PQpass(const PGconn *conn)
Definition: fe-connect.c:6491
static char * password
Definition: streamutil.c:53

◆ PQconnectionUsedPassword()

int PQconnectionUsedPassword ( const PGconn conn)

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

References pg_conn::password_needed.

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

6675 {
6676  if (!conn)
6677  return false;
6678  if (conn->password_needed)
6679  return true;
6680  else
6681  return false;
6682 }
bool password_needed
Definition: libpq-int.h:417

◆ PQconnectPoll()

PostgresPollingStatusType PQconnectPoll ( PGconn conn)

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

References SockAddr::addr, pg_conn::addr_cur, pg_conn::addrlist, pg_conn::addrlist_family, addrinfo::ai_addr, addrinfo::ai_addrlen, addrinfo::ai_family, addrinfo::ai_flags, addrinfo::ai_next, AI_NUMERICHOST, addrinfo::ai_socktype, appendPQExpBuffer(), appendPQExpBufferChar(), appendPQExpBufferStr(), pg_conn::appname, Assert, pg_conn::asyncStatus, AUTH_REQ_MD5, AUTH_REQ_OK, pg_conn::auth_req_received, CHT_HOST_ADDRESS, CHT_HOST_NAME, CHT_UNIX_SOCKET, connect, connectFailureMessage(), CONNECTION_AUTH_OK, CONNECTION_AWAITING_RESPONSE, CONNECTION_BAD, CONNECTION_CHECK_TARGET, CONNECTION_CHECK_WRITABLE, CONNECTION_CONSUME, CONNECTION_GSS_STARTUP, CONNECTION_MADE, CONNECTION_NEEDED, CONNECTION_OK, CONNECTION_SETENV, CONNECTION_SSL_STARTUP, CONNECTION_STARTED, connectNoDelay(), pg_conn::connhost, pg_conn::connip, PQExpBufferData::data, EINPROGRESS, EINTR, emitCouldNotConnect(), EnvironmentOptions, ERRCODE_APPNAME_UNKNOWN, ERRCODE_CANNOT_CONNECT_NOW, pg_conn::errorMessage, EWOULDBLOCK, pg_conn::fbappname, free, gai_strerror, getHostaddr(), getpeereid(), pg_conn::gssencmode, pg_conn_host::host, pg_conn_host::hostaddr, pg_conn::inCursor, pg_conn::inEnd, pg_conn::inStart, IS_AF_UNIX, pg_conn::laddr, pg_conn::last_sqlstate, PQExpBufferData::len, libpq_gettext, MAXPGPATH, MemSet, pg_conn::nconnhost, NEGOTIATE_GSS_CODE, NEGOTIATE_SSL_CODE, pg_conn::next_eo, NI_MAXHOST, parse_int_param(), PG_DIAG_SQLSTATE, pg_fe_sendauth(), pg_getaddrinfo_all(), pg_GSS_have_cred_cache(), pg_hton32, PG_PROTOCOL, PG_PROTOCOL_MAJOR, 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_host::port, pqBuildStartupPacket2(), pqBuildStartupPacket3(), pqCheckInBufferSpace(), PQclear(), pqClearAsyncResult(), PQconsumeInput(), pqDropConnection(), pqDropServerData(), pqFlush(), pqGetc(), pqGetErrorNotice3(), pqGetInt(), pqGetpwuid(), PQgetResult(), pqGets_append(), PQgetvalue(), PQisBusy(), PQntuples(), pqPacketSend(), pqReadData(), PQresultErrorField(), PQresultStatus(), pqsecure_initialize(), pqsecure_open_client(), pqsecure_open_gss(), PQsendQueryContinue(), pqSetenvPoll(), PQTRANS_IDLE, pg_conn::pversion, pg_conn::raddr, release_conn_addrinfo(), pg_conn::requirepeer, pg_result::resultStatus, SockAddr::salen, pg_conn::send_appname, sendTerminateConn(), pg_conn::setenv_state, SETENV_STATE_CLIENT_ENCODING_SEND, setKeepalivesCount(), setKeepalivesIdle(), setKeepalivesInterval(), setTCPUserTimeout(), pg_conn::sigpipe_flag, pg_conn::sigpipe_so, snprintf, pg_conn::sock, SOCK_ERRNO, SOCK_STRERROR, socket, pg_conn::ssl_in_use, pg_conn::sslmode, pg_conn::status, STATUS_OK, strerror_r, pg_conn::sversion, pg_conn::target_session_attrs, pg_conn::try_next_addr, pg_conn::try_next_host, pg_conn_host::type, UNIXSOCK_PATH, UNIXSOCK_PATH_BUFLEN, useKeepalives(), _internalPQconninfoOption::val, pg_conn::whichhost, and pg_conn::xactStatus.

Referenced by connectDBComplete(), connectDBStart(), libpqrcv_connect(), and PQresetPoll().

2225 {
2226  bool reset_connection_state_machine = false;
2227  bool need_new_connection = false;
2228  PGresult *res;
2229  char sebuf[PG_STRERROR_R_BUFLEN];
2230  int optval;
2231 
2232  if (conn == NULL)
2233  return PGRES_POLLING_FAILED;
2234 
2235  /* Get the new data */
2236  switch (conn->status)
2237  {
2238  /*
2239  * We really shouldn't have been polled in these two cases, but we
2240  * can handle it.
2241  */
2242  case CONNECTION_BAD:
2243  return PGRES_POLLING_FAILED;
2244  case CONNECTION_OK:
2245  return PGRES_POLLING_OK;
2246 
2247  /* These are reading states */
2249  case CONNECTION_AUTH_OK:
2250  {
2251  /* Load waiting data */
2252  int n = pqReadData(conn);
2253 
2254  if (n < 0)
2255  goto error_return;
2256  if (n == 0)
2257  return PGRES_POLLING_READING;
2258 
2259  break;
2260  }
2261 
2262  /* These are writing states, so we just proceed. */
2263  case CONNECTION_STARTED:
2264  case CONNECTION_MADE:
2265  break;
2266 
2267  /* We allow pqSetenvPoll to decide whether to proceed. */
2268  case CONNECTION_SETENV:
2269  break;
2270 
2271  /* Special cases: proceed without waiting. */
2273  case CONNECTION_NEEDED:
2275  case CONNECTION_CONSUME:
2277  break;
2278 
2279  default:
2281  libpq_gettext("invalid connection state, probably indicative of memory corruption\n"));
2282  goto error_return;
2283  }
2284 
2285 
2286 keep_going: /* We will come back to here until there is
2287  * nothing left to do. */
2288 
2289  /* Time to advance to next address, or next host if no more addresses? */
2290  if (conn->try_next_addr)
2291  {
2292  if (conn->addr_cur && conn->addr_cur->ai_next)
2293  {
2294  conn->addr_cur = conn->addr_cur->ai_next;
2295  reset_connection_state_machine = true;
2296  }
2297  else
2298  conn->try_next_host = true;
2299  conn->try_next_addr = false;
2300  }
2301 
2302  /* Time to advance to next connhost[] entry? */
2303  if (conn->try_next_host)
2304  {
2305  pg_conn_host *ch;
2306  struct addrinfo hint;
2307  int thisport;
2308  int ret;
2309  char portstr[MAXPGPATH];
2310 
2311  if (conn->whichhost + 1 >= conn->nconnhost)
2312  {
2313  /*
2314  * Oops, no more hosts. An appropriate error message is already
2315  * set up, so just set the right status.
2316  */
2317  goto error_return;
2318  }
2319  conn->whichhost++;
2320 
2321  /* Drop any address info for previous host */
2322  release_conn_addrinfo(conn);
2323 
2324  /*
2325  * Look up info for the new host. On failure, log the problem in
2326  * conn->errorMessage, then loop around to try the next host. (Note
2327  * we don't clear try_next_host until we've succeeded.)
2328  */
2329  ch = &conn->connhost[conn->whichhost];
2330 
2331  /* Initialize hint structure */
2332  MemSet(&hint, 0, sizeof(hint));
2333  hint.ai_socktype = SOCK_STREAM;
2334  conn->addrlist_family = hint.ai_family = AF_UNSPEC;
2335 
2336  /* Figure out the port number we're going to use. */
2337  if (ch->port == NULL || ch->port[0] == '\0')
2338  thisport = DEF_PGPORT;
2339  else
2340  {
2341  if (!parse_int_param(ch->port, &thisport, conn, "port"))
2342  goto error_return;
2343 
2344  if (thisport < 1 || thisport > 65535)
2345  {
2347  libpq_gettext("invalid port number: \"%s\"\n"),
2348  ch->port);
2349  goto keep_going;
2350  }
2351  }
2352  snprintf(portstr, sizeof(portstr), "%d", thisport);
2353 
2354  /* Use pg_getaddrinfo_all() to resolve the address */
2355  switch (ch->type)
2356  {
2357  case CHT_HOST_NAME:
2358  ret = pg_getaddrinfo_all(ch->host, portstr, &hint,
2359  &conn->addrlist);
2360  if (ret || !conn->addrlist)
2361  {
2363  libpq_gettext("could not translate host name \"%s\" to address: %s\n"),
2364  ch->host, gai_strerror(ret));
2365  goto keep_going;
2366  }
2367  break;
2368 
2369  case CHT_HOST_ADDRESS:
2370  hint.ai_flags = AI_NUMERICHOST;
2371  ret = pg_getaddrinfo_all(ch->hostaddr, portstr, &hint,
2372  &conn->addrlist);
2373  if (ret || !conn->addrlist)
2374  {
2376  libpq_gettext("could not parse network address \"%s\": %s\n"),
2377  ch->hostaddr, gai_strerror(ret));
2378  goto keep_going;
2379  }
2380  break;
2381 
2382  case CHT_UNIX_SOCKET:
2383 #ifdef HAVE_UNIX_SOCKETS
2384  conn->addrlist_family = hint.ai_family = AF_UNIX;
2385  UNIXSOCK_PATH(portstr, thisport, ch->host);
2386  if (strlen(portstr) >= UNIXSOCK_PATH_BUFLEN)
2387  {
2389  libpq_gettext("Unix-domain socket path \"%s\" is too long (maximum %d bytes)\n"),
2390  portstr,
2391  (int) (UNIXSOCK_PATH_BUFLEN - 1));
2392  goto keep_going;
2393  }
2394 
2395  /*
2396  * NULL hostname tells pg_getaddrinfo_all to parse the service
2397  * name as a Unix-domain socket path.
2398  */
2399  ret = pg_getaddrinfo_all(NULL, portstr, &hint,
2400  &conn->addrlist);
2401  if (ret || !conn->addrlist)
2402  {
2404  libpq_gettext("could not translate Unix-domain socket path \"%s\" to address: %s\n"),
2405  portstr, gai_strerror(ret));
2406  goto keep_going;
2407  }
2408 #else
2409  Assert(false);
2410 #endif
2411  break;
2412  }
2413 
2414  /* OK, scan this addrlist for a working server address */
2415  conn->addr_cur = conn->addrlist;
2416  reset_connection_state_machine = true;
2417  conn->try_next_host = false;
2418  }
2419 
2420  /* Reset connection state machine? */
2421  if (reset_connection_state_machine)
2422  {
2423  /*
2424  * (Re) initialize our connection control variables for a set of
2425  * connection attempts to a single server address. These variables
2426  * must persist across individual connection attempts, but we must
2427  * reset them when we start to consider a new server.
2428  */
2429  conn->pversion = PG_PROTOCOL(3, 0);
2430  conn->send_appname = true;
2431 #ifdef USE_SSL
2432  /* initialize these values based on SSL mode */
2433  conn->allow_ssl_try = (conn->sslmode[0] != 'd'); /* "disable" */
2434  conn->wait_ssl_try = (conn->sslmode[0] == 'a'); /* "allow" */
2435 #endif
2436 #ifdef ENABLE_GSS
2437  conn->try_gss = (conn->gssencmode[0] != 'd'); /* "disable" */
2438 #endif
2439 
2440  reset_connection_state_machine = false;
2441  need_new_connection = true;
2442  }
2443 
2444  /* Force a new connection (perhaps to the same server as before)? */
2445  if (need_new_connection)
2446  {
2447  /* Drop any existing connection */
2448  pqDropConnection(conn, true);
2449 
2450  /* Reset all state obtained from old server */
2451  pqDropServerData(conn);
2452 
2453  /* Drop any PGresult we might have, too */
2454  conn->asyncStatus = PGASYNC_IDLE;
2455  conn->xactStatus = PQTRANS_IDLE;
2456  pqClearAsyncResult(conn);
2457 
2458  /* Reset conn->status to put the state machine in the right state */
2459  conn->status = CONNECTION_NEEDED;
2460 
2461  need_new_connection = false;
2462  }
2463 
2464  /* Now try to advance the state machine for this connection */
2465  switch (conn->status)
2466  {
2467  case CONNECTION_NEEDED:
2468  {
2469  /*
2470  * Try to initiate a connection to one of the addresses
2471  * returned by pg_getaddrinfo_all(). conn->addr_cur is the
2472  * next one to try.
2473  *
2474  * The extra level of braces here is historical. It's not
2475  * worth reindenting this whole switch case to remove 'em.
2476  */
2477  {
2478  struct addrinfo *addr_cur = conn->addr_cur;
2479  char host_addr[NI_MAXHOST];
2480 
2481  /*
2482  * Advance to next possible host, if we've tried all of
2483  * the addresses for the current host.
2484  */
2485  if (addr_cur == NULL)
2486  {
2487  conn->try_next_host = true;
2488  goto keep_going;
2489  }
2490 
2491  /* Remember current address for possible use later */
2492  memcpy(&conn->raddr.addr, addr_cur->ai_addr,
2493  addr_cur->ai_addrlen);
2494  conn->raddr.salen = addr_cur->ai_addrlen;
2495 
2496  /*
2497  * Set connip, too. Note we purposely ignore strdup
2498  * failure; not a big problem if it fails.
2499  */
2500  if (conn->connip != NULL)
2501  {
2502  free(conn->connip);
2503  conn->connip = NULL;
2504  }
2505  getHostaddr(conn, host_addr, NI_MAXHOST);
2506  if (host_addr[0])
2507  conn->connip = strdup(host_addr);
2508 
2509  /* Try to create the socket */
2510  conn->sock = socket(addr_cur->ai_family, SOCK_STREAM, 0);
2511  if (conn->sock == PGINVALID_SOCKET)
2512  {
2513  int errorno = SOCK_ERRNO;
2514 
2515  /*
2516  * Silently ignore socket() failure if we have more
2517  * addresses to try; this reduces useless chatter in
2518  * cases where the address list includes both IPv4 and
2519  * IPv6 but kernel only accepts one family.
2520  */
2521  if (addr_cur->ai_next != NULL ||
2522  conn->whichhost + 1 < conn->nconnhost)
2523  {
2524  conn->try_next_addr = true;
2525  goto keep_going;
2526  }
2527  emitCouldNotConnect(conn, host_addr);
2529  libpq_gettext("could not create socket: %s\n"),
2530  SOCK_STRERROR(errorno, sebuf, sizeof(sebuf)));
2531  goto error_return;
2532  }
2533 
2534  /*
2535  * Once we've identified a target address, all errors
2536  * except the preceding socket()-failure case should be
2537  * prefixed with "could not connect to <target>: ".
2538  */
2539  emitCouldNotConnect(conn, host_addr);
2540 
2541  /*
2542  * Select socket options: no delay of outgoing data for
2543  * TCP sockets, nonblock mode, close-on-exec. Try the
2544  * next address if any of this fails.
2545  */
2546  if (!IS_AF_UNIX(addr_cur->ai_family))
2547  {
2548  if (!connectNoDelay(conn))
2549  {
2550  /* error message already created */
2551  conn->try_next_addr = true;
2552  goto keep_going;
2553  }
2554  }
2555  if (!pg_set_noblock(conn->sock))
2556  {
2558  libpq_gettext("could not set socket to nonblocking mode: %s\n"),
2559  SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
2560  conn->try_next_addr = true;
2561  goto keep_going;
2562  }
2563 
2564 #ifdef F_SETFD
2565  if (fcntl(conn->sock, F_SETFD, FD_CLOEXEC) == -1)
2566  {
2568  libpq_gettext("could not set socket to close-on-exec mode: %s\n"),
2569  SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
2570  conn->try_next_addr = true;
2571  goto keep_going;
2572  }
2573 #endif /* F_SETFD */
2574 
2575  if (!IS_AF_UNIX(addr_cur->ai_family))
2576  {
2577 #ifndef WIN32
2578  int on = 1;
2579 #endif
2580  int usekeepalives = useKeepalives(conn);
2581  int err = 0;
2582 
2583  if (usekeepalives < 0)
2584  {
2586  libpq_gettext("keepalives parameter must be an integer\n"));
2587  err = 1;
2588  }
2589  else if (usekeepalives == 0)
2590  {
2591  /* Do nothing */
2592  }
2593 #ifndef WIN32
2594  else if (setsockopt(conn->sock,
2595  SOL_SOCKET, SO_KEEPALIVE,
2596  (char *) &on, sizeof(on)) < 0)
2597  {
2599  libpq_gettext("setsockopt(%s) failed: %s\n"),
2600  "SO_KEEPALIVE",
2601  SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
2602  err = 1;
2603  }
2604  else if (!setKeepalivesIdle(conn)
2605  || !setKeepalivesInterval(conn)
2606  || !setKeepalivesCount(conn))
2607  err = 1;
2608 #else /* WIN32 */
2609 #ifdef SIO_KEEPALIVE_VALS
2610  else if (!setKeepalivesWin32(conn))
2611  err = 1;
2612 #endif /* SIO_KEEPALIVE_VALS */
2613 #endif /* WIN32 */
2614  else if (!setTCPUserTimeout(conn))
2615  err = 1;
2616 
2617  if (err)
2618  {
2619  conn->try_next_addr = true;
2620  goto keep_going;
2621  }
2622  }
2623 
2624  /*----------
2625  * We have three methods of blocking SIGPIPE during
2626  * send() calls to this socket:
2627  *
2628  * - setsockopt(sock, SO_NOSIGPIPE)
2629  * - send(sock, ..., MSG_NOSIGNAL)
2630  * - setting the signal mask to SIG_IGN during send()
2631  *
2632  * The third method requires three syscalls per send,
2633  * so we prefer either of the first two, but they are
2634  * less portable. The state is tracked in the following
2635  * members of PGconn:
2636  *
2637  * conn->sigpipe_so - we have set up SO_NOSIGPIPE
2638  * conn->sigpipe_flag - we're specifying MSG_NOSIGNAL
2639  *
2640  * If we can use SO_NOSIGPIPE, then set sigpipe_so here
2641  * and we're done. Otherwise, set sigpipe_flag so that
2642  * we will try MSG_NOSIGNAL on sends. If we get an error
2643  * with MSG_NOSIGNAL, we'll clear that flag and revert to
2644  * signal masking.
2645  *----------
2646  */
2647  conn->sigpipe_so = false;
2648 #ifdef MSG_NOSIGNAL
2649  conn->sigpipe_flag = true;
2650 #else
2651  conn->sigpipe_flag = false;
2652 #endif /* MSG_NOSIGNAL */
2653 
2654 #ifdef SO_NOSIGPIPE
2655  optval = 1;
2656  if (setsockopt(conn->sock, SOL_SOCKET, SO_NOSIGPIPE,
2657  (char *) &optval, sizeof(optval)) == 0)
2658  {
2659  conn->sigpipe_so = true;
2660  conn->sigpipe_flag = false;
2661  }
2662 #endif /* SO_NOSIGPIPE */
2663 
2664  /*
2665  * Start/make connection. This should not block, since we
2666  * are in nonblock mode. If it does, well, too bad.
2667  */
2668  if (connect(conn->sock, addr_cur->ai_addr,
2669  addr_cur->ai_addrlen) < 0)
2670  {
2671  if (SOCK_ERRNO == EINPROGRESS ||
2672 #ifdef WIN32
2673  SOCK_ERRNO == EWOULDBLOCK ||
2674 #endif
2675  SOCK_ERRNO == EINTR)
2676  {
2677  /*
2678  * This is fine - we're in non-blocking mode, and
2679  * the connection is in progress. Tell caller to
2680  * wait for write-ready on socket.
2681  */
2682  conn->status = CONNECTION_STARTED;
2683  return PGRES_POLLING_WRITING;
2684  }
2685  /* otherwise, trouble */
2686  }
2687  else
2688  {
2689  /*
2690  * Hm, we're connected already --- seems the "nonblock
2691  * connection" wasn't. Advance the state machine and
2692  * go do the next stuff.
2693  */
2694  conn->status = CONNECTION_STARTED;
2695  goto keep_going;
2696  }
2697 
2698  /*
2699  * This connection failed. Add the error report to
2700  * conn->errorMessage, then try the next address if any.
2701  */
2703  conn->try_next_addr = true;
2704  goto keep_going;
2705  }
2706  }
2707 
2708  case CONNECTION_STARTED:
2709  {
2710  ACCEPT_TYPE_ARG3 optlen = sizeof(optval);
2711 
2712  /*
2713  * Write ready, since we've made it here, so the connection
2714  * has been made ... or has failed.
2715  */
2716 
2717  /*
2718  * Now check (using getsockopt) that there is not an error
2719  * state waiting for us on the socket.
2720  */
2721 
2722  if (getsockopt(conn->sock, SOL_SOCKET, SO_ERROR,
2723  (char *) &optval, &optlen) == -1)
2724  {
2726  libpq_gettext("could not get socket error status: %s\n"),
2727  SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
2728  goto error_return;
2729  }
2730  else if (optval != 0)
2731  {
2732  /*
2733  * When using a nonblocking connect, we will typically see
2734  * connect failures at this point, so provide a friendly
2735  * error message.
2736  */
2737  connectFailureMessage(conn, optval);
2738 
2739  /*
2740  * Try the next address if any, just as in the case where
2741  * connect() returned failure immediately.
2742  */
2743  conn->try_next_addr = true;
2744  goto keep_going;
2745  }
2746 
2747  /* Fill in the client address */
2748  conn->laddr.salen = sizeof(conn->laddr.addr);
2749  if (getsockname(conn->sock,
2750  (struct sockaddr *) &conn->laddr.addr,
2751  &conn->laddr.salen) < 0)
2752  {
2754  libpq_gettext("could not get client address from socket: %s\n"),
2755  SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
2756  goto error_return;
2757  }
2758 
2759  /*
2760  * Make sure we can write before advancing to next step.
2761  */
2762  conn->status = CONNECTION_MADE;
2763  return PGRES_POLLING_WRITING;
2764  }
2765 
2766  case CONNECTION_MADE:
2767  {
2768  char *startpacket;
2769  int packetlen;
2770 
2771  /*
2772  * Implement requirepeer check, if requested and it's a
2773  * Unix-domain socket.
2774  */
2775  if (conn->requirepeer && conn->requirepeer[0] &&
2776  IS_AF_UNIX(conn->raddr.addr.ss_family))
2777  {
2778 #ifndef WIN32
2779  char pwdbuf[BUFSIZ];
2780  struct passwd pass_buf;
2781  struct passwd *pass;
2782  int passerr;
2783 #endif
2784  uid_t uid;
2785  gid_t gid;
2786 
2787  errno = 0;
2788  if (getpeereid(conn->sock, &uid, &gid) != 0)
2789  {
2790  /*
2791  * Provide special error message if getpeereid is a
2792  * stub
2793  */
2794  if (errno == ENOSYS)
2796  libpq_gettext("requirepeer parameter is not supported on this platform\n"));
2797  else
2799  libpq_gettext("could not get peer credentials: %s\n"),
2800  strerror_r(errno, sebuf, sizeof(sebuf)));
2801  goto error_return;
2802  }
2803 
2804 #ifndef WIN32
2805  passerr = pqGetpwuid(uid, &pass_buf, pwdbuf, sizeof(pwdbuf), &pass);
2806  if (pass == NULL)
2807  {
2808  if (passerr != 0)
2810  libpq_gettext("could not look up local user ID %d: %s\n"),
2811  (int) uid,
2812  strerror_r(passerr, sebuf, sizeof(sebuf)));
2813  else
2815  libpq_gettext("local user with ID %d does not exist\n"),
2816  (int) uid);
2817  goto error_return;
2818  }
2819 
2820  if (strcmp(pass->pw_name, conn->requirepeer) != 0)
2821  {
2823  libpq_gettext("requirepeer specifies \"%s\", but actual peer user name is \"%s\"\n"),
2824  conn->requirepeer, pass->pw_name);
2825  goto error_return;
2826  }
2827 #else /* WIN32 */
2828  /* should have failed with ENOSYS above */
2829  Assert(false);
2830 #endif /* WIN32 */
2831  }
2832 
2833  if (IS_AF_UNIX(conn->raddr.addr.ss_family))
2834  {
2835  /* Don't request SSL or GSSAPI over Unix sockets */
2836 #ifdef USE_SSL
2837  conn->allow_ssl_try = false;
2838 #endif
2839 #ifdef ENABLE_GSS
2840  conn->try_gss = false;
2841 #endif
2842  }
2843 
2844 #ifdef ENABLE_GSS
2845 
2846  /*
2847  * If GSSAPI encryption is enabled, then call
2848  * pg_GSS_have_cred_cache() which will return true if we can
2849  * acquire credentials (and give us a handle to use in
2850  * conn->gcred), and then send a packet to the server asking
2851  * for GSSAPI Encryption (and skip past SSL negotiation and
2852  * regular startup below).
2853  */
2854  if (conn->try_gss && !conn->gctx)
2855  conn->try_gss = pg_GSS_have_cred_cache(&conn->gcred);
2856  if (conn->try_gss && !conn->gctx)
2857  {
2859 
2860  if (pqPacketSend(conn, 0, &pv, sizeof(pv)) != STATUS_OK)
2861  {
2863  libpq_gettext("could not send GSSAPI negotiation packet: %s\n"),
2864  SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
2865  goto error_return;
2866  }
2867 
2868  /* Ok, wait for response */
2870  return PGRES_POLLING_READING;
2871  }
2872  else if (!conn->gctx && conn->gssencmode[0] == 'r')
2873  {
2875  libpq_gettext("GSSAPI encryption required but was impossible (possibly no credential cache, no server support, or using a local socket)\n"));
2876  goto error_return;
2877  }
2878 #endif
2879 
2880 #ifdef USE_SSL
2881 
2882  /*
2883  * If SSL is enabled and we haven't already got encryption of
2884  * some sort running, request SSL instead of sending the
2885  * startup message.
2886  */
2887  if (conn->allow_ssl_try && !conn->wait_ssl_try &&
2888  !conn->ssl_in_use
2889 #ifdef ENABLE_GSS
2890  && !conn->gssenc
2891 #endif
2892  )
2893  {
2894  ProtocolVersion pv;
2895 
2896  /*
2897  * Send the SSL request packet.
2898  *
2899  * Theoretically, this could block, but it really
2900  * shouldn't since we only got here if the socket is
2901  * write-ready.
2902  */
2904  if (pqPacketSend(conn, 0, &pv, sizeof(pv)) != STATUS_OK)
2905  {
2907  libpq_gettext("could not send SSL negotiation packet: %s\n"),
2908  SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
2909  goto error_return;
2910  }
2911  /* Ok, wait for response */
2913  return PGRES_POLLING_READING;
2914  }
2915 #endif /* USE_SSL */
2916 
2917  /*
2918  * Build the startup packet.
2919  */
2920  if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
2921  startpacket = pqBuildStartupPacket3(conn, &packetlen,
2923  else
2924  startpacket = pqBuildStartupPacket2(conn, &packetlen,
2926  if (!startpacket)
2927  {
2929  libpq_gettext("out of memory\n"));
2930  goto error_return;
2931  }
2932 
2933  /*
2934  * Send the startup packet.
2935  *
2936  * Theoretically, this could block, but it really shouldn't
2937  * since we only got here if the socket is write-ready.
2938  */
2939  if (pqPacketSend(conn, 0, startpacket, packetlen) != STATUS_OK)
2940  {
2942  libpq_gettext("could not send startup packet: %s\n"),
2943  SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
2944  free(startpacket);
2945  goto error_return;
2946  }
2947 
2948  free(startpacket);
2949 
2951  return PGRES_POLLING_READING;
2952  }
2953 
2954  /*
2955  * Handle SSL negotiation: wait for postmaster messages and
2956  * respond as necessary.
2957  */
2959  {
2960 #ifdef USE_SSL
2961  PostgresPollingStatusType pollres;
2962 
2963  /*
2964  * On first time through, get the postmaster's response to our
2965  * SSL negotiation packet.
2966  */
2967  if (!conn->ssl_in_use)
2968  {
2969  /*
2970  * We use pqReadData here since it has the logic to
2971  * distinguish no-data-yet from connection closure. Since
2972  * conn->ssl isn't set, a plain recv() will occur.
2973  */
2974  char SSLok;
2975  int rdresult;
2976 
2977  rdresult = pqReadData(conn);
2978  if (rdresult < 0)
2979  {
2980  /* errorMessage is already filled in */
2981  goto error_return;
2982  }
2983  if (rdresult == 0)
2984  {
2985  /* caller failed to wait for data */
2986  return PGRES_POLLING_READING;
2987  }
2988  if (pqGetc(&SSLok, conn) < 0)
2989  {
2990  /* should not happen really */
2991  return PGRES_POLLING_READING;
2992  }
2993  if (SSLok == 'S')
2994  {
2995  /* mark byte consumed */
2996  conn->inStart = conn->inCursor;
2997  /* Set up global SSL state if required */
2998  if (pqsecure_initialize(conn) != 0)
2999  goto error_return;
3000  }
3001  else if (SSLok == 'N')
3002  {
3003  /* mark byte consumed */
3004  conn->inStart = conn->inCursor;
3005  /* OK to do without SSL? */
3006  if (conn->sslmode[0] == 'r' || /* "require" */
3007  conn->sslmode[0] == 'v') /* "verify-ca" or
3008  * "verify-full" */
3009  {
3010  /* Require SSL, but server does not want it */
3012  libpq_gettext("server does not support SSL, but SSL was required\n"));
3013  goto error_return;
3014  }
3015  /* Otherwise, proceed with normal startup */
3016  conn->allow_ssl_try = false;
3017  /* We can proceed using this connection */
3018  conn->status = CONNECTION_MADE;
3019  return PGRES_POLLING_WRITING;
3020  }
3021  else if (SSLok == 'E')
3022  {
3023  /*
3024  * Server failure of some sort, such as failure to
3025  * fork a backend process. We need to process and
3026  * report the error message, which might be formatted
3027  * according to either protocol 2 or protocol 3.
3028  * Rather than duplicate the code for that, we flip
3029  * into AWAITING_RESPONSE state and let the code there
3030  * deal with it. Note we have *not* consumed the "E"
3031  * byte here.
3032  */
3034  goto keep_going;
3035  }
3036  else
3037  {
3039  libpq_gettext("received invalid response to SSL negotiation: %c\n"),
3040  SSLok);
3041  goto error_return;
3042  }
3043  }
3044 
3045  /*
3046  * Begin or continue the SSL negotiation process.
3047  */
3048  pollres = pqsecure_open_client(conn);
3049  if (pollres == PGRES_POLLING_OK)
3050  {
3051  /* SSL handshake done, ready to send startup packet */
3052  conn->status = CONNECTION_MADE;
3053  return PGRES_POLLING_WRITING;
3054  }
3055  if (pollres == PGRES_POLLING_FAILED)
3056  {
3057  /*
3058  * Failed ... if sslmode is "prefer" then do a non-SSL
3059  * retry
3060  */
3061  if (conn->sslmode[0] == 'p' /* "prefer" */
3062  && conn->allow_ssl_try /* redundant? */
3063  && !conn->wait_ssl_try) /* redundant? */
3064  {
3065  /* only retry once */
3066  conn->allow_ssl_try = false;
3067  need_new_connection = true;
3068  goto keep_going;
3069  }
3070  /* Else it's a hard failure */
3071  goto error_return;
3072  }
3073  /* Else, return POLLING_READING or POLLING_WRITING status */
3074  return pollres;
3075 #else /* !USE_SSL */
3076  /* can't get here */
3077  goto error_return;
3078 #endif /* USE_SSL */
3079  }
3080 
3082  {
3083 #ifdef ENABLE_GSS
3084  PostgresPollingStatusType pollres;
3085 
3086  /*
3087  * If we haven't yet, get the postmaster's response to our
3088  * negotiation packet
3089  */
3090  if (conn->try_gss && !conn->gctx)
3091  {
3092  char gss_ok;
3093  int rdresult = pqReadData(conn);
3094 
3095  if (rdresult < 0)
3096  /* pqReadData fills in error message */
3097  goto error_return;
3098  else if (rdresult == 0)
3099  /* caller failed to wait for data */
3100  return PGRES_POLLING_READING;
3101  if (pqGetc(&gss_ok, conn) < 0)
3102  /* shouldn't happen... */
3103  return PGRES_POLLING_READING;
3104 
3105  if (gss_ok == 'E')
3106  {
3107  /*
3108  * Server failure of some sort. Assume it's a
3109  * protocol version support failure, and let's see if
3110  * we can't recover (if it's not, we'll get a better
3111  * error message on retry). Server gets fussy if we
3112  * don't hang up the socket, though.
3113  */
3114  conn->try_gss = false;
3115  need_new_connection = true;
3116  goto keep_going;
3117  }
3118 
3119  /* mark byte consumed */
3120  conn->inStart = conn->inCursor;
3121 
3122  if (gss_ok == 'N')
3123  {
3124  /* Server doesn't want GSSAPI; fall back if we can */
3125  if (conn->gssencmode[0] == 'r')
3126  {
3128  libpq_gettext("server doesn't support GSSAPI encryption, but it was required\n"));
3129  goto error_return;
3130  }
3131 
3132  conn->try_gss = false;
3133  /* We can proceed using this connection */
3134  conn->status = CONNECTION_MADE;
3135  return PGRES_POLLING_WRITING;
3136  }
3137  else if (gss_ok != 'G')
3138  {
3140  libpq_gettext("received invalid response to GSSAPI negotiation: %c\n"),
3141  gss_ok);
3142  goto error_return;
3143  }
3144  }
3145 
3146  /* Begin or continue GSSAPI negotiation */
3147  pollres = pqsecure_open_gss(conn);
3148  if (pollres == PGRES_POLLING_OK)
3149  {
3150  /* All set for startup packet */
3151  conn->status = CONNECTION_MADE;
3152  return PGRES_POLLING_WRITING;
3153  }
3154  else if (pollres == PGRES_POLLING_FAILED &&
3155  conn->gssencmode[0] == 'p')
3156  {
3157  /*
3158  * We failed, but we can retry on "prefer". Have to drop
3159  * the current connection to do so, though.
3160  */
3161  conn->try_gss = false;
3162  need_new_connection = true;
3163  goto keep_going;
3164  }
3165  return pollres;
3166 #else /* !ENABLE_GSS */
3167  /* unreachable */
3168  goto error_return;
3169 #endif /* ENABLE_GSS */
3170  }
3171 
3172  /*
3173  * Handle authentication exchange: wait for postmaster messages
3174  * and respond as necessary.
3175  */
3177  {
3178  char beresp;
3179  int msgLength;
3180  int avail;
3181  AuthRequest areq;
3182  int res;
3183 
3184  /*
3185  * Scan the message from current point (note that if we find
3186  * the message is incomplete, we will return without advancing
3187  * inStart, and resume here next time).
3188  */
3189  conn->inCursor = conn->inStart;
3190 
3191  /* Read type byte */
3192  if (pqGetc(&beresp, conn))
3193  {
3194  /* We'll come back when there is more data */
3195  return PGRES_POLLING_READING;
3196  }
3197 
3198  /*
3199  * Validate message type: we expect only an authentication
3200  * request or an error here. Anything else probably means
3201  * it's not Postgres on the other end at all.
3202  */
3203  if (!(beresp == 'R' || beresp == 'E'))
3204  {
3206  libpq_gettext("expected authentication request from server, but received %c\n"),
3207  beresp);
3208  goto error_return;
3209  }
3210 
3211  if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
3212  {
3213  /* Read message length word */
3214  if (pqGetInt(&msgLength, 4, conn))
3215  {
3216  /* We'll come back when there is more data */
3217  return PGRES_POLLING_READING;
3218  }
3219  }
3220  else
3221  {
3222  /* Set phony message length to disable checks below */
3223  msgLength = 8;
3224  }
3225 
3226  /*
3227  * Try to validate message length before using it.
3228  * Authentication requests can't be very large, although GSS
3229  * auth requests may not be that small. Errors can be a
3230  * little larger, but not huge. If we see a large apparent
3231  * length in an error, it means we're really talking to a
3232  * pre-3.0-protocol server; cope.
3233  */
3234  if (beresp == 'R' && (msgLength < 8 || msgLength > 2000))
3235  {
3237  libpq_gettext("expected authentication request from server, but received %c\n"),
3238  beresp);
3239  goto error_return;
3240  }
3241 
3242  if (beresp == 'E' && (msgLength < 8 || msgLength > 30000))
3243  {
3244  /* Handle error from a pre-3.0 server */
3245  conn->inCursor = conn->inStart + 1; /* reread data */
3246  if (pqGets_append(&conn->errorMessage, conn))
3247  {
3248  /* We'll come back when there is more data */
3249  return PGRES_POLLING_READING;
3250  }
3251  /* OK, we read the message; mark data consumed */
3252  conn->inStart = conn->inCursor;
3253 
3254  /*
3255  * The postmaster typically won't end its message with a
3256  * newline, so add one to conform to libpq conventions.
3257  */
3258  appendPQExpBufferChar(&conn->errorMessage, '\n');
3259 
3260  /*
3261  * If we tried to open the connection in 3.0 protocol,
3262  * fall back to 2.0 protocol.
3263  */
3264  if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
3265  {
3266  conn->pversion = PG_PROTOCOL(2, 0);
3267  need_new_connection = true;
3268  goto keep_going;
3269  }
3270 
3271  goto error_return;
3272  }
3273 
3274  /*
3275  * Can't process if message body isn't all here yet.
3276  *
3277  * (In protocol 2.0 case, we are assuming messages carry at
3278  * least 4 bytes of data.)
3279  */
3280  msgLength -= 4;
3281  avail = conn->inEnd - conn->inCursor;
3282  if (avail < msgLength)
3283  {
3284  /*
3285  * Before returning, try to enlarge the input buffer if
3286  * needed to hold the whole message; see notes in
3287  * pqParseInput3.
3288  */
3289  if (pqCheckInBufferSpace(conn->inCursor + (size_t) msgLength,
3290  conn))
3291  goto error_return;
3292  /* We'll come back when there is more data */
3293  return PGRES_POLLING_READING;
3294  }
3295 
3296  /* Handle errors. */
3297  if (beresp == 'E')
3298  {
3299  if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
3300  {
3301  if (pqGetErrorNotice3(conn, true))
3302  {
3303  /* We'll come back when there is more data */
3304  return PGRES_POLLING_READING;
3305  }
3306  }
3307  else
3308  {
3309  if (pqGets_append(&conn->errorMessage, conn))
3310  {
3311  /* We'll come back when there is more data */
3312  return PGRES_POLLING_READING;
3313  }
3314  }
3315  /* OK, we read the message; mark data consumed */
3316  conn->inStart = conn->inCursor;
3317 
3318  /*
3319  * If error is "cannot connect now", try the next host if
3320  * any (but we don't want to consider additional addresses
3321  * for this host, nor is there much point in changing SSL
3322  * or GSS mode). This is helpful when dealing with
3323  * standby servers that might not be in hot-standby state.
3324  */
3325  if (strcmp(conn->last_sqlstate,
3327  {
3328  conn->try_next_host = true;
3329  goto keep_going;
3330  }
3331 
3332  /* Check to see if we should mention pgpassfile */
3333  pgpassfileWarning(conn);
3334 
3335 #ifdef ENABLE_GSS
3336 
3337  /*
3338  * If gssencmode is "prefer" and we're using GSSAPI, retry
3339  * without it.
3340  */
3341  if (conn->gssenc && conn->gssencmode[0] == 'p')
3342  {
3343  /* only retry once */
3344  conn->try_gss = false;
3345  need_new_connection = true;
3346  goto keep_going;
3347  }
3348 #endif
3349 
3350 #ifdef USE_SSL
3351 
3352  /*
3353  * if sslmode is "allow" and we haven't tried an SSL
3354  * connection already, then retry with an SSL connection
3355  */
3356  if (conn->sslmode[0] == 'a' /* "allow" */
3357  && !conn->ssl_in_use
3358  && conn->allow_ssl_try
3359  && conn->wait_ssl_try)
3360  {
3361  /* only retry once */
3362  conn->wait_ssl_try = false;
3363  need_new_connection = true;
3364  goto keep_going;
3365  }
3366 
3367  /*
3368  * if sslmode is "prefer" and we're in an SSL connection,
3369  * then do a non-SSL retry
3370  */
3371  if (conn->sslmode[0] == 'p' /* "prefer" */
3372  && conn->ssl_in_use
3373  && conn->allow_ssl_try /* redundant? */
3374  && !conn->wait_ssl_try) /* redundant? */
3375  {
3376  /* only retry once */
3377  conn->allow_ssl_try = false;
3378  need_new_connection = true;
3379  goto keep_going;
3380  }
3381 #endif
3382 
3383  goto error_return;
3384  }
3385 
3386  /* It is an authentication request. */
3387  conn->auth_req_received = true;
3388 
3389  /* Get the type of request. */
3390  if (pqGetInt((int *) &areq, 4, conn))
3391  {
3392  /* We'll come back when there are more data */
3393  return PGRES_POLLING_READING;
3394  }
3395  msgLength -= 4;
3396 
3397  /*
3398  * Ensure the password salt is in the input buffer, if it's an
3399  * MD5 request. All the other authentication methods that
3400  * contain extra data in the authentication request are only
3401  * supported in protocol version 3, in which case we already
3402  * read the whole message above.
3403  */
3404  if (areq == AUTH_REQ_MD5 && PG_PROTOCOL_MAJOR(conn->pversion) < 3)
3405  {
3406  msgLength += 4;
3407 
3408  avail = conn->inEnd - conn->inCursor;
3409  if (avail < 4)
3410  {
3411  /*
3412  * Before returning, try to enlarge the input buffer
3413  * if needed to hold the whole message; see notes in
3414  * pqParseInput3.
3415  */
3416  if (pqCheckInBufferSpace(conn->inCursor + (size_t) 4,
3417  conn))
3418  goto error_return;
3419  /* We'll come back when there is more data */
3420  return PGRES_POLLING_READING;
3421  }
3422  }
3423 
3424  /*
3425  * Process the rest of the authentication request message, and
3426  * respond to it if necessary.
3427  *
3428  * Note that conn->pghost must be non-NULL if we are going to
3429  * avoid the Kerberos code doing a hostname look-up.
3430  */
3431  res = pg_fe_sendauth(areq, msgLength, conn);
3432 
3433  /* OK, we have processed the message; mark data consumed */
3434  conn->inStart = conn->inCursor;
3435 
3436  if (res != STATUS_OK)
3437  goto error_return;
3438 
3439  /*
3440  * Just make sure that any data sent by pg_fe_sendauth is
3441  * flushed out. Although this theoretically could block, it
3442  * really shouldn't since we don't send large auth responses.
3443  */
3444  if (pqFlush(conn))
3445  goto error_return;
3446 
3447  if (areq == AUTH_REQ_OK)
3448  {
3449  /* We are done with authentication exchange */
3450  conn->status = CONNECTION_AUTH_OK;
3451 
3452  /*
3453  * Set asyncStatus so that PQgetResult will think that
3454  * what comes back next is the result of a query. See
3455  * below.
3456  */
3457  conn->asyncStatus = PGASYNC_BUSY;
3458  }
3459 
3460  /* Look to see if we have more data yet. */
3461  goto keep_going;
3462  }
3463 
3464  case CONNECTION_AUTH_OK:
3465  {
3466  /*
3467  * Now we expect to hear from the backend. A ReadyForQuery
3468  * message indicates that startup is successful, but we might
3469  * also get an Error message indicating failure. (Notice
3470  * messages indicating nonfatal warnings are also allowed by
3471  * the protocol, as are ParameterStatus and BackendKeyData
3472  * messages.) Easiest way to handle this is to let
3473  * PQgetResult() read the messages. We just have to fake it
3474  * out about the state of the connection, by setting
3475  * asyncStatus = PGASYNC_BUSY (done above).
3476  */
3477 
3478  if (PQisBusy(conn))
3479  return PGRES_POLLING_READING;
3480 
3481  res = PQgetResult(conn);
3482 
3483  /*
3484  * NULL return indicating we have gone to IDLE state is
3485  * expected
3486  */
3487  if (res)
3488  {
3489  if (res->resultStatus != PGRES_FATAL_ERROR)
3491  libpq_gettext("unexpected message from server during startup\n"));
3492  else if (conn->send_appname &&
3493  (conn->appname || conn->fbappname))
3494  {
3495  /*
3496  * If we tried to send application_name, check to see
3497  * if the error is about that --- pre-9.0 servers will
3498  * reject it at this stage of the process. If so,
3499  * close the connection and retry without sending
3500  * application_name. We could possibly get a false
3501  * SQLSTATE match here and retry uselessly, but there
3502  * seems no great harm in that; we'll just get the
3503  * same error again if it's unrelated.
3504  */
3505  const char *sqlstate;
3506 
3507  sqlstate = PQresultErrorField(res, PG_DIAG_SQLSTATE);
3508  if (sqlstate &&
3509  strcmp(sqlstate, ERRCODE_APPNAME_UNKNOWN) == 0)
3510  {
3511  PQclear(res);
3512  conn->send_appname = false;
3513  need_new_connection = true;
3514  goto keep_going;
3515  }
3516  }
3517 
3518  /*
3519  * if the resultStatus is FATAL, then conn->errorMessage
3520  * already has a copy of the error; needn't copy it back.
3521  * But add a newline if it's not there already, since
3522  * postmaster error messages may not have one.
3523  */
3524  if (conn->errorMessage.len <= 0 ||
3525  conn->errorMessage.data[conn->errorMessage.len - 1] != '\n')
3526  appendPQExpBufferChar(&conn->errorMessage, '\n');
3527  PQclear(res);
3528  goto error_return;
3529  }
3530 
3531  /* Fire up post-connection housekeeping if needed */
3532  if (PG_PROTOCOL_MAJOR(conn->pversion) < 3)
3533  {
3534  conn->status = CONNECTION_SETENV;
3536  conn->next_eo = EnvironmentOptions;
3537  return PGRES_POLLING_WRITING;
3538  }
3539 
3540  /* Almost there now ... */
3542  goto keep_going;
3543  }
3544 
3546  {
3547  /*
3548  * If a read-write connection is required, see if we have one.
3549  *
3550  * Servers before 7.4 lack the transaction_read_only GUC, but
3551  * by the same token they don't have any read-only mode, so we
3552  * may just skip the test in that case.
3553  */
3554  if (conn->sversion >= 70400 &&
3555  conn->target_session_attrs != NULL &&
3556  strcmp(conn->target_session_attrs, "read-write") == 0)
3557  {
3558  /*
3559  * We use PQsendQueryContinue so that conn->errorMessage
3560  * does not get cleared. We need to preserve any error
3561  * messages related to previous hosts we have tried and
3562  * failed to connect to.
3563  */
3564  conn->status = CONNECTION_OK;
3565  if (!PQsendQueryContinue(conn,
3566  "SHOW transaction_read_only"))
3567  goto error_return;
3569  return PGRES_POLLING_READING;
3570  }
3571 
3572  /* We can release the address list now. */
3573  release_conn_addrinfo(conn);
3574 
3575  /* We are open for business! */
3576  conn->status = CONNECTION_OK;
3577  return PGRES_POLLING_OK;
3578  }
3579 
3580  case CONNECTION_SETENV:
3581  {
3582  /*
3583  * Do post-connection housekeeping (only needed in protocol
3584  * 2.0).
3585  *
3586  * We pretend that the connection is OK for the duration of
3587  * these queries.
3588  */
3589  conn->status = CONNECTION_OK;
3590 
3591  switch (pqSetenvPoll(conn))
3592  {
3593  case PGRES_POLLING_OK: /* Success */
3594  break;
3595 
3596  case PGRES_POLLING_READING: /* Still going */
3597  conn->status = CONNECTION_SETENV;
3598  return PGRES_POLLING_READING;
3599 
3600  case PGRES_POLLING_WRITING: /* Still going */
3601  conn->status = CONNECTION_SETENV;
3602  return PGRES_POLLING_WRITING;
3603 
3604  default:
3605  goto error_return;
3606  }
3607 
3608  /* Almost there now ... */
3610  goto keep_going;
3611  }
3612 
3613  case CONNECTION_CONSUME:
3614  {
3615  conn->status = CONNECTION_OK;
3616  if (!PQconsumeInput(conn))
3617  goto error_return;
3618 
3619  if (PQisBusy(conn))
3620  {
3621  conn->status = CONNECTION_CONSUME;
3622  return PGRES_POLLING_READING;
3623  }
3624 
3625  /*
3626  * Call PQgetResult() again to consume NULL result.
3627  */
3628  res = PQgetResult(conn);
3629  if (res != NULL)
3630  {
3631  PQclear(res);
3632  conn->status = CONNECTION_CONSUME;
3633  goto keep_going;
3634  }
3635 
3636  /* We can release the address list now. */
3637  release_conn_addrinfo(conn);
3638 
3639  /* We are open for business! */
3640  conn->status = CONNECTION_OK;
3641  return PGRES_POLLING_OK;
3642  }
3644  {
3645  conn->status = CONNECTION_OK;
3646  if (!PQconsumeInput(conn))
3647  goto error_return;
3648 
3649  if (PQisBusy(conn))
3650  {
3652  return PGRES_POLLING_READING;
3653  }
3654 
3655  res = PQgetResult(conn);
3656  if (res && (PQresultStatus(res) == PGRES_TUPLES_OK) &&
3657  PQntuples(res) == 1)
3658  {
3659  char *val;
3660 
3661  val = PQgetvalue(res, 0, 0);
3662  if (strncmp(val, "on", 2) == 0)
3663  {
3664  /* Not writable; fail this connection. */
3665  PQclear(res);
3666 
3667  /* Append error report to conn->errorMessage. */
3669  libpq_gettext("session is read-only\n"));
3670 
3671  /* Close connection politely. */
3672  conn->status = CONNECTION_OK;
3673  sendTerminateConn(conn);
3674 
3675  /*
3676  * Try next host if any, but we don't want to consider
3677  * additional addresses for this host.
3678  */
3679  conn->try_next_host = true;
3680  goto keep_going;
3681  }
3682 
3683  /* Session is read-write, so we're good. */
3684  PQclear(res);
3685 
3686  /*
3687  * Finish reading any remaining messages before being
3688  * considered as ready.
3689  */
3690  conn->status = CONNECTION_CONSUME;
3691  goto keep_going;
3692  }
3693 
3694  /*
3695  * Something went wrong with "SHOW transaction_read_only". We
3696  * should try next addresses.
3697  */
3698  if (res)
3699  PQclear(res);
3700 
3701  /* Append error report to conn->errorMessage. */
3703  libpq_gettext("test \"SHOW transaction_read_only\" failed\n"));
3704 
3705  /* Close connection politely. */
3706  conn->status = CONNECTION_OK;
3707  sendTerminateConn(conn);
3708 
3709  /* Try next address */
3710  conn->try_next_addr = true;
3711  goto keep_going;
3712  }
3713 
3714  default:
3716  libpq_gettext("invalid connection state %d, "
3717  "probably indicative of memory corruption\n"),
3718  conn->status);
3719  goto error_return;
3720  }
3721 
3722  /* Unreachable */
3723 
3724 error_return:
3725 
3726  /*
3727  * We used to close the socket at this point, but that makes it awkward
3728  * for those above us if they wish to remove this socket from their own
3729  * records (an fd_set for example). We'll just have this socket closed
3730  * when PQfinish is called (which is compulsory even after an error, since
3731  * the connection structure must be freed).
3732  */
3733  conn->status = CONNECTION_BAD;
3734  return PGRES_POLLING_FAILED;
3735 }
int pqFlush(PGconn *conn)
Definition: fe-misc.c:1012
bool sigpipe_flag
Definition: libpq-int.h:419
char * gssencmode
Definition: libpq-int.h:366
#define NEGOTIATE_GSS_CODE
Definition: pqcomm.h:215
int inEnd
Definition: libpq-int.h:448
#define UNIXSOCK_PATH(path, port, sockdir)
Definition: pqcomm.h:70
int inStart
Definition: libpq-int.h:446
static void release_conn_addrinfo(PGconn *conn)
Definition: fe-connect.c:4040
struct addrinfo * addr_cur
Definition: libpq-int.h:427
char * PQgetvalue(const PGresult *res, int tup_num, int field_num)
Definition: fe-exec.c:3122
static int connectNoDelay(PGconn *conn)
Definition: fe-connect.c:1618
int pg_fe_sendauth(AuthRequest areq, int payloadlen, PGconn *conn)
Definition: fe-auth.c:867
int getpeereid(int sock, uid_t *uid, gid_t *gid)
Definition: getpeereid.c:35
#define UNIXSOCK_PATH_BUFLEN
Definition: pqcomm.h:86
bool sigpipe_so
Definition: libpq-int.h:418
char * pqBuildStartupPacket2(PGconn *conn, int *packetlen, const PQEnvironmentOption *options)
void appendPQExpBufferStr(PQExpBuffer str, const char *data)
Definition: pqexpbuffer.c:369
#define AUTH_REQ_OK
Definition: pqcomm.h:174
int pqCheckInBufferSpace(size_t bytes_needed, PGconn *conn)
Definition: fe-misc.c:394
#define PG_STRERROR_R_BUFLEN
Definition: port.h:233
static void pgpassfileWarning(PGconn *conn)
Definition: fe-connect.c:7028
char * requirepeer
Definition: libpq-int.h:365
char * host
Definition: libpq-int.h:312
struct sockaddr_storage addr
Definition: pqcomm.h:64
static int setKeepalivesIdle(PGconn *conn)
Definition: fe-connect.c:1828
#define MemSet(start, val, len)
Definition: c.h:996
int pqGetInt(int *result, size_t bytes, PGconn *conn)
Definition: fe-misc.c:253
#define connect(s, name, namelen)
Definition: win32_port.h:463
static void sendTerminateConn(PGconn *conn)
Definition: fe-connect.c:4055
void pqDropConnection(PGconn *conn, bool flushInput)
Definition: fe-connect.c:459
#define PG_PROTOCOL_MAJOR(v)
Definition: pqcomm.h:113
#define AI_NUMERICHOST
Definition: getaddrinfo.h:73
int PQntuples(const PGresult *res)
Definition: fe-exec.c:2728
#define PG_DIAG_SQLSTATE
Definition: postgres_ext.h:57
uint32 AuthRequest
Definition: pqcomm.h:188
struct addrinfo * addrlist
Definition: libpq-int.h:426
#define AUTH_REQ_MD5
Definition: pqcomm.h:179
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:2651
pg_conn_host_type type
Definition: libpq-int.h:311
PostgresPollingStatusType pqSetenvPoll(PGconn *conn)
Definition: fe-protocol2.c:47
static void getHostaddr(PGconn *conn, char *host_addr, int host_addr_len)
Definition: fe-connect.c:1645
#define gai_strerror
Definition: getaddrinfo.h:146
int pg_getaddrinfo_all(const char *hostname, const char *servname, const struct addrinfo *hintp, struct addrinfo **result)
Definition: ip.c:57
static bool parse_int_param(const char *value, int *result, PGconn *conn, const char *context)
Definition: fe-connect.c:1782
int sversion
Definition: libpq-int.h:415
#define SOCK_STRERROR
Definition: libpq-int.h:823
PGAsyncStatusType asyncStatus
Definition: libpq-int.h:389
#define NI_MAXHOST
Definition: getaddrinfo.h:88
PGSetenvStatusType setenv_state
Definition: libpq-int.h:429
static int setTCPUserTimeout(PGconn *conn)
Definition: fe-connect.c:1983
static int useKeepalives(PGconn *conn)
Definition: fe-connect.c:1763
#define pg_hton32(x)
Definition: pg_bswap.h:121
#define IS_AF_UNIX(fam)
Definition: ip.h:24
#define SOCK_ERRNO
Definition: libpq-int.h:822
int pqGetErrorNotice3(PGconn *conn, bool isError)
Definition: fe-protocol3.c:871
#define MAXPGPATH
void appendPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:267
bool try_next_host
Definition: libpq-int.h:425
#define ERRCODE_APPNAME_UNKNOWN
Definition: fe-connect.c:92
char * hostaddr
Definition: libpq-int.h:313
pg_conn_host * connhost
Definition: libpq-int.h:406
int pqReadData(PGconn *conn)
Definition: fe-misc.c:615
bool ssl_in_use
Definition: libpq-int.h:472
const PQEnvironmentOption * next_eo
Definition: libpq-int.h:430
char * appname
Definition: libpq-int.h:343
PostgresPollingStatusType pqsecure_open_client(PGconn *conn)
Definition: fe-secure.c:183
ACCEPT_TYPE_ARG3 salen
Definition: pqcomm.h:65
char * target_session_attrs
Definition: libpq-int.h:374
static void pqDropServerData(PGconn *conn)
Definition: fe-connect.c:554
#define STATUS_OK
Definition: c.h:1158
pgsocket sock
Definition: libpq-int.h:410
uint32 ProtocolVersion
Definition: pqcomm.h:122
int pqGetc(char *result, PGconn *conn)
Definition: fe-misc.c:80
static void connectFailureMessage(PGconn *conn, int errorno)
Definition: fe-connect.c:1739
#define socket(af, type, protocol)
Definition: win32_port.h:459
SockAddr raddr
Definition: libpq-int.h:413
#define PGINVALID_SOCKET
Definition: port.h:33
int addrlist_family
Definition: libpq-int.h:428
int pqsecure_initialize(PGconn *conn)
Definition: fe-secure.c:168
int PQconsumeInput(PGconn *conn)
Definition: fe-exec.c:1672
void appendPQExpBufferChar(PQExpBuffer str, char ch)
Definition: pqexpbuffer.c:380
char * sslmode
Definition: libpq-int.h:358
PQExpBufferData errorMessage
Definition: libpq-int.h:530
bool try_next_addr
Definition: libpq-int.h:424
void PQclear(PGresult *res)
Definition: fe-exec.c:676
#define free(a)
Definition: header.h:65
#define ERRCODE_CANNOT_CONNECT_NOW
Definition: fe-connect.c:97
char * PQresultErrorField(const PGresult *res, int fieldcode)
Definition: fe-exec.c:2713
#define Assert(condition)
Definition: c.h:792
bool pg_set_noblock(pgsocket sock)
Definition: noblock.c:25
char * connip
Definition: libpq-int.h:407
int PQisBusy(PGconn *conn)
Definition: fe-exec.c:1722
char * pqBuildStartupPacket3(PGconn *conn, int *packetlen, const PQEnvironmentOption *options)
#define strerror_r
Definition: port.h:232
ProtocolVersion pversion
Definition: libpq-int.h:414
ConnStatusType status
Definition: libpq-int.h:388
bool auth_req_received
Definition: libpq-int.h:416
int uid_t
Definition: win32_port.h:236
static int setKeepalivesInterval(PGconn *conn)
Definition: fe-connect.c:1862
static void emitCouldNotConnect(PGconn *conn, const char *host_addr)
Definition: fe-connect.c:1681
SockAddr laddr
Definition: libpq-int.h:412
PostgresPollingStatusType
Definition: libpq-fe.h:74
struct addrinfo * ai_next
Definition: getaddrinfo.h:107
int pqGetpwuid(uid_t uid, struct passwd *resultbuf, char *buffer, size_t buflen, struct passwd **result)
Definition: thread.c:65
bool pg_GSS_have_cred_cache(gss_cred_id_t *cred_out)
int pqPacketSend(PGconn *conn, char pack_type, const void *buf, size_t buf_len)
Definition: fe-connect.c:4465
int gid_t
Definition: win32_port.h:237
#define EINPROGRESS
Definition: win32_port.h:355
char * fbappname
Definition: libpq-int.h:344
#define EWOULDBLOCK
Definition: win32_port.h:349
size_t ai_addrlen
Definition: getaddrinfo.h:104
PostgresPollingStatusType pqsecure_open_gss(PGconn *conn)
int PQsendQueryContinue(PGconn *conn, const char *query)
Definition: fe-exec.c:1193
void pqClearAsyncResult(PGconn *conn)
Definition: fe-exec.c:731
int inCursor
Definition: libpq-int.h:447
#define EINTR
Definition: win32_port.h:343
char * port
Definition: libpq-int.h:314
#define NEGOTIATE_SSL_CODE
Definition: pqcomm.h:214
int nconnhost
Definition: libpq-int.h:404
#define snprintf
Definition: port.h:215
#define PG_PROTOCOL(m, n)
Definition: pqcomm.h:115
int pqGets_append(PQExpBuffer buf, PGconn *conn)
Definition: fe-misc.c:155
long val
Definition: informix.c:664
PGresult * PQgetResult(PGconn *conn)
Definition: fe-exec.c:1746
struct sockaddr * ai_addr
Definition: getaddrinfo.h:105
static int setKeepalivesCount(PGconn *conn)
Definition: fe-connect.c:1897
int whichhost
Definition: libpq-int.h:405
#define libpq_gettext(x)
Definition: libpq-int.h:809
bool send_appname
Definition: libpq-int.h:431
PGTransactionStatusType xactStatus
Definition: libpq-int.h:390
static const PQEnvironmentOption EnvironmentOptions[]
Definition: fe-connect.c:363
char last_sqlstate[6]
Definition: libpq-int.h:393
int ai_family
Definition: getaddrinfo.h:101

◆ PQconnectStart()

PGconn* PQconnectStart ( const char *  conninfo)

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

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

Referenced by PQconnectdb(), and PQping().

832 {
833  PGconn *conn;
834 
835  /*
836  * Allocate memory for the conn structure. Note that we also expect this
837  * to initialize conn->errorMessage to empty. All subsequent steps during
838  * connection initialization will only append to that buffer.
839  */
840  conn = makeEmptyPGconn();
841  if (conn == NULL)
842  return NULL;
843 
844  /*
845  * Parse the conninfo string
846  */
847  if (!connectOptions1(conn, conninfo))
848  return conn;
849 
850  /*
851  * Compute derived options
852  */
853  if (!connectOptions2(conn))
854  return conn;
855 
856  /*
857  * Connect to the database
858  */
859  if (!connectDBStart(conn))
860  {
861  /* Just in case we failed to set it in connectDBStart */
862  conn->status = CONNECTION_BAD;
863  }
864 
865  return conn;
866 }
static bool connectOptions1(PGconn *conn, const char *conninfo)
Definition: fe-connect.c:919
PGconn * conn
Definition: streamutil.c:54
static int connectDBStart(PGconn *conn)
Definition: fe-connect.c:2022
static PGconn * makeEmptyPGconn(void)
Definition: fe-connect.c:3810
ConnStatusType status
Definition: libpq-int.h:388
static bool connectOptions2(PGconn *conn)
Definition: fe-connect.c:1017

◆ PQconnectStartParams()

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

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

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

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

753 {
754  PGconn *conn;
755  PQconninfoOption *connOptions;
756 
757  /*
758  * Allocate memory for the conn structure. Note that we also expect this
759  * to initialize conn->errorMessage to empty. All subsequent steps during
760  * connection initialization will only append to that buffer.
761  */
762  conn = makeEmptyPGconn();
763  if (conn == NULL)
764  return NULL;
765 
766  /*
767  * Parse the conninfo arrays
768  */
769  connOptions = conninfo_array_parse(keywords, values,
770  &conn->errorMessage,
771  true, expand_dbname);
772  if (connOptions == NULL)
773  {
774  conn->status = CONNECTION_BAD;
775  /* errorMessage is already set */
776  return conn;
777  }
778 
779  /*
780  * Move option values into conn structure
781  */
782  if (!fillPGconn(conn, connOptions))
783  {
784  PQconninfoFree(connOptions);
785  return conn;
786  }
787 
788  /*
789  * Free the option info - all is in conn now
790  */
791  PQconninfoFree(connOptions);
792 
793  /*
794  * Compute derived options
795  */
796  if (!connectOptions2(conn))
797  return conn;
798 
799  /*
800  * Connect to the database
801  */
802  if (!connectDBStart(conn))
803  {
804  /* Just in case we failed to set it in connectDBStart */
805  conn->status = CONNECTION_BAD;
806  }
807 
808  return conn;
809 }
PGconn * conn
Definition: streamutil.c:54
static int connectDBStart(PGconn *conn)
Definition: fe-connect.c:2022
void PQconninfoFree(PQconninfoOption *connOptions)
Definition: fe-connect.c:6457
static PGconn * makeEmptyPGconn(void)
Definition: fe-connect.c:3810
PQExpBufferData errorMessage
Definition: libpq-int.h:530
static bool fillPGconn(PGconn *conn, PQconninfoOption *connOptions)
Definition: fe-connect.c:877
ConnStatusType status
Definition: libpq-int.h:388
static Datum values[MAXATTR]
Definition: bootstrap.c:165
static bool connectOptions2(PGconn *conn)
Definition: fe-connect.c:1017
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:5516

◆ PQconninfo()

PQconninfoOption* PQconninfo ( PGconn conn)

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

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

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

6414 {
6415  PQExpBufferData errorBuf;
6416  PQconninfoOption *connOptions;
6417 
6418  if (conn == NULL)
6419  return NULL;
6420 
6421  /*
6422  * We don't actually report any errors here, but callees want a buffer,
6423  * and we prefer not to trash the conn's errorMessage.
6424  */
6425  initPQExpBuffer(&errorBuf);
6426  if (PQExpBufferDataBroken(errorBuf))
6427  return NULL; /* out of memory already :-( */
6428 
6429  connOptions = conninfo_init(&errorBuf);
6430 
6431  if (connOptions != NULL)
6432  {
6434 
6435  for (option = PQconninfoOptions; option->keyword; option++)
6436  {
6437  char **connmember;
6438 
6439  if (option->connofs < 0)
6440  continue;
6441 
6442  connmember = (char **) ((char *) conn + option->connofs);
6443 
6444  if (*connmember)
6445  conninfo_storeval(connOptions, option->keyword, *connmember,
6446  &errorBuf, true, false);
6447  }
6448  }
6449 
6450  termPQExpBuffer(&errorBuf);
6451 
6452  return connOptions;
6453 }
static PQconninfoOption * conninfo_storeval(PQconninfoOption *connOptions, const char *keyword, const char *value, PQExpBuffer errorMessage, bool ignoreMissing, bool uri_decode)
Definition: fe-connect.c:6330
void termPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:131
static PQconninfoOption * conninfo_init(PQExpBuffer errorMessage)
Definition: fe-connect.c:5244
static const internalPQconninfoOption PQconninfoOptions[]
Definition: fe-connect.c:194
#define PQExpBufferDataBroken(buf)
Definition: pqexpbuffer.h:67
void initPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:92

◆ PQconninfoFree()

void PQconninfoFree ( PQconninfoOption connOptions)

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

References free, _PQconninfoOption::keyword, and _PQconninfoOption::val.

Referenced by check_pghost_envvar(), connectDatabase(), connectOptions1(), conninfo_array_parse(), conninfo_parse(), conninfo_uri_parse(), dblink_connstr_check(), do_connect(), GenerateRecoveryConfig(), GetConnection(), libpqrcv_check_conninfo(), libpqrcv_get_conninfo(), PQconndefaults(), and PQconnectStartParams().

6458 {
6460 
6461  if (connOptions == NULL)
6462  return;
6463 
6464  for (option = connOptions; option->keyword != NULL; option++)
6465  {
6466  if (option->val != NULL)
6467  free(option->val);
6468  }
6469  free(connOptions);
6470 }
#define free(a)
Definition: header.h:65

◆ PQconninfoParse()

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

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

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

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

5223 {
5224  PQExpBufferData errorBuf;
5225  PQconninfoOption *connOptions;
5226 
5227  if (errmsg)
5228  *errmsg = NULL; /* default */
5229  initPQExpBuffer(&errorBuf);
5230  if (PQExpBufferDataBroken(errorBuf))
5231  return NULL; /* out of memory already :-( */
5232  connOptions = parse_connection_string(conninfo, &errorBuf, false);
5233  if (connOptions == NULL && errmsg)
5234  *errmsg = errorBuf.data;
5235  else
5236  termPQExpBuffer(&errorBuf);
5237  return connOptions;
5238 }
void termPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:131
static PQconninfoOption * parse_connection_string(const char *conninfo, PQExpBuffer errorMessage, bool use_defaults)
Definition: fe-connect.c:5284
#define PQExpBufferDataBroken(buf)
Definition: pqexpbuffer.h:67
int errmsg(const char *fmt,...)
Definition: elog.c:915
void initPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:92

◆ PQconsumeInput()

int PQconsumeInput ( PGconn conn)

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

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

Referenced by advanceConnectionState(), CopyStreamReceive(), dblink_get_notify(), dblink_is_busy(), ecpg_process_output(), libpqrcv_PQgetResult(), libpqrcv_receive(), main(), ParallelSlotsGetIdle(), pgfdw_get_cleanup_result(), pgfdw_get_result(), PQconnectPoll(), PrintNotifications(), StreamLogicalLog(), and try_complete_step().

1673 {
1674  if (!conn)
1675  return 0;
1676 
1677  /*
1678  * for non-blocking connections try to flush the send-queue, otherwise we
1679  * may never get a response for something that may not have already been
1680  * sent because it's in our write buffer!
1681  */
1682  if (pqIsnonblocking(conn))
1683  {
1684  if (pqFlush(conn) < 0)
1685  return 0;
1686  }
1687 
1688  /*
1689  * Load more data, if available. We do this no matter what state we are
1690  * in, since we are probably getting called because the application wants
1691  * to get rid of a read-select condition. Note that we will NOT block
1692  * waiting for more input.
1693  */
1694  if (pqReadData(conn) < 0)
1695  return 0;
1696 
1697  /* Parsing of the data waits till later. */
1698  return 1;
1699 }
int pqFlush(PGconn *conn)
Definition: fe-misc.c:1012
#define pqIsnonblocking(conn)
Definition: libpq-int.h:803
int pqReadData(PGconn *conn)
Definition: fe-misc.c:615

◆ PQcopyResult()

PGresult* PQcopyResult ( const PGresult src,
int  flags 
)

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

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

Referenced by pqRowProcessor().

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

◆ PQdb()

char* PQdb ( const PGconn conn)

◆ PQdefaultSSLKeyPassHook_OpenSSL()

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

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

References fprintf, libpq_gettext, and pg_conn::sslpassword.

Referenced by PQssl_passwd_cb().

1714 {
1715  if (conn->sslpassword)
1716  {
1717  if (strlen(conn->sslpassword) + 1 > size)
1718  fprintf(stderr, libpq_gettext("WARNING: sslpassword truncated\n"));
1719  strncpy(buf, conn->sslpassword, size);
1720  buf[size - 1] = '\0';
1721  return strlen(buf);
1722  }
1723  else
1724  {
1725  buf[0] = '\0';
1726  return 0;
1727  }
1728 }
#define fprintf
Definition: port.h:219
static char * buf
Definition: pg_test_fsync.c:68
char * sslpassword
Definition: libpq-int.h:362
#define libpq_gettext(x)
Definition: libpq-int.h:809

◆ PQdescribePortal()

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

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

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

2134 {
2135  if (!PQexecStart(conn))
2136  return NULL;
2137  if (!PQsendDescribe(conn, 'P', portal))
2138  return NULL;
2139  return PQexecFinish(conn);
2140 }
static int PQsendDescribe(PGconn *conn, char desc_type, const char *desc_target)
Definition: fe-exec.c:2178
static PGresult * PQexecFinish(PGconn *conn)
Definition: fe-exec.c:2068
static bool PQexecStart(PGconn *conn)
Definition: fe-exec.c:1989

◆ PQdescribePrepared()

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

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

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

Referenced by DescribeQuery(), and ECPGdescribe().

2115 {
2116  if (!PQexecStart(conn))
2117  return NULL;
2118  if (!PQsendDescribe(conn, 'S', stmt))
2119  return NULL;
2120  return PQexecFinish(conn);
2121 }
static int PQsendDescribe(PGconn *conn, char desc_type, const char *desc_target)
Definition: fe-exec.c:2178
static PGresult * PQexecFinish(PGconn *conn)
Definition: fe-exec.c:2068
static bool PQexecStart(PGconn *conn)
Definition: fe-exec.c:1989

◆ PQdisplayTuples()

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

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

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

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

◆ PQdsplen()

int PQdsplen ( const char *  s,
int  encoding 
)

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

References pg_encoding_dsplen().

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

1242 {
1243  return pg_encoding_dsplen(encoding, s);
1244 }
int pg_encoding_dsplen(int encoding, const char *mbstr)
Definition: wchar.c:1565
int32 encoding
Definition: pg_database.h:41

◆ PQencryptPassword()

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

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

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

1155 {
1156  char *crypt_pwd;
1157 
1158  crypt_pwd = malloc(MD5_PASSWD_LEN + 1);
1159  if (!crypt_pwd)
1160  return NULL;
1161 
1162  if (!pg_md5_encrypt(passwd, user, strlen(user), crypt_pwd))
1163  {
1164  free(crypt_pwd);
1165  return NULL;
1166  }
1167 
1168  return crypt_pwd;
1169 }
#define malloc(a)
Definition: header.h:50
bool pg_md5_encrypt(const char *passwd, const char *salt, size_t salt_len, char *buf)
Definition: md5_common.c:124
#define free(a)
Definition: header.h:65
static char * user
Definition: pg_regress.c:95
#define MD5_PASSWD_LEN
Definition: md5.h:24

◆ PQencryptPasswordConn()

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

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

References appendPQExpBuffer(), appendPQExpBufferStr(), pg_conn::errorMessage, free, libpq_gettext, malloc, MAX_ALGORITHM_NAME_LEN, MD5_PASSWD_LEN, pg_fe_scram_build_secret(), pg_md5_encrypt(), PGRES_TUPLES_OK, PQclear(), PQexec(), PQgetvalue(), PQnfields(), PQntuples(), PQresultStatus(), resetPQExpBuffer(), and val.

Referenced by exec_command_password(), and main().

1198 {
1199 #define MAX_ALGORITHM_NAME_LEN 50
1200  char algobuf[MAX_ALGORITHM_NAME_LEN + 1];
1201  char *crypt_pwd = NULL;
1202 
1203  if (!conn)
1204  return NULL;
1205 
1207 
1208  /* If no algorithm was given, ask the server. */
1209  if (algorithm == NULL)
1210  {
1211  PGresult *res;
1212  char *val;
1213 
1214  res = PQexec(conn, "show password_encryption");
1215  if (res == NULL)
1216  {
1217  /* PQexec() should've set conn->errorMessage already */
1218  return NULL;
1219  }
1220  if (PQresultStatus(res) != PGRES_TUPLES_OK)
1221  {
1222  /* PQexec() should've set conn->errorMessage already */
1223  PQclear(res);
1224  return NULL;
1225  }
1226  if (PQntuples(res) != 1 || PQnfields(res) != 1)
1227  {
1228  PQclear(res);
1230  libpq_gettext("unexpected shape of result set returned for SHOW\n"));
1231  return NULL;
1232  }
1233  val = PQgetvalue(res, 0, 0);
1234 
1235  if (strlen(val) > MAX_ALGORITHM_NAME_LEN)
1236  {
1237  PQclear(res);
1239  libpq_gettext("password_encryption value too long\n"));
1240  return NULL;
1241  }
1242  strcpy(algobuf, val);
1243  PQclear(res);
1244 
1245  algorithm = algobuf;
1246  }
1247 
1248  /*
1249  * Also accept "on" and "off" as aliases for "md5", because
1250  * password_encryption was a boolean before PostgreSQL 10. We refuse to
1251  * send the password in plaintext even if it was "off".
1252  */
1253  if (strcmp(algorithm, "on") == 0 ||
1254  strcmp(algorithm, "off") == 0)
1255  algorithm = "md5";
1256 
1257  /*
1258  * Ok, now we know what algorithm to use
1259  */
1260  if (strcmp(algorithm, "scram-sha-256") == 0)
1261  {
1262  crypt_pwd = pg_fe_scram_build_secret(passwd);
1263  }
1264  else if (strcmp(algorithm, "md5") == 0)
1265  {
1266  crypt_pwd = malloc(MD5_PASSWD_LEN + 1);
1267  if (crypt_pwd)
1268  {
1269  if (!pg_md5_encrypt(passwd, user, strlen(user), crypt_pwd))
1270  {
1271  free(crypt_pwd);
1272  crypt_pwd = NULL;
1273  }
1274  }
1275  }
1276  else
1277  {
1279  libpq_gettext("unrecognized password encryption algorithm \"%s\"\n"),
1280  algorithm);
1281  return NULL;
1282  }
1283 
1284  if (!crypt_pwd)
1286  libpq_gettext("out of memory\n"));
1287 
1288  return crypt_pwd;
1289 }
int PQnfields(const PGresult *res)
Definition: fe-exec.c:2736
char * PQgetvalue(const PGresult *res, int tup_num, int field_num)
Definition: fe-exec.c:3122
void appendPQExpBufferStr(PQExpBuffer str, const char *data)
Definition: pqexpbuffer.c:369
int PQntuples(const PGresult *res)
Definition: fe-exec.c:2728
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:2651
#define malloc(a)
Definition: header.h:50
#define MAX_ALGORITHM_NAME_LEN
void appendPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:267
char * pg_fe_scram_build_secret(const char *password)
bool pg_md5_encrypt(const char *passwd, const char *salt, size_t salt_len, char *buf)
Definition: md5_common.c:124
PQExpBufferData errorMessage
Definition: libpq-int.h:530
void PQclear(PGresult *res)
Definition: fe-exec.c:676
#define free(a)
Definition: header.h:65
static char * user
Definition: pg_regress.c:95
#define MD5_PASSWD_LEN
Definition: md5.h:24
PGresult * PQexec(PGconn *conn, const char *query)
Definition: fe-exec.c:1907
void resetPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:148
long val
Definition: informix.c:664
#define libpq_gettext(x)
Definition: libpq-int.h:809

◆ PQendcopy()

int PQendcopy ( PGconn conn)

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

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

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

2576 {
2577  if (!conn)
2578  return 0;
2579 
2580  if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
2581  return pqEndcopy3(conn);
2582  else
2583  return pqEndcopy2(conn);
2584 }
#define PG_PROTOCOL_MAJOR(v)
Definition: pqcomm.h:113
int pqEndcopy3(PGconn *conn)
ProtocolVersion pversion
Definition: libpq-int.h:414
int pqEndcopy2(PGconn *conn)

◆ PQenv2encoding()

int PQenv2encoding ( void  )

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

References dgettext, dngettext, encoding, libpq_gettext, libpq_ngettext, pg_char_to_encoding(), PG_SQL_ASCII, PG_TEXTDOMAIN, and generate_unaccent_rules::str.

Referenced by main().

1251 {
1252  char *str;
1253  int encoding = PG_SQL_ASCII;
1254 
1255  str = getenv("PGCLIENTENCODING");
1256  if (str && *str != '\0')
1257  {
1258  encoding = pg_char_to_encoding(str);
1259  if (encoding < 0)
1260  encoding = PG_SQL_ASCII;
1261  }
1262  return encoding;
1263 }
int pg_char_to_encoding(const char *name)
Definition: encnames.c:550
int32 encoding
Definition: pg_database.h:41

◆ PQerrorMessage()