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

Go to the source code of this file.

Data Structures

struct  pgNotify
 
struct  _PQprintOpt
 
struct  _PQconninfoOption
 
struct  PQArgBlock
 
struct  pgresAttDesc
 

Macros

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

Typedefs

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

Enumerations

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

Functions

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

Macro Definition Documentation

#define PG_COPYRES_ATTRS   0x01

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

Referenced by PQcopyResult(), and pqRowProcessor().

#define PG_COPYRES_EVENTS   0x04

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

Referenced by PQcopyResult(), and pqRowProcessor().

#define PG_COPYRES_NOTICEHOOKS   0x08

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

Referenced by PQcopyResult(), and pqRowProcessor().

#define PG_COPYRES_TUPLES   0x02 /* Implies PG_COPYRES_ATTRS */

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

Referenced by PQcopyResult().

#define PQfreeNotify (   ptr)    PQfreemem(ptr)

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

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

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

Referenced by pg_fe_sendauth(), and pg_SASL_init().

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

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

Referenced by main().

Typedef Documentation

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

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

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

typedef void(* pgthreadlock_t)(int acquire)

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

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

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

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

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

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

Enumeration Type Documentation

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Function Documentation

int lo_close ( PGconn conn,
int  fd 
)

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

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

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

101 {
102  PQArgBlock argv[1];
103  PGresult *res;
104  int retval;
105  int result_len;
106 
107  if (conn == NULL || conn->lobjfuncs == NULL)
108  {
109  if (lo_initialize(conn) < 0)
110  return -1;
111  }
112 
113  argv[0].isint = 1;
114  argv[0].len = 4;
115  argv[0].u.integer = fd;
116  res = PQfn(conn, conn->lobjfuncs->fn_lo_close,
117  &retval, &result_len, 1, argv, 1);
118  if (PQresultStatus(res) == PGRES_COMMAND_OK)
119  {
120  PQclear(res);
121  return retval;
122  }
123  else
124  {
125  PQclear(res);
126  return -1;
127  }
128 }
union PQArgBlock::@139 u
PGresult * PQfn(PGconn *conn, int fnid, int *result_buf, int *result_len, int result_is_int, const PQArgBlock *args, int nargs)
Definition: fe-exec.c:2556
static int fd(const char *x, int i)
Definition: preproc-init.c:105
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:2596
void PQclear(PGresult *res)
Definition: fe-exec.c:650
#define NULL
Definition: c.h:229
Oid fn_lo_close
Definition: libpq-int.h:268
int isint
Definition: libpq-fe.h:223
PGlobjfuncs * lobjfuncs
Definition: libpq-int.h:427
int integer
Definition: libpq-fe.h:227
static int lo_initialize(PGconn *conn)
Definition: fe-lobj.c:877
Oid lo_creat ( PGconn conn,
int  mode 
)

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

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

Referenced by importFile(), and lo_import_internal().

467 {
468  PQArgBlock argv[1];
469  PGresult *res;
470  int retval;
471  int result_len;
472 
473  if (conn == NULL || conn->lobjfuncs == NULL)
474  {
475  if (lo_initialize(conn) < 0)
476  return InvalidOid;
477  }
478 
479  argv[0].isint = 1;
480  argv[0].len = 4;
481  argv[0].u.integer = mode;
482  res = PQfn(conn, conn->lobjfuncs->fn_lo_creat,
483  &retval, &result_len, 1, argv, 1);
484  if (PQresultStatus(res) == PGRES_COMMAND_OK)
485  {
486  PQclear(res);
487  return (Oid) retval;
488  }
489  else
490  {
491  PQclear(res);
492  return InvalidOid;
493  }
494 }
union PQArgBlock::@139 u
unsigned int Oid
Definition: postgres_ext.h:31
PGresult * PQfn(PGconn *conn, int fnid, int *result_buf, int *result_len, int result_is_int, const PQArgBlock *args, int nargs)
Definition: fe-exec.c:2556
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:2596
#define InvalidOid
Definition: postgres_ext.h:36
void PQclear(PGresult *res)
Definition: fe-exec.c:650
#define NULL
Definition: c.h:229
Oid fn_lo_creat
Definition: libpq-int.h:269
int isint
Definition: libpq-fe.h:223
PGlobjfuncs * lobjfuncs
Definition: libpq-int.h:427
int integer
Definition: libpq-fe.h:227
static int lo_initialize(PGconn *conn)
Definition: fe-lobj.c:877
Oid lo_create ( PGconn conn,
Oid  lobjId 
)

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

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

Referenced by lo_import_internal(), and StartRestoreBlob().

506 {
507  PQArgBlock argv[1];
508  PGresult *res;
509  int retval;
510  int result_len;
511 
512  if (conn == NULL || conn->lobjfuncs == NULL)
513  {
514  if (lo_initialize(conn) < 0)
515  return InvalidOid;
516  }
517 
518  /* Must check this on-the-fly because it's not there pre-8.1 */
519  if (conn->lobjfuncs->fn_lo_create == 0)
520  {
522  libpq_gettext("cannot determine OID of function lo_create\n"));
523  return InvalidOid;
524  }
525 
526  argv[0].isint = 1;
527  argv[0].len = 4;
528  argv[0].u.integer = lobjId;
529  res = PQfn(conn, conn->lobjfuncs->fn_lo_create,
530  &retval, &result_len, 1, argv, 1);
531  if (PQresultStatus(res) == PGRES_COMMAND_OK)
532  {
533  PQclear(res);
534  return (Oid) retval;
535  }
536  else
537  {
538  PQclear(res);
539  return InvalidOid;
540  }
541 }
union PQArgBlock::@139 u
void printfPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:234
Oid fn_lo_create
Definition: libpq-int.h:270
unsigned int Oid
Definition: postgres_ext.h:31
PGresult * PQfn(PGconn *conn, int fnid, int *result_buf, int *result_len, int result_is_int, const PQArgBlock *args, int nargs)
Definition: fe-exec.c:2556
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:2596
PQExpBufferData errorMessage
Definition: libpq-int.h:492
#define InvalidOid
Definition: postgres_ext.h:36
void PQclear(PGresult *res)
Definition: fe-exec.c:650
#define NULL
Definition: c.h:229
int isint
Definition: libpq-fe.h:223
PGlobjfuncs * lobjfuncs
Definition: libpq-int.h:427
#define libpq_gettext(x)
Definition: libpq-int.h:683
int integer
Definition: libpq-fe.h:227
static int lo_initialize(PGconn *conn)
Definition: fe-lobj.c:877
int lo_export ( PGconn conn,
Oid  lobjId,
const char *  filename 
)

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

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

Referenced by do_lo_export(), and main().

