RefLib

Reference library for AI

Back

postgresql_16:5.1.3.1 Main Functions

PostgreSQL 16 > Client Interfaces > libpq — C Library > Command Execution Functions > Main Functions

PQexec Submits a command to the server and waits for the result. PGresult *PQexec(PGconn *conn, const char *command); Returns a PGresult pointer or possibly a null pointer. A non-null pointer will generally be returned except in out-of-memory conditions or serious errors such as inability to send the command to the server. The (see libpq-PQresultStatus) function should be called to check the return value for any errors (including the value of a null pointer, in which case it will return PGRES_FATAL_ERROR). Use (see libpq-PQerrorMessage) to get more information about such errors. The command string can include multiple SQL commands (separated by semicolons). Multiple queries sent in a single (see libpq-PQexec) call are processed in a single transaction, unless there are explicit BEGIN/COMMIT commands included in the query string to divide it into multiple transactions. (See (see postgresql_16:8.4.2.2) for more details about how the server handles multi-query strings.) Note however that the returned PGresult structure describes only the result of the last command executed from the string. Should one of the commands fail, processing of the string stops with it and the returned PGresult describes the error condition.

PQexecParams Submits a command to the server and waits for the result, with the ability to pass parameters separately from the SQL command text. PGresult *PQexecParams(PGconn *conn, const char *command, int nParams, const Oid *paramTypes, const char * const *paramValues, const int *paramLengths, const int *paramFormats, int resultFormat); (see libpq-PQexecParams) is like (see libpq-PQexec), but offers additional functionality: parameter values can be specified separately from the command string proper, and query results can be requested in either text or binary format. The function arguments are: conn The connection object to send the command through. command The SQL command string to be executed. If parameters are used, they are referred to in the command string as $1, $2, etc. nParams The number of parameters supplied; it is the length of the arrays paramTypes[], paramValues[], paramLengths[], and paramFormats[]. (The array pointers can be NULL when nParams is zero.) paramTypes[] Specifies, by OID, the data types to be assigned to the parameter symbols. If paramTypes is NULL, or any particular element in the array is zero, the server infers a data type for the parameter symbol in the same way it would do for an untyped literal string. paramValues[] Specifies the actual values of the parameters. A null pointer in this array means the corresponding parameter is null; otherwise the pointer points to a zero-terminated text string (for text format) or binary data in the format expected by the server (for binary format). paramLengths[] Specifies the actual data lengths of binary-format parameters. It is ignored for null parameters and text-format parameters. The array pointer can be null when there are no binary parameters. paramFormats[] Specifies whether parameters are text (put a zero in the array entry for the corresponding parameter) or binary (put a one in the array entry for the corresponding parameter). If the array pointer is null then all parameters are presumed to be text strings. Values passed in binary format require knowledge of the internal representation expected by the backend. For example, integers must be passed in network byte order. Passing numeric values requires knowledge of the server storage format, as implemented in src/backend/utils/adt/numeric.c::numeric_send() and src/backend/utils/adt/numeric.c::numeric_recv(). resultFormat Specify zero to obtain results in text format, or one to obtain results in binary format. (There is not currently a provision to obtain different result columns in different formats, although that is possible in the underlying protocol.)

The primary advantage of (see libpq-PQexecParams) over (see libpq-PQexec) is that parameter values can be separated from the command string, thus avoiding the need for tedious and error-prone quoting and escaping.

Unlike (see libpq-PQexec), (see libpq-PQexecParams) allows at most one SQL command in the given string. (There can be semicolons in it, but not more than one nonempty command.) This is a limitation of the underlying protocol, but has some usefulness as an extra defense against SQL-injection attacks.

Tip

Specifying parameter types via OIDs is tedious, particularly if you prefer not to hard-wire particular OID values into your program. However, you can avoid doing so even in cases where the server by itself cannot determine the type of the parameter, or chooses a different type than you want. In the SQL command text, attach an explicit cast to the parameter symbol to show what data type you will send. For example: SELECT * FROM mytable WHERE x = $1::bigint; This forces parameter $1 to be treated as bigint, whereas by default it would be assigned the same type as x. Forcing the parameter type decision, either this way or by specifying a numeric type OID, is strongly recommended when sending parameter values in binary format, because binary format has less redundancy than text format and so there is less chance that the server will detect a type mismatch mistake for you.

