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, 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:2607
static int fd(const char *x, int i)
Definition: preproc-init.c:105
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:2647
void PQclear(PGresult *res)
Definition: fe-exec.c:671
Oid fn_lo_close
Definition: libpq-int.h:268
int isint
Definition: libpq-fe.h:223
PGlobjfuncs * lobjfuncs
Definition: libpq-int.h:426
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, 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:2607
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:2647
#define InvalidOid
Definition: postgres_ext.h:36
void PQclear(PGresult *res)
Definition: fe-exec.c:671
Oid fn_lo_creat
Definition: libpq-int.h:269
int isint
Definition: libpq-fe.h:223
PGlobjfuncs * lobjfuncs
Definition: libpq-int.h:426
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, 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:2607
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:2647
PQExpBufferData errorMessage
Definition: libpq-int.h:491
#define InvalidOid
Definition: postgres_ext.h:36
void PQclear(PGresult *res)
Definition: fe-exec.c:671
int isint
Definition: libpq-fe.h:223
PGlobjfuncs * lobjfuncs
Definition: libpq-int.h:426
#define libpq_gettext(x)
Definition: libpq-int.h:682
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(), 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
static int fd(const char *x, int i)
Definition: preproc-init.c:105
#define PG_BINARY
Definition: c.h:1027
#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:67
int lo_open(PGconn *conn, Oid lobjId, int mode)
Definition: fe-lobj.c:58
PQExpBufferData errorMessage
Definition: libpq-int.h:491
#define LO_BUFSIZE
Definition: fe-lobj.c:43
static char * filename
Definition: pg_dumpall.c:90
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:682
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:90
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:90
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, 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:2607
static int fd(const char *x, int i)
Definition: preproc-init.c:105
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:2647
void PQclear(PGresult *res)
Definition: fe-exec.c:671
int isint
Definition: libpq-fe.h:223
PGlobjfuncs * lobjfuncs
Definition: libpq-int.h:426
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, 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:2607
static int fd(const char *x, int i)
Definition: preproc-init.c:105
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:2647
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:491
void PQclear(PGresult *res)
Definition: fe-exec.c:671
Oid fn_lo_lseek64
Definition: libpq-int.h:273
int isint
Definition: libpq-fe.h:223
PGlobjfuncs * lobjfuncs
Definition: libpq-int.h:426
int * ptr
Definition: libpq-fe.h:226
#define libpq_gettext(x)
Definition: libpq-int.h:682
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, 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:2607
static int fd(const char *x, int i)
Definition: preproc-init.c:105
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:2647
Oid fn_lo_open
Definition: libpq-int.h:267
void PQclear(PGresult *res)
Definition: fe-exec.c:671
int isint
Definition: libpq-fe.h:223
PGlobjfuncs * lobjfuncs
Definition: libpq-int.h:426
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, 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:2607
static int fd(const char *x, int i)
Definition: preproc-init.c:105
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:2647
Oid fn_lo_read
Definition: libpq-int.h:278
static char * buf
Definition: pg_test_fsync.c:67
PQExpBufferData errorMessage
Definition: libpq-int.h:491
void PQclear(PGresult *res)
Definition: fe-exec.c:671
int isint
Definition: libpq-fe.h:223
PGlobjfuncs * lobjfuncs
Definition: libpq-int.h:426
#define libpq_gettext(x)
Definition: libpq-int.h:682
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, 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:2607
static int fd(const char *x, int i)
Definition: preproc-init.c:105
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:2647
Oid fn_lo_tell
Definition: libpq-int.h:274
void PQclear(PGresult *res)
Definition: fe-exec.c:671
int isint
Definition: libpq-fe.h:223
PGlobjfuncs * lobjfuncs
Definition: libpq-int.h:426
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, 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:2607
static int fd(const char *x, int i)
Definition: preproc-init.c:105
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:2647
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:491
void PQclear(PGresult *res)
Definition: fe-exec.c:671
int isint
Definition: libpq-fe.h:223
PGlobjfuncs * lobjfuncs
Definition: libpq-int.h:426
#define libpq_gettext(x)
Definition: libpq-int.h:682
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, 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:2607
static int fd(const char *x, int i)
Definition: preproc-init.c:105
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:2647
Oid fn_lo_truncate
Definition: libpq-int.h:276
PQExpBufferData errorMessage
Definition: libpq-int.h:491
void PQclear(PGresult *res)
Definition: fe-exec.c:671
int isint
Definition: libpq-fe.h:223
PGlobjfuncs * lobjfuncs
Definition: libpq-int.h:426
#define libpq_gettext(x)
Definition: libpq-int.h:682
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, 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:2607
static int fd(const char *x, int i)
Definition: preproc-init.c:105
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:2647
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:491
void PQclear(PGresult *res)
Definition: fe-exec.c:671
int isint
Definition: libpq-fe.h:223
PGlobjfuncs * lobjfuncs
Definition: libpq-int.h:426
int * ptr
Definition: libpq-fe.h:226
#define libpq_gettext(x)
Definition: libpq-int.h:682
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, 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:2607
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:2647
void PQclear(PGresult *res)
Definition: fe-exec.c:671
Oid fn_lo_unlink
Definition: libpq-int.h:271
int isint
Definition: libpq-fe.h:223
PGlobjfuncs * lobjfuncs
Definition: libpq-int.h:426
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, 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:2607
static int fd(const char *x, int i)
Definition: preproc-init.c:105
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:2647
static char * buf
Definition: pg_test_fsync.c:67
PQExpBufferData errorMessage
Definition: libpq-int.h:491
void PQclear(PGresult *res)
Definition: fe-exec.c:671
int isint
Definition: libpq-fe.h:223
PGlobjfuncs * lobjfuncs
Definition: libpq-int.h:426
int * ptr
Definition: libpq-fe.h:226
#define libpq_gettext(x)
Definition: libpq-int.h:682
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, and pg_encname_tbl.

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

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
#define lengthof(array)
Definition: c.h:556
#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
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:123
#define PG_VALID_BE_ENCODING(_enc)
Definition: pg_wchar.h:295
int PQbackendPID ( const PGconn conn)

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

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

