Eneboo - Documentación para desarrolladores
src/libpq/libpq-int.h
Ir a la documentación de este archivo.
00001 /*-------------------------------------------------------------------------
00002  *
00003  * libpq-int.h
00004  *        This file contains internal definitions meant to be used only by
00005  *        the frontend libpq library, not by applications that call it.
00006  *
00007  *        An application can include this file if it wants to bypass the
00008  *        official API defined by libpq-fe.h, but code that does so is much
00009  *        more likely to break across PostgreSQL releases than code that uses
00010  *        only the official API.
00011  *
00012  * Portions Copyright (c) 1996-2005, PostgreSQL Global Development Group
00013  * Portions Copyright (c) 1994, Regents of the University of California
00014  *
00015  * $PostgreSQL: pgsql/src/interfaces/libpq/libpq-int.h,v 1.108.2.2 2006/05/21 20:19:44 tgl Exp $
00016  *
00017  *-------------------------------------------------------------------------
00018  */
00019 
00020 #ifndef LIBPQ_INT_H
00021 #define LIBPQ_INT_H
00022 
00023 /* We assume libpq-fe.h has already been included. */
00024 #include "postgres_fe.h"
00025 
00026 #include <time.h>
00027 #include <sys/types.h>
00028 #ifndef WIN32
00029 #include <sys/time.h>
00030 #endif
00031 
00032 #ifdef ENABLE_THREAD_SAFETY
00033 #ifdef WIN32
00034 #include "pthread-win32.h"
00035 #else
00036 #include <pthread.h>
00037 #endif
00038 #include <signal.h>
00039 #endif
00040 
00041 #ifdef WIN32_CLIENT_ONLY
00042 typedef int ssize_t;                    /* ssize_t doesn't exist in VC (at least not
00043                                                                  * VC6) */
00044 #endif
00045 
00046 /* include stuff common to fe and be */
00047 #include "getaddrinfo.h"
00048 #include "libpq/pqcomm.h"
00049 /* include stuff found in fe only */
00050 #include "pqexpbuffer.h"
00051 
00052 #ifdef USE_SSL
00053 #include <openssl/ssl.h>
00054 #include <openssl/err.h>
00055 #endif
00056 
00057 /*
00058  * POSTGRES backend dependent Constants.
00059  */
00060 #define PQERRORMSG_LENGTH 1024
00061 #define CMDSTATUS_LEN 40
00062 
00063 /*
00064  * PGresult and the subsidiary types PGresAttDesc, PGresAttValue
00065  * represent the result of a query (or more precisely, of a single SQL
00066  * command --- a query string given to PQexec can contain multiple commands).
00067  * Note we assume that a single command can return at most one tuple group,
00068  * hence there is no need for multiple descriptor sets.
00069  */
00070 
00071 /* Subsidiary-storage management structure for PGresult.
00072  * See space management routines in fe-exec.c for details.
00073  * Note that space[k] refers to the k'th byte starting from the physical
00074  * head of the block --- it's a union, not a struct!
00075  */
00076 typedef union pgresult_data PGresult_data;
00077 
00078 union pgresult_data
00079 {
00080         PGresult_data *next;            /* link to next block, or NULL */
00081         char            space[1];               /* dummy for accessing block as bytes */
00082 };
00083 
00084 /* Data about a single attribute (column) of a query result */
00085 
00086 typedef struct pgresAttDesc
00087 {
00088         char       *name;                       /* column name */
00089         Oid                     tableid;                /* source table, if known */
00090         int                     columnid;               /* source column, if known */
00091         int                     format;                 /* format code for value (text/binary) */
00092         Oid                     typid;                  /* type id */
00093         int                     typlen;                 /* type size */
00094         int                     atttypmod;              /* type-specific modifier info */
00095 } PGresAttDesc;
00096 
00097 /*
00098  * Data for a single attribute of a single tuple
00099  *
00100  * We use char* for Attribute values.
00101  *
00102  * The value pointer always points to a null-terminated area; we add a
00103  * null (zero) byte after whatever the backend sends us.  This is only
00104  * particularly useful for text values ... with a binary value, the
00105  * value might have embedded nulls, so the application can't use C string
00106  * operators on it.  But we add a null anyway for consistency.
00107  * Note that the value itself does not contain a length word.
00108  *
00109  * A NULL attribute is a special case in two ways: its len field is NULL_LEN
00110  * and its value field points to null_field in the owning PGresult.  All the
00111  * NULL attributes in a query result point to the same place (there's no need
00112  * to store a null string separately for each one).
00113  */
00114 
00115 #define NULL_LEN                (-1)    /* pg_result len for NULL value */
00116 
00117 typedef struct pgresAttValue
00118 {
00119         int                     len;                    /* length in bytes of the value */
00120         char       *value;                      /* actual value, plus terminating zero byte */
00121 } PGresAttValue;
00122 
00123 /* Typedef for message-field list entries */
00124 typedef struct pgMessageField
00125 {
00126         struct pgMessageField *next;    /* list link */
00127         char            code;                   /* field code */
00128         char            contents[1];    /* field value (VARIABLE LENGTH) */
00129 } PGMessageField;
00130 
00131 /* Fields needed for notice handling */
00132 typedef struct
00133 {
00134         PQnoticeReceiver noticeRec; /* notice message receiver */
00135         void       *noticeRecArg;
00136         PQnoticeProcessor noticeProc;           /* notice message processor */
00137         void       *noticeProcArg;
00138 } PGNoticeHooks;
00139 
00140 struct pg_result
00141 {
00142         int                     ntups;
00143         int                     numAttributes;
00144         PGresAttDesc *attDescs;
00145         PGresAttValue **tuples;         /* each PGresTuple is an array of
00146                                                                  * PGresAttValue's */
00147         int                     tupArrSize;             /* allocated size of tuples array */
00148         ExecStatusType resultStatus;
00149         char            cmdStatus[CMDSTATUS_LEN];               /* cmd status from the query */
00150         int                     binary;                 /* binary tuple values if binary == 1,
00151                                                                  * otherwise text */
00152 
00153         /*
00154          * These fields are copied from the originating PGconn, so that operations
00155          * on the PGresult don't have to reference the PGconn.
00156          */
00157         PGNoticeHooks noticeHooks;
00158         int                     client_encoding;        /* encoding id */
00159 
00160         /*
00161          * Error information (all NULL if not an error result).  errMsg is the
00162          * "overall" error message returned by PQresultErrorMessage.  If we have
00163          * per-field info then it is stored in a linked list.
00164          */
00165         char       *errMsg;                     /* error message, or NULL if no error */
00166         PGMessageField *errFields;      /* message broken into fields */
00167 
00168         /* All NULL attributes in the query result point to this null string */
00169         char            null_field[1];
00170 
00171         /*
00172          * Space management information.  Note that attDescs and error stuff, if
00173          * not null, point into allocated blocks.  But tuples points to a
00174          * separately malloc'd block, so that we can realloc it.
00175          */
00176         PGresult_data *curBlock;        /* most recently allocated block */
00177         int                     curOffset;              /* start offset of free space in block */
00178         int                     spaceLeft;              /* number of free bytes remaining in block */
00179 };
00180 
00181 /* PGAsyncStatusType defines the state of the query-execution state machine */
00182 typedef enum
00183 {
00184         PGASYNC_IDLE,                           /* nothing's happening, dude */
00185         PGASYNC_BUSY,                           /* query in progress */
00186         PGASYNC_READY,                          /* result ready for PQgetResult */
00187         PGASYNC_COPY_IN,                        /* Copy In data transfer in progress */
00188         PGASYNC_COPY_OUT                        /* Copy Out data transfer in progress */
00189 } PGAsyncStatusType;
00190 
00191 /* PGQueryClass tracks which query protocol we are now executing */
00192 typedef enum
00193 {
00194         PGQUERY_SIMPLE,                         /* simple Query protocol (PQexec) */
00195         PGQUERY_EXTENDED,                       /* full Extended protocol (PQexecParams) */
00196         PGQUERY_PREPARE                         /* Parse only (PQprepare) */
00197 } PGQueryClass;
00198 
00199 /* PGSetenvStatusType defines the state of the PQSetenv state machine */
00200 /* (this is used only for 2.0-protocol connections) */
00201 typedef enum
00202 {
00203         SETENV_STATE_OPTION_SEND,       /* About to send an Environment Option */
00204         SETENV_STATE_OPTION_WAIT,       /* Waiting for above send to complete */
00205         SETENV_STATE_QUERY1_SEND,       /* About to send a status query */
00206         SETENV_STATE_QUERY1_WAIT,       /* Waiting for query to complete */
00207         SETENV_STATE_QUERY2_SEND,       /* About to send a status query */
00208         SETENV_STATE_QUERY2_WAIT,       /* Waiting for query to complete */
00209         SETENV_STATE_IDLE
00210 } PGSetenvStatusType;
00211 
00212 /* Typedef for the EnvironmentOptions[] array */
00213 typedef struct PQEnvironmentOption
00214 {
00215         const char *envName,            /* name of an environment variable */
00216                            *pgName;                     /* name of corresponding SET variable */
00217 } PQEnvironmentOption;
00218 
00219 /* Typedef for parameter-status list entries */
00220 typedef struct pgParameterStatus
00221 {
00222         struct pgParameterStatus *next;         /* list link */
00223         char       *name;                       /* parameter name */
00224         char       *value;                      /* parameter value */
00225         /* Note: name and value are stored in same malloc block as struct is */
00226 } pgParameterStatus;
00227 
00228 /* large-object-access data ... allocated only if large-object code is used. */
00229 typedef struct pgLobjfuncs
00230 {
00231         Oid                     fn_lo_open;             /* OID of backend function lo_open              */
00232         Oid                     fn_lo_close;    /* OID of backend function lo_close             */
00233         Oid                     fn_lo_creat;    /* OID of backend function lo_creat             */
00234         Oid                     fn_lo_create;   /* OID of backend function lo_create    */
00235         Oid                     fn_lo_unlink;   /* OID of backend function lo_unlink    */
00236         Oid                     fn_lo_lseek;    /* OID of backend function lo_lseek             */
00237         Oid                     fn_lo_tell;             /* OID of backend function lo_tell              */
00238         Oid                     fn_lo_read;             /* OID of backend function LOread               */
00239         Oid                     fn_lo_write;    /* OID of backend function LOwrite              */
00240 } PGlobjfuncs;
00241 
00242 /*
00243  * PGconn stores all the state data associated with a single connection
00244  * to a backend.
00245  */
00246 struct pg_conn
00247 {
00248         /* Saved values of connection options */
00249         char       *pghost;                     /* the machine on which the server is running */
00250         char       *pghostaddr;         /* the IPv4 address of the machine on which
00251                                                                  * the server is running, in IPv4
00252                                                                  * numbers-and-dots notation. Takes precedence
00253                                                                  * over above. */
00254         char       *pgport;                     /* the server's communication port */
00255         char       *pgunixsocket;       /* the Unix-domain socket that the server is
00256                                                                  * listening on; if NULL, uses a default
00257                                                                  * constructed from pgport */
00258         char       *pgtty;                      /* tty on which the backend messages is
00259                                                                  * displayed (OBSOLETE, NOT USED) */
00260         char       *connect_timeout;    /* connection timeout (numeric string) */
00261         char       *pgoptions;          /* options to start the backend with */
00262         char       *dbName;                     /* database name */
00263         char       *pguser;                     /* Postgres username and password, if any */
00264         char       *pgpass;
00265         char       *sslmode;            /* SSL mode (require,prefer,allow,disable) */
00266 #ifdef KRB5
00267         char       *krbsrvname;         /* Kerberos service name */
00268 #endif
00269 
00270         /* Optional file to write trace info to */
00271         FILE       *Pfdebug;
00272 
00273         /* Callback procedures for notice message processing */
00274         PGNoticeHooks noticeHooks;
00275 
00276         /* Status indicators */
00277         ConnStatusType status;
00278         PGAsyncStatusType asyncStatus;
00279         PGTransactionStatusType xactStatus;
00280         /* note: xactStatus never changes to ACTIVE */
00281         PGQueryClass queryclass;
00282         bool            nonblocking;    /* whether this connection is using nonblock
00283                                                                  * sending semantics */
00284         char            copy_is_binary; /* 1 = copy binary, 0 = copy text */
00285         int                     copy_already_done;              /* # bytes already returned in COPY
00286                                                                                  * OUT */
00287         PGnotify   *notifyHead;         /* oldest unreported Notify msg */
00288         PGnotify   *notifyTail;         /* newest unreported Notify msg */
00289 
00290         /* Connection data */
00291         int                     sock;                   /* Unix FD for socket, -1 if not connected */
00292         SockAddr        laddr;                  /* Local address */
00293         SockAddr        raddr;                  /* Remote address */
00294         ProtocolVersion pversion;       /* FE/BE protocol version in use */
00295         int                     sversion;               /* server version, e.g. 70401 for 7.4.1 */
00296 
00297         /* Transient state needed while establishing connection */
00298         struct addrinfo *addrlist;      /* list of possible backend addresses */
00299         struct addrinfo *addr_cur;      /* the one currently being tried */
00300         int                     addrlist_family;        /* needed to know how to free addrlist */
00301         PGSetenvStatusType setenv_state;        /* for 2.0 protocol only */
00302         const PQEnvironmentOption *next_eo;
00303 
00304         /* Miscellaneous stuff */
00305         int                     be_pid;                 /* PID of backend --- needed for cancels */
00306         int                     be_key;                 /* key of backend --- needed for cancels */
00307         char            md5Salt[4];             /* password salt received from backend */
00308         char            cryptSalt[2];   /* password salt received from backend */
00309         pgParameterStatus *pstatus; /* ParameterStatus data */
00310         int                     client_encoding;        /* encoding id */
00311         bool            std_strings;    /* standard_conforming_strings */
00312         PGVerbosity verbosity;          /* error/notice message verbosity */
00313         PGlobjfuncs *lobjfuncs;         /* private state for large-object access fns */
00314 
00315         /* Buffer for data received from backend and not yet processed */
00316         char       *inBuffer;           /* currently allocated buffer */
00317         int                     inBufSize;              /* allocated size of buffer */
00318         int                     inStart;                /* offset to first unconsumed data in buffer */
00319         int                     inCursor;               /* next byte to tentatively consume */
00320         int                     inEnd;                  /* offset to first position after avail data */
00321 
00322         /* Buffer for data not yet sent to backend */
00323         char       *outBuffer;          /* currently allocated buffer */
00324         int                     outBufSize;             /* allocated size of buffer */
00325         int                     outCount;               /* number of chars waiting in buffer */
00326 
00327         /* State for constructing messages in outBuffer */
00328         int                     outMsgStart;    /* offset to msg start (length word); if -1,
00329                                                                  * msg has no length word */
00330         int                     outMsgEnd;              /* offset to msg end (so far) */
00331 
00332         /* Status for asynchronous result construction */
00333         PGresult   *result;                     /* result being constructed */
00334         PGresAttValue *curTuple;        /* tuple currently being read */
00335 
00336 #ifdef USE_SSL
00337         bool            allow_ssl_try;  /* Allowed to try SSL negotiation */
00338         bool            wait_ssl_try;   /* Delay SSL negotiation until after
00339                                                                  * attempting normal connection */
00340         SSL                *ssl;                        /* SSL status, if have SSL connection */
00341         X509       *peer;                       /* X509 cert of server */
00342         char            peer_dn[256 + 1];               /* peer distinguished name */
00343         char            peer_cn[SM_USER + 1];   /* peer common name */
00344 #endif
00345 
00346         /* Buffer for current error message */
00347         PQExpBufferData errorMessage;           /* expansible string */
00348 
00349         /* Buffer for receiving various parts of messages */
00350         PQExpBufferData workBuffer; /* expansible string */
00351 };
00352 
00353 /* PGcancel stores all data necessary to cancel a connection. A copy of this
00354  * data is required to safely cancel a connection running on a different
00355  * thread.
00356  */
00357 struct pg_cancel
00358 {
00359         SockAddr        raddr;                  /* Remote address */
00360         int                     be_pid;                 /* PID of backend --- needed for cancels */
00361         int                     be_key;                 /* key of backend --- needed for cancels */
00362 };
00363 
00364 
00365 /* String descriptions of the ExecStatusTypes.
00366  * direct use of this array is deprecated; call PQresStatus() instead.
00367  */
00368 extern char *const pgresStatus[];
00369 
00370 /* ----------------
00371  * Internal functions of libpq
00372  * Functions declared here need to be visible across files of libpq,
00373  * but are not intended to be called by applications.  We use the
00374  * convention "pqXXX" for internal functions, vs. the "PQxxx" names
00375  * used for application-visible routines.
00376  * ----------------
00377  */
00378 
00379 /* === in fe-connect.c === */
00380 
00381 extern int pqPacketSend(PGconn *conn, char pack_type,
00382                          const void *buf, size_t buf_len);
00383 extern bool pqGetHomeDirectory(char *buf, int bufsize);
00384 
00385 #ifdef ENABLE_THREAD_SAFETY
00386 extern pgthreadlock_t pg_g_threadlock;
00387 
00388 #define pglock_thread()         pg_g_threadlock(true)
00389 #define pgunlock_thread()       pg_g_threadlock(false)
00390 #else
00391 #define pglock_thread()         ((void) 0)
00392 #define pgunlock_thread()       ((void) 0)
00393 #endif
00394 
00395 
00396 /* === in fe-exec.c === */
00397 
00398 extern void pqSetResultError(PGresult *res, const char *msg);
00399 extern void pqCatenateResultError(PGresult *res, const char *msg);
00400 extern void *pqResultAlloc(PGresult *res, size_t nBytes, bool isBinary);
00401 extern char *pqResultStrdup(PGresult *res, const char *str);
00402 extern void pqClearAsyncResult(PGconn *conn);
00403 extern void pqSaveErrorResult(PGconn *conn);
00404 extern PGresult *pqPrepareAsyncResult(PGconn *conn);
00405 extern void
00406 pqInternalNotice(const PGNoticeHooks *hooks, const char *fmt,...)
00407 /* This lets gcc check the format string for consistency. */
00408 __attribute__((format(printf, 2, 3)));
00409 extern int      pqAddTuple(PGresult *res, PGresAttValue *tup);
00410 extern void pqSaveMessageField(PGresult *res, char code,
00411                                    const char *value);
00412 extern void pqSaveParameterStatus(PGconn *conn, const char *name,
00413                                           const char *value);
00414 extern void pqHandleSendFailure(PGconn *conn);
00415 
00416 /* === in fe-protocol2.c === */
00417 
00418 extern PostgresPollingStatusType pqSetenvPoll(PGconn *conn);
00419 
00420 extern char *pqBuildStartupPacket2(PGconn *conn, int *packetlen,
00421                                           const PQEnvironmentOption *options);
00422 extern void pqParseInput2(PGconn *conn);
00423 extern int      pqGetCopyData2(PGconn *conn, char **buffer, int async);
00424 extern int      pqGetline2(PGconn *conn, char *s, int maxlen);
00425 extern int      pqGetlineAsync2(PGconn *conn, char *buffer, int bufsize);
00426 extern int      pqEndcopy2(PGconn *conn);
00427 extern PGresult *pqFunctionCall2(PGconn *conn, Oid fnid,
00428                                 int *result_buf, int *actual_result_len,
00429                                 int result_is_int,
00430                                 const PQArgBlock *args, int nargs);
00431 
00432 /* === in fe-protocol3.c === */
00433 
00434 extern char *pqBuildStartupPacket3(PGconn *conn, int *packetlen,
00435                                           const PQEnvironmentOption *options);
00436 extern void pqParseInput3(PGconn *conn);
00437 extern int      pqGetErrorNotice3(PGconn *conn, bool isError);
00438 extern int      pqGetCopyData3(PGconn *conn, char **buffer, int async);
00439 extern int      pqGetline3(PGconn *conn, char *s, int maxlen);
00440 extern int      pqGetlineAsync3(PGconn *conn, char *buffer, int bufsize);
00441 extern int      pqEndcopy3(PGconn *conn);
00442 extern PGresult *pqFunctionCall3(PGconn *conn, Oid fnid,
00443                                 int *result_buf, int *actual_result_len,
00444                                 int result_is_int,
00445                                 const PQArgBlock *args, int nargs);
00446 
00447 /* === in fe-misc.c === */
00448 
00449  /*
00450   * "Get" and "Put" routines return 0 if successful, EOF if not. Note that for
00451   * Get, EOF merely means the buffer is exhausted, not that there is
00452   * necessarily any error.
00453   */
00454 extern int      pqCheckOutBufferSpace(int bytes_needed, PGconn *conn);
00455 extern int      pqCheckInBufferSpace(int bytes_needed, PGconn *conn);
00456 extern int      pqGetc(char *result, PGconn *conn);
00457 extern int      pqPutc(char c, PGconn *conn);
00458 extern int      pqGets(PQExpBuffer buf, PGconn *conn);
00459 extern int      pqPuts(const char *s, PGconn *conn);
00460 extern int      pqGetnchar(char *s, size_t len, PGconn *conn);
00461 extern int      pqPutnchar(const char *s, size_t len, PGconn *conn);
00462 extern int      pqGetInt(int *result, size_t bytes, PGconn *conn);
00463 extern int      pqPutInt(int value, size_t bytes, PGconn *conn);
00464 extern int      pqPutMsgStart(char msg_type, bool force_len, PGconn *conn);
00465 extern int      pqPutMsgEnd(PGconn *conn);
00466 extern int      pqReadData(PGconn *conn);
00467 extern int      pqFlush(PGconn *conn);
00468 extern int      pqWait(int forRead, int forWrite, PGconn *conn);
00469 extern int pqWaitTimed(int forRead, int forWrite, PGconn *conn,
00470                         time_t finish_time);
00471 extern int      pqReadReady(PGconn *conn);
00472 extern int      pqWriteReady(PGconn *conn);
00473 
00474 /* === in fe-secure.c === */
00475 
00476 extern int      pqsecure_initialize(PGconn *);
00477 extern void pqsecure_destroy(void);
00478 extern PostgresPollingStatusType pqsecure_open_client(PGconn *);
00479 extern void pqsecure_close(PGconn *);
00480 extern ssize_t pqsecure_read(PGconn *, void *ptr, size_t len);
00481 extern ssize_t pqsecure_write(PGconn *, const void *ptr, size_t len);
00482 
00483 #if defined(ENABLE_THREAD_SAFETY) && !defined(WIN32)
00484 extern int      pq_block_sigpipe(sigset_t *osigset, bool *sigpipe_pending);
00485 extern void pq_reset_sigpipe(sigset_t *osigset, bool sigpipe_pending,
00486                                  bool got_epipe);
00487 #endif
00488 
00489 /*
00490  * this is so that we can check if a connection is non-blocking internally
00491  * without the overhead of a function call
00492  */
00493 #define pqIsnonblocking(conn)   ((conn)->nonblocking)
00494 
00495 #ifdef ENABLE_NLS
00496 extern char *
00497 libpq_gettext(const char *msgid)
00498 __attribute__((format_arg(1)));
00499 #else
00500 #define libpq_gettext(x) (x)
00501 #endif
00502 
00503 /*
00504  * These macros are needed to let error-handling code be portable between
00505  * Unix and Windows.  (ugh)
00506  */
00507 #ifdef WIN32
00508 #define SOCK_ERRNO (WSAGetLastError())
00509 #define SOCK_STRERROR winsock_strerror
00510 #define SOCK_ERRNO_SET(e) WSASetLastError(e)
00511 #else
00512 #define SOCK_ERRNO errno
00513 #define SOCK_STRERROR pqStrerror
00514 #define SOCK_ERRNO_SET(e) (errno = (e))
00515 #endif
00516 
00517 #endif   /* LIBPQ_INT_H */
 Todo Clases Namespaces Archivos Funciones Variables 'typedefs' Enumeraciones Valores de enumeraciones Propiedades Amigas 'defines'