786 {
787  int result = 1;
788  int fd;
789  int nbytes,
790  tmp;
791  char buf[LO_BUFSIZE];
792  int lobj;
793  char sebuf[256];
794 
795  /*
796  * open the large object.
797  */
798  lobj = lo_open(conn, lobjId, INV_READ);
799  if (lobj == -1)
800  {
801  /* we assume lo_open() already set a suitable error message */
802  return -1;
803  }
804 
805  /*
806  * create the file to be written to
807  */
808  fd = open(filename, O_CREAT | O_WRONLY | O_TRUNC | PG_BINARY, 0666);
809  if (fd < 0)
810  {
811  /* We must do lo_close before setting the errorMessage */
812  int save_errno = errno;
813 
814  (void) lo_close(conn, lobj);
816  libpq_gettext("could not open file \"%s\": %s\n"),
817  filename,
818  pqStrerror(save_errno, sebuf, sizeof(sebuf)));
819  return -1;
820  }
821 
822  /*
823  * read in from the large object and write to the file
824  */
825  while ((nbytes = lo_read(conn, lobj, buf, LO_BUFSIZE)) > 0)
826  {
827  tmp = write(fd, buf, nbytes);
828  if (tmp != nbytes)
829  {
830  /* We must do lo_close before setting the errorMessage */
831  int save_errno = errno;
832 
833  (void) lo_close(conn, lobj);
834  (void) close(fd);
836  libpq_gettext("could not write to file \"%s\": %s\n"),
837  filename,
838  pqStrerror(save_errno, sebuf, sizeof(sebuf)));
839  return -1;
840  }
841  }
842 
843  /*
844  * If lo_read() failed, we are now in an aborted transaction so there's no
845  * need for lo_close(); furthermore, if we tried it we'd overwrite the
846  * useful error result with a useless one. So skip lo_close() if we got a
847  * failure result.
848  */
849  if (nbytes < 0 ||
850  lo_close(conn, lobj) != 0)
851  {
852  /* assume lo_read() or lo_close() left a suitable error message */
853  result = -1;
854  }
855 
856  /* if we already failed, don't overwrite that msg with a close error */
857  if (close(fd) && result >= 0)
858  {
860  libpq_gettext("could not write to file \"%s\": %s\n"),
861  filename, pqStrerror(errno, sebuf, sizeof(sebuf)));
862  result = -1;
863  }
864 
865  return result;
866 }
void printfPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:234
#define write(a, b, c)
Definition: win32.h:14
char * pqStrerror(int errnum, char *strerrbuf, size_t buflen)
Definition: thread.c:61
return result
Definition: formatting.c:1632
static int fd(const char *x, int i)
Definition: preproc-init.c:105
#define PG_BINARY
Definition: c.h:1038
#define INV_READ
Definition: libpq-fs.h:22
int lo_close(PGconn *conn, int fd)
Definition: fe-lobj.c:100
static char * buf
Definition: pg_test_fsync.c:66
int lo_open(PGconn *conn, Oid lobjId, int mode)
Definition: fe-lobj.c:58
PQExpBufferData errorMessage
Definition: libpq-int.h:492
#define LO_BUFSIZE
Definition: fe-lobj.c:43
static char * filename
Definition: pg_dumpall.c:89
int lo_read(PGconn *conn, int fd, char *buf, size_t len)
Definition: fe-lobj.c:259
#define close(a)
Definition: win32.h:12
#define libpq_gettext(x)
Definition: libpq-int.h:683
Oid lo_import ( PGconn conn,
const char *  filename 
)

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

References InvalidOid, and lo_import_internal().

Referenced by do_lo_import(), and main().

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

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

References lo_import_internal().

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

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

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

Referenced by overwrite(), and pickout().

367 {
368  PQArgBlock argv[3];
369  PGresult *res;
370  int retval;
371  int result_len;
372 
373  if (conn == NULL || conn->lobjfuncs == NULL)
374  {
375  if (lo_initialize(conn) < 0)
376  return -1;
377  }
378 
379  argv[0].isint = 1;
380  argv[0].len = 4;
381  argv[0].u.integer = fd;
382 
383  argv[1].isint = 1;
384  argv[1].len = 4;
385  argv[1].u.integer = offset;
386 
387  argv[2].isint = 1;
388  argv[2].len = 4;
389  argv[2].u.integer = whence;
390 
391  res = PQfn(conn, conn->lobjfuncs->fn_lo_lseek,
392  &retval, &result_len, 1, argv, 3);
393  if (PQresultStatus(res) == PGRES_COMMAND_OK)
394  {
395  PQclear(res);
396  return retval;
397  }
398  else
399  {
400  PQclear(res);
401  return -1;
402  }
403 }
union PQArgBlock::@139 u
Oid fn_lo_lseek
Definition: libpq-int.h:272
PGresult * PQfn(PGconn *conn, int fnid, int *result_buf, int *result_len, int result_is_int, const PQArgBlock *args, int nargs)
Definition: fe-exec.c:2556
static int fd(const char *x, int i)
Definition: preproc-init.c:105
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:2596
void PQclear(PGresult *res)
Definition: fe-exec.c:650
#define NULL
Definition: c.h:229
int isint
Definition: libpq-fe.h:223
PGlobjfuncs * lobjfuncs
Definition: libpq-int.h:427
int integer
Definition: libpq-fe.h:227
static int lo_initialize(PGconn *conn)
Definition: fe-lobj.c:877
pg_int64 lo_lseek64 ( PGconn conn,
int  fd,
pg_int64  offset,
int  whence 
)

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

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

Referenced by overwrite(), and pickout().

411 {
412  PQArgBlock argv[3];
413  PGresult *res;
414  pg_int64 retval;
415  int result_len;
416 
417  if (conn == NULL || conn->lobjfuncs == NULL)
418  {
419  if (lo_initialize(conn) < 0)
420  return -1;
421  }
422 
423  if (conn->lobjfuncs->fn_lo_lseek64 == 0)
424  {
426  libpq_gettext("cannot determine OID of function lo_lseek64\n"));
427  return -1;
428  }
429 
430  argv[0].isint = 1;
431  argv[0].len = 4;
432  argv[0].u.integer = fd;
433 
434  offset = lo_hton64(offset);
435  argv[1].isint = 0;
436  argv[1].len = 8;
437  argv[1].u.ptr = (int *) &offset;
438 
439  argv[2].isint = 1;
440  argv[2].len = 4;
441  argv[2].u.integer = whence;
442 
443  res = PQfn(conn, conn->lobjfuncs->fn_lo_lseek64,
444  (void *) &retval, &result_len, 0, argv, 3);
445  if (PQresultStatus(res) == PGRES_COMMAND_OK && result_len == 8)
446  {
447  PQclear(res);
448  return lo_ntoh64(retval);
449  }
450  else
451  {
452  PQclear(res);
453  return -1;
454  }
455 }
union PQArgBlock::@139 u
void printfPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:234
PGresult * PQfn(PGconn *conn, int fnid, int *result_buf, int *result_len, int result_is_int, const PQArgBlock *args, int nargs)
Definition: fe-exec.c:2556
static int fd(const char *x, int i)
Definition: preproc-init.c:105
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:2596
PG_INT64_TYPE pg_int64
Definition: postgres_ext.h:47
static pg_int64 lo_hton64(pg_int64 host64)
Definition: fe-lobj.c:1062
PQExpBufferData errorMessage
Definition: libpq-int.h:492
void PQclear(PGresult *res)
Definition: fe-exec.c:650
#define NULL
Definition: c.h:229
Oid fn_lo_lseek64
Definition: libpq-int.h:273
int isint
Definition: libpq-fe.h:223
PGlobjfuncs * lobjfuncs
Definition: libpq-int.h:427
int * ptr
Definition: libpq-fe.h:226
#define libpq_gettext(x)
Definition: libpq-int.h:683
int integer
Definition: libpq-fe.h:227
static pg_int64 lo_ntoh64(pg_int64 net64)
Definition: fe-lobj.c:1087
static int lo_initialize(PGconn *conn)
Definition: fe-lobj.c:877
int lo_open ( PGconn conn,
Oid  lobjId,
int  mode 
)

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

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

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