Referenced by get_prompt(), and LogStreamerMain().

6124 {
6125  if (!conn || conn->status != CONNECTION_OK)
6126  return 0;
6127  return conn->be_pid;
6128 }
ConnStatusType status
Definition: libpq-int.h:379
int be_pid
Definition: libpq-int.h:419
int PQbinaryTuples ( const PGresult res)

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

References pg_result::binary.

Referenced by ProcessResult().

2741 {
2742  if (!res)
2743  return 0;
2744  return res->binary;
2745 }
int binary
Definition: libpq-int.h:179
int PQcancel ( PGcancel cancel,
char *  errbuf,
int  errbufsize 
)

Definition at line 3906 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_cancel_query(), ShutdownWorkersHard(), sigTermHandler(), and try_complete_step().

3907 {
3908  if (!cancel)
3909  {
3910  strlcpy(errbuf, "PQcancel() -- no cancel object supplied", errbufsize);
3911  return FALSE;
3912  }
3913 
3914  return internal_cancel(&cancel->raddr, cancel->be_pid, cancel->be_key,
3915  errbuf, errbufsize);
3916 }
static int internal_cancel(SockAddr *raddr, int be_pid, int be_key, char *errbuf, int errbufsize)
Definition: fe-connect.c:3802
int be_pid
Definition: libpq-int.h:504
#define FALSE
Definition: c.h:219
int be_key
Definition: libpq-int.h:505
size_t strlcpy(char *dst, const char *src, size_t siz)
Definition: strlcpy.c:45
SockAddr raddr
Definition: libpq-int.h:503
void PQclear ( PGresult res)

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

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

Referenced by _check_database_version(), _doSetSessionAuth(), _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(), DescribeQuery(), 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_cancel_query(), pgfdw_exec_cleanup_query(), pgfdw_get_cleanup_result(), pgfdw_get_result(), pgfdw_report_error(), 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(), RetrieveWalSegSize(), 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().

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

Definition at line 6157 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().

6158 {
6159  if (!conn || conn->status != CONNECTION_OK)
6160  return -1;
6161  return conn->client_encoding;
6162 }
ConnStatusType status
Definition: libpq-int.h:379
int client_encoding
Definition: libpq-int.h:422
char* PQcmdStatus ( PGresult res)

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

References pg_result::cmdStatus.

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

2996 {
2997  if (!res)
2998  return NULL;
2999  return res->cmdStatus;
3000 }
char cmdStatus[CMDSTATUS_LEN]
Definition: libpq-int.h:178
char* PQcmdTuples ( PGresult res)

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

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

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

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

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

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

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