PQprepare Submits a request to create a prepared statement with the given parameters, and waits for completion. PGresult *PQprepare(PGconn *conn, const char *stmtName, const char *query, int nParams, const Oid *paramTypes); (see libpq-PQprepare) creates a prepared statement for later execution with (see libpq-PQexecPrepared). This feature allows commands to be executed repeatedly without being parsed and planned each time; see (see postgresql_16:7.1.157) for details. The function creates a prepared statement named stmtName from the query string, which must contain a single SQL command. stmtName can be "" to create an unnamed statement, in which case any pre-existing unnamed statement is automatically replaced; otherwise it is an error if the statement name is already defined in the current session. If any parameters are used, they are referred to in the query as $1, $2, etc. nParams is the number of parameters for which types are pre-specified in the array paramTypes[]. (The array pointer can be NULL when nParams is zero.) paramTypes[] specifies, by OID, the data types to be assigned to the parameter symbols. If paramTypes is NULL, or any particular element in the array is zero, the server assigns a data type to the parameter symbol in the same way it would do for an untyped literal string. Also, the query can use parameter symbols with numbers higher than nParams; data types will be inferred for these symbols as well. (See (see libpq-PQdescribePrepared) for a means to find out what data types were inferred.) As with (see libpq-PQexec), the result is normally a PGresult object whose contents indicate server-side success or failure. A null result indicates out-of-memory or inability to send the command at all. Use (see libpq-PQerrorMessage) to get more information about such errors. Prepared statements for use with (see libpq-PQexecPrepared) can also be created by executing SQL (see postgresql_16:7.1.157) statements. Also, although there is no libpq function for deleting a prepared statement, the SQL (see postgresql_16:7.1.96) statement can be used for that purpose.