59 {
60  int fd;
61  int result_len;
62  PQArgBlock argv[2];
63  PGresult *res;
64 
65  if (conn == NULL || conn->lobjfuncs == NULL)
66  {
67  if (lo_initialize(conn) < 0)
68  return -1;
69  }
70 
71  argv[0].isint = 1;
72  argv[0].len = 4;
73  argv[0].u.integer = lobjId;
74 
75  argv[1].isint = 1;
76  argv[1].len = 4;
77  argv[1].u.integer = mode;
78 
79  res = PQfn(conn, conn->lobjfuncs->fn_lo_open, &fd, &result_len, 1, argv, 2);
80  if (PQresultStatus(res) == PGRES_COMMAND_OK)
81  {
82  PQclear(res);
83  return fd;
84  }
85  else
86  {
87  PQclear(res);
88  return -1;
89  }
90 }
union PQArgBlock::@139 u
PGresult * PQfn(PGconn *conn, int fnid, int *result_buf, int *result_len, int result_is_int, const PQArgBlock *args, int nargs)
Definition: fe-exec.c:2556
static int fd(const char *x, int i)
Definition: preproc-init.c:105
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:2596
Oid fn_lo_open
Definition: libpq-int.h:267
void PQclear(PGresult *res)
Definition: fe-exec.c:650
#define NULL
Definition: c.h:229
int isint
Definition: libpq-fe.h:223
PGlobjfuncs * lobjfuncs
Definition: libpq-int.h:427
int integer
Definition: libpq-fe.h:227
static int lo_initialize(PGconn *conn)
Definition: fe-lobj.c:877
int lo_read ( PGconn conn,
int  fd,
char *  buf,
size_t  len 
)

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

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

Referenced by lo_export().

260 {
261  PQArgBlock argv[2];
262  PGresult *res;
263  int result_len;
264 
265  if (conn == NULL || conn->lobjfuncs == NULL)
266  {
267  if (lo_initialize(conn) < 0)
268  return -1;
269  }
270 
271  /*
272  * Long ago, somebody thought it'd be a good idea to declare this function
273  * as taking size_t ... but the underlying backend function only accepts a
274  * signed int32 length. So throw error if the given value overflows
275  * int32.
276  */
277  if (len > (size_t) INT_MAX)
278  {
280  libpq_gettext("argument of lo_read exceeds integer range\n"));
281  return -1;
282  }
283 
284  argv[0].isint = 1;
285  argv[0].len = 4;
286  argv[0].u.integer = fd;
287 
288  argv[1].isint = 1;
289  argv[1].len = 4;
290  argv[1].u.integer = (int) len;
291 
292  res = PQfn(conn, conn->lobjfuncs->fn_lo_read,
293  (void *) buf, &result_len, 0, argv, 2);
294  if (PQresultStatus(res) == PGRES_COMMAND_OK)
295  {
296  PQclear(res);
297  return result_len;
298  }
299  else
300  {
301  PQclear(res);
302  return -1;
303  }
304 }
union PQArgBlock::@139 u
void printfPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:234
PGresult * PQfn(PGconn *conn, int fnid, int *result_buf, int *result_len, int result_is_int, const PQArgBlock *args, int nargs)
Definition: fe-exec.c:2556
static int fd(const char *x, int i)
Definition: preproc-init.c:105
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:2596
Oid fn_lo_read
Definition: libpq-int.h:278
static char * buf
Definition: pg_test_fsync.c:66
PQExpBufferData errorMessage
Definition: libpq-int.h:492
void PQclear(PGresult *res)
Definition: fe-exec.c:650
#define NULL
Definition: c.h:229
int isint
Definition: libpq-fe.h:223
PGlobjfuncs * lobjfuncs
Definition: libpq-int.h:427
#define libpq_gettext(x)
Definition: libpq-int.h:683
int integer
Definition: libpq-fe.h:227
static int lo_initialize(PGconn *conn)
Definition: fe-lobj.c:877
int lo_tell ( PGconn conn,
int  fd 
)

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

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

550 {
551  int retval;
552  PQArgBlock argv[1];
553  PGresult *res;
554  int result_len;
555 
556  if (conn == NULL || conn->lobjfuncs == NULL)
557  {
558  if (lo_initialize(conn) < 0)
559  return -1;
560  }
561 
562  argv[0].isint = 1;
563  argv[0].len = 4;
564  argv[0].u.integer = fd;
565 
566  res = PQfn(conn, conn->lobjfuncs->fn_lo_tell,
567  &retval, &result_len, 1, argv, 1);
568  if (PQresultStatus(res) == PGRES_COMMAND_OK)
569  {
570  PQclear(res);
571  return retval;
572  }
573  else
574  {
575  PQclear(res);
576  return -1;
577  }
578 }
union PQArgBlock::@139 u
PGresult * PQfn(PGconn *conn, int fnid, int *result_buf, int *result_len, int result_is_int, const PQArgBlock *args, int nargs)
Definition: fe-exec.c:2556
static int fd(const char *x, int i)
Definition: preproc-init.c:105
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:2596
Oid fn_lo_tell
Definition: libpq-int.h:274
void PQclear(PGresult *res)
Definition: fe-exec.c:650
#define NULL
Definition: c.h:229
int isint
Definition: libpq-fe.h:223
PGlobjfuncs * lobjfuncs
Definition: libpq-int.h:427
int integer
Definition: libpq-fe.h:227
static int lo_initialize(PGconn *conn)
Definition: fe-lobj.c:877
pg_int64 lo_tell64 ( PGconn conn,
int  fd 
)

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

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

Referenced by pickout().

586 {
587  pg_int64 retval;
588  PQArgBlock argv[1];
589  PGresult *res;
590  int result_len;
591 
592  if (conn == NULL || conn->lobjfuncs == NULL)
593  {
594  if (lo_initialize(conn) < 0)
595  return -1;
596  }
597 
598  if (conn->lobjfuncs->fn_lo_tell64 == 0)
599  {
601  libpq_gettext("cannot determine OID of function lo_tell64\n"));
602  return -1;
603  }
604 
605  argv[0].isint = 1;
606  argv[0].len = 4;
607  argv[0].u.integer = fd;
608 
609  res = PQfn(conn, conn->lobjfuncs->fn_lo_tell64,
610  (void *) &retval, &result_len, 0, argv, 1);
611  if (PQresultStatus(res) == PGRES_COMMAND_OK && result_len == 8)
612  {
613  PQclear(res);
614  return lo_ntoh64(retval);
615  }
616  else
617  {
618  PQclear(res);
619  return -1;
620  }
621 }
union PQArgBlock::@139 u
void printfPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:234
PGresult * PQfn(PGconn *conn, int fnid, int *result_buf, int *result_len, int result_is_int, const PQArgBlock *args, int nargs)
Definition: fe-exec.c:2556
static int fd(const char *x, int i)
Definition: preproc-init.c:105
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:2596
PG_INT64_TYPE pg_int64
Definition: postgres_ext.h:47
Oid fn_lo_tell64
Definition: libpq-int.h:275
PQExpBufferData errorMessage
Definition: libpq-int.h:492
void PQclear(PGresult *res)
Definition: fe-exec.c:650
#define NULL
Definition: c.h:229
int isint
Definition: libpq-fe.h:223
PGlobjfuncs * lobjfuncs
Definition: libpq-int.h:427
#define libpq_gettext(x)
Definition: libpq-int.h:683
int integer
Definition: libpq-fe.h:227
static pg_int64 lo_ntoh64(pg_int64 net64)
Definition: fe-lobj.c:1087
static int lo_initialize(PGconn *conn)
Definition: fe-lobj.c:877
int lo_truncate ( PGconn conn,
int  fd,
size_t  len 
)

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

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