1225 {
1226  PQExpBufferData errorBuf;
1227  PQconninfoOption *connOptions;
1228 
1229  /* We don't actually report any errors here, but callees want a buffer */
1230  initPQExpBuffer(&errorBuf);
1231  if (PQExpBufferDataBroken(errorBuf))
1232  return NULL; /* out of memory already :-( */
1233 
1234  connOptions = conninfo_init(&errorBuf);
1235  if (connOptions != NULL)
1236  {
1237  /* pass NULL errorBuf to ignore errors */
1238  if (!conninfo_add_defaults(connOptions, NULL))
1239  {
1240  PQconninfoFree(connOptions);
1241  connOptions = NULL;
1242  }
1243  }
1244 
1245  termPQExpBuffer(&errorBuf);
1246  return connOptions;
1247 }
void termPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:128
static PQconninfoOption * conninfo_init(PQExpBuffer errorMessage)
Definition: fe-connect.c:4739
void PQconninfoFree(PQconninfoOption *connOptions)
Definition: fe-connect.c:5947
#define PQExpBufferDataBroken(buf)
Definition: pqexpbuffer.h:67
static bool conninfo_add_defaults(PQconninfoOption *options, PQExpBuffer errorMessage)
Definition: fe-connect.c:5175
void initPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:89
PGconn* PQconnectdb ( const char *  conninfo)

Definition at line 585 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().

586 {
587  PGconn *conn = PQconnectStart(conninfo);
588 
589  if (conn && conn->status != CONNECTION_BAD)
590  (void) connectDBComplete(conn);
591 
592  return conn;
593 }
PGconn * conn
Definition: streamutil.c:49
static int connectDBComplete(PGconn *conn)
Definition: fe-connect.c:1835
PGconn * PQconnectStart(const char *conninfo)
Definition: fe-connect.c:711
ConnStatusType status
Definition: libpq-int.h:379
PGconn* PQconnectdbParams ( const char *const *  keywords,
const char *const *  values,
int  expand_dbname 
)

Definition at line 529 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().

532 {
533  PGconn *conn = PQconnectStartParams(keywords, values, expand_dbname);
534 
535  if (conn && conn->status != CONNECTION_BAD)
536  (void) connectDBComplete(conn);
537 
538  return conn;
539 
540 }
PGconn * conn
Definition: streamutil.c:49
static int connectDBComplete(PGconn *conn)
Definition: fe-connect.c:1835
ConnStatusType status
Definition: libpq-int.h:379
static Datum values[MAXATTR]
Definition: bootstrap.c:164
PGconn * PQconnectStartParams(const char *const *keywords, const char *const *values, int expand_dbname)
Definition: fe-connect.c:632
int PQconnectionNeedsPassword ( const PGconn conn)

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

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

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

6132 {
6133  char *password;
6134 
6135  if (!conn)
6136  return false;
6137  password = PQpass(conn);
6138  if (conn->password_needed &&
6139  (password == NULL || password[0] == '\0'))
6140  return true;
6141  else
6142  return false;
6143 }
static char password[100]
Definition: streamutil.c:48
bool password_needed
Definition: libpq-int.h:407
char * PQpass(const PGconn *conn)
Definition: fe-connect.c:5981
int PQconnectionUsedPassword ( const PGconn conn)

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

References pg_conn::password_needed.

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

6147 {
6148  if (!conn)
6149  return false;
6150  if (conn->password_needed)
6151  return true;
6152  else
6153  return false;
6154 }
bool password_needed
Definition: libpq-int.h:407
PostgresPollingStatusType PQconnectPoll ( PGconn conn)

Definition at line 1997 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, CHT_HOST_ADDRESS, 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_host::hostaddr, 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, 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(), pg_conn_host::type, useKeepalives(), val, and pg_conn::whichhost.

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

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

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

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

Referenced by PQconnectdb(), and PQping().

712 {
713  PGconn *conn;
714 
715  /*
716  * Allocate memory for the conn structure
717  */
718  conn = makeEmptyPGconn();
719  if (conn == NULL)
720  return NULL;
721 
722  /*
723  * Parse the conninfo string
724  */
725  if (!connectOptions1(conn, conninfo))
726  return conn;
727 
728  /*
729  * Compute derived options
730  */
731  if (!connectOptions2(conn))
732  return conn;
733 
734  /*
735  * Connect to the database
736  */
737  if (!connectDBStart(conn))
738  {
739  /* Just in case we failed to set it in connectDBStart */
740  conn->status = CONNECTION_BAD;
741  }
742 
743  return conn;
744 }
static bool connectOptions1(PGconn *conn, const char *conninfo)
Definition: fe-connect.c:797
PGconn * conn
Definition: streamutil.c:49
static int connectDBStart(PGconn *conn)
Definition: fe-connect.c:1682
static PGconn * makeEmptyPGconn(void)
Definition: fe-connect.c:3307
ConnStatusType status
Definition: libpq-int.h:379
static bool connectOptions2(PGconn *conn)
Definition: fe-connect.c:895
PGconn* PQconnectStartParams ( const char *const *  keywords,
const char *const *  values,
int  expand_dbname 
)

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

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

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

