+ sortas="libpq">with libpq>
+
requiressl
- This option is deprecated in favor of the sslmode>
- setting.
-
- If set to 1, an
SSL connection to the server is required
- (this is equivalent to sslmode> require>).
-
libpq> will then refuse to connect if the server does not
- accept an
SSL connection.
- If set to 0 (default),
libpq> will negotiate the connection
- type with the server (equivalent to sslmode> prefer>).
- This option is only available if
-
PostgreSQL> is compiled with SSL support.
-
+ This option is deprecated in favor of the sslmode>
+ setting.
+
+
+ If set to 1, an
SSL connection to the server
+ is required (this is equivalent to sslmode>
+
require>). libpq> will then refuse
+ to connect if the server does not accept an
+
SSL connection. If set to 0 (default),
+
libpq> will negotiate the connection type with
+ the server (equivalent to sslmode>
+ prefer>). This option is only available if
+
PostgreSQL> is compiled with SSL support.
+
- PQsetdbLogin
+
PQsetdbLogin <indexterm>PQsetdbLogin>>< /term>
Makes a new connection to the database server.
- PQsetdb
+
PQsetdb <indexterm>PQsetdb>>< /term>
Makes a new connection to the database server.
- PQconnectStart
- PQconnectPoll
+
PQconnectStart <indexterm>PQconnectStart>>< /term>
+
PQconnectPoll <indexterm>PQconnectPoll>>< /term>
- PQconndefaults
+
PQconndefaults <indexterm>PQconndefaults>>< /term>
Returns the default connection options.
- PQfinish
+
PQfinish <indexterm>PQfinish>>< /term>
Closes the connection to the server. Also frees
- PQreset
+
PQreset <indexterm>PQreset>>< /term>
Resets the communication channel to the server.
- PQresetStart
- PQresetPoll
+
PQresetStart <indexterm>PQresetStart>>< /term>
+
PQresetPoll <indexterm>PQresetPoll>>< /term>
Reset the communication channel to the server, in a nonblocking manner.
-PQdb
+
PQdb <indexterm>PQdb>>< /term>
Returns the database name of the connection.
-PQuser
+
PQuser <indexterm>PQuser>>< /term>
Returns the user name of the connection.
-PQpass
+
PQpass <indexterm>PQpass>>< /term>
Returns the password of the connection.
-PQhost
+
PQhost <indexterm>PQhost>>< /term>
Returns the server host name of the connection.
-PQport
+
PQport <indexterm>PQport>>< /term>
Returns the port of the connection.
-PQtty
+
PQtty <indexterm>PQtty>>< /term>
Returns the debug
TTY of the connection.
- (This is obsolete, since the server no longer pays attention
- to the
TTY setting, but the function remains
- for backwards compatibility.)
+ (This is obsolete, since the server no longer pays attention
+
to the
TTY setting, but the function remains
+ for backwards compatibility.)
char *PQtty(const PGconn *conn);
-PQoptions
+
PQoptions <indexterm>PQoptions>>< /term>
Returns the command-line options passed in the connection request.
-PQstatus
+
PQstatus <indexterm>PQstatus>>< /term>
Returns the status of the connection.
-PQtransactionStatus
+
PQtransactionStatus <indexterm>PQtransactionStatus>>< /term>
Returns the current in-transaction status of the server.
-PQparameterStatus
+
PQparameterStatus <indexterm>PQparameterStatus>>< /term>
Looks up a current parameter setting of the server.
-PQprotocolVersion
+
PQprotocolVersion <indexterm>PQprotocolVersion>>< /term>
Interrogates the frontend/backend protocol being used.
- PQerrorMessage
+
PQerrorMessage <indexterm>PQerrorMessage>>< /term>
- PQsocket
+
PQsocket <indexterm>PQsocket>>< /term>
Obtains the file descriptor number of the connection socket to
- PQbackendPID
+
PQbackendPID <indexterm>PQbackendPID>>< /term>
- Returns the process
ID of the backend server process
- handling this connection.
+ (PID)
PID>determining PID of
+ server process>in libpq>> of the backend server
+ process handling this connection.
int PQbackendPID(const PGconn *conn);
- PQgetssl
+
PQgetssl <indexterm>PQgetssl>>< /term>
+
SSL><secondary sortas="libpq">in libpq >
Returns the SSL structure used in the connection, or null
if SSL is not in use.
-PQexec
+
PQexec <indexterm>PQexec>>< /term>
Submits a command to the server
out-of-memory conditions or serious errors such as inability
to send the command to the server.
If a null pointer is returned, it
- should be treated like a PGRES_FATAL_ERROR result. Use
- PQerrorMessage to get more information about the error.
+ should be treated like a PGRES_FATAL_ERROR result. Use
+ PQerrorMessage to get more information about the error.
-PQexecParams
+
PQexecParams <indexterm>PQexecParams>>< /term>
Submits a command to the server and waits for the result,
- with the ability to pass parameters separately from the SQL
- command text.
+ with the ability to pass parameters separately from the SQL
+ command text.
PGresult *PQexecParams(PGconn *conn,
const char *command,
-PQexecPrepared
+
PQexecPrepared <indexterm>PQexecPrepared>>< /term>
Sends a request to execute a prepared statement with given
- parameters, and waits for the result.
+ parameters, and waits for the result.
PGresult *PQexecPrepared(PGconn *conn,
const char *stmtName,
-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.
+The
+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
+
PQresultStatus <indexterm>PQresultStatus>>< /term>
Returns the result status of the command.
-PQresStatus
+
PQresStatus <indexterm>PQresStatus>>< /term>
- Converts the enumerated type returned by PQresultStatus> into
- a string constant describing the status code.
+ Converts the enumerated type returned by PQresultStatus> into
+ a string constant describing the status code.
char *PQresStatus(ExecStatusType status);
-PQresultErrorMessage
+
PQresultErrorMessage <indexterm>PQresultErrorMessage>>< /term>
Returns the error message associated with the command, or an empty string
-PQresultErrorField
+
PQresultErrorField <indexterm>PQresultErrorField>>< /term>
Returns an individual field of an error report.
-PQclear
+
PQclear <indexterm>PQclear>>< /term>
Frees the storage associated with a PGresult .
-PQmakeEmptyPGresult
+
PQmakeEmptyPGresult <indexterm>PQmakeEmptyPGresult>>< /term>
Constructs an empty PGresult object with the given status.
-PQntuples
+
PQntuples <indexterm>PQntuples>>< /term>
Returns the number of rows (tuples)
-PQnfields
+
PQnfields <indexterm>PQnfields>>< /term>
Returns the number of columns (fields)
-PQfname
+
PQfname <indexterm>PQfname>>< /term>
Returns the column name associated with the given column number.
-PQfnumber
+
PQfnumber <indexterm>PQfnumber>>< /term>
Returns the column number
-PQftable
+
PQftable <indexterm>PQftable>>< /term>
Returns the OID of the table from which the given column was fetched.
-PQftablecol
+
PQftablecol <indexterm>PQftablecol>>< /term>
Returns the column number (within its table) of the column making up
-PQfformat
+
PQfformat <indexterm>PQfformat>>< /term>
Returns the format code indicating the format of the given column.
-PQftype
+
PQftype <indexterm>PQftype>>< /term>
Returns the data type associated with the
-PQfmod
+
PQfmod <indexterm>PQfmod>>< /term>
Returns the type modifier of the column
-PQfsize
+
PQfsize <indexterm>PQfsize>>< /term>
Returns the size in bytes of the column
-PQbinaryTuples
+
PQbinaryTuples <indexterm>PQbinaryTuples>>< /term>
Returns 1 if the PGresult> contains binary data
-PQgetvalue
+
PQgetvalue <indexterm>PQgetvalue>>< /term>
Returns a single field value of one row
- of a PGresult .
+ of a PGresult .
Row and column numbers start at 0.
char* PQgetvalue(const PGresult *res,
-PQgetisnull
-
+
PQgetisnull <indexterm>PQgetisnull>>< /term>
+<
indexterm>null value>in libpq>< listitem>
Tests a field for a null value.
Row and column numbers start at 0.
-PQgetlength
+
PQgetlength <indexterm>PQgetlength>>< /term>
Returns the actual length of a field value in bytes.
-PQprint
+
PQprint <indexterm>PQprint>>< /term>
Prints out all the rows and, optionally, the
-PQcmdStatus
+
PQcmdStatus <indexterm>PQcmdStatus>>< /term>
Returns the command status tag from the SQL command that
- generated the PGresult .
+ generated the PGresult .
char * PQcmdStatus(PGresult *res);
-PQcmdTuples
+
PQcmdTuples <indexterm>PQcmdTuples>>< /term>
- Returns the number of rows affected by the SQL command.
+ Returns the number of rows affected by the SQL command.
char * PQcmdTuples(PGresult *res);
If the
SQL command that generated the
- PGresult was INSERT>,
- UPDATE>, DELETE , MOVE>,
- or FETCH>, this returns a
- string containing the number of rows affected. If the
+ PGresult was INSERT>,
+ UPDATE>, DELETE , MOVE>,
+ or FETCH>, this returns a
+ string containing the number of rows affected. If the
command was anything else, it returns the empty string.
-PQoidValue
+
PQoidValue <indexterm>PQoidValue>>< /term>
- Returns the OID of the inserted row, if the
-
SQL command was an
INSERT
- that inserted exactly one row into a table that has OIDs.
- Otherwise, returns InvalidOid .
+ libpq>> of the inserted row, if the
+ INSERT that inserted exactly one row into
+ a table that has OIDs. Otherwise, returns
+ InvalidOid .
Oid PQoidValue(const PGresult *res);
-PQoidStatus
+
PQoidStatus <indexterm>PQoidStatus>>< /term>
Returns a string with the OID of the inserted row, if the
Escaping Strings for Inclusion in SQL Commands
Escaping Binary Strings for Inclusion in SQL Commands
+
-
escaping binary strings
+ in libpq>
- PQescapeBytea
+
PQescapeBytea <indexterm>PQescapeBytea>>< /term>
Escapes binary data for use within an SQL command with the type
- PQunescapeBytea
+
PQunescapeBytea <indexterm>PQunescapeBytea>>< /term>
Converts an escaped string representation of binary data into binary
- PQfreemem
+
PQfreemem <indexterm>PQfreemem>>< /term>
Frees memory allocated by
libpq>.
-PQsendQuery
+
PQsendQuery <indexterm>PQsendQuery>>< /term>
Submits a command to the server without
- waiting for the result(s). 1 is returned if the command was
- successfully dispatched and 0 if not (in which case, use
- PQerrorMessage> to get more information about the failure).
+ waiting for the result(s). 1 is returned if the command was
+ successfully dispatched and 0 if not (in which case, use
+ PQerrorMessage> to get more information about the failure).
int PQsendQuery(PGconn *conn, const char *command);
- After successfully calling PQsendQuery , call
+ After successfully calling PQsendQuery , call
PQgetResult one or more
- times to obtain the results. PQsendQuery may not be called
- again (on the same connection) until PQgetResult has returned a null pointer,
- indicating that the command is done.
+ times to obtain the results. PQsendQuery may not be called
+ again (on the same connection) until PQgetResult has returned a null pointer,
+ indicating that the command is done.
-PQsendQueryParams
+
PQsendQueryParams <indexterm>PQsendQueryParams>>< /term>
Submits a command and separate parameters to the server without
- waiting for the result(s).
+ waiting for the result(s).
int PQsendQueryParams(PGconn *conn,
const char *command,
int resultFormat);
- This is equivalent to PQsendQuery except that
- query parameters can be specified separately from the query string.
- The function's parameters are handled identically to
- PQexecParams . Like
- PQexecParams , it will not work on 2.0-protocol
- connections, and it allows only one command in the query string.
+ This is equivalent to PQsendQuery except that
+ query parameters can be specified separately from the query string.
+ The function's parameters are handled identically to
+ PQexecParams . Like
+ PQexecParams , it will not work on 2.0-protocol
+ connections, and it allows only one command in the query string.
-PQsendQueryPrepared
+
PQsendQueryPrepared <indexterm>PQsendQueryPrepared>>< /term>
Sends a request to execute a prepared statement with given
- parameters, without waiting for the result(s).
+ parameters, without waiting for the result(s).
int PQsendQueryPrepared(PGconn *conn,
const char *stmtName,
int resultFormat);
- This is similar to PQsendQueryParams , but the
- command to be executed is specified by naming a previously-prepared
- statement, instead of giving a query string.
- The function's parameters are handled identically to
- PQexecPrepared . Like
- PQexecPrepared , it will not work on 2.0-protocol
- connections.
+ This is similar to PQsendQueryParams , but the
+ command to be executed is specified by naming a previously-prepared
+ statement, instead of giving a query string.
+ The function's parameters are handled identically to
+ PQexecPrepared . Like
+ PQexecPrepared , it will not work on 2.0-protocol
+ connections.
-PQgetResult
+
PQgetResult <indexterm>PQgetResult>>< /term>
Waits for the next result from a prior
- PQsendQuery ,
- PQsendQueryParams , or
- PQsendQueryPrepared call,
- and returns it. A null pointer is returned when the command is complete
- and there will be no more results.
+ PQsendQuery ,
+ PQsendQueryParams , or
+ PQsendQueryPrepared call,
+ and returns it. A null pointer is returned when the command is complete
+ and there will be no more results.
PGresult *PQgetResult(PGconn *conn);
- PQgetResult must be called repeatedly until it returns a null pointer,
- indicating that the command is done. (If called when no command is
- active, PQgetResult will just return a null pointer at once.)
- Each non-null result from PQgetResult should be processed using
- the same PGresult> accessor functions previously described.
- Don't forget to free each result object with PQclear when done with it.
- Note that PQgetResult will block only if a command is active and the
- necessary response data has not yet been read by PQconsumeInput .
+ PQgetResult must be called repeatedly until it returns a null pointer,
+ indicating that the command is done. (If called when no command is
+ active, PQgetResult will just return a null pointer at once.)
+ Each non-null result from PQgetResult should be processed using
+ the same PGresult> accessor functions previously described.
+ Don't forget to free each result object with PQclear when done with it.
+ Note that PQgetResult will block only if a command is active and the
+ necessary response data has not yet been read by PQconsumeInput .
-PQconsumeInput
+
PQconsumeInput <indexterm>PQconsumeInput>>< /term>
- If input is available from the server, consume it.
+ If input is available from the server, consume it.
int PQconsumeInput(PGconn *conn);
-PQisBusy
+
PQisBusy <indexterm>PQisBusy>>< /term>
Returns 1 if a command is busy, that is, PQgetResult would block
-A client that uses PQsendQuery /PQgetResult
-can also attempt to cancel a command that is still being processed by the server.
+A client that uses
+PQsendQuery /PQgetResult can
+also attempt to cancel a command that is still being processed by the
+server.
canceling>SQL command>>
-PQrequestCancel
+
PQrequestCancel <indexterm>PQrequestCancel>>< /term>
- Requests that the server abandon
- processing of the current command.
+ Requests that the server abandon
+ processing of the current command.
int PQrequestCancel(PGconn *conn);
- PQsetnonblocking
+
PQsetnonblocking <indexterm>PQsetnonblocking>>< /term>
Sets the nonblocking status of the connection.
-PQisnonblocking
+
PQisnonblocking <indexterm>PQisnonblocking>>< /term>
Returns the blocking status of the database connection.
-PQflush
+
PQflush <indexterm>PQflush>>< /term>
Attempts to flush any queued output data to the server.
The Fast-Path Interface
+
PostgreSQL provides a fast-path interface to send
simple function calls to the server.
-The function PQfn requests execution of a server
-function via the fast-path interface:
+requests execution of a server function via the fast-path interface:
PGresult* PQfn(PGconn* conn,
int fnid,
Asynchronous Notification
+
+ in libpq
+
PostgreSQL offers asynchronous notification via the
-
libpq applications submit
LISTEN and
UNLISTEN
-commands as ordinary SQL commands. The arrival of NOTIFY
-messages can subsequently be detected by calling PQnotifies .
+
libpq applications submit
+LISTEN and UNLISTEN commands as
+ordinary SQL commands. The arrival of NOTIFY
+messages can subsequently be detected by calling
returns the next notification from a list of unhandled
notification messages received from the server. It returns a null pointer if
there are no pending notifications. Once a notification is
- returned from PQnotifies>, it is considered handled and will be
- removed from the list of notifications.
+ returned from PQnotifies>, it is considered handled and will be
+ removed from the list of notifications.
PGnotify* PQnotifies(PGconn *conn);
-PQnfields
+
PQnfields <indexterm>PQnfields>with COPY>>< /term>
Returns the number of columns (fields) to be copied.
-PQbinaryTuples
+
PQbinaryTuples <indexterm>PQbinaryTuples>with COPY>>< /term>
0 indicates the overall copy format is textual (rows
- separated by newlines, columns separated by separator
- characters, etc).
- 1 indicates the overall copy format is binary.
- See
- for more information.
+ separated by newlines, columns separated by separator
+ characters, etc).
+ 1 indicates the overall copy format is binary.
+ See
+ for more information.
-PQfformat
+
PQfformat <indexterm>PQfformat>with COPY>>< /term>
Returns the format code (0 for text, 1 for binary) associated
- with each column of the copy operation. The per-column format
- codes will always be zero when the overall copy format is textual,
- but the binary format can support both text and binary columns.
- (However, as of the current implementation of COPY>,
- only binary columns appear in a binary copy; so the per-column
- formats always match the overall format at present.)
+ with each column of the copy operation. The per-column format
+ codes will always be zero when the overall copy format is textual,
+ but the binary format can support both text and binary columns.
+ (However, as of the current implementation of COPY>,
+ only binary columns appear in a binary copy; so the per-column
+ formats always match the overall format at present.)
-PQputCopyData
+
PQputCopyData <indexterm>PQputCopyData>>< /term>
Sends data to the server during COPY_IN> state.
-PQputCopyEnd
+
PQputCopyEnd <indexterm>PQputCopyEnd>>< /term>
Sends end-of-data indication to the server during COPY_IN> state.
-PQgetCopyData
+
PQgetCopyData <indexterm>PQgetCopyData>>< /term>
Receives data from the server during COPY_OUT> state.
-PQgetline
+
PQgetline <indexterm>PQgetline>>< /term>
Reads a newline-terminated line of characters
-PQgetlineAsync
+
PQgetlineAsync <indexterm>PQgetlineAsync>>< /term>
Reads a row of COPY data
-PQputline
+
PQputline <indexterm>PQputline>>< /term>
Sends a null-terminated string to the server.
-PQputnbytes
+
PQputnbytes <indexterm>PQputnbytes>>< /term>
Sends a non-null-terminated string to the server.
-PQendcopy
+
PQendcopy <indexterm>PQendcopy>>< /term>
Synchronizes with the server.
-PQsetErrorVerbosity
+
PQsetErrorVerbosity <indexterm>PQsetErrorVerbosity>>< /term>
Determines the verbosity of messages returned by
-PQtrace
+
PQtrace <indexterm>PQtrace>>< /term>
Enables tracing of the client/server communication to a debugging file stream.
-PQuntrace
+
PQuntrace <indexterm>PQuntrace>>< /term>
Disables tracing started by PQtrace .
Notice Processing
+
+ in libpq
+
+
Notice and warning messages generated by the server are not returned by the
query execution functions, since they do not imply failure of the query.
The function PQsetNoticeReceiver
+
notice receiver>>PQsetNoticeReceiver>>
sets or examines the current notice receiver for a connection object.
Similarly, PQsetNoticeProcessor
+
notice processor>>PQsetNoticeProcessor>>
sets or examines the current notice processor.
Environment Variables
-
libpq applications that use the
crypt
-authentication method rely on the crypt() operating
-system function, which is often not thread-safe. It is better to use the
-md5 method, which is thread-safe on all
-platforms.
+
libpq applications that use the
+crypt authentication method rely on the
+crypt() operating system function, which is often
+not thread-safe.
crypt>thread
+safety>> It is better to use the md5 method,
+which is thread-safe on all platforms.
+
+ libpq applications
+
+
To build (i.e., compile and link) your
libpq programs you need to
do all of the following things:
If there is any chance that your program might be compiled by
other users then you should not hardcode the directory location
like that. Instead, you can run the utility
- pg_config to find out where the header files
- are on the local system:
+
pg_config pg_config>
+ sortas="libpq">with libpq>> to find out where the header
+ files are on the local system:
/usr/local/include
/*
* testlibpq.c
*
- * Test the C version of LIBPQ, the POSTGRES frontend library.
+ * Test the C version of LIBPQ, the POSTGRES frontend library.
*/
#include <stdio.h>
#include <stdlib.h>
static void
exit_nicely(PGconn *conn)
{
- PQfinish(conn);
- exit(1);
+ PQfinish(conn);
+ exit(1);
}
int
main(int argc, char **argv)
{
- const char *conninfo;
- PGconn *conn;
- PGresult *res;
- int nFields;
- int i,
- j;
-
- /*
- * If the user supplies a parameter on the command line, use it as
- * the conninfo string; otherwise default to setting dbname=template1
- * and using environment variables or defaults for all other connection
- * parameters.
- */
- if (argc > 1)
- conninfo = argv[1];
- else
- conninfo = "dbname = template1";
-
- /* Make a connection to the database */
- conn = PQconnectdb(conninfo);
-
- /* Check to see that the backend connection was successfully made */
- if (PQstatus(conn) != CONNECTION_OK)
- {
- fprintf(stderr, "Connection to database '%s' failed.\n", PQdb(conn));
- fprintf(stderr, "%s", PQerrorMessage(conn));
- exit_nicely(conn);
- }
-
- /*
- * Our test case here involves using a cursor, for which we must be
- * inside a transaction block. We could do the whole thing with a
- * single PQexec() of "select * from pg_database", but that's too
- * trivial to make a good example.
- */
-
- /* Start a transaction block */
- res = PQexec(conn, "BEGIN");
- if (PQresultStatus(res) != PGRES_COMMAND_OK)
- {
- fprintf(stderr, "BEGIN command failed: %s", PQerrorMessage(conn));
- PQclear(res);
- exit_nicely(conn);
- }
-
- /*
- * Should PQclear PGresult whenever it is no longer needed to avoid
- * memory leaks
- */
- PQclear(res);
-
- /*
- * Fetch rows from pg_database, the system catalog of databases
- */
- res = PQexec(conn, "DECLARE myportal CURSOR FOR select * from pg_database");
- if (PQresultStatus(res) != PGRES_COMMAND_OK)
- {
- fprintf(stderr, "DECLARE CURSOR failed: %s", PQerrorMessage(conn));
- PQclear(res);
- exit_nicely(conn);
- }
- PQclear(res);
-
- res = PQexec(conn, "FETCH ALL in myportal");
- if (PQresultStatus(res) != PGRES_TUPLES_OK)
- {
- fprintf(stderr, "FETCH ALL failed: %s", PQerrorMessage(conn));
- PQclear(res);
- exit_nicely(conn);
- }
-
- /* first, print out the attribute names */
- nFields = PQnfields(res);
- for (i = 0; i < nFields; i++)
- printf("%-15s", PQfname(res, i));
- printf("\n\n");
-
- /* next, print out the rows */
- for (i = 0; i < PQntuples(res); i++)
- {
- for (j = 0; j < nFields; j++)
- printf("%-15s", PQgetvalue(res, i, j));
- printf("\n");
- }
-
- PQclear(res);
-
- /* close the portal ... we don't bother to check for errors ... */
- res = PQexec(conn, "CLOSE myportal");
- PQclear(res);
-
- /* end the transaction */
- res = PQexec(conn, "END");
- PQclear(res);
-
- /* close the connection to the database and cleanup */
- PQfinish(conn);
-
- return 0;
+ const char *conninfo;
+ PGconn *conn;
+ PGresult *res;
+ int nFields;
+ int i,
+ j;
+
+ /*
+ * If the user supplies a parameter on the command line, use it as
+ * the conninfo string; otherwise default to setting dbname=template1
+ * and using environment variables or defaults for all other connection
+ * parameters.
+ */
+ if (argc > 1)
+ conninfo = argv[1];
+ else
+ conninfo = "dbname = template1";
+
+ /* Make a connection to the database */
+ conn = PQconnectdb(conninfo);
+
+ /* Check to see that the backend connection was successfully made */
+ if (PQstatus(conn) != CONNECTION_OK)
+ {
+ fprintf(stderr, "Connection to database '%s' failed.\n", PQdb(conn));
+ fprintf(stderr, "%s", PQerrorMessage(conn));
+ exit_nicely(conn);
+ }
+
+ /*
+ * Our test case here involves using a cursor, for which we must be
+ * inside a transaction block. We could do the whole thing with a
+ * single PQexec() of "select * from pg_database", but that's too
+ * trivial to make a good example.
+ */
+
+ /* Start a transaction block */
+ res = PQexec(conn, "BEGIN");
+ if (PQresultStatus(res) != PGRES_COMMAND_OK)
+ {
+ fprintf(stderr, "BEGIN command failed: %s", PQerrorMessage(conn));
+ PQclear(res);
+ exit_nicely(conn);
+ }
+
+ /*
+ * Should PQclear PGresult whenever it is no longer needed to avoid
+ * memory leaks
+ */
+ PQclear(res);
+
+ /*
+ * Fetch rows from pg_database, the system catalog of databases
+ */
+ res = PQexec(conn, "DECLARE myportal CURSOR FOR select * from pg_database");
+ if (PQresultStatus(res) != PGRES_COMMAND_OK)
+ {
+ fprintf(stderr, "DECLARE CURSOR failed: %s", PQerrorMessage(conn));
+ PQclear(res);
+ exit_nicely(conn);
+ }
+ PQclear(res);
+
+ res = PQexec(conn, "FETCH ALL in myportal");
+ if (PQresultStatus(res) != PGRES_TUPLES_OK)
+ {
+ fprintf(stderr, "FETCH ALL failed: %s", PQerrorMessage(conn));
+ PQclear(res);
+ exit_nicely(conn);
+ }
+
+ /* first, print out the attribute names */
+ nFields = PQnfields(res);
+ for (i = 0; i < nFields; i++)
+ printf("%-15s", PQfname(res, i));
+ printf("\n\n");
+
+ /* next, print out the rows */
+ for (i = 0; i < PQntuples(res); i++)
+ {
+ for (j = 0; j < nFields; j++)
+ printf("%-15s", PQgetvalue(res, i, j));
+ printf("\n");
+ }
+
+ PQclear(res);
+
+ /* close the portal ... we don't bother to check for errors ... */
+ res = PQexec(conn, "CLOSE myportal");
+ PQclear(res);
+
+ /* end the transaction */
+ res = PQexec(conn, "END");
+ PQclear(res);
+
+ /* close the connection to the database and cleanup */
+ PQfinish(conn);
+
+ return 0;
}
/*
* testlibpq2.c
- * Test of the asynchronous notification interface
+ * Test of the asynchronous notification interface
*
* Start this program, then from psql in another window do
* NOTIFY TBL2;
static void
exit_nicely(PGconn *conn)
{
- PQfinish(conn);
- exit(1);
+ PQfinish(conn);
+ exit(1);
}
int
main(int argc, char **argv)
{
- const char *conninfo;
- PGconn *conn;
- PGresult *res;
- PGnotify *notify;
- int nnotifies;
-
- /*
- * If the user supplies a parameter on the command line, use it as
- * the conninfo string; otherwise default to setting dbname=template1
- * and using environment variables or defaults for all other connection
- * parameters.
- */
- if (argc > 1)
- conninfo = argv[1];
- else
- conninfo = "dbname = template1";
-
- /* Make a connection to the database */
- conn = PQconnectdb(conninfo);
-
- /* Check to see that the backend connection was successfully made */
- if (PQstatus(conn) != CONNECTION_OK)
- {
- fprintf(stderr, "Connection to database '%s' failed.\n", PQdb(conn));
- fprintf(stderr, "%s", PQerrorMessage(conn));
- exit_nicely(conn);
- }
-
- /*
- * Issue LISTEN command to enable notifications from the rule's NOTIFY.
- */
- res = PQexec(conn, "LISTEN TBL2");
- if (PQresultStatus(res) != PGRES_COMMAND_OK)
- {
- fprintf(stderr, "LISTEN command failed: %s", PQerrorMessage(conn));
- PQclear(res);
- exit_nicely(conn);
- }
-
- /*
- * should PQclear PGresult whenever it is no longer needed to avoid
- * memory leaks
- */
- PQclear(res);
-
- /* Quit after four notifies are received. */
- nnotifies = 0;
- while (nnotifies < 4)
- {
- /*
- * Sleep until something happens on the connection. We use select(2)
- * to wait for input, but you could also use poll() or similar
- * facilities.
- */
- int sock;
- fd_set input_mask;
-
- sock = PQsocket(conn);
-
- if (sock < 0)
- break; /* shouldn't happen */
-
- FD_ZERO(&input_mask);
- FD_SET(sock, &input_mask);
-
- if (select(sock + 1, &input_mask, NULL, NULL, NULL) < 0)
- {
- fprintf(stderr, "select() failed: %s\n", strerror(errno));
- exit_nicely(conn);
- }
-
- /* Now check for input */
- PQconsumeInput(conn);
- while ((notify = PQnotifies(conn)) != NULL)
- {
- fprintf(stderr,
- "ASYNC NOTIFY of '%s' received from backend pid %d\n",
- notify->relname, notify->be_pid);
- PQfreemem(notify);
- nnotifies++;
- }
- }
-
- fprintf(stderr, "Done.\n");
-
- /* close the connection to the database and cleanup */
- PQfinish(conn);
-
- return 0;
+ const char *conninfo;
+ PGconn *conn;
+ PGresult *res;
+ PGnotify *notify;
+ int nnotifies;
+
+ /*
+ * If the user supplies a parameter on the command line, use it as
+ * the conninfo string; otherwise default to setting dbname=template1
+ * and using environment variables or defaults for all other connection
+ * parameters.
+ */
+ if (argc > 1)
+ conninfo = argv[1];
+ else
+ conninfo = "dbname = template1";
+
+ /* Make a connection to the database */
+ conn = PQconnectdb(conninfo);
+
+ /* Check to see that the backend connection was successfully made */
+ if (PQstatus(conn) != CONNECTION_OK)
+ {
+ fprintf(stderr, "Connection to database '%s' failed.\n", PQdb(conn));
+ fprintf(stderr, "%s", PQerrorMessage(conn));
+ exit_nicely(conn);
+ }
+
+ /*
+ * Issue LISTEN command to enable notifications from the rule's NOTIFY.
+ */
+ res = PQexec(conn, "LISTEN TBL2");
+ if (PQresultStatus(res) != PGRES_COMMAND_OK)
+ {
+ fprintf(stderr, "LISTEN command failed: %s", PQerrorMessage(conn));
+ PQclear(res);
+ exit_nicely(conn);
+ }
+
+ /*
+ * should PQclear PGresult whenever it is no longer needed to avoid
+ * memory leaks
+ */
+ PQclear(res);
+
+ /* Quit after four notifies are received. */
+ nnotifies = 0;
+ while (nnotifies < 4)
+ {
+ /*
+ * Sleep until something happens on the connection. We use select(2)
+ * to wait for input, but you could also use poll() or similar
+ * facilities.
+ */
+ int sock;
+ fd_set input_mask;
+
+ sock = PQsocket(conn);
+
+ if (sock < 0)
+ break; /* shouldn't happen */
+
+ FD_ZERO(&input_mask);
+ FD_SET(sock, &input_mask);
+
+ if (select(sock + 1, &input_mask, NULL, NULL, NULL) < 0)
+ {
+ fprintf(stderr, "select() failed: %s\n", strerror(errno));
+ exit_nicely(conn);
+ }
+
+ /* Now check for input */
+ PQconsumeInput(conn);
+ while ((notify = PQnotifies(conn)) != NULL)
+ {
+ fprintf(stderr,
+ "ASYNC NOTIFY of '%s' received from backend pid %d\n",
+ notify->relname, notify->be_pid);
+ PQfreemem(notify);
+ nnotifies++;
+ }
+ }
+
+ fprintf(stderr, "Done.\n");
+
+ /* close the connection to the database and cleanup */
+ PQfinish(conn);
+
+ return 0;
}
/*
* testlibpq3.c
- * Test out-of-line parameters and binary I/O.
+ * Test out-of-line parameters and binary I/O.
*
* Before running this, populate a database with the following commands
* (provided in src/test/examples/testlibpq3.sql):
static void
exit_nicely(PGconn *conn)
{
- PQfinish(conn);
- exit(1);
+ PQfinish(conn);
+ exit(1);
}
int
main(int argc, char **argv)
{
- const char *conninfo;
- PGconn *conn;
- PGresult *res;
- const char *paramValues[1];
- int i,
- j;
- int i_fnum,
- t_fnum,
- b_fnum;
-
- /*
- * If the user supplies a parameter on the command line, use it as
- * the conninfo string; otherwise default to setting dbname=template1
- * and using environment variables or defaults for all other connection
- * parameters.
- */
- if (argc > 1)
- conninfo = argv[1];
- else
- conninfo = "dbname = template1";
-
- /* Make a connection to the database */
- conn = PQconnectdb(conninfo);
-
- /* Check to see that the backend connection was successfully made */
- if (PQstatus(conn) != CONNECTION_OK)
- {
- fprintf(stderr, "Connection to database '%s' failed.\n", PQdb(conn));
- fprintf(stderr, "%s", PQerrorMessage(conn));
- exit_nicely(conn);
- }
-
- /*
- * The point of this program is to illustrate use of PQexecParams()
- * with out-of-line parameters, as well as binary transmission of
- * results. By using out-of-line parameters we can avoid a lot of
- * tedious mucking about with quoting and escaping. Notice how we
- * don't have to do anything special with the quote mark in the
- * parameter value.
- */
-
- /* Here is our out-of-line parameter value */
- paramValues[0] = "joe's place";
-
- res = PQexecParams(conn,
- "SELECT * FROM test1 WHERE t = $1",
- 1, /* one param */
- NULL, /* let the backend deduce param type */
- paramValues,
- NULL, /* don't need param lengths since text */
- NULL, /* default to all text params */
- 1); /* ask for binary results */
-
- if (PQresultStatus(res) != PGRES_TUPLES_OK)
- {
- fprintf(stderr, "SELECT failed: %s", PQerrorMessage(conn));
- PQclear(res);
- exit_nicely(conn);
- }
-
- /* Use PQfnumber to avoid assumptions about field order in result */
- i_fnum = PQfnumber(res, "i");
- t_fnum = PQfnumber(res, "t");
- b_fnum = PQfnumber(res, "b");
-
- for (i = 0; i < PQntuples(res); i++)
- {
- char *iptr;
- char *tptr;
- char *bptr;
- int blen;
- int ival;
-
- /* Get the field values (we ignore possibility they are null!) */
- iptr = PQgetvalue(res, i, i_fnum);
- tptr = PQgetvalue(res, i, t_fnum);
- bptr = PQgetvalue(res, i, b_fnum);
-
- /*
- * The binary representation of INT4 is in network byte order,
- * which we'd better coerce to the local byte order.
- */
- ival = ntohl(*((uint32_t *) iptr));
-
- /*
- * The binary representation of TEXT is, well, text, and since
- * libpq was nice enough to append a zero byte to it, it'll work
- * just fine as a C string.
- *
- * The binary representation of BYTEA is a bunch of bytes, which
- * could include embedded nulls so we have to pay attention to
- * field length.
- */
- blen = PQgetlength(res, i, b_fnum);
-
- printf("tuple %d: got\n", i);
- printf(" i = (%d bytes) %d\n",
- PQgetlength(res, i, i_fnum), ival);
- printf(" t = (%d bytes) '%s'\n",
- PQgetlength(res, i, t_fnum), tptr);
- printf(" b = (%d bytes) ", blen);
- for (j = 0; j < blen; j++)
- printf("\\%03o", bptr[j]);
- printf("\n\n");
- }
-
- PQclear(res);
-
- /* close the connection to the database and cleanup */
- PQfinish(conn);
-
- return 0;
+ const char *conninfo;
+ PGconn *conn;
+ PGresult *res;
+ const char *paramValues[1];
+ int i,
+ j;
+ int i_fnum,
+ t_fnum,
+ b_fnum;
+
+ /*
+ * If the user supplies a parameter on the command line, use it as
+ * the conninfo string; otherwise default to setting dbname=template1
+ * and using environment variables or defaults for all other connection
+ * parameters.
+ */
+ if (argc > 1)
+ conninfo = argv[1];
+ else
+ conninfo = "dbname = template1";
+
+ /* Make a connection to the database */
+ conn = PQconnectdb(conninfo);
+
+ /* Check to see that the backend connection was successfully made */
+ if (PQstatus(conn) != CONNECTION_OK)
+ {
+ fprintf(stderr, "Connection to database '%s' failed.\n", PQdb(conn));
+ fprintf(stderr, "%s", PQerrorMessage(conn));
+ exit_nicely(conn);
+ }
+
+ /*
+ * The point of this program is to illustrate use of PQexecParams()
+ * with out-of-line parameters, as well as binary transmission of
+ * results. By using out-of-line parameters we can avoid a lot of
+ * tedious mucking about with quoting and escaping. Notice how we
+ * don't have to do anything special with the quote mark in the
+ * parameter value.
+ */
+
+ /* Here is our out-of-line parameter value */
+ paramValues[0] = "joe's place";
+
+ res = PQexecParams(conn,
+ "SELECT * FROM test1 WHERE t = $1",
+ 1, /* one param */
+ NULL, /* let the backend deduce param type */
+ paramValues,
+ NULL, /* don't need param lengths since text */
+ NULL, /* default to all text params */
+ 1); /* ask for binary results */
+
+ if (PQresultStatus(res) != PGRES_TUPLES_OK)
+ {
+ fprintf(stderr, "SELECT failed: %s", PQerrorMessage(conn));
+ PQclear(res);
+ exit_nicely(conn);
+ }
+
+ /* Use PQfnumber to avoid assumptions about field order in result */
+ i_fnum = PQfnumber(res, "i");
+ t_fnum = PQfnumber(res, "t");
+ b_fnum = PQfnumber(res, "b");
+
+ for (i = 0; i < PQntuples(res); i++)
+ {
+ char *iptr;
+ char *tptr;
+ char *bptr;
+ int blen;
+ int ival;
+
+ /* Get the field values (we ignore possibility they are null!) */
+ iptr = PQgetvalue(res, i, i_fnum);
+ tptr = PQgetvalue(res, i, t_fnum);
+ bptr = PQgetvalue(res, i, b_fnum);
+
+ /*
+ * The binary representation of INT4 is in network byte order,
+ * which we'd better coerce to the local byte order.
+ */
+ ival = ntohl(*((uint32_t *) iptr));
+
+ /*
+ * The binary representation of TEXT is, well, text, and since
+ * libpq was nice enough to append a zero byte to it, it'll work
+ * just fine as a C string.
+ *
+ * The binary representation of BYTEA is a bunch of bytes, which
+ * could include embedded nulls so we have to pay attention to
+ * field length.
+ */
+ blen = PQgetlength(res, i, b_fnum);
+
+ printf("tuple %d: got\n", i);
+ printf(" i = (%d bytes) %d\n",
+ PQgetlength(res, i, i_fnum), ival);
+ printf(" t = (%d bytes) '%s'\n",
+ PQgetlength(res, i, t_fnum), tptr);
+ printf(" b = (%d bytes) ", blen);
+ for (j = 0; j < blen; j++)
+ printf("\\%03o", bptr[j]);
+ printf("\n\n");
+ }
+
+ PQclear(res);
+
+ /* close the connection to the database and cleanup */
+ PQfinish(conn);
+
+ return 0;
}
Oid lo_creat(PGconn *conn, int mode);
creates a new large object.
mode is a bit mask
describing several different attributes of the new
Oid lo_import(PGconn *conn, const char *filename);
- filename
+ filename
specifies the operating system name of
the file to be imported as a large object.
The return value is the OID that was assigned to the new large object.
int lo_export(PGconn *conn, Oid lobjId, const char *filename);
The
lobjId argument specifies the OID of the large
object to export and the
filename argument specifies
the operating system name name of the file.
int lo_open(PGconn *conn, Oid lobjId, int mode);
The
lobjId argument specifies the OID of the large
object to open. The
mode bits control whether the
object is opened for reading (INV_READ>), writing (INV_WRITE ), or
int lo_write(PGconn *conn, int fd, const char *buf, size_t len);
- writes
len bytes from
buf to large object
fd>. The fd
- argument must have been returned by a previous lo_open .
- The number of bytes actually written is returned. In
- the event of an error, the return value is negative.
+ to large object
fd>. The fd
+ argument must have been returned by a previous
+ lo_open . The number of bytes actually
+ written is returned. In the event of an error, the return value
+ is negative.
int lo_read(PGconn *conn, int fd, char *buf, size_t len);
- reads
len bytes from large object
fd into
buf . The
fd
- argument must have been returned by a previous lo_open .
- The number of bytes actually read is returned. In
- the event of an error, the return value is negative.
+
len bytes from large object
+
fd argument must have been returned by a
+ previous lo_open . The number of bytes
+ actually read is returned. In the event of an error, the return
+ value is negative.
int lo_lseek(PGconn *conn, int fd, int offset, int whence);
- This function moves the current location pointer for the
- large object described by
fd> to the new location specified
- by
offset>. The valid values for whence> are
- SEEK_SET> (seek from object start), SEEK_CUR> (seek from current position), and SEEK_END> (seek from object end). The return value is the new location pointer.
+
lo_lseek>> This function moves the
+ current location pointer for the large object described by
+
fd> to the new location specified by
+
offset>. The valid values for whence>
+ are SEEK_SET> (seek from object start),
+ SEEK_CUR> (seek from current position), and
+ SEEK_END> (seek from object end). The return value is
+ the new location pointer.
int lo_tell(PGconn *conn, int fd);
- If there is an error, the return value is negative.
+
lo_tell>> If there is an error, the
+ return value is negative.
int lo_close(PGconn *conn, int fd);
- where
fd> is a large object descriptor returned by
- lo_open . On success, lo_close
- returns zero. On error, the return value is negative.
+
lo_close>> where fd> is a
+ large object descriptor returned by lo_open .
+ On success, lo_close returns zero. On
+ error, the return value is negative.
int lo_unlink(PGconn *conn, Oid lobjId);
- The
lobjId argument specifies the OID of the large
- object to remove. In the event of an error, the return value is negative.
+
lobjId argument specifies the OID of the
+ large object to remove. In the event of an error, the return
+ value is negative.
Server-side Functions
- There are two built-in server-side functions, lo_import
- and lo_export , for large object access, which are available for use
- commands.
- Here is an example of their use:
+ There are two built-in server-side functions,
+ and
+ for large object access, which are available for use in
+
SQL commands. Here is an example of their
+ use:
CREATE TABLE image (
name text,
Routine Database Maintenance Tasks
+
+
+
There are a few routine maintenance chores that must be performed on
a regular basis to keep a
PostgreSQL
Updating planner statistics
+
+ of the planner
+
+
+
+
+
The
PostgreSQL query planner relies on
statistical information about the contents of tables in order to
Log File Maintenance
+ log file maintenance
Overview
+
+
+
A database is a named collection of
SQL objects
(database objects
). Generally, every database
- Databases are created with the SQL command
- CREATE DATABASE :
+ Databases are created with the SQL command CREATE
+ DATABASE:
CREATE DATABASE>>
CREATE DATABASE name>;
question remains how the first> database at any given
site can be created. The first database is always created by the
initdb> command when the data storage area is
- initialized. (See .)
- This database is called template1>. So to create the
- first real> database you can connect to
+ initialized. (See .) This
+ database is called
+
template1>.template1>> So to
+ create the first real> database you can connect to
template1>.
As an extra convenience, there is also a program that you can
execute from the shell to create new databases,
- createdb>.
createdb dbname
CREATE DATABASE> actually works by copying an existing
database. By default, it copies the standard system database named
- template1>. Thus that database is the template>
- from which new databases are made. If you add objects to
- template1>, these objects
+
template1>.template1>> Thus that
+ database is the template> from which new databases are
+ made. If you add objects to template1>, these objects
will be copied into subsequently created user databases. This
behavior allows site-local modifications to the standard set of
objects in databases. For example, if you install the procedural
language
PL/pgSQL> in template1>, it will
- automatically be available in user databases without any extra action
- being taken when those databases are made.
+ automatically be available in user databases without any extra
+ action being taken when those databases are made.
- There is a second standard system database named template0>.
- This database contains the same data as the initial contents of
- template1>, that is, only the standard objects predefined by
- your version of
PostgreSQL .
- template0> should never be changed
- after initdb>. By instructing CREATE DATABASE> to
- copy template0> instead of template1>, you can
- create a virgin> user database that contains none of the
- site-local additions in template1>. This is particularly
- handy when restoring a pg_dump> dump: the dump script should
- be restored in a virgin database to ensure that one recreates the
- correct contents of the dumped database, without any conflicts with
- additions that may now be present in template1>.
+ There is a second standard system database named
+
template0>.template0>> This
+ database contains the same data as the initial contents of
+ template1>, that is, only the standard objects
+ predefined by your version of
+ should never be changed after initdb>. By instructing
+ CREATE DATABASE> to copy template0> instead
+ of template1>, you can create a virgin> user
+ database that contains none of the site-local additions in
+ template1>. This is particularly handy when restoring a
+ pg_dump> dump: the dump script should be restored in a
+ virgin database to ensure that one recreates the correct contents
+ of the dumped database, without any conflicts with additions that
+ may now be present in template1>.
- Two useful flags exist in pg_database for each
+ Two useful flags exist in
pg_database pg_database>> for each
database: the columns datistemplate and
datallowconn . datistemplate
may be set to indicate that a database is intended as a template for
Destroying a Database
- Databases are destroyed with the command DROP DATABASE :
+ Databases are destroyed with the command DROP
+ DATABASE:
DROP DATABASE>>
DROP DATABASE name>;
- For convenience, there is also a shell program to drop databases:
+ For convenience, there is also a shell program to drop
dropdb dbname
Monitoring Database Activity
+
+ database activity
+
+
+
+ monitoring
+
+
A database administrator frequently wonders, What is the system
doing right now?
Viewing Locks
+
+ monitoring
+
+
Another useful tool for monitoring database activity is the
pg_locks system table. It allows the
Introduction
+
+
+
Unlike traditional database systems which use locks for concurrency control,
Transaction Isolation
+
+
+
The
SQL standard defines four levels of
transaction isolation in terms of three phenomena that must be
+
transaction isolation level
The four transaction isolation levels and the corresponding
behaviors are described in .
Read Committed Isolation Level
+
transaction isolation level
read committed
Serializable Isolation Level
+
transaction isolation level
serializable
Explicit Locking
Table-Level Locks
+
+
+
The list below shows the available lock modes and the contexts in
which they are used automatically by
Deadlocks
+
+
+
The use of explicit locking can increase the likelyhood of
deadlocks>, wherein two (or more) transactions each
Locking and Indexes
+
+ locks
+
+
provides nonblocking read/write access to table
Using EXPLAIN
+
+
+
+
+
+
PostgreSQL devises a
query
plan for each query it is given. Choosing the right
Statistics Used by the Planner
+
+ of the planner
+
+
As we saw in the previous section, the query planner needs to estimate
the number of rows retrieved by a query in order to make good choices
since it does not read every row of the table.
+
+
+
Most queries retrieve only a fraction of the rows in a table, due
to having WHERE> clauses that restrict the rows to be examined.
and are always approximate even when freshly updated.
+
+
+
Rather than look at pg_statistic directly,
it's better to look at its view pg_stats
Controlling the Planner with Explicit JOIN> Clauses
+
+ controlling the order
+
+
It is possible
to control the query planner to some extent by using the explicit JOIN>
Disable Autocommit
+
+
+
Turn off autocommit and just do one commit at
the end. (In plain SQL, this means issuing BEGIN
- If an SQL null value is passed to a function, the argument value
- will appear as undefined> in Perl. The above function
- definition will not behave very nicely with null inputs (in fact,
- it will act as though they are zeroes). We could add
- STRICT> to the function definition to make
+ If an SQL null value
null value>
+ sortas="PL/Perl">in PL/Perl> is passed to a function,
+ the argument value will appear as undefined> in Perl. The
+ above function definition will not behave very nicely with null
+ inputs (in fact, it will act as though they are zeroes). We could
+ add STRICT> to the function definition to make
PostgreSQL do something more reasonable:
if a null value is passed, the function will not be called at all,
but will just return a null result automatically. Alternatively,
mirror sites). This module makes available a
DBI>-compliant database-handle named
$pg_dbh that can be used to perform queries
- with normal
DBI> syntax.
+ with normal
DBI> syntax.DBI>
- PL/Perl
+ in PL/Perl
elog> level , msg
Trusted and Untrusted PL/Perl
+
+ PL/Perl
+
+
Normally, PL/Perl is installed as a trusted> programming
language named plperl>. In this setup, certain Perl
Sometimes it is desirable to write Perl functions that are not
- restricted. For example, one might want a Perl function that
- sends mail. To handle these cases, PL/Perl can also be installed
- as an untrusted> language (usually called
-
PL/PerlU ). In this case the full Perl language is
- available. If the createlang program is used to
- install the language, the language name plperlu
- will select the untrusted PL/Perl variant.
+ restricted. For example, one might want a Perl function that sends
+ mail. To handle these cases, PL/Perl can also be installed as an
+ untrusted> language (usually called
+ In this case the full Perl language is available. If the
+ createlang program is used to install the
+ language, the language name plperlu will select
+ the untrusted PL/Perl variant.
- PL/Perl cannot be used to write trigger functions.
+ PL/Perl cannot be used to write trigger
+ PL/Perl>
- As each expression and
SQL command is first used
- in the function, the
PL/pgSQL> interpreter creates
- a prepared execution plan (using the
SPI
- manager's SPI_prepare and
- SPI_saveplan functions). Subsequent visits
- to that expression or command reuse the prepared plan. Thus, a
- function with conditional code that contains many statements for
- which execution plans might be required will only prepare and save
- those plans that are really used during the lifetime of the
- database connection. This can substantially reduce the total
- amount of time required to parse, and generate execution plans for the
- statements in a
PL/pgSQL> function. A disadvantage is
- that errors in a specific expression or command may not be detected
- until that part of the function is reached in execution.
+ As each expression and
SQL command is first
+ used in the function, the
PL/pgSQL> interpreter
+ creates a prepared execution plan (using the
+
SPI manager's
SPI_prepare
+ and SPI_saveplan
+ functions).
preparing a query>in
+ PL/pgSQL>> Subsequent visits to that expression or command
+ reuse the prepared plan. Thus, a function with conditional code
+ that contains many statements for which execution plans might be
+ required will only prepare and save those plans that are really
+ used during the lifetime of the database connection. This can
+ substantially reduce the total amount of time required to parse,
+ and generate execution plans for the statements in a
+
PL/pgSQL> function. A disadvantage is that errors
+ in a specific expression or command may not be detected until that
+ part of the function is reached in execution.
and return the polymorphic> types
anyelement and anyarray . The actual
datatypes handled by a polymorphic function can vary from call to
- call, as discussed in .
+ call, as discussed in extend-types-polymorphic">.
An example is shown in .
or anyarray ), a special parameter $0
is created. Its datatype is the actual return type of the function,
as deduced from the actual input types (see
- linkend="types-polymorphic">).
+ linkend="extend- types-polymorphic">).
This allows the function to access its actual return type
as shown in .
$0 is initialized to NULL and can be modified by
SELECT INTO
+
+ in PL/pgSQL
+
+
The result of a SELECT command yielding multiple columns (but
only one row) can be assigned to a record variable, row-type
This example shows use of the functions
quote_ident(text ) and
- quote_literal(text ) .
- Variables containing column and table identifiers should be
- passed to function quote_ident .
- Variables containing values that should be literal strings in the
- constructed command should be passed to
- quote_literal . Both take the
- appropriate steps to return the input text enclosed in double
- or single quotes respectively, with any embedded special characters
+
quote_literal(text ) .
quote_ident>use
+ in
+ PL/pgSQL>
quote_literal>use
+ in PL/pgSQL> Variables containing column and table
+ identifiers should be passed to function
+ quote_ident . Variables containing values
+ that should be literal strings in the constructed command should
+ be passed to quote_literal . Both take the
+ appropriate steps to return the input text enclosed in double or
+ single quotes respectively, with any embedded special characters
properly escaped.
Simple Loops
+
+ in PL/pgSQL
+
+
With the LOOP>, EXIT>, WHILE>,
and FOR> statements, you can arrange for your
Cursors
+
+ in PL/pgSQL
+
+
Rather than executing a whole query at once, it is possible to set
up a cursor> that encapsulates the query, and then read
Trigger Procedures
+
+ in PL/pgSQL
+
+
PL/pgSQL can be used to define trigger
procedures. A trigger procedure is created with the
+ porting from PL/SQL to PL/pgSQL
+ porting to PL/pgSQL
with OUT> parameters and string manipulation.
PostgreSQL> does not have an
instr function, but you can work around it
- using a combination of other functions. In
+ using a combination of other
+ functions.
instr> In
linkend="plpgsql-porting-appendix"> there is a
PL/pgSQL implementation of
instr that you can use to make your porting
-
+
PL/Python - Python Procedural Language
If you do not provide a return value, Python returns the default
- None . The
- language module translates Python's None into the
- SQL null value.
+ None . The language module translates Python's
+ None into the SQL null
+ value.
null value>
+ sortas="PL/Python">in PL/Python>
The global dictionary SD is available to store
data between function calls. This variable is private static data.
The global dictionary GD is public data,
- available to all Python functions within a session. Use with care.
+ available to all Python functions within a session. Use with
+ PL/Python>
Trigger Functions
+
+ in PL/Python
+
+
When a function is used in a trigger, the dictionary
TD contains trigger-related values. The trigger
plpy.error("msg") , and
plpy.fatal("msg") . They are mostly equivalent
to calling elog(LEVEL>, "msg")
- from C code. plpy.error and
+ PL/Python> plpy.error and
plpy.fatal actually raise a Python exception
which, if uncaught, causes the PL/Python module to call
elog(ERROR, msg) when the function handler
- The second function, plpy.prepare , prepares the
- execution plan for a query. It is called with a query string and a
- list of parameter types, if you have parameter references in the
- query. For example:
+
preparing a query>in PL/Python>
+ The second function, plpy.prepare , prepares
+ the execution plan for a query. It is called with a query string
+ and a list of parameter types, if you have parameter references in
+ the query. For example:
plan = plpy.prepare("SELECT last_name FROM my_users WHERE first_name = $1", [ "text" ])
-
Restricted Environment
--- >
+]] >
Global Data in PL/Tcl
+
+ in PL/Tcl
+
+
Sometimes it
is useful to have some global data that is held between two
spi_prepare query typelist
- Prepares and saves a query plan for later execution. The saved plan
- will be retained for the life of the current session.
+ Prepares and saves a query plan for later execution. The
+ saved plan will be retained for the life of the current
+ session.
preparing a query>in
+ PL/Tcl>>
The query may use parameters, that is, placeholders for
- PL/Tcl
+ in PL/Tcl
elog> level msg
Trigger Procedures in PL/Tcl
in PL/Tcl
-
+
Queries
+
+
+
+
+
+
The previous chapters explained how to create tables, how to fill
them with data, and how to manipulate that data. Now we finally
Table Expressions
+
+
+
A table expression computes a table. The
table expression contains a FROM> clause that is
overall table expression.
+
+
+
When a table reference names a table that is the supertable of a
table inheritance hierarchy, the table reference produces rows of
Joined Tables
Cross join
cross
+
+
+
T1 CROSS JOIN T2
Qualified joins
outer
+
+
+
T1 { INNER | { LEFT | RIGHT | FULL } OUTER } JOIN T2 ON boolean_expression
natural
+
+
Finally, NATURAL> is a shorthand form of
USING>: it forms a USING> list
consisting of exactly those column names that appear in both
LEFT OUTER JOIN>
left
+
+
+
First, an inner join is performed. Then, for each row in
RIGHT OUTER JOIN>
+
+ right
+
+
+
+
+
First, an inner join is performed. Then, for each row in
Table and Column Aliases
- tabl e
+ in the FROM claus e
- label
+ alias
Subqueries
+
+ in the FROM clause>
+
+
Table functions are functions that produce a set of rows, made up
of either base data types (scalar types) or composite data types
The WHERE Clause
The GROUP BY and HAVING Clauses
+
+
+
column names is also allowed.
+
+
+
If a table has been grouped using a GROUP BY
clause, but then only certain groups are of interest, the
Select Lists
select list
Select-List Items
+
+
+
The simplest kind of select list is * which
emits all columns that the table expression produces. Otherwise,
Column Labels
- column
+ in the select list
DISTINCT
+
+
+
+ DISTINCT>
Obviously, two rows are considered distinct if they differ in at
least one column value. Null values are considered equal in this
comparison.
Combining Queries
+
+
+
+
+
+
+
+
- query results
+
+
+
LIMIT and OFFSET
- with query results
+
cluster of databases database cluster
Tables are grouped into databases, and a collection of databases
managed by a single
PostgreSQL server
Aggregate Functions
abort the current transaction
+
+
+
ABORT [ WORK | TRANSACTION ]
change the definition of an aggregate function
+
+
+
ALTER AGGREGATE name ( type ) RENAME TO newname
change the definition of a conversion
+
+
+
ALTER CONVERSION name RENAME TO newname
change a database
+
+
+
ALTER DATABASE name SET variable { TO | = } { value | DEFAULT }
ALTER DOMAIN
SQL - Language Statements
+
ALTER DOMAIN
change the definition of a domain
+
+
+
+
2002-11-27
change the definition of a function
+
+
+
ALTER FUNCTION name ( [ type [, ...] ] ) RENAME TO newname
change a user group
+
+
+
ALTER GROUP groupname ADD USER username [, ... ]
change the definition of a procedural language
+
+
+
ALTER LANGUAGE name RENAME TO newname
change the definition of an operator class
+
+
+
ALTER OPERATOR CLASS name USING index_method RENAME TO newname
change the definition of a schema
+
+
+
ALTER SCHEMA name RENAME TO newname
ALTER SEQUENCE
SQL - Language Statements
+
ALTER SEQUENCE
alter the definition of a sequence generator
+
+
+
+
1999-07-20
change the definition of a table
+
+
+
ALTER TABLE [ ONLY ] table [ * ]
change the definition of a trigger
+
+
+
ALTER TRIGGER trigger ON table
change a database user account
+
+
+
ALTER USER username [ [ WITH ] option [ ... ] ]
collect statistics about a database
+
+
+
ANALYZE [ VERBOSE ] [ table [ (column [, ...] ) ] ]
start a transaction block
+
+
+
BEGIN [ WORK | TRANSACTION ]
-
+
force a transaction log checkpoint
+
+
+
CHECKPOINT
close a cursor
+
+
+
CLOSE cursor
cluster a table according to an index
+
+
+
CLUSTER indexname ON tablename
cluster a PostgreSQL database
+
+
+
clusterdb
define or change the comment of an object
+
+
+
COMMENT ON
commit the current transaction
+
+
+
COMMIT [ WORK | TRANSACTION ]
copy data between files and tables
+
+
+
COPY table [ ( column [, ...] ) ]
define a new aggregate function
+
+
+
CREATE AGGREGATE name (
-
+
define a user-defined cast
+
+
+
CREATE CAST (sourcetype AS targettype )
define a new constraint trigger
+
+
+
CREATE CONSTRAINT TRIGGER name
-
+
define a user-defined conversion
+
+
+
CREATE [DEFAULT] CONVERSION name
create a new database
+
+
+
CREATE DATABASE name
define a new domain
+
+
+
CREATE DOMAIN domainname [AS] data_type
define a new function
+
+
+
CREATE [ OR REPLACE ] FUNCTION name ( [ argtype [, ...] ] )
define a new user group
+
+
+
CREATE GROUP name [ [ WITH ] option [ ... ] ]
define a new index
+
+
+
CREATE [ UNIQUE ] INDEX index_name ON table [ USING method ]
define a new procedural language
+
+
+
CREATE [ TRUSTED ] [ PROCEDURAL ] LANGUAGE langname
define a new operator class for indexes
+
+
+
CREATE OPERATOR CLASS name [ DEFAULT ] FOR TYPE data_type USING index_method AS
define a new operator
+
+
+
CREATE OPERATOR name (
define a new rewrite rule
+
+
+
CREATE [ OR REPLACE ] RULE name AS ON event
define a new schema
+
+
+
CREATE SCHEMA schemaname [ AUTHORIZATION username ] [ schema_element [ ... ] ]
define a new sequence generator
+
+
+
CREATE [ TEMPORARY | TEMP ] SEQUENCE seqname [ INCREMENT [ BY ] increment ]
define a new table
+
+
+
CREATE [ [ GLOBAL | LOCAL ] { TEMPORARY | TEMP } ] TABLE table_name (
create a new table from the results of a query
+
+
+
CREATE [ [ GLOBAL | LOCAL ] { TEMPORARY | TEMP } ] TABLE table_name [ (column_name [, ...] ) ]
define a new trigger
+
+
+
CREATE TRIGGER name { BEFORE | AFTER } { event [ OR ... ] }
define a new data type
+
+
+
CREATE TYPE typename AS
define a new database user account
+
+
+
CREATE USER username [ [ WITH ] option [ ... ] ]
define a new view
+
+
+
CREATE [ OR REPLACE ] VIEW name [ (
create a new PostgreSQL database
+
+
+
createdb
define a new PostgreSQL procedural language
+
+
+
createlang
define a new PostgreSQL user account
+
+
+
createuser
deallocate a prepared statement
+
+
+
DEALLOCATE [ PREPARE ] plan_name
define a cursor
+
+
+
DECLARE cursorname [ BINARY ] [ INSENSITIVE ] [ [ NO ] SCROLL ]
delete rows of a table
+
+
+
DELETE FROM [ ONLY ] table [ WHERE condition ]
remove a user-defined aggregate function
+
+
+
DROP AGGREGATE name ( type ) [ CASCADE | RESTRICT ]
-
+
remove a user-defined cast
+
+
+
DROP CAST (sourcetype AS targettype ) [ CASCADE | RESTRICT ]
-
+
remove a user-defined conversion
+
+
+
DROP CONVERSION conversion_name [ CASCADE | RESTRICT ]
remove a database
+
+
+
DROP DATABASE name
remove a domain
+
+
+
DROP DOMAIN domainname [, ...] [ CASCADE | RESTRICT ]
remove a user-defined function
+
+
+
DROP FUNCTION name ( [ type [, ...] ] ) [ CASCADE | RESTRICT ]
remove a user group
+
+
+
DROP GROUP name
remove an index
+
+
+
DROP INDEX name [, ...] [ CASCADE | RESTRICT ]
remove a user-defined procedural language
+
+
+
DROP [ PROCEDURAL ] LANGUAGE name [ CASCADE | RESTRICT ]
remove a user-defined operator class
+
+
+
DROP OPERATOR CLASS name USING index_method [ CASCADE | RESTRICT ]
remove a user-defined operator
+
+
+
DROP OPERATOR name ( lefttype | NONE , righttype | NONE ) [ CASCADE | RESTRICT ]
remove a rewrite rule
+
+
+
DROP RULE name ON relation [ CASCADE | RESTRICT ]
remove a schema
+
+
+
DROP SCHEMA name [, ...] [ CASCADE | RESTRICT ]
remove a sequence
+
+
+
DROP SEQUENCE name [, ...] [ CASCADE | RESTRICT ]
remove a table
+
+
+
DROP TABLE name [, ...] [ CASCADE | RESTRICT ]
remove a trigger
+
+
+
DROP TRIGGER name ON table [ CASCADE | RESTRICT ]
remove a user-defined data type
+
+
+
DROP TYPE typename [, ...] [ CASCADE | RESTRICT ]
remove a database user account
+
+
+
DROP USER name
remove a view
+
+
+
DROP VIEW name [, ...] [ CASCADE | RESTRICT ]
remove a PostgreSQL database
+
+
+
dropdb
remove a PostgreSQL procedural language
+
+
+
droplang
remove a PostgreSQL user account
+
+
+
dropuser
embedded SQL C preprocessor
+
+
+
ecpg
commit the current transaction
+
+
+
END [ WORK | TRANSACTION ]
execute a prepared statement
+
+
+
EXECUTE plan_name [ (parameter [, ...] ) ]
show the execution plan of a statement
+
+
+
EXPLAIN [ ANALYZE ] [ VERBOSE ] statement
retrieve rows from a query using a cursor
+
+
+
FETCH [ direction { FROM | IN } ] cursor
define access privileges
+
+
+
GRANT { { SELECT | INSERT | UPDATE | DELETE | RULE | REFERENCES | TRIGGER }
create a new PostgreSQL database cluster
+
+
+
initdb
create a secondary PostgreSQL database storage area
+
+
+
initlocation
create new rows in a table
+
+
+
INSERT INTO table [ ( column [, ...] ) ]
remove shared memory and semaphores from an aborted PostgreSQL server
+
+
+
ipcclean
listen for a notification
+
+
+
LISTEN name
load or reload a shared library file
+
+
+
LOAD 'filename '
lock a table
+
+
+
LOCK [ TABLE ] name [, ...] [ IN lockmode MODE ]
reposition a cursor
+
+
+
MOVE [ direction { FROM | IN } ] cursor
generate a notification
+
+
+
NOTIFY name
-
+
retrieve information about the installed version of PostgreSQL>
+
+
+
pg_config
display control information of a PostgreSQL database cluster
+
+
+
pg_controldata
start, stop, or restart a PostgreSQL server
+
+
+
pg_ctl
extract a PostgreSQL database cluster into a script file
+
+
+
pg_dumpall
run a PostgreSQL server in single-user mode
+
+
+
PostgreSQL multiuser database server
+
+
+
postmaster
prepare a statement for execution
+
+
+
PREPARE plan_name [ (datatype [, ...] ) ] AS statement
rebuild indexes
+
+
+
REINDEX { DATABASE | TABLE | INDEX } name [ FORCE ]
restore the value of a run-time parameter to the default value
+
+
+
RESET parameter
remove access privileges
+
+
+
REVOKE [ GRANT OPTION FOR ]
abort the current transaction
+
+
+
ROLLBACK [ WORK | TRANSACTION ]
retrieve rows from a table or view
+
+
+
SELECT [ ALL | DISTINCT [ ON ( expression [, ...] ) ] ]
create a new table from the results of a query
+
+
+
SELECT [ ALL | DISTINCT [ ON ( expression [, ...] ) ] ]
change a run-time parameter
+
+
+
SET [ SESSION | LOCAL ] variable { TO | = } { value | 'value ' | DEFAULT }
-
+
SET CONSTRAINTS
set the constraint mode of the current transaction
+
+
+
SET CONSTRAINTS { ALL | constraint [, ...] } { DEFERRED | IMMEDIATE }
-
+
SET SESSION AUTHORIZATION
set the session user identifier and the current user identifier of the current session
+
+
SET SESSION AUTHORIZATION
+
+
SET [ SESSION | LOCAL ] SESSION AUTHORIZATION username
-
+
SET TRANSACTION
set the characteristics of the current transaction
+
+
+
SET TRANSACTION
show the value of a run-time parameter
+
+
+
SHOW name
start a transaction block
+
+
+
START TRANSACTION [ ISOLATION LEVEL { READ COMMITTED | SERIALIZABLE } ] [ READ WRITE | READ ONLY ]
empty a table
+
+
+
TRUNCATE [ TABLE ] name
stop listening for a notification
+
+
+
UNLISTEN { name | * }
update rows of a table
+
+
+
UPDATE [ ONLY ] table SET column = { expression | DEFAULT } [, ...]
garbage-collect and optionally analyze a database
+
+
+
VACUUM [ FULL ] [ FREEZE ] [ VERBOSE ] [ table ]
garbage-collect and analyze a PostgreSQL database
+
+
+
vacuumdb
-
+
Regression Tests
+
+
+
+
+
+
The regression tests are a comprehensive set of tests for the SQL
implementation in
PostgreSQL . They test
-
+
The Rule System
The Query Tree
+
+
+
To understand how the rule system works it is necessary to know
when it is invoked and what its input and results are.
the target list
The target list is a list of expressions that define the
Views and the Rule System
+
+
+ and views
+
+
+
+ implementation through rules>
+
Views in
PostgreSQL are implemented
same thing: relations.
-
+ id="rules-select">
How SELECT Rules Work
+
+ for SELECT
+
+
Rules ON SELECT> are applied to all queries as the last step, even
if the command given is an INSERT ,
To resolve this problem, another entry is added to the target list
in UPDATE (and also in
DELETE ) statements: the current tuple ID
- (
CTID>). This is a system column containing the
+ (
CTID>).CTID>> This is a system column containing the
file block number and position in the block for the row. Knowing
the table, the
CTID> can be used to retrieve the
original row of
t1> to be updated. After adding the CTID>
Rules on INSERT>, UPDATE>, and DELETE>
+
+ for INSERT
+
+
+
+ for UPDATE
+
+
+
+ for DELETE
+
+
Rules that are defined on INSERT>, UPDATE>,
and DELETE> are significantly different from the view rules
Cooperation with Views
A simple way to protect view relations from the mentioned
Rules and Privileges
+
+ with rules
+
+
+
+ with views
+
+
Due to rewriting of queries by the
PostgreSQL
rule system, other tables/views than those used in the original
Rules versus Triggers
+
+ compared with triggers
+
+
+
+ compared with rules
+
+
Many things that can be done using triggers can also be
implemented using the
PostgreSQL
default, although locations such as
/usr/local/pgsql/data or
/var/lib/pgsql/data are popular. To initialize a
- database cluster, use the command initdb , which is
+ database cluster, use the command
initdb ,
initdb>> which is
installed with
PostgreSQL . The desired
file system location of your database system is indicated by the
-D option, for example
However, while the directory contents are secure, the default
client authentication setup allows any local user to connect to the
- database and even become the database superuser. If you do not trust
- other local users, we recommend you use initdb 's
- -W or --pwprompt option to assign a
- password to the database superuser. After initdb ,
- modify the pg_hba.conf file to use md5> or
+ database and even become the database superuser. If you do not
+ trust other local users, we recommend you use
+ initdb 's -W or
+ --pwprompt option to assign a password to the
+ database superuser.
password>of the
+ superuser> After initdb , modify
+ the pg_hba.conf file to use md5> or
password> instead of trust> authentication
before> you start the server for the first time. (Other
approaches include using ident authentication or
Normally, you will want to start the database server when the
- computer boots. Autostart scripts are operating system-specific.
- There are a few distributed with
+ computer boots.
booting>starting
+ the server during>> Autostart scripts are operating
+ system-specific. There are a few distributed with
contrib/start-scripts> directory. This may require root
privileges.
For
FreeBSD , look at the file
contrib/start-scripts/freebsd in the
PostgreSQL source distribution.
+
FreeBSD><secondary>start script< />
On
OpenBSD , add the following lines
to the file /etc/rc.local :
+
OpenBSD><secondary>start script< />
if [ -x /usr/local/pgsql/bin/pg_ctl -a -x /usr/local/pgsql/bin/postmaster ]; then
su - -c '/usr/local/pgsql/bin/pg_ctl start -l /var/postgresql/log -s' postgres
On
Linux systems either add
+
Linux><secondary>start script< />
/usr/local/pgsql/bin/pg_ctl start -l logfile -D /usr/local/pgsql/data
On
NetBSD , either use the
Linux start scripts, depending on
+ preference.
NetBSD><secondary>start script< />
On
Solaris , create a file called
/etc/init.d/postgresql that contains
the following line:
+
Solaris><secondary>start script< />
su - postgres -c "/usr/local/pgsql/bin/pg_ctl start -l logfile -D /usr/local/pgsql/data"
- server
+ of the server
One way to set these options is to edit the file
- postgresql.conf in the data directory. (A
+
postgresql.conf postgresql.conf>> in the data directory. (A
default file is installed there.) An example of what this file might
look like is:
TCPIP_SOCKET (boolean )
- If this is true, then the server will accept TCP/IP connections.
+ If this is true, then the server will accept TCP/IP connections.
TCP/IP>>
Otherwise only local Unix domain socket connections are
accepted. It is off by default. This option can only be set at
server start.
AUTHENTICATION_TIMEOUT (integer )
-
timeout>authentication>
+
timeout>client authentication>
+
client authentication>timeout during>
Maximum time to complete client authentication, in seconds. If a
Error Reporting and Logging
+
+
+
Syslog
+
+
+
+
AUSTRALIAN_TIMEZONES (boolean )
-
Australian time zones >>
If set to true, ACST ,
- of float numbers
+ display
EXTRA_FLOAT_DIGITS (integer )
CLIENT_ENCODING (string )
-
character set encoding >>
Sets the client-side encoding (character set).
- timeout
+ timeout during
Version and Platform Compatibility
-
Previous Postgres Versions
+
Previous PostgreSQL Versions
ADD_MISSING_FROM (boolean )
When true>, tables that are referenced by a query will be
BSD/OS>
+
BSD/OS><secondary>IPC configuration>< />
Shared Memory>
FreeBSD>
NetBSD>
OpenBSD>
+
FreeBSD><secondary>IPC configuration>< />
+
NetBSD><secondary>IPC configuration>< />
+
OpenBSD><secondary>IPC configuration>< />
The options SYSVSHM> and SYSVSEM> need
HP-UX>
+
HP-UX><secondary>IPC configuration>< />
The default settings tend to suffice for normal installations.
Linux>
+
Linux><secondary>IPC configuration>< />
The default shared memory limit (both
MacOS X>
+
MacOS X><secondary>IPC configuration>< />
Edit the file
SCO OpenServer>
+
SCO OpenServer><secondary>IPC configuration>< />
In the default configuration, only 512 kB of shared memory per
Solaris>
+
Solaris><secondary>IPC configuration>< />
At least in version 2.6, the default maximum size of a shared
UnixWare>
+
UnixWare><secondary>IPC configuration>< />
On
UnixWare> 7, the maximum size for shared
Shutting Down the Server
+
+
+
There are several ways to shut down the database server. You control
the type of shutdown by sending different signals to the server
process.
- SIGTERM
+
SIGTERM <indexterm>SIGTERM>>< /term>
After receiving SIGTERM , the server
- SIGINT
+
SIGINT <indexterm>SIGINT>>< /term>
The server disallows new connections and sends all existing
- SIGQUIT
+
SIGQUIT <indexterm>SIGQUIT>>< /term>
This is the Immediate Shutdown , which
PostgreSQL allocates memory within
- context, which provide a convenient method of
+ context<secondary>in SPI< /indexterm>, which provide a convenient method of
managing allocations made in many different places that need to
live for differing amounts of time. Destroying a context releases
all the memory that was allocated in it. Thus, it is not necessary
Lexical Structure
+
+
+
SQL input consists of a sequence of
commands . A command is composed of a
Identifiers and Key Words
+ syntax of
- syntax
+ syntax of
+
+
+
+ syntax of
The system uses no more than NAMEDATALEN -1
characters of an identifier; longer names can be written in
commands, but they will be truncated. By default,
- SQL commands
+ of SQL commands
Identifier and key word names are case insensitive. Therefore
and identifiers
There is a second kind of identifier: the delimited
Constants
String Constants
- constants
+ constant
escaping
A string constant in SQL is an arbitrary sequence of characters
Bit-String Constants
- constants
+ constant
Numeric Constants
- constants
+ constant
A numeric constant that contains neither a decimal point nor an
exponent is initially presumed to be type integer> if its
value fits in type integer> (32 bits); otherwise it is
The initially assigned data type of a numeric constant is just a
- starting point for the type resolution algorithms. In most
- cases the constant will be automatically coerced to the most
- appropriate type depending on context. When necessary, you
- can force a numeric value to be interpreted as a specific
- data type by casting it. For example, you can force a numeric
- value to be treated as type real> (float4>)
- by writing
+ starting point for the type resolution algorithms. In most cases
+ the constant will be automatically coerced to the most
+ appropriate type depending on context. When necessary, you can
+ force a numeric value to be interpreted as a specific data type
+ by casting it.
type cast
+ For example, you can force a numeric value to be treated as type
+ real> (float4>) by writing
REAL '1.23' -- string style
Constants of Other Types
- constants
+ constant
Array constants
- constants
+ constant
Operators
syntax
Comments
- in SQL
+ sortas="SQL">in SQL
Lexical Precedence
precedence
Value Expressions
+
+ syntax
+
+
+
+
+
+
+ expression
+
+
Value expressions are used in a variety of contexts, such
as in the target list of the SELECT command, as
- Another value expression in parentheses, useful to group subexpressions and override precedence.
+ Another value expression in parentheses, useful to group
+ subexpressions and override
+ precedence.
parenthesis>>
Column References
+
+
+
A column can be referenced in the form
Positional Parameters
+
+ syntax
+
+
+
+
+
A positional parameter reference is used to indicate a value
that is supplied externally to an SQL statement. Parameters are
Operator Invocations
+
+ invocation
+
+
There are three possible syntaxes for an operator invocation:
Function Calls
+
+ invocation
+
+
The syntax for a function call is the name of a function
(possibly qualified with a schema name), followed by its argument list
Aggregate Expressions
+ invocation
Type Casts
-
- type casts
-
+
+ type cast
+
+
+
+
A type cast specifies a conversion from one data type to another.
Scalar Subqueries
+
+
+
A scalar subquery is an ordinary
SELECT query in parentheses that returns exactly one
Array Constructors
-
- constructors
-
+
+ constructor
+
An array constructor> is an expression that builds an
Expression Evaluation Rules
+
+ order of evaluation
+
+
The order of evaluation of subexpressions is not defined. In
particular, the inputs of an operator or function are not necessarily
Triggers
+
+
+
This chapter describes how to write trigger functions. In
particular, it describes the C-language interface for trigger
When a trigger is being defined, arguments can be specified for
- it. The purpose of including arguments in the trigger definition
- is to allow different triggers with similar requirements to call
- the same function. As an example, there could be a generalized
- trigger function that takes as its arguments two column names and
- puts the current user in one and the current time stamp in the
- other. Properly written, this trigger function would be
- independent of the specific table it is triggering on. So the
- same function could be used for INSERT events
- on any table with suitable columns, to automatically track creation
- of records in a transaction table for example. It could also be
- used to track last-update events if defined as an
- UPDATE trigger.
+ it.
trigger>arguments for trigger
+ functions> The purpose of including arguments in the
+ trigger definition is to allow different triggers with similar
+ requirements to call the same function. As an example, there
+ could be a generalized trigger function that takes as its
+ arguments two column names and puts the current user in one and
+ the current time stamp in the other. Properly written, this
+ trigger function would be independent of the specific table it is
+ triggering on. So the same function could be used for
+ INSERT events on any table with suitable
+ columns, to automatically track creation of records in a
+ transaction table for example. It could also be used to track
+ last-update events if defined as an UPDATE
+ trigger.
Interaction with the Trigger Manager
+
+ in C
+
+
This section describes the low-level details of the interface to a
trigger function. This information is only needed when writing a
Type Conversion
+
+ conversion
+
+
SQL statements can, intentionally or not, require
mixing of different data types in the same expression.
altered.)
+
+ category
+
+
An additional heuristic is provided in the parser to allow better guesses
at proper behavior for
SQL standard types. There are
Operators
+
+ type resolution in an invocation
+
+
The specific operator to be used in an operator invocation is determined
by following
Functions
+
+ type resolution in an invocation
+
+
The specific function to be used in a function invocation is determined
according to the following steps.
-
UNION , CASE , and
-ARRAY Constructs
+
UNION , CASE , and ARRAY Constructs
+
+
+ determination of result type
+
+
+
+ determination of result type
+
+
+
+ determination of result type
+
SQL UNION> constructs must match up possibly dissimilar types to
Database Users
+
+
+
+
+
+
+
+
+
Database users are conceptually completely separate from
operating system users. In practice it might be convenient to
+
+
+
+
+
+
For convenience, the programs createuser
and dropuser are provided as wrappers
- superuser
+
superuser<indexterm>superuser>>< /term>
A database superuser bypasses all permission checks. Also,
- database creation
+
database creation<indexterm>database>privilege to create>>< /term>
A user must be explicitly given permission to create databases
- password
+
password<indexterm>password>>< /term>
A password is only significant if the client authentication
A user's attributes can be modified after creation with
- ALTER USER .
+
ALTER USER .
ALTER USER>>
See the reference pages for CREATE USER and
ALTER USER for details.
Groups
+
+
+
As in Unix, groups are a way of logically grouping users to ease
management of privileges: privileges can be granted to, or revoked
Privileges
+
+
+
+
+
+
+
+
+
+
+
+
Being moved to the DDL chapter. Will eventually disappear here.
-
+
Write-Ahead Logging (WAL )
+
+
+
+
+ WAL
+
+
Write-Ahead Logging (
WAL )
is a standard approach to transaction logging. Its detailed
+
+
+
The first obvious benefit of using
WAL is a
significantly reduced number of disk writes, since only the log
With UNDO, it will also be possible to implement
- savepoints to allow partial rollback of
+
savepoints savepoint>> to allow partial rollback of
invalid transaction operations (parser errors caused by mistyping
commands, insertion of duplicate primary/unique keys and so on)
with the ability to continue or commit valid operations made by
- Checkpoints are points in the sequence of
+
Checkpoints checkpoint>> are points in the sequence of
transactions at which it is guaranteed that the data files have
been updated with all information logged before the checkpoint. At
checkpoint time, all dirty data pages are flushed to disk and a
The aim of
WAL , to ensure that the log is
written before database records are altered, may be subverted by
- disk drives that falsely report a successful write to the kernel,
+ disk drives
disk drive>> that falsely report a successful write to the kernel,
when, in fact, they have only cached the data and not yet stored it
on the disk. A power failure in such a situation may still lead to
irrecoverable data corruption. Administrators should try to ensure
User-Defined Aggregates
- extending
+ user-defined
Aggregate functions may use polymorphic
state transition functions or final functions, so that the same functions
can be used to implement multiple aggregates.
- See
+ See extend-types-polymorphic">
for an explanation of polymorphic functions.
Going a step further, the aggregate function itself may be specified
with a polymorphic base type and state type, allowing a single
User-Defined Functions
+
+ user-defined
+
PostgreSQL provides four kinds of
Query Language (SQL ) Functions
+
+ user-defined
+ in SQL
+
SQL functions execute an arbitrary list of SQL statements, returning
- Alternatively, an SQL function may be declared to return a set,
- by specifying the function's return type
- as SETOF sometype> . In this case
- all rows of the last query's result are returned. Further details
- appear below.
+
SETOF>function>> Alternatively,
+ an SQL function may be declared to return a set, by specifying the
+ function's return type as SETOF
+ In this case all rows of the last query's result are returned.
+ Further details appear below.
SQL functions may be declared to accept and
return the polymorphic> types
anyelement and anyarray .
- See for a more detailed explanation
+ See extend-types-polymorphic"> for a more detailed explanation
of polymorphic functions. Here is a polymorphic function
make_array that builds up an array from two
arbitrary data type elements:
C-Language Functions
+
+ user-defined
+ in C
+
+
User-defined functions can be written in C (or a language that can
be made compatible with C, such as C++). Such functions are
Dynamic Loading
+
+
+
The first time a user-defined function in a particular
loadable object file is called in a session,
-
+ id="xfunc-c-basetype">
Base Types in C-Language Functions
+
+ internal organisation
+
+
To know how to write C-language functions, you need to know how
PostgreSQL internally represents base data types and how they can
Use pg_config
- --includedir-server
pg_config>>
+ --includedir-server
pg_config><secondary>with user-defined C functions>< />
to find out where the
PostgreSQL> server header
files are installed on your system (or the system that your
users will be running on). This option is new with
When allocating memory, use the
- palloc and pfree >
+
palloc palloc>> and pfree pfree> >
instead of the corresponding C library functions
malloc and free .
The memory allocated by palloc will be
C-language functions may be declared to accept and
return the polymorphic> types
anyelement and anyarray .
- See for a more detailed explanation
+ See extend-types-polymorphic"> for a more detailed explanation
of polymorphic functions. When function arguments or return types
are defined as polymorphic types, the function author cannot know
in advance what data type it will be called with, or
Function Overloading
+
+ functions
+
More than one function may be defined with the same SQL name, so long
Procedural Language Handlers
+
+ handler for
+
+
All calls to functions that are written in a language other than
the current version 1
interface for compiled
Interfacing Extensions To Indexes
+
+ for user-defined data type
+
+
The procedures described thus far let you define new types, new
functions, and new operators. However, we cannot yet define an
The routines for an index method do not directly know anything
- about the data types that the index method will operate on. Instead, an
- operator class> identifies the set of operations that the
- index method needs to use to work with a particular data type.
- Operator classes are so called because one thing they specify is the set
- of WHERE>-clause operators that can be used with an index (i.e., can be
- converted into an index-scan qualification). An operator class may also
- specify some support procedures> that are needed by the
- internal operations of the index method, but do not directly
- correspond to any WHERE>-clause operator that can be used with the index.
+ about the data types that the index method will operate on.
+ Instead, an operator
+ identifies the set of operations that the index method needs to use
+ to work with a particular data type. Operator classes are so
+ called because one thing they specify is the set of
+ WHERE>-clause operators that can be used with an index
+ (i.e., can be converted into an index-scan qualification). An
+ operator class may also specify some support
+ procedures> that are needed by the internal operations of the
+ index method, but do not directly correspond to any
+ WHERE>-clause operator that can be used with the index.
User-defined Operators
+
+ user-defined
+
+
Every operator is syntactic sugar
for a call to an
underlying function that does the real work; so you must
PostgreSQL supports left unary, right
- unary, and binary operators. Operators can be overloaded; that is,
- the same operator name can be used for different operators that
- have different numbers and types of operands. When a query is
+ unary, and binary operators. Operators can be
+ overloaded;
overloading operators
+ that is, the same operator name can be used for different operators
+ that have different numbers and types of operands. When a query is
executed, the system determines the operator to call from the
number and types of the provided operands.
Procedural Languages
+
+
+
PostgreSQL allows users to add new
programming languages to be available for writing functions and
User-Defined Types
- extending
+ user-defined
- A user-defined type must always have input and output functions.
+ A user-defined type must always have input and output
+ functions.
input function of
+ functionof a data type
These functions determine how the type appears in strings (for input
by the user and output to the user) and how the type is organized in
memory. The input function takes a null-terminated character string
- as its argument and returns the internal (in memory) representation of
- the type. The output function takes the internal representation of
- the type as argument and returns a null-terminated character string.
+ as its argument and returns the internal (in memory) representation
+ of the type. The output function takes the internal representation
+ of the type as argument and returns a null-terminated character
+ string.