139 {
140  PQArgBlock argv[2];
141  PGresult *res;
142  int retval;
143  int result_len;
144 
145  if (conn == NULL || conn->lobjfuncs == NULL)
146  {
147  if (lo_initialize(conn) < 0)
148  return -1;
149  }
150 
151  /* Must check this on-the-fly because it's not there pre-8.3 */
152  if (conn->lobjfuncs->fn_lo_truncate == 0)
153  {
155  libpq_gettext("cannot determine OID of function lo_truncate\n"));
156  return -1;
157  }
158 
159  /*
160  * Long ago, somebody thought it'd be a good idea to declare this function
161  * as taking size_t ... but the underlying backend function only accepts a
162  * signed int32 length. So throw error if the given value overflows
163  * int32. (A possible alternative is to automatically redirect the call
164  * to lo_truncate64; but if the caller wanted to rely on that backend
165  * function being available, he could have called lo_truncate64 for
166  * himself.)
167  */
168  if (len > (size_t) INT_MAX)
169  {
171  libpq_gettext("argument of lo_truncate exceeds integer range\n"));
172  return -1;
173  }
174 
175  argv[0].isint = 1;
176  argv[0].len = 4;
177  argv[0].u.integer = fd;
178 
179  argv[1].isint = 1;
180  argv[1].len = 4;
181  argv[1].u.integer = (int) len;
182 
183  res = PQfn(conn, conn->lobjfuncs->fn_lo_truncate,
184  &retval, &result_len, 1, argv, 2);
185 
186  if (PQresultStatus(res) == PGRES_COMMAND_OK)
187  {
188  PQclear(res);
189  return retval;
190  }
191  else
192  {
193  PQclear(res);
194  return -1;
195  }
196 }
union PQArgBlock::@139 u
void printfPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:234
PGresult * PQfn(PGconn *conn, int fnid, int *result_buf, int *result_len, int result_is_int, const PQArgBlock *args, int nargs)
Definition: fe-exec.c:2556
static int fd(const char *x, int i)
Definition: preproc-init.c:105
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:2596
Oid fn_lo_truncate
Definition: libpq-int.h:276
PQExpBufferData errorMessage
Definition: libpq-int.h:492
void PQclear(PGresult *res)
Definition: fe-exec.c:650
#define NULL
Definition: c.h:229
int isint
Definition: libpq-fe.h:223
PGlobjfuncs * lobjfuncs
Definition: libpq-int.h:427
#define libpq_gettext(x)
Definition: libpq-int.h:683
int integer
Definition: libpq-fe.h:227
static int lo_initialize(PGconn *conn)
Definition: fe-lobj.c:877
int lo_truncate64 ( PGconn conn,
int  fd,
pg_int64  len 
)

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

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

Referenced by my_truncate().

207 {
208  PQArgBlock argv[2];
209  PGresult *res;
210  int retval;
211  int result_len;
212 
213  if (conn == NULL || conn->lobjfuncs == NULL)
214  {
215  if (lo_initialize(conn) < 0)
216  return -1;
217  }
218 
219  if (conn->lobjfuncs->fn_lo_truncate64 == 0)
220  {
222  libpq_gettext("cannot determine OID of function lo_truncate64\n"));
223  return -1;
224  }
225 
226  argv[0].isint = 1;
227  argv[0].len = 4;
228  argv[0].u.integer = fd;
229 
230  len = lo_hton64(len);
231  argv[1].isint = 0;
232  argv[1].len = 8;
233  argv[1].u.ptr = (int *) &len;
234 
235  res = PQfn(conn, conn->lobjfuncs->fn_lo_truncate64,
236  &retval, &result_len, 1, argv, 2);
237 
238  if (PQresultStatus(res) == PGRES_COMMAND_OK)
239  {
240  PQclear(res);
241  return retval;
242  }
243  else
244  {
245  PQclear(res);
246  return -1;
247  }
248 }
union PQArgBlock::@139 u
void printfPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:234
PGresult * PQfn(PGconn *conn, int fnid, int *result_buf, int *result_len, int result_is_int, const PQArgBlock *args, int nargs)
Definition: fe-exec.c:2556
static int fd(const char *x, int i)
Definition: preproc-init.c:105
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:2596
static pg_int64 lo_hton64(pg_int64 host64)
Definition: fe-lobj.c:1062
Oid fn_lo_truncate64
Definition: libpq-int.h:277
PQExpBufferData errorMessage
Definition: libpq-int.h:492
void PQclear(PGresult *res)
Definition: fe-exec.c:650
#define NULL
Definition: c.h:229
int isint
Definition: libpq-fe.h:223
PGlobjfuncs * lobjfuncs
Definition: libpq-int.h:427
int * ptr
Definition: libpq-fe.h:226
#define libpq_gettext(x)
Definition: libpq-int.h:683
int integer
Definition: libpq-fe.h:227
static int lo_initialize(PGconn *conn)
Definition: fe-lobj.c:877
int lo_unlink ( PGconn conn,
Oid  lobjId 
)

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

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

Referenced by do_lo_unlink(), and vacuumlo().

630 {
631  PQArgBlock argv[1];
632  PGresult *res;
633  int result_len;
634  int retval;
635 
636  if (conn == NULL || conn->lobjfuncs == NULL)
637  {
638  if (lo_initialize(conn) < 0)
639  return -1;
640  }
641 
642  argv[0].isint = 1;
643  argv[0].len = 4;
644  argv[0].u.integer = lobjId;
645 
646  res = PQfn(conn, conn->lobjfuncs->fn_lo_unlink,
647  &retval, &result_len, 1, argv, 1);
648  if (PQresultStatus(res) == PGRES_COMMAND_OK)
649  {
650  PQclear(res);
651  return retval;
652  }
653  else
654  {
655  PQclear(res);
656  return -1;
657  }
658 }
union PQArgBlock::@139 u
PGresult * PQfn(PGconn *conn, int fnid, int *result_buf, int *result_len, int result_is_int, const PQArgBlock *args, int nargs)
Definition: fe-exec.c:2556
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:2596
void PQclear(PGresult *res)
Definition: fe-exec.c:650
#define NULL
Definition: c.h:229
Oid fn_lo_unlink
Definition: libpq-int.h:271
int isint
Definition: libpq-fe.h:223
PGlobjfuncs * lobjfuncs
Definition: libpq-int.h:427
int integer
Definition: libpq-fe.h:227
static int lo_initialize(PGconn *conn)
Definition: fe-lobj.c:877
int lo_write ( PGconn conn,
int  fd,
const char *  buf,
size_t  len 
)

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

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

Referenced by lo_import_internal().