635 {
636  PGconn *conn;
637  PQconninfoOption *connOptions;
638 
639  /*
640  * Allocate memory for the conn structure
641  */
642  conn = makeEmptyPGconn();
643  if (conn == NULL)
644  return NULL;
645 
646  /*
647  * Parse the conninfo arrays
648  */
649  connOptions = conninfo_array_parse(keywords, values,
650  &conn->errorMessage,
651  true, expand_dbname);
652  if (connOptions == NULL)
653  {
654  conn->status = CONNECTION_BAD;
655  /* errorMessage is already set */
656  return conn;
657  }
658 
659  /*
660  * Move option values into conn structure
661  */
662  if (!fillPGconn(conn, connOptions))
663  {
664  PQconninfoFree(connOptions);
665  return conn;
666  }
667 
668  /*
669  * Free the option info - all is in conn now
670  */
671  PQconninfoFree(connOptions);
672 
673  /*
674  * Compute derived options
675  */
676  if (!connectOptions2(conn))
677  return conn;
678 
679  /*
680  * Connect to the database
681  */
682  if (!connectDBStart(conn))
683  {
684  /* Just in case we failed to set it in connectDBStart */
685  conn->status = CONNECTION_BAD;
686  }
687 
688  return conn;
689 }
PGconn * conn
Definition: streamutil.c:49
static int connectDBStart(PGconn *conn)
Definition: fe-connect.c:1682
void PQconninfoFree(PQconninfoOption *connOptions)
Definition: fe-connect.c:5947
static PGconn * makeEmptyPGconn(void)
Definition: fe-connect.c:3307
PQExpBufferData errorMessage
Definition: libpq-int.h:491
static bool fillPGconn(PGconn *conn, PQconninfoOption *connOptions)
Definition: fe-connect.c:755
ConnStatusType status
Definition: libpq-int.h:379
static Datum values[MAXATTR]
Definition: bootstrap.c:164
static bool connectOptions2(PGconn *conn)
Definition: fe-connect.c:895
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:5011
PQconninfoOption* PQconninfo ( PGconn conn)

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

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

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

5907 {
5908  PQExpBufferData errorBuf;
5909  PQconninfoOption *connOptions;
5910 
5911  if (conn == NULL)
5912  return NULL;
5913 
5914  /* We don't actually report any errors here, but callees want a buffer */
5915  initPQExpBuffer(&errorBuf);
5916  if (PQExpBufferDataBroken(errorBuf))
5917  return NULL; /* out of memory already :-( */
5918 
5919  connOptions = conninfo_init(&errorBuf);
5920 
5921  if (connOptions != NULL)
5922  {
5924 
5925  for (option = PQconninfoOptions; option->keyword; option++)
5926  {
5927  char **connmember;
5928 
5929  if (option->connofs < 0)
5930  continue;
5931 
5932  connmember = (char **) ((char *) conn + option->connofs);
5933 
5934  if (*connmember)
5935  conninfo_storeval(connOptions, option->keyword, *connmember,
5936  &errorBuf, true, false);
5937  }
5938  }
5939 
5940  termPQExpBuffer(&errorBuf);
5941 
5942  return connOptions;
5943 }
static PQconninfoOption * conninfo_storeval(PQconninfoOption *connOptions, const char *keyword, const char *value, PQExpBuffer errorMessage, bool ignoreMissing, bool uri_decode)
Definition: fe-connect.c:5823
void termPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:128
static PQconninfoOption * conninfo_init(PQExpBuffer errorMessage)
Definition: fe-connect.c:4739
static const internalPQconninfoOption PQconninfoOptions[]
Definition: fe-connect.c:181
#define PQExpBufferDataBroken(buf)
Definition: pqexpbuffer.h:67
void initPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:89
void PQconninfoFree ( PQconninfoOption connOptions)

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

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

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