PQexecPrepared Sends a request to execute a prepared statement with given parameters, and waits for the result. PGresult *PQexecPrepared(PGconn *conn, const char *stmtName, int nParams, const char * const *paramValues, const int *paramLengths, const int *paramFormats, int resultFormat); (see libpq-PQexecPrepared) is like (see libpq-PQexecParams), but the command to be executed is specified by naming a previously-prepared statement, instead of giving a query string. This feature allows commands that will be used repeatedly to be parsed and planned just once, rather than each time they are executed. The statement must have been prepared previously in the current session. The parameters are identical to (see libpq-PQexecParams), except that the name of a prepared statement is given instead of a query string, and the paramTypes[] parameter is not present (it is not needed since the prepared statement's parameter types were determined when it was created). PQdescribePrepared Submits a request to obtain information about the specified prepared statement, and waits for completion. PGresult *PQdescribePrepared(PGconn *conn, const char *stmtName); (see libpq-PQdescribePrepared) allows an application to obtain information about a previously prepared statement. stmtName can be "" or NULL to reference the unnamed statement, otherwise it must be the name of an existing prepared statement. On success, a PGresult with status PGRES_COMMAND_OK is returned. The functions (see libpq-PQnparams) and (see libpq-PQparamtype) can be applied to this PGresult to obtain information about the parameters of the prepared statement, and the functions (see libpq-PQnfields), (see libpq-PQfname), (see libpq-PQftype), etc. provide information about the result columns (if any) of the statement. PQdescribePortal Submits a request to obtain information about the specified portal, and waits for completion. PGresult *PQdescribePortal(PGconn *conn, const char *portalName); (see libpq-PQdescribePortal) allows an application to obtain information about a previously created portal. (libpq does not provide any direct access to portals, but you can use this function to inspect the properties of a cursor created with a DECLARE CURSOR SQL command.) portalName can be "" or NULL to reference the unnamed portal, otherwise it must be the name of an existing portal. On success, a PGresult with status PGRES_COMMAND_OK is returned. The functions (see libpq-PQnfields), (see libpq-PQfname), (see libpq-PQftype), etc. can be applied to the PGresult to obtain information about the result columns (if any) of the portal.

The PGresult structure encapsulates the result returned by the server. libpq application programmers should be careful to maintain the PGresult abstraction. Use the accessor functions below to get at the contents of PGresult. Avoid directly referencing the fields of the PGresult structure because they are subject to change in the future. PQresultStatus Returns the result status of the command. ExecStatusType PQresultStatus(const PGresult *res); (see libpq-PQresultStatus) can return one of the following values: PGRES_EMPTY_QUERY The string sent to the server was empty. PGRES_COMMAND_OK Successful completion of a command returning no data. PGRES_TUPLES_OK Successful completion of a command returning data (such as a SELECT or SHOW). PGRES_COPY_OUT Copy Out (from server) data transfer started. PGRES_COPY_IN Copy In (to server) data transfer started. PGRES_BAD_RESPONSE The server's response was not understood. PGRES_NONFATAL_ERROR A nonfatal error (a notice or warning) occurred. PGRES_FATAL_ERROR A fatal error occurred. PGRES_COPY_BOTH Copy In/Out (to and from server) data transfer started. This feature is currently used only for streaming replication, so this status should not occur in ordinary applications. PGRES_SINGLE_TUPLE The PGresult contains a single result tuple from the current command. This status occurs only when single-row mode has been selected for the query (see (see postgresql_16:5.1.6)). PGRES_PIPELINE_SYNC The PGresult represents a synchronization point in pipeline mode, requested by (see libpq-PQpipelineSync). This status occurs only when pipeline mode has been selected. PGRES_PIPELINE_ABORTED The PGresult represents a pipeline that has received an error from the server. PQgetResult must be called repeatedly, and each time it will return this status code until the end of the current pipeline, at which point it will return PGRES_PIPELINE_SYNC and normal processing can resume. If the result status is PGRES_TUPLES_OK or PGRES_SINGLE_TUPLE, then the functions described below can be used to retrieve the rows returned by the query. Note that a SELECT command that happens to retrieve zero rows still shows PGRES_TUPLES_OK. PGRES_COMMAND_OK is for commands that can never return rows (INSERT or UPDATE without a RETURNING clause, etc.). A response of PGRES_EMPTY_QUERY might indicate a bug in the client software. A result of status PGRES_NONFATAL_ERROR will never be returned directly by (see libpq-PQexec) or other query execution functions; results of this kind are instead passed to the notice processor (see (see postgresql_16:5.1.13)). PQresStatus Converts the enumerated type returned by (see libpq-PQresultStatus) into a string constant describing the status code. The caller should not free the result. char *PQresStatus(ExecStatusType status); PQresultErrorMessage Returns the error message associated with the command, or an empty string if there was no error. char *PQresultErrorMessage(const PGresult *res); If there was an error, the returned string will include a trailing newline. The caller should not free the result directly. It will be freed when the associated PGresult handle is passed to (see libpq-PQclear). Immediately following a (see libpq-PQexec) or (see libpq-PQgetResult) call, (see libpq-PQerrorMessage) (on the connection) will return the same string as (see libpq-PQresultErrorMessage) (on the result). However, a PGresult will retain its error message until destroyed, whereas the connection's error message will change when subsequent operations are done. Use (see libpq-PQresultErrorMessage) when you want to know the status associated with a particular PGresult; use (see libpq-PQerrorMessage) when you want to know the status from the latest operation on the connection. PQresultVerboseErrorMessage Returns a reformatted version of the error message associated with a PGresult object. char *PQresultVerboseErrorMessage(const PGresult *res, PGVerbosity verbosity, PGContextVisibility show_context); In some situations a client might wish to obtain a more detailed version of a previously-reported error. (see libpq-PQresultVerboseErrorMessage) addresses this need by computing the message that would have been produced by (see libpq-PQresultErrorMessage) if the specified verbosity settings had been in effect for the connection when the given PGresult was generated. If the PGresult is not an error result, “PGresult is not an error result” is reported instead. The returned string includes a trailing newline. Unlike most other functions for extracting data from a PGresult, the result of this function is a freshly allocated string. The caller must free it using PQfreemem() when the string is no longer needed. A NULL return is possible if there is insufficient memory. PQresultErrorField Returns an individual field of an error report. char *PQresultErrorField(const PGresult *res, int fieldcode); fieldcode is an error field identifier; see the symbols listed below. NULL is returned if the PGresult is not an error or warning result, or does not include the specified field. Field values will normally not include a trailing newline. The caller should not free the result directly. It will be freed when the associated PGresult handle is passed to (see libpq-PQclear). The following field codes are available: PG_DIAG_SEVERITY The severity; the field contents are ERROR, FATAL, or PANIC (in an error message), or WARNING, NOTICE, DEBUG, INFO, or LOG (in a notice message), or a localized translation of one of these. Always present. PG_DIAG_SEVERITY_NONLOCALIZED The severity; the field contents are ERROR, FATAL, or PANIC (in an error message), or WARNING, NOTICE, DEBUG, INFO, or LOG (in a notice message). This is identical to the PG_DIAG_SEVERITY field except that the contents are never localized. This is present only in reports generated by PostgreSQL versions 9.6 and later. PG_DIAG_SQLSTATE The SQLSTATE code for the error. The SQLSTATE code identifies the type of error that has occurred; it can be used by front-end applications to perform specific operations (such as error handling) in response to a particular database error. For a list of the possible SQLSTATE codes, see (see postgresql_16:9.1). This field is not localizable, and is always present. PG_DIAG_MESSAGE_PRIMARY The primary human-readable error message (typically one line). Always present. PG_DIAG_MESSAGE_DETAIL Detail: an optional secondary error message carrying more detail about the problem. Might run to multiple lines. PG_DIAG_MESSAGE_HINT Hint: an optional suggestion what to do about the problem. This is intended to differ from detail in that it offers advice (potentially inappropriate) rather than hard facts. Might run to multiple lines. PG_DIAG_STATEMENT_POSITION A string containing a decimal integer indicating an error cursor position as an index into the original statement string. The first character has index 1, and positions are measured in characters not bytes. PG_DIAG_INTERNAL_POSITION This is defined the same as the PG_DIAG_STATEMENT_POSITION field, but it is used when the cursor position refers to an internally generated command rather than the one submitted by the client. The PG_DIAG_INTERNAL_QUERY field will always appear when this field appears. PG_DIAG_INTERNAL_QUERY The text of a failed internally-generated command. This could be, for example, an SQL query issued by a PL/pgSQL function. PG_DIAG_CONTEXT An indication of the context in which the error occurred. Presently this includes a call stack traceback of active procedural language functions and internally-generated queries. The trace is one entry per line, most recent first. PG_DIAG_SCHEMA_NAME If the error was associated with a specific database object, the name of the schema containing that object, if any. PG_DIAG_TABLE_NAME If the error was associated with a specific table, the name of the table. (Refer to the schema name field for the name of the table's schema.) PG_DIAG_COLUMN_NAME If the error was associated with a specific table column, the name of the column. (Refer to the schema and table name fields to identify the table.) PG_DIAG_DATATYPE_NAME If the error was associated with a specific data type, the name of the data type. (Refer to the schema name field for the name of the data type's schema.) PG_DIAG_CONSTRAINT_NAME If the error was associated with a specific constraint, the name of the constraint. Refer to fields listed above for the associated table or domain. (For this purpose, indexes are treated as constraints, even if they weren't created with constraint syntax.) PG_DIAG_SOURCE_FILE The file name of the source-code location where the error was reported. PG_DIAG_SOURCE_LINE The line number of the source-code location where the error was reported. PG_DIAG_SOURCE_FUNCTION The name of the source-code function reporting the error. The fields for schema name, table name, column name, data type name, and constraint name are supplied only for a limited number of error types; see (see postgresql_16:9.1). Do not assume that the presence of any of these fields guarantees the presence of another field. Core error sources observe the interrelationships noted above, but user-defined functions may use these fields in other ways. In the same vein, do not assume that these fields denote contemporary objects in the current database. The client is responsible for formatting displayed information to meet its needs; in particular it should break long lines as needed. Newline characters appearing in the error message fields should be treated as paragraph breaks, not line breaks. Errors generated internally by libpq will have severity and primary message, but typically no other fields. Note that error fields are only available from PGresult objects, not PGconn objects; there is no PQerrorField function. PQclear Frees the storage associated with a PGresult. Every command result should be freed via (see libpq-PQclear) when it is no longer needed. void PQclear(PGresult *res); If the argument is a NULL pointer, no operation is performed. You can keep a PGresult object around for as long as you need it; it does not go away when you issue a new command, nor even if you close the connection. To get rid of it, you must call (see libpq-PQclear). Failure to do this will result in memory leaks in your application.

Back