314 {
315  PQArgBlock argv[2];
316  PGresult *res;
317  int result_len;
318  int retval;
319 
320  if (conn == NULL || conn->lobjfuncs == NULL)
321  {
322  if (lo_initialize(conn) < 0)
323  return -1;
324  }
325 
326  /*
327  * Long ago, somebody thought it'd be a good idea to declare this function
328  * as taking size_t ... but the underlying backend function only accepts a
329  * signed int32 length. So throw error if the given value overflows
330  * int32.
331  */
332  if (len > (size_t) INT_MAX)
333  {
335  libpq_gettext("argument of lo_write exceeds integer range\n"));
336  return -1;
337  }
338 
339  argv[0].isint = 1;
340  argv[0].len = 4;
341  argv[0].u.integer = fd;
342 
343  argv[1].isint = 0;
344  argv[1].len = (int) len;
345  argv[1].u.ptr = (int *) buf;
346 
347  res = PQfn(conn, conn->lobjfuncs->fn_lo_write,
348  &retval, &result_len, 1, argv, 2);
349  if (PQresultStatus(res) == PGRES_COMMAND_OK)
350  {
351  PQclear(res);
352  return retval;
353  }
354  else
355  {
356  PQclear(res);
357  return -1;
358  }
359 }
union PQArgBlock::@139 u
void printfPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:234
Oid fn_lo_write
Definition: libpq-int.h:279
PGresult * PQfn(PGconn *conn, int fnid, int *result_buf, int *result_len, int result_is_int, const PQArgBlock *args, int nargs)
Definition: fe-exec.c:2556
static int fd(const char *x, int i)
Definition: preproc-init.c:105
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:2596
static char * buf
Definition: pg_test_fsync.c:66
PQExpBufferData errorMessage
Definition: libpq-int.h:492
void PQclear(PGresult *res)
Definition: fe-exec.c:650
#define NULL
Definition: c.h:229
int isint
Definition: libpq-fe.h:223
PGlobjfuncs * lobjfuncs
Definition: libpq-int.h:427
int * ptr
Definition: libpq-fe.h:226
#define libpq_gettext(x)
Definition: libpq-int.h:683
int integer
Definition: libpq-fe.h:227
static int lo_initialize(PGconn *conn)
Definition: fe-lobj.c:877
int pg_char_to_encoding ( const char *  name)

Definition at line 551 of file encnames.c.

References clean_encoding_name(), ereport, errcode(), errmsg(), ERROR, lengthof, NAMEDATALEN, NULL, pg_encname_tbl, and result.

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

552 {
553  unsigned int nel = lengthof(pg_encname_tbl);
554  const pg_encname *base = pg_encname_tbl,
555  *last = base + nel - 1,
556  *position;
557  int result;
558  char buff[NAMEDATALEN],
559  *key;
560 
561  if (name == NULL || *name == '\0')
562  return -1;
563 
564  if (strlen(name) >= NAMEDATALEN)
565  {
566 #ifdef FRONTEND
567  fprintf(stderr, "encoding name too long\n");
568  return -1;
569 #else
570  ereport(ERROR,
571  (errcode(ERRCODE_NAME_TOO_LONG),
572  errmsg("encoding name too long")));
573 #endif
574  }
575  key = clean_encoding_name(name, buff);
576 
577  while (last >= base)
578  {
579  position = base + ((last - base) >> 1);
580  result = key[0] - position->name[0];
581 
582  if (result == 0)
583  {
584  result = strcmp(key, position->name);
585  if (result == 0)
586  return position->encoding;
587  }
588  if (result < 0)
589  last = position - 1;
590  else
591  base = position + 1;
592  }
593  return -1;
594 }
int errcode(int sqlerrcode)
Definition: elog.c:575
return result
Definition: formatting.c:1632
#define lengthof(array)
Definition: c.h:562
#define NAMEDATALEN
#define ERROR
Definition: elog.h:43
static const pg_encname pg_encname_tbl[]
Definition: encnames.c:38
#define ereport(elevel, rest)
Definition: elog.h:122
#define NULL
Definition: c.h:229
const char * name
Definition: encode.c:521
int errmsg(const char *fmt,...)
Definition: elog.c:797
static char * clean_encoding_name(const char *key, char *newkey)
Definition: encnames.c:525
const char* pg_encoding_to_char ( int  encoding)
int pg_valid_server_encoding_id ( int  encoding)

Definition at line 515 of file encnames.c.

References PG_VALID_BE_ENCODING.

Referenced by setup_locale_encoding().

516 {
518 }
static char * encoding
Definition: initdb.c:122
#define PG_VALID_BE_ENCODING(_enc)
Definition: pg_wchar.h:293
int PQbackendPID ( const PGconn conn)

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

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

Referenced by get_prompt().

6015 {
6016  if (!conn || conn->status != CONNECTION_OK)
6017  return 0;
6018  return conn->be_pid;
6019 }
ConnStatusType status
Definition: libpq-int.h:378
int be_pid
Definition: libpq-int.h:420
int PQbinaryTuples ( const PGresult res)

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

References pg_result::binary.

Referenced by ProcessResult().

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

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

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

Referenced by dblink_cancel_query(), DisconnectDatabase(), handle_sigint(), pgfdw_subxact_callback(), pgfdw_xact_callback(), ShutdownWorkersHard(), sigTermHandler(), and try_complete_step().

3798 {
3799  if (!cancel)
3800  {
3801  strlcpy(errbuf, "PQcancel() -- no cancel object supplied", errbufsize);
3802  return FALSE;
3803  }
3804 
3805  return internal_cancel(&cancel->raddr, cancel->be_pid, cancel->be_key,
3806  errbuf, errbufsize);
3807 }
static int internal_cancel(SockAddr *raddr, int be_pid, int be_key, char *errbuf, int errbufsize)
Definition: fe-connect.c:3693
int be_pid
Definition: libpq-int.h:505
#define FALSE
Definition: c.h:221
int be_key
Definition: libpq-int.h:506
size_t strlcpy(char *dst, const char *src, size_t siz)
Definition: strlcpy.c:45
SockAddr raddr
Definition: libpq-int.h:504
void PQclear ( PGresult res)

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

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