5948 {
5950 
5951  if (connOptions == NULL)
5952  return;
5953 
5954  for (option = connOptions; option->keyword != NULL; option++)
5955  {
5956  if (option->val != NULL)
5957  free(option->val);
5958  }
5959  free(connOptions);
5960 }
#define free(a)
Definition: header.h:65
PQconninfoOption* PQconninfoParse ( const char *  conninfo,
char **  errmsg 
)

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

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

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

4718 {
4719  PQExpBufferData errorBuf;
4720  PQconninfoOption *connOptions;
4721 
4722  if (errmsg)
4723  *errmsg = NULL; /* default */
4724  initPQExpBuffer(&errorBuf);
4725  if (PQExpBufferDataBroken(errorBuf))
4726  return NULL; /* out of memory already :-( */
4727  connOptions = parse_connection_string(conninfo, &errorBuf, false);
4728  if (connOptions == NULL && errmsg)
4729  *errmsg = errorBuf.data;
4730  else
4731  termPQExpBuffer(&errorBuf);
4732  return connOptions;
4733 }
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:4779
#define PQExpBufferDataBroken(buf)
Definition: pqexpbuffer.h:67
int errmsg(const char *fmt,...)
Definition: elog.c:797
void initPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:89
int PQconsumeInput ( PGconn conn)

Definition at line 1682 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_cleanup_result(), pgfdw_get_result(), PQconnectPoll(), StreamLogicalLog(), and try_complete_step().

1683 {
1684  if (!conn)
1685  return 0;
1686 
1687  /*
1688  * for non-blocking connections try to flush the send-queue, otherwise we
1689  * may never get a response for something that may not have already been
1690  * sent because it's in our write buffer!
1691  */
1692  if (pqIsnonblocking(conn))
1693  {
1694  if (pqFlush(conn) < 0)
1695  return 0;
1696  }
1697 
1698  /*
1699  * Load more data, if available. We do this no matter what state we are
1700  * in, since we are probably getting called because the application wants
1701  * to get rid of a read-select condition. Note that we will NOT block
1702  * waiting for more input.
1703  */
1704  if (pqReadData(conn) < 0)
1705  return 0;
1706 
1707  /* Parsing of the data waits till later. */
1708  return 1;
1709 }
int pqFlush(PGconn *conn)
Definition: fe-misc.c:963
#define pqIsnonblocking(conn)
Definition: libpq-int.h:676
int pqReadData(PGconn *conn)
Definition: fe-misc.c:631
PGresult* PQcopyResult ( const PGresult src,
int  flags 
)

Definition at line 293 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, 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().

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

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

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

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

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

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

Referenced by DescribeQuery(), and ECPGdescribe().

2115 {
2116  if (!PQexecStart(conn))
2117  return NULL;
2118  if (!PQsendDescribe(conn, 'S', stmt))
2119  return NULL;
2120  return PQexecFinish(conn);
2121 }
static int PQsendDescribe(PGconn *conn, char desc_type, const char *desc_target)
Definition: fe-exec.c:2178
static PGresult * PQexecFinish(PGconn *conn)
Definition: fe-exec.c:2053
static bool PQexecStart(PGconn *conn)
Definition: fe-exec.c:1979
void PQdisplayTuples ( const PGresult res,
FILE *  fp,
int  fillAlign,
const char *  fieldSep,
int  printHeader,
int  quiet 
)

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

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

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

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

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

1099 {
1100  char *crypt_pwd;
1101 
1102  crypt_pwd = malloc(MD5_PASSWD_LEN + 1);
1103  if (!crypt_pwd)
1104  return NULL;
1105 
1106  if (!pg_md5_encrypt(passwd, user, strlen(user), crypt_pwd))
1107  {
1108  free(crypt_pwd);
1109  return NULL;
1110  }
1111 
1112  return crypt_pwd;
1113 }
#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
static char * user
Definition: pg_regress.c:92
char* PQencryptPasswordConn ( PGconn conn,
const char *  passwd,
const char *  user,
const char *  algorithm 
)

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

References pg_conn::errorMessage, free, libpq_gettext, malloc, MAX_ALGORITHM_NAME_LEN, MD5_PASSWD_LEN, 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().