Referenced by _check_database_version(), _doSetSessionAuth(), _doSetWithOids(), _selectOutputSchema(), _selectTablespace(), add_tablespace_footer(), BaseBackup(), binary_upgrade_set_pg_class_oids(), binary_upgrade_set_type_oids_by_rel_oid(), binary_upgrade_set_type_oids_by_type_oid(), buildMatViewRefreshDependencies(), buildShSecLabels(), check_for_isn_and_int8_passing_mismatch(), check_for_jsonb_9_4_usage(), check_for_pg_role_prefix(), check_for_prepared_transactions(), check_for_reg_data_type_usage(), check_is_install_user(), check_loadable_libraries(), check_proper_datallowconn(), ClearOrSaveResult(), close_cursor(), cluster_all_databases(), convertTSFunction(), create_cursor(), CreateReplicationSlot(), createViewAsClause(), dblink_close(), dblink_exec(), dblink_fetch(), dblink_open(), dblink_res_error(), deallocate_one(), describeAccessMethods(), describeAggregates(), describeFunctions(), describeOneTableDetails(), describeOneTSConfig(), describeOneTSParser(), describeOperators(), describePublications(), describeRoles(), describeSubscriptions(), describeTableDetails(), describeTablespaces(), describeTypes(), descriptor_free(), discard_response(), do_lo_import(), do_lo_list(), do_sql_command(), doCustom(), dropDBs(), DropReplicationSlot(), dropRoles(), dropTablespaces(), dumpAgg(), dumpBaseType(), dumpBlobs(), dumpCollation(), dumpCompositeType(), dumpCompositeTypeColComments(), dumpConversion(), dumpCreateDB(), dumpDatabase(), dumpDatabaseConfig(), dumpDatabases(), dumpDbRoleConfig(), dumpDomain(), dumpEnumType(), dumpFunc(), dumpGroups(), dumpOpclass(), dumpOpfamily(), dumpOpr(), dumpRangeType(), dumpRoleMembership(), dumpRoles(), dumpRule(), dumpSequence(), dumpSequenceData(), dumpTable(), dumpTableData_copy(), dumpTableData_insert(), dumpTableSchema(), dumpTablespaces(), dumpTSConfig(), dumpTSDictionary(), dumpUserConfig(), dumpUserMappings(), ecpg_autostart_transaction(), ecpg_check_PQresult(), ecpg_is_type_an_array(), ecpg_process_output(), ECPGdescribe(), ECPGsetcommit(), ECPGtrans(), EndDBCopyMode(), exec_command_password(), ExecQueryUsingCursor(), executeCommand(), executeMaintenanceCommand(), executeQueryOrDie(), ExecuteSqlCommand(), ExecuteSqlStatement(), executeStatement(), expand_schema_name_patterns(), expand_table_name_patterns(), fail_lo_xact(), fetch_more_data(), findLastBuiltinOid_V71(), finish_lo_xact(), get_create_object_cmd(), get_db_infos(), get_language_name(), get_loadable_libraries(), get_rel_infos(), get_remote_estimate(), get_returning_data(), get_synchronized_snapshot(), get_tablespace_paths(), getAccessMethods(), getAggregates(), getBlobs(), getCasts(), getCollations(), getConstraints(), getConversions(), getCopyStart(), getDefaultACLs(), getDependencies(), getDomainConstraints(), getEventTriggers(), getExtendedStatistics(), getExtensionMembership(), getExtensions(), getForeignDataWrappers(), getForeignServers(), getFormattedTypeName(), getFuncs(), getIndexes(), getInherits(), getNamespaces(), getOpclasses(), getOperators(), getOpfamilies(), getParamDescriptions(), getPolicies(), getProcLangs(), getPublications(), getPublicationTables(), GetQueryResult(), getRowDescriptions(), getRules(), getSubscriptions(), getTableAttrs(), getTables(), getTransforms(), getTriggers(), getTSConfigurations(), getTSDictionaries(), getTSParsers(), getTSTemplates(), getTypes(), handleCopyIn(), HandleEndOfCopyStream(), init(), libpq_executeFileMap(), libpqConnect(), libpqGetFile(), libpqProcessFileList(), libpqrcv_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(), listPublications(), listSchemas(), listTables(), listTSConfigs(), listTSConfigsVerbose(), listTSDictionaries(), listTSParsers(), listTSParsersVerbose(), listTSTemplates(), listUserMappings(), lo_close(), lo_creat(), lo_create(), lo_initialize(), lo_lseek(), lo_lseek64(), lo_open(), lo_read(), lo_tell(), lo_tell64(), lo_truncate(), lo_truncate64(), lo_unlink(), lo_write(), lockTableForWorker(), lookup_object_oid(), main(), materializeQueryResult(), materializeResult(), new_9_0_populate_pg_largeobject_metadata(), objectDescription(), old_9_3_check_for_line_data_type_usage(), old_9_6_check_for_unknown_data_type_usage(), old_9_6_invalidate_hash_indexes(), permissionsList(), pg_attribute_noreturn(), pgfdw_get_result(), pgfdw_report_error(), pgfdw_subxact_callback(), pgfdw_xact_callback(), postgresAcquireSampleRowsFunc(), postgresAnalyzeForeignTable(), postgresEndDirectModify(), postgresEndForeignModify(), postgresExecForeignDelete(), postgresExecForeignInsert(), postgresExecForeignUpdate(), postgresImportForeignSchema(), postgresReScanForeignScan(), pqClearAsyncResult(), PQconnectPoll(), PQcopyResult(), PQencryptPasswordConn(), pqEndcopy2(), pqEndcopy3(), PQexecFinish(), PQexecStart(), pqGetErrorNotice2(), pqGetErrorNotice3(), pqInternalNotice(), PQmakeEmptyPGresult(), pqRowProcessor(), PQsetClientEncoding(), pqSetenvPoll(), prepare_common(), prepare_foreign_modify(), processExtensionTables(), ProcessResult(), PSQLexecWatch(), receiveFileChunks(), ReceiveXlogStream(), reindex_all_databases(), run_permutation(), run_simple_query(), RunIdentifySystem(), sendCommand(), SendQuery(), set_frozenxids(), sql_exec(), start_lo_xact(), store_returning_result(), storeQueryResult(), StreamLogicalLog(), try_complete_step(), tryExecuteStatement(), vacuum_all_databases(), vacuum_one_database(), and vacuumlo().

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

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

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

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

6049 {
6050  if (!conn || conn->status != CONNECTION_OK)
6051  return -1;
6052  return conn->client_encoding;
6053 }
ConnStatusType status
Definition: libpq-int.h:378
int client_encoding
Definition: libpq-int.h:423
char* PQcmdStatus ( PGresult res)

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

References pg_result::cmdStatus, and NULL.

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

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

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

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

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

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

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

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

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

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

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

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

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

523 {
524  PGconn *conn = PQconnectStart(conninfo);
525 
526  if (conn && conn->status != CONNECTION_BAD)
527  (void) connectDBComplete(conn);
528 
529  return conn;
530 }
PGconn * conn
Definition: streamutil.c:42
static int connectDBComplete(PGconn *conn)
Definition: fe-connect.c:1719
PGconn * PQconnectStart(const char *conninfo)
Definition: fe-connect.c:648
ConnStatusType status
Definition: libpq-int.h:378
PGconn* PQconnectdbParams ( const char *const *  keywords,
const char *const *  values,
int  expand_dbname 
)

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

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

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

469 {
470  PGconn *conn = PQconnectStartParams(keywords, values, expand_dbname);
471 
472  if (conn && conn->status != CONNECTION_BAD)
473  (void) connectDBComplete(conn);
474 
475  return conn;
476 
477 }
PGconn * conn
Definition: streamutil.c:42
static int connectDBComplete(PGconn *conn)
Definition: fe-connect.c:1719
ConnStatusType status
Definition: libpq-int.h:378
static Datum values[MAXATTR]
Definition: bootstrap.c:163
PGconn * PQconnectStartParams(const char *const *keywords, const char *const *values, int expand_dbname)
Definition: fe-connect.c:569
int PQconnectionNeedsPassword ( const PGconn conn)

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

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

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

6023 {
6024  char *password;
6025 
6026  if (!conn)
6027  return false;
6028  password = PQpass(conn);
6029  if (conn->password_needed &&
6030  (password == NULL || password[0] == '\0'))
6031  return true;
6032  else
6033  return false;
6034 }
static char password[100]
Definition: streamutil.c:41
bool password_needed
Definition: libpq-int.h:408
char * PQpass(const PGconn *conn)
Definition: fe-connect.c:5872
#define NULL
Definition: c.h:229
int PQconnectionUsedPassword ( const PGconn conn)

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

References pg_conn::password_needed.

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

6038 {
6039  if (!conn)
6040  return false;
6041  if (conn->password_needed)
6042  return true;
6043  else
6044  return false;
6045 }
bool password_needed
Definition: libpq-int.h:408
PostgresPollingStatusType PQconnectPoll ( PGconn conn)

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

References SockAddr::addr, pg_conn::addr_cur, pg_conn_host::addrlist, addrinfo::ai_addr, addrinfo::ai_addrlen, addrinfo::ai_family, addrinfo::ai_next, appendPQExpBuffer(), appendPQExpBufferChar(), appendPQExpBufferStr(), pg_conn::appname, pg_conn::asyncStatus, AUTH_REQ_MD5, AUTH_REQ_OK, pg_conn::auth_req_received, connect, connectFailureMessage(), CONNECTION_AUTH_OK, CONNECTION_AWAITING_RESPONSE, CONNECTION_BAD, CONNECTION_CHECK_WRITABLE, CONNECTION_CONSUME, CONNECTION_MADE, CONNECTION_NEEDED, CONNECTION_OK, CONNECTION_SETENV, CONNECTION_SSL_STARTUP, CONNECTION_STARTED, connectNoDelay(), pg_conn::connhost, PQExpBufferData::data, EINPROGRESS, EINTR, EnvironmentOptions, ERRCODE_APPNAME_UNKNOWN, pg_conn::errorMessage, EWOULDBLOCK, pg_conn::fbappname, free, getpeereid(), pg_conn_host::host, pg_conn::inCursor, pg_conn::inEnd, pg_conn::inStart, IS_AF_UNIX, pg_conn::laddr, PQExpBufferData::len, libpq_gettext, pg_conn::nconnhost, NEGOTIATE_SSL_CODE, pg_conn::next_eo, NULL, PG_DIAG_SQLSTATE, pg_fe_sendauth(), PG_PROTOCOL, PG_PROTOCOL_MAJOR, pg_set_noblock(), PGASYNC_BUSY, PGINVALID_SOCKET, pgpassfileWarning(), PGRES_FATAL_ERROR, PGRES_POLLING_FAILED, PGRES_POLLING_OK, PGRES_POLLING_READING, PGRES_POLLING_WRITING, PGRES_TUPLES_OK, pg_conn_host::port, pqBuildStartupPacket2(), pqBuildStartupPacket3(), pqCheckInBufferSpace(), PQclear(), PQconsumeInput(), pqDropConnection(), pqFlush(), pqGetc(), pqGetErrorNotice3(), pqGetInt(), pqGetpwuid(), PQgetResult(), pqGets_append(), PQgetvalue(), PQisBusy(), PQntuples(), pqPacketSend(), pqReadData(), PQresultErrorField(), PQresultStatus(), pqsecure_initialize(), pqsecure_open_client(), PQsendQuery(), pqSetenvPoll(), pqStrerror(), printfPQExpBuffer(), pg_conn::pversion, pg_conn::raddr, release_all_addrinfo(), pg_conn::requirepeer, restoreErrorMessage(), pg_result::resultStatus, SockAddr::salen, saveErrorMessage(), pg_conn::send_appname, sendTerminateConn(), pg_conn::setenv_state, SETENV_STATE_CLIENT_ENCODING_SEND, setKeepalivesCount(), setKeepalivesIdle(), setKeepalivesInterval(), pg_conn::sigpipe_flag, pg_conn::sigpipe_so, pg_conn::sock, SOCK_ERRNO, SOCK_STRERROR, socket, pg_conn::sslmode, pg_conn::status, STATUS_OK, pg_conn::target_session_attrs, termPQExpBuffer(), useKeepalives(), val, and pg_conn::whichhost.

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

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

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

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

Referenced by PQconnectdb(), and PQping().

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

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

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

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

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

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

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

Referenced by exec_command_conninfo(), GenerateRecoveryConf(), and libpqrcv_get_conninfo().

5798 {
5799  PQExpBufferData errorBuf;
5800  PQconninfoOption *connOptions;
5801 
5802  if (conn == NULL)
5803  return NULL;
5804 
5805  /* We don't actually report any errors here, but callees want a buffer */
5806  initPQExpBuffer(&errorBuf);
5807  if (PQExpBufferDataBroken(errorBuf))
5808  return NULL; /* out of memory already :-( */
5809 
5810  connOptions = conninfo_init(&errorBuf);
5811 
5812  if (connOptions != NULL)
5813  {
5815 
5816  for (option = PQconninfoOptions; option->keyword; option++)
5817  {
5818  char **connmember;
5819 
5820  if (option->connofs < 0)
5821  continue;
5822 
5823  connmember = (char **) ((char *) conn + option->connofs);
5824 
5825  if (*connmember)
5826  conninfo_storeval(connOptions, option->keyword, *connmember,
5827  &errorBuf, true, false);
5828  }
5829  }
5830 
5831  termPQExpBuffer(&errorBuf);
5832 
5833  return connOptions;
5834 }
static PQconninfoOption * conninfo_storeval(PQconninfoOption *connOptions, const char *keyword, const char *value, PQExpBuffer errorMessage, bool ignoreMissing, bool uri_decode)
Definition: fe-connect.c:5714
void termPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:128
static PQconninfoOption * conninfo_init(PQExpBuffer errorMessage)
Definition: fe-connect.c:4630
static const internalPQconninfoOption PQconninfoOptions[]
Definition: fe-connect.c:162
#define PQExpBufferDataBroken(buf)
Definition: pqexpbuffer.h:67
#define NULL
Definition: c.h:229
void initPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:89
void PQconninfoFree ( PQconninfoOption connOptions)

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

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

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

5839 {
5841 
5842  if (connOptions == NULL)
5843  return;
5844 
5845  for (option = connOptions; option->keyword != NULL; option++)
5846  {
5847  if (option->val != NULL)
5848  free(option->val);
5849  }
5850  free(connOptions);
5851 }
#define free(a)
Definition: header.h:65
#define NULL
Definition: c.h:229
PQconninfoOption* PQconninfoParse ( const char *  conninfo,
char **  errmsg 
)

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

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

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

4609 {
4610  PQExpBufferData errorBuf;
4611  PQconninfoOption *connOptions;
4612 
4613  if (errmsg)
4614  *errmsg = NULL; /* default */
4615  initPQExpBuffer(&errorBuf);
4616  if (PQExpBufferDataBroken(errorBuf))
4617  return NULL; /* out of memory already :-( */
4618  connOptions = parse_connection_string(conninfo, &errorBuf, false);
4619  if (connOptions == NULL && errmsg)
4620  *errmsg = errorBuf.data;
4621  else
4622  termPQExpBuffer(&errorBuf);
4623  return connOptions;
4624 }
void termPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:128
static PQconninfoOption * parse_connection_string(const char *conninfo, PQExpBuffer errorMessage, bool use_defaults)
Definition: fe-connect.c:4670
#define PQExpBufferDataBroken(buf)
Definition: pqexpbuffer.h:67
#define NULL
Definition: c.h:229
int errmsg(const char *fmt,...)
Definition: elog.c:797
void initPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:89
int PQconsumeInput ( PGconn conn)

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

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

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

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

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

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

Referenced by pqRowProcessor().

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

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

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

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

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

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

Referenced by ECPGdescribe().

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

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

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

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

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

References pg_encoding_dsplen().

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

1193 {
1194  return pg_encoding_dsplen(encoding, s);
1195 }
int pg_encoding_dsplen(int encoding, const char *mbstr)
Definition: wchar.c:1796
static char * encoding
Definition: initdb.c:122
char* PQencryptPassword ( const char *  passwd,
const char *  user 
)

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

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