1142 {
1143 #define MAX_ALGORITHM_NAME_LEN 50
1144  char algobuf[MAX_ALGORITHM_NAME_LEN + 1];
1145  char *crypt_pwd = NULL;
1146 
1147  if (!conn)
1148  return NULL;
1149 
1150  /* If no algorithm was given, ask the server. */
1151  if (algorithm == NULL)
1152  {
1153  PGresult *res;
1154  char *val;
1155 
1156  res = PQexec(conn, "show password_encryption");
1157  if (res == NULL)
1158  {
1159  /* PQexec() should've set conn->errorMessage already */
1160  return NULL;
1161  }
1162  if (PQresultStatus(res) != PGRES_TUPLES_OK)
1163  {
1164  /* PQexec() should've set conn->errorMessage already */
1165  PQclear(res);
1166  return NULL;
1167  }
1168  if (PQntuples(res) != 1 || PQnfields(res) != 1)
1169  {
1170  PQclear(res);
1172  libpq_gettext("unexpected shape of result set returned for SHOW\n"));
1173  return NULL;
1174  }
1175  val = PQgetvalue(res, 0, 0);
1176 
1177  if (strlen(val) > MAX_ALGORITHM_NAME_LEN)
1178  {
1179  PQclear(res);
1181  libpq_gettext("password_encryption value too long\n"));
1182  return NULL;
1183  }
1184  strcpy(algobuf, val);
1185  PQclear(res);
1186 
1187  algorithm = algobuf;
1188  }
1189 
1190  /*
1191  * Also accept "on" and "off" as aliases for "md5", because
1192  * password_encryption was a boolean before PostgreSQL 10. We refuse to
1193  * send the password in plaintext even if it was "off".
1194  */
1195  if (strcmp(algorithm, "on") == 0 ||
1196  strcmp(algorithm, "off") == 0)
1197  algorithm = "md5";
1198 
1199  /*
1200  * Ok, now we know what algorithm to use
1201  */
1202  if (strcmp(algorithm, "scram-sha-256") == 0)
1203  {
1204  crypt_pwd = pg_fe_scram_build_verifier(passwd);
1205  }
1206  else if (strcmp(algorithm, "md5") == 0)
1207  {
1208  crypt_pwd = malloc(MD5_PASSWD_LEN + 1);
1209  if (crypt_pwd)
1210  {
1211  if (!pg_md5_encrypt(passwd, user, strlen(user), crypt_pwd))
1212  {
1213  free(crypt_pwd);
1214  crypt_pwd = NULL;
1215  }
1216  }
1217  }
1218  else
1219  {
1221  libpq_gettext("unrecognized password encryption algorithm \"%s\"\n"),
1222  algorithm);
1223  return NULL;
1224  }
1225 
1226  if (!crypt_pwd)
1228  libpq_gettext("out of memory\n"));
1229 
1230  return crypt_pwd;
1231 }
int PQnfields(const PGresult *res)
Definition: fe-exec.c:2732
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:3118
int PQntuples(const PGresult *res)
Definition: fe-exec.c:2724
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:2647
#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:491
void PQclear(PGresult *res)
Definition: fe-exec.c:671
#define MD5_PASSWD_LEN
Definition: md5.h:19
#define free(a)
Definition: header.h:65
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:1897
long val
Definition: informix.c:689
#define libpq_gettext(x)
Definition: libpq-int.h:682
int PQendcopy ( PGconn conn)

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

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

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

2574 {
2575  if (!conn)
2576  return 0;
2577 
2578  if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
2579  return pqEndcopy3(conn);
2580  else
2581  return pqEndcopy2(conn);
2582 }
#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:123
char* PQerrorMessage ( const PGconn conn)

Definition at line 6097 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(), DescribeQuery(), 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(), RetrieveWalSegSize(), 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().

6098 {
6099  if (!conn)
6100  return libpq_gettext("connection pointer is NULL\n");
6101 
6102  return conn->errorMessage.data;
6103 }
PQExpBufferData errorMessage
Definition: libpq-int.h:491
#define libpq_gettext(x)
Definition: libpq-int.h:682
unsigned char* PQescapeBytea ( const unsigned char *  from,
size_t  from_length,
size_t *  to_length 
)

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

References PQescapeByteaInternal(), and static_std_strings.

3682 {
3683  return PQescapeByteaInternal(NULL, from, from_length, to_length,
3685  false /* can't use hex */ );
3686 }
static bool static_std_strings
Definition: fe-exec.c:51
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:3572
unsigned char* PQescapeByteaConn ( PGconn conn,
const unsigned char *  from,
size_t  from_length,
size_t *  to_length 
)

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

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