1089 {
1090  char *crypt_pwd;
1091 
1092  crypt_pwd = malloc(MD5_PASSWD_LEN + 1);
1093  if (!crypt_pwd)
1094  return NULL;
1095 
1096  if (!pg_md5_encrypt(passwd, user, strlen(user), crypt_pwd))
1097  {
1098  free(crypt_pwd);
1099  return NULL;
1100  }
1101 
1102  return crypt_pwd;
1103 }
#define malloc(a)
Definition: header.h:50
bool pg_md5_encrypt(const char *passwd, const char *salt, size_t salt_len, char *buf)
Definition: md5.c:323
#define MD5_PASSWD_LEN
Definition: md5.h:19
#define free(a)
Definition: header.h:65
#define NULL
Definition: c.h:229
static char * user
Definition: pg_regress.c:92
char* PQencryptPasswordConn ( PGconn conn,
const char *  passwd,
const char *  user,
const char *  algorithm 
)

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

References pg_conn::errorMessage, free, libpq_gettext, malloc, MAX_ALGORITHM_NAME_LEN, MD5_PASSWD_LEN, NULL, pg_fe_scram_build_verifier(), pg_md5_encrypt(), PGRES_TUPLES_OK, PQclear(), PQexec(), PQgetvalue(), PQnfields(), PQntuples(), PQresultStatus(), printfPQExpBuffer(), and val.

Referenced by exec_command_password(), and main().

1132 {
1133 #define MAX_ALGORITHM_NAME_LEN 50
1134  char algobuf[MAX_ALGORITHM_NAME_LEN + 1];
1135  char *crypt_pwd = NULL;
1136 
1137  if (!conn)
1138  return NULL;
1139 
1140  /* If no algorithm was given, ask the server. */
1141  if (algorithm == NULL)
1142  {
1143  PGresult *res;
1144  char *val;
1145 
1146  res = PQexec(conn, "show password_encryption");
1147  if (res == NULL)
1148  {
1149  /* PQexec() should've set conn->errorMessage already */
1150  return NULL;
1151  }
1152  if (PQresultStatus(res) != PGRES_TUPLES_OK)
1153  {
1154  /* PQexec() should've set conn->errorMessage already */
1155  PQclear(res);
1156  return NULL;
1157  }
1158  if (PQntuples(res) != 1 || PQnfields(res) != 1)
1159  {
1160  PQclear(res);
1162  libpq_gettext("unexpected shape of result set returned for SHOW\n"));
1163  return NULL;
1164  }
1165  val = PQgetvalue(res, 0, 0);
1166 
1167  if (strlen(val) > MAX_ALGORITHM_NAME_LEN)
1168  {
1169  PQclear(res);
1171  libpq_gettext("password_encryption value too long\n"));
1172  return NULL;
1173  }
1174  strcpy(algobuf, val);
1175  PQclear(res);
1176 
1177  algorithm = algobuf;
1178  }
1179 
1180  /*
1181  * Also accept "on" and "off" as aliases for "md5", because
1182  * password_encryption was a boolean before PostgreSQL 10. We refuse to
1183  * send the password in plaintext even if it was "off".
1184  */
1185  if (strcmp(algorithm, "on") == 0 ||
1186  strcmp(algorithm, "off") == 0)
1187  algorithm = "md5";
1188 
1189  /*
1190  * Ok, now we know what algorithm to use
1191  */
1192  if (strcmp(algorithm, "scram-sha-256") == 0)
1193  {
1194  crypt_pwd = pg_fe_scram_build_verifier(passwd);
1195  }
1196  else if (strcmp(algorithm, "md5") == 0)
1197  {
1198  crypt_pwd = malloc(MD5_PASSWD_LEN + 1);
1199  if (crypt_pwd)
1200  {
1201  if (!pg_md5_encrypt(passwd, user, strlen(user), crypt_pwd))
1202  {
1203  free(crypt_pwd);
1204  crypt_pwd = NULL;
1205  }
1206  }
1207  }
1208  else
1209  {
1211  libpq_gettext("unknown password encryption algorithm\n"));
1212  return NULL;
1213  }
1214 
1215  if (!crypt_pwd)
1217  libpq_gettext("out of memory\n"));
1218 
1219  return crypt_pwd;
1220 }
int PQnfields(const PGresult *res)
Definition: fe-exec.c:2681
void printfPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:234
char * PQgetvalue(const PGresult *res, int tup_num, int field_num)
Definition: fe-exec.c:3067
int PQntuples(const PGresult *res)
Definition: fe-exec.c:2673
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:2596
#define malloc(a)
Definition: header.h:50
#define MAX_ALGORITHM_NAME_LEN
bool pg_md5_encrypt(const char *passwd, const char *salt, size_t salt_len, char *buf)
Definition: md5.c:323
PQExpBufferData errorMessage
Definition: libpq-int.h:492
void PQclear(PGresult *res)
Definition: fe-exec.c:650
#define MD5_PASSWD_LEN
Definition: md5.h:19
#define free(a)
Definition: header.h:65
#define NULL
Definition: c.h:229
char * pg_fe_scram_build_verifier(const char *password)
static char * user
Definition: pg_regress.c:92
PGresult * PQexec(PGconn *conn, const char *query)
Definition: fe-exec.c:1846
long val
Definition: informix.c:689
#define libpq_gettext(x)
Definition: libpq-int.h:683
int PQendcopy ( PGconn conn)

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

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

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

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

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

References encoding, pg_char_to_encoding(), and PG_SQL_ASCII.

Referenced by main().

1202 {
1203  char *str;
1204  int encoding = PG_SQL_ASCII;
1205 
1206  str = getenv("PGCLIENTENCODING");
1207  if (str && *str != '\0')
1208  {
1209  encoding = pg_char_to_encoding(str);
1210  if (encoding < 0)
1211  encoding = PG_SQL_ASCII;
1212  }
1213  return encoding;
1214 }
int pg_char_to_encoding(const char *name)
Definition: encnames.c:551
static char * encoding
Definition: initdb.c:122
char* PQerrorMessage ( const PGconn conn)

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

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

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

5989 {
5990  if (!conn)
5991  return libpq_gettext("connection pointer is NULL\n");
5992 
5993  return conn->errorMessage.data;
5994 }
PQExpBufferData errorMessage
Definition: libpq-int.h:492
#define libpq_gettext(x)
Definition: libpq-int.h:683
unsigned char* PQescapeBytea ( const unsigned char *  from,
size_t  from_length,
size_t *  to_length 
)

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

References NULL, PQescapeByteaInternal(), and static_std_strings.

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

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

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

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

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

References PQescapeInternal().

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

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

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

References PQescapeInternal().

Referenced by libpqrcv_startstreaming(), and psql_get_variable().

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

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

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

Referenced by get_comma_elts(), and quote_postgres().

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Referenced by ecpg_execute(), and try_complete_step().

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

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

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

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

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

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

References closePGconn(), and freePGconn().

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

3522 {
3523  if (conn)
3524  {
3525  closePGconn(conn);
3526  freePGconn(conn);
3527  }
3528 }
static void closePGconn(PGconn *conn)
Definition: fe-connect.c:3431
static void freePGconn(PGconn *conn)
Definition: fe-connect.c:3259
int PQflush ( PGconn conn)

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

References pqFlush().

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

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

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

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

Referenced by ECPGget_desc().

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

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

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

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

2563 {
2564  *result_len = 0;
2565 
2566  if (!conn)
2567  return NULL;
2568 
2569  /* clear the error string */
2571 
2572  if (conn->sock == PGINVALID_SOCKET || conn->asyncStatus != PGASYNC_IDLE ||
2573  conn->result != NULL)
2574  {
2576  libpq_gettext("connection in wrong state\n"));
2577  return NULL;
2578  }
2579 
2580  if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
2581  return pqFunctionCall3(conn, fnid,
2582  result_buf, result_len,
2583