3672 {
3673  if (!conn)
3674  return NULL;
3675  return PQescapeByteaInternal(conn, from, from_length, to_length,
3676  conn->std_strings,
3677  (conn->sversion >= 90000));
3678 }
int sversion
Definition: libpq-int.h:405
bool std_strings
Definition: libpq-int.h:423
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:3572
char* PQescapeIdentifier ( PGconn conn,
const char *  str,
size_t  len 
)

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

References PQescapeInternal().

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

3526 {
3527  return PQescapeInternal(conn, str, len, true);
3528 }
static char * PQescapeInternal(PGconn *conn, const char *str, size_t len, bool as_ident)
Definition: fe-exec.c:3398
char* PQescapeLiteral ( PGconn conn,
const char *  str,
size_t  len 
)

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

References PQescapeInternal().

Referenced by DescribeQuery(), libpqrcv_startstreaming(), and psql_get_variable().

3520 {
3521  return PQescapeInternal(conn, str, len, false);
3522 }
static char * PQescapeInternal(PGconn *conn, const char *str, size_t len, bool as_ident)
Definition: fe-exec.c:3398
size_t PQescapeString ( char *  to,
const char *  from,
size_t  length 
)

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

References PQescapeStringInternal(), static_client_encoding, and static_std_strings.

Referenced by get_comma_elts(), and quote_postgres().

3384 {
3385  return PQescapeStringInternal(NULL, to, from, length, NULL,
3388 }
static bool static_std_strings
Definition: fe-exec.c:51
int length(const List *list)
Definition: list.c:1271
static int static_client_encoding
Definition: fe-exec.c:50
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:3290
size_t PQescapeStringConn ( PGconn conn,
char *  to,
const char *  from,
size_t  length,
int *  error 
)

Definition at line 3365 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().

3368 {
3369  if (!conn)
3370  {
3371  /* force empty-string result */
3372  *to = '\0';
3373  if (error)
3374  *error = 1;
3375  return 0;
3376  }
3377  return PQescapeStringInternal(conn, to, from, length, error,
3378  conn->client_encoding,
3379  conn->std_strings);
3380 }
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:423
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:3290
int client_encoding
Definition: libpq-int.h:422
PGresult* PQexec ( PGconn conn,
const char *  query 
)

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

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

Referenced by _doSetSessionAuth(), _doSetWithOids(), _selectOutputSchema(), _selectTablespace(), check_loadable_libraries(), CreateReplicationSlot(), dblink_close(), dblink_exec(), dblink_fetch(), dblink_open(), deallocate_one(), DescribeQuery(), 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_xact_callback(), PQencryptPasswordConn(), PQsetClientEncoding(), PSQLexec(), PSQLexecWatch(), ReceiveXlogStream(), RetrieveWalSegSize(), run_permutation(), run_simple_query(), RunIdentifySystem(), SendQuery(), sql_exec(), StreamLogicalLog(), tryExecuteStatement(), and vacuumlo().

1898 {
1899  if (!PQexecStart(conn))
1900  return NULL;
1901  if (!PQsendQuery(conn, query))
1902  return NULL;
1903  return PQexecFinish(conn);
1904 }
int PQsendQuery(PGconn *conn, const char *query)
Definition: fe-exec.c:1183
static PGresult * PQexecFinish(PGconn *conn)
Definition: fe-exec.c:2053
static bool PQexecStart(PGconn *conn)
Definition: fe-exec.c:1979
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 1911 of file fe-exec.c.

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

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

1919 {
1920  if (!PQexecStart(conn))
1921  return NULL;
1922  if (!PQsendQueryParams(conn, command,
1923  nParams, paramTypes, paramValues, paramLengths,
1924  paramFormats, resultFormat))
1925  return NULL;
1926  return PQexecFinish(conn);
1927 }
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:1234
static PGresult * PQexecFinish(PGconn *conn)
Definition: fe-exec.c:2053
static bool PQexecStart(PGconn *conn)
Definition: fe-exec.c:1979
PGresult* PQexecPrepared ( PGconn conn,
const char *  stmtName,
int  nParams,
const char *const *  paramValues,
const int *  paramLengths,
const int *  paramFormats,
int  resultFormat 
)

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

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

Referenced by ecpg_execute(), and try_complete_step().

1965 {
1966  if (!PQexecStart(conn))
1967  return NULL;
1968  if (!PQsendQueryPrepared(conn, stmtName,
1969  nParams, paramValues, paramLengths,
1970  paramFormats, resultFormat))
1971  return NULL;
1972  return PQexecFinish(conn);
1973 }
static PGresult * PQexecFinish(PGconn *conn)
Definition: fe-exec.c:2053
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:1376
static bool PQexecStart(PGconn *conn)
Definition: fe-exec.c:1979
int PQfformat ( const PGresult res,
int  field_num 
)

Definition at line 2951 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().

2952 {
2953  if (!check_field_number(res, field_num))
2954  return 0;
2955  if (res->attDescs)
2956  return res->attDescs[field_num].format;
2957  else
2958  return 0;
2959 }
PGresAttDesc * attDescs
Definition: libpq-int.h:171
static int check_field_number(const PGresult *res, int field_num)
Definition: fe-exec.c:2753
void PQfinish ( PGconn conn)

Definition at line 3630 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(), disconnect_pg_server(), 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(), 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().

3631 {
3632  if (conn)
3633  {
3634  closePGconn(conn);
3635  freePGconn(conn);
3636  }
3637 }
static void closePGconn(PGconn *conn)
Definition: fe-connect.c:3577
static void freePGconn(PGconn *conn)
Definition: fe-connect.c:3403
int PQflush ( PGconn conn)

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

References pqFlush().

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

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

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

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

Referenced by DescribeQuery(), and ECPGget_desc().

2985 {
2986  if (!check_field_number(res, field_num))
2987  return 0;
2988  if (res->attDescs)
2989  return res->attDescs[field_num].atttypmod;
2990  else
2991  return 0;
2992 }
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:2753
PGresult* PQfn ( PGconn conn,
int  fnid,
int *  result_buf,
int *  result_len,
int  result_is_int,
const PQArgBlock args,
int  nargs 
)

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

References pg_conn::asyncStatus, pg_conn::errorMessage, libpq_gettext, 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().

2614 {
2615  *result_len = 0;
2616 
2617  if (!conn)
2618  return NULL;
2619 
2620  /* clear the error string */
2622 
2623  if (conn->sock == PGINVALID_SOCKET || conn->asyncStatus != PGASYNC_IDLE ||
2624  conn->result != NULL)
2625  {
2627  libpq_gettext("connection in wrong state\n"));
2628  return NULL;
2629  }
2630 
2631  if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
2632  return pqFunctionCall3(conn, fnid,
2633  result_buf, result_len,
2634  result_is_int,
2635  args, nargs);
2636  else
2637  return pqFunctionCall2(conn, fnid,
2638  result_buf, result_len,
2639  result_is_int,
2640  args, nargs);
2641 }
void printfPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:234
PGresult * pqFunctionCall2(PGconn *conn, Oid fnid, int *result_buf, int *actual_result_len, int result_is_int, const PQArgBlock *args, int nargs)
PGresult * pqFunctionCall3(PGconn *conn, Oid fnid, int *result_buf, int *actual_result_len, int result_is_int, const PQArgBlock *args, int nargs)
#define PG_PROTOCOL_MAJOR(v)
Definition: pqcomm.h:104
PGresult * result
Definition: libpq-int.h:450
PGAsyncStatusType asyncStatus
Definition: libpq-int.h:380
pgsocket sock
Definition: libpq-int.h:400
#define PGINVALID_SOCKET
Definition: port.h:24
PQExpBufferData errorMessage
Definition: libpq-int.h:491
ProtocolVersion pversion
Definition: libpq-int.h:404
void resetPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:145
#define libpq_gettext(x)
Definition: libpq-int.h:682
char* PQfname ( const PGresult res,
int  field_num 
)

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

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

Referenced by DescribeQuery(), do_header(), dumpTableData_insert(), ecpg_build_compat_sqlda(), ecpg_build_native_sqlda(), ECPGget_desc(), indexOfColumn(), libpqrcv_processTuples(), main(), PQdisplayTuples(), PQprint(), PQprintTuples(), printCrosstab(), printQuery(), printResultSet(), sql_exec(), sqlda_compat_empty_size(), and StoreQueryTuple().

2811 {
2812  if (!check_field_number(res, field_num))
2813  return NULL;
2814  if (res->attDescs)
2815  return res->attDescs[field_num].name;
2816  else
2817  return NULL;
2818 }
PGresAttDesc * attDescs
Definition: libpq-int.h:171
static int check_field_number(const PGresult *res, int field_num)
Definition: fe-exec.c:2753
char * name
Definition: libpq-fe.h:237