Server IP : 103.119.228.120 / Your IP : 3.137.178.122 Web Server : Apache System : Linux v8.techscape8.com 3.10.0-1160.119.1.el7.tuxcare.els2.x86_64 #1 SMP Mon Jul 15 12:09:18 UTC 2024 x86_64 User : nobody ( 99) PHP Version : 5.6.40 Disable Function : shell_exec,symlink,system,exec,proc_get_status,proc_nice,proc_terminate,define_syslog_variables,syslog,openlog,closelog,escapeshellcmd,passthru,ocinum cols,ini_alter,leak,listen,chgrp,apache_note,apache_setenv,debugger_on,debugger_off,ftp_exec,dl,dll,myshellexec,proc_open,socket_bind,proc_close,escapeshellarg,parse_ini_filepopen,fpassthru,exec,passthru,escapeshellarg,escapeshellcmd,proc_close,proc_open,ini_alter,popen,show_source,proc_nice,proc_terminate,proc_get_status,proc_close,pfsockopen,leak,apache_child_terminate,posix_kill,posix_mkfifo,posix_setpgid,posix_setsid,posix_setuid,dl,symlink,shell_exec,system,dl,passthru,escapeshellarg,escapeshellcmd,myshellexec,c99_buff_prepare,c99_sess_put,fpassthru,getdisfunc,fx29exec,fx29exec2,is_windows,disp_freespace,fx29sh_getupdate,fx29_buff_prepare,fx29_sess_put,fx29shexit,fx29fsearch,fx29ftpbrutecheck,fx29sh_tools,fx29sh_about,milw0rm,imagez,sh_name,myshellexec,checkproxyhost,dosyayicek,c99_buff_prepare,c99_sess_put,c99getsource,c99sh_getupdate,c99fsearch,c99shexit,view_perms,posix_getpwuid,posix_getgrgid,posix_kill,parse_perms,parsesort,view_perms_color,set_encoder_input,ls_setcheckboxall,ls_reverse_all,rsg_read,rsg_glob,selfURL,dispsecinfo,unix2DosTime,addFile,system,get_users,view_size,DirFiles,DirFilesWide,DirPrintHTMLHeaders,GetFilesTotal,GetTitles,GetTimeTotal,GetMatchesCount,GetFileMatchesCount,GetResultFiles,fs_copy_dir,fs_copy_obj,fs_move_dir,fs_move_obj,fs_rmdir,SearchText,getmicrotime MySQL : ON | cURL : ON | WGET : ON | Perl : ON | Python : ON | Sudo : ON | Pkexec : ON Directory : /usr/local/ssl/share/doc/postgresql-9.2.24/html/ |
Upload File : |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <HTML ><HEAD ><TITLE >Message Flow</TITLE ><META NAME="GENERATOR" CONTENT="Modular DocBook HTML Stylesheet Version 1.79"><LINK REV="MADE" HREF="mailto:pgsql-docs@postgresql.org"><LINK REL="HOME" TITLE="PostgreSQL 9.2.24 Documentation" HREF="index.html"><LINK REL="UP" TITLE="Frontend/Backend Protocol" HREF="protocol.html"><LINK REL="PREVIOUS" TITLE="Overview" HREF="protocol-overview.html"><LINK REL="NEXT" TITLE="Streaming Replication Protocol" HREF="protocol-replication.html"><LINK REL="STYLESHEET" TYPE="text/css" HREF="stylesheet.css"><META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=ISO-8859-1"><META NAME="creation" CONTENT="2017-11-06T22:43:11"></HEAD ><BODY CLASS="SECT1" ><DIV CLASS="NAVHEADER" ><TABLE SUMMARY="Header navigation table" WIDTH="100%" BORDER="0" CELLPADDING="0" CELLSPACING="0" ><TR ><TH COLSPAN="5" ALIGN="center" VALIGN="bottom" ><A HREF="index.html" >PostgreSQL 9.2.24 Documentation</A ></TH ></TR ><TR ><TD WIDTH="10%" ALIGN="left" VALIGN="top" ><A TITLE="Overview" HREF="protocol-overview.html" ACCESSKEY="P" >Prev</A ></TD ><TD WIDTH="10%" ALIGN="left" VALIGN="top" ><A HREF="protocol.html" ACCESSKEY="U" >Up</A ></TD ><TD WIDTH="60%" ALIGN="center" VALIGN="bottom" >Chapter 46. Frontend/Backend Protocol</TD ><TD WIDTH="20%" ALIGN="right" VALIGN="top" ><A TITLE="Streaming Replication Protocol" HREF="protocol-replication.html" ACCESSKEY="N" >Next</A ></TD ></TR ></TABLE ><HR ALIGN="LEFT" WIDTH="100%"></DIV ><DIV CLASS="SECT1" ><H1 CLASS="SECT1" ><A NAME="PROTOCOL-FLOW" >46.2. Message Flow</A ></H1 ><P > This section describes the message flow and the semantics of each message type. (Details of the exact representation of each message appear in <A HREF="protocol-message-formats.html" >Section 46.5</A >.) There are several different sub-protocols depending on the state of the connection: start-up, query, function call, <TT CLASS="COMMAND" >COPY</TT >, and termination. There are also special provisions for asynchronous operations (including notification responses and command cancellation), which can occur at any time after the start-up phase. </P ><DIV CLASS="SECT2" ><H2 CLASS="SECT2" ><A NAME="AEN95777" >46.2.1. Start-up</A ></H2 ><P > To begin a session, a frontend opens a connection to the server and sends a startup message. This message includes the names of the user and of the database the user wants to connect to; it also identifies the particular protocol version to be used. (Optionally, the startup message can include additional settings for run-time parameters.) The server then uses this information and the contents of its configuration files (such as <TT CLASS="FILENAME" >pg_hba.conf</TT >) to determine whether the connection is provisionally acceptable, and what additional authentication is required (if any). </P ><P > The server then sends an appropriate authentication request message, to which the frontend must reply with an appropriate authentication response message (such as a password). For all authentication methods except GSSAPI and SSPI, there is at most one request and one response. In some methods, no response at all is needed from the frontend, and so no authentication request occurs. For GSSAPI and SSPI, multiple exchanges of packets may be needed to complete the authentication. </P ><P > The authentication cycle ends with the server either rejecting the connection attempt (ErrorResponse), or sending AuthenticationOk. </P ><P > The possible messages from the server in this phase are: <P ></P ></P><DIV CLASS="VARIABLELIST" ><DL ><DT >ErrorResponse</DT ><DD ><P > The connection attempt has been rejected. The server then immediately closes the connection. </P ></DD ><DT >AuthenticationOk</DT ><DD ><P > The authentication exchange is successfully completed. </P ></DD ><DT >AuthenticationKerberosV5</DT ><DD ><P > The frontend must now take part in a Kerberos V5 authentication dialog (not described here, part of the Kerberos specification) with the server. If this is successful, the server responds with an AuthenticationOk, otherwise it responds with an ErrorResponse. </P ></DD ><DT >AuthenticationCleartextPassword</DT ><DD ><P > The frontend must now send a PasswordMessage containing the password in clear-text form. If this is the correct password, the server responds with an AuthenticationOk, otherwise it responds with an ErrorResponse. </P ></DD ><DT >AuthenticationMD5Password</DT ><DD ><P > The frontend must now send a PasswordMessage containing the password (with username) encrypted via MD5, then encrypted again using the 4-byte random salt specified in the AuthenticationMD5Password message. If this is the correct password, the server responds with an AuthenticationOk, otherwise it responds with an ErrorResponse. The actual PasswordMessage can be computed in SQL as <TT CLASS="LITERAL" >concat('md5', md5(concat(md5(concat(password, username)), random-salt)))</TT >. (Keep in mind the <CODE CLASS="FUNCTION" >md5()</CODE > function returns its result as a hex string.) </P ></DD ><DT >AuthenticationSCMCredential</DT ><DD ><P > This response is only possible for local Unix-domain connections on platforms that support SCM credential messages. The frontend must issue an SCM credential message and then send a single data byte. (The contents of the data byte are uninteresting; it's only used to ensure that the server waits long enough to receive the credential message.) If the credential is acceptable, the server responds with an AuthenticationOk, otherwise it responds with an ErrorResponse. (This message type is only issued by pre-9.1 servers. It may eventually be removed from the protocol specification.) </P ></DD ><DT >AuthenticationGSS</DT ><DD ><P > The frontend must now initiate a GSSAPI negotiation. The frontend will send a PasswordMessage with the first part of the GSSAPI data stream in response to this. If further messages are needed, the server will respond with AuthenticationGSSContinue. </P ></DD ><DT >AuthenticationSSPI</DT ><DD ><P > The frontend must now initiate a SSPI negotiation. The frontend will send a PasswordMessage with the first part of the SSPI data stream in response to this. If further messages are needed, the server will respond with AuthenticationGSSContinue. </P ></DD ><DT >AuthenticationGSSContinue</DT ><DD ><P > This message contains the response data from the previous step of GSSAPI or SSPI negotiation (AuthenticationGSS, AuthenticationSSPI or a previous AuthenticationGSSContinue). If the GSSAPI or SSPI data in this message indicates more data is needed to complete the authentication, the frontend must send that data as another PasswordMessage. If GSSAPI or SSPI authentication is completed by this message, the server will next send AuthenticationOk to indicate successful authentication or ErrorResponse to indicate failure. </P ></DD ></DL ></DIV ><P> </P ><P > If the frontend does not support the authentication method requested by the server, then it should immediately close the connection. </P ><P > After having received AuthenticationOk, the frontend must wait for further messages from the server. In this phase a backend process is being started, and the frontend is just an interested bystander. It is still possible for the startup attempt to fail (ErrorResponse), but in the normal case the backend will send some ParameterStatus messages, BackendKeyData, and finally ReadyForQuery. </P ><P > During this phase the backend will attempt to apply any additional run-time parameter settings that were given in the startup message. If successful, these values become session defaults. An error causes ErrorResponse and exit. </P ><P > The possible messages from the backend in this phase are: <P ></P ></P><DIV CLASS="VARIABLELIST" ><DL ><DT >BackendKeyData</DT ><DD ><P > This message provides secret-key data that the frontend must save if it wants to be able to issue cancel requests later. The frontend should not respond to this message, but should continue listening for a ReadyForQuery message. </P ></DD ><DT >ParameterStatus</DT ><DD ><P > This message informs the frontend about the current (initial) setting of backend parameters, such as <A HREF="runtime-config-client.html#GUC-CLIENT-ENCODING" >client_encoding</A > or <A HREF="runtime-config-client.html#GUC-DATESTYLE" >DateStyle</A >. The frontend can ignore this message, or record the settings for its future use; see <A HREF="protocol-flow.html#PROTOCOL-ASYNC" >Section 46.2.6</A > for more details. The frontend should not respond to this message, but should continue listening for a ReadyForQuery message. </P ></DD ><DT >ReadyForQuery</DT ><DD ><P > Start-up is completed. The frontend can now issue commands. </P ></DD ><DT >ErrorResponse</DT ><DD ><P > Start-up failed. The connection is closed after sending this message. </P ></DD ><DT >NoticeResponse</DT ><DD ><P > A warning message has been issued. The frontend should display the message but continue listening for ReadyForQuery or ErrorResponse. </P ></DD ></DL ></DIV ><P> </P ><P > The ReadyForQuery message is the same one that the backend will issue after each command cycle. Depending on the coding needs of the frontend, it is reasonable to consider ReadyForQuery as starting a command cycle, or to consider ReadyForQuery as ending the start-up phase and each subsequent command cycle. </P ></DIV ><DIV CLASS="SECT2" ><H2 CLASS="SECT2" ><A NAME="AEN95852" >46.2.2. Simple Query</A ></H2 ><P > A simple query cycle is initiated by the frontend sending a Query message to the backend. The message includes an SQL command (or commands) expressed as a text string. The backend then sends one or more response messages depending on the contents of the query command string, and finally a ReadyForQuery response message. ReadyForQuery informs the frontend that it can safely send a new command. (It is not actually necessary for the frontend to wait for ReadyForQuery before issuing another command, but the frontend must then take responsibility for figuring out what happens if the earlier command fails and already-issued later commands succeed.) </P ><P > The possible response messages from the backend are: <P ></P ></P><DIV CLASS="VARIABLELIST" ><DL ><DT >CommandComplete</DT ><DD ><P > An SQL command completed normally. </P ></DD ><DT >CopyInResponse</DT ><DD ><P > The backend is ready to copy data from the frontend to a table; see <A HREF="protocol-flow.html#PROTOCOL-COPY" >Section 46.2.5</A >. </P ></DD ><DT >CopyOutResponse</DT ><DD ><P > The backend is ready to copy data from a table to the frontend; see <A HREF="protocol-flow.html#PROTOCOL-COPY" >Section 46.2.5</A >. </P ></DD ><DT >RowDescription</DT ><DD ><P > Indicates that rows are about to be returned in response to a <TT CLASS="COMMAND" >SELECT</TT >, <TT CLASS="COMMAND" >FETCH</TT >, etc query. The contents of this message describe the column layout of the rows. This will be followed by a DataRow message for each row being returned to the frontend. </P ></DD ><DT >DataRow</DT ><DD ><P > One of the set of rows returned by a <TT CLASS="COMMAND" >SELECT</TT >, <TT CLASS="COMMAND" >FETCH</TT >, etc query. </P ></DD ><DT >EmptyQueryResponse</DT ><DD ><P > An empty query string was recognized. </P ></DD ><DT >ErrorResponse</DT ><DD ><P > An error has occurred. </P ></DD ><DT >ReadyForQuery</DT ><DD ><P > Processing of the query string is complete. A separate message is sent to indicate this because the query string might contain multiple SQL commands. (CommandComplete marks the end of processing one SQL command, not the whole string.) ReadyForQuery will always be sent, whether processing terminates successfully or with an error. </P ></DD ><DT >NoticeResponse</DT ><DD ><P > A warning message has been issued in relation to the query. Notices are in addition to other responses, i.e., the backend will continue processing the command. </P ></DD ></DL ></DIV ><P> </P ><P > The response to a <TT CLASS="COMMAND" >SELECT</TT > query (or other queries that return row sets, such as <TT CLASS="COMMAND" >EXPLAIN</TT > or <TT CLASS="COMMAND" >SHOW</TT >) normally consists of RowDescription, zero or more DataRow messages, and then CommandComplete. <TT CLASS="COMMAND" >COPY</TT > to or from the frontend invokes special protocol as described in <A HREF="protocol-flow.html#PROTOCOL-COPY" >Section 46.2.5</A >. All other query types normally produce only a CommandComplete message. </P ><P > Since a query string could contain several queries (separated by semicolons), there might be several such response sequences before the backend finishes processing the query string. ReadyForQuery is issued when the entire string has been processed and the backend is ready to accept a new query string. </P ><P > If a completely empty (no contents other than whitespace) query string is received, the response is EmptyQueryResponse followed by ReadyForQuery. </P ><P > In the event of an error, ErrorResponse is issued followed by ReadyForQuery. All further processing of the query string is aborted by ErrorResponse (even if more queries remained in it). Note that this might occur partway through the sequence of messages generated by an individual query. </P ><P > In simple Query mode, the format of retrieved values is always text, except when the given command is a <TT CLASS="COMMAND" >FETCH</TT > from a cursor declared with the <TT CLASS="LITERAL" >BINARY</TT > option. In that case, the retrieved values are in binary format. The format codes given in the RowDescription message tell which format is being used. </P ><P > A frontend must be prepared to accept ErrorResponse and NoticeResponse messages whenever it is expecting any other type of message. See also <A HREF="protocol-flow.html#PROTOCOL-ASYNC" >Section 46.2.6</A > concerning messages that the backend might generate due to outside events. </P ><P > Recommended practice is to code frontends in a state-machine style that will accept any message type at any time that it could make sense, rather than wiring in assumptions about the exact sequence of messages. </P ></DIV ><DIV CLASS="SECT2" ><H2 CLASS="SECT2" ><A NAME="PROTOCOL-FLOW-EXT-QUERY" >46.2.3. Extended Query</A ></H2 ><P > The extended query protocol breaks down the above-described simple query protocol into multiple steps. The results of preparatory steps can be re-used multiple times for improved efficiency. Furthermore, additional features are available, such as the possibility of supplying data values as separate parameters instead of having to insert them directly into a query string. </P ><P > In the extended protocol, the frontend first sends a Parse message, which contains a textual query string, optionally some information about data types of parameter placeholders, and the name of a destination prepared-statement object (an empty string selects the unnamed prepared statement). The response is either ParseComplete or ErrorResponse. Parameter data types can be specified by OID; if not given, the parser attempts to infer the data types in the same way as it would do for untyped literal string constants. </P ><DIV CLASS="NOTE" ><BLOCKQUOTE CLASS="NOTE" ><P ><B >Note: </B > A parameter data type can be left unspecified by setting it to zero, or by making the array of parameter type OIDs shorter than the number of parameter symbols (<TT CLASS="LITERAL" >$</TT ><TT CLASS="REPLACEABLE" ><I >n</I ></TT >) used in the query string. Another special case is that a parameter's type can be specified as <TT CLASS="TYPE" >void</TT > (that is, the OID of the <TT CLASS="TYPE" >void</TT > pseudotype). This is meant to allow parameter symbols to be used for function parameters that are actually OUT parameters. Ordinarily there is no context in which a <TT CLASS="TYPE" >void</TT > parameter could be used, but if such a parameter symbol appears in a function's parameter list, it is effectively ignored. For example, a function call such as <TT CLASS="LITERAL" >foo($1,$2,$3,$4)</TT > could match a function with two IN and two OUT arguments, if <TT CLASS="LITERAL" >$3</TT > and <TT CLASS="LITERAL" >$4</TT > are specified as having type <TT CLASS="TYPE" >void</TT >. </P ></BLOCKQUOTE ></DIV ><DIV CLASS="NOTE" ><BLOCKQUOTE CLASS="NOTE" ><P ><B >Note: </B > The query string contained in a Parse message cannot include more than one SQL statement; else a syntax error is reported. This restriction does not exist in the simple-query protocol, but it does exist in the extended protocol, because allowing prepared statements or portals to contain multiple commands would complicate the protocol unduly. </P ></BLOCKQUOTE ></DIV ><P > If successfully created, a named prepared-statement object lasts till the end of the current session, unless explicitly destroyed. An unnamed prepared statement lasts only until the next Parse statement specifying the unnamed statement as destination is issued. (Note that a simple Query message also destroys the unnamed statement.) Named prepared statements must be explicitly closed before they can be redefined by another Parse message, but this is not required for the unnamed statement. Named prepared statements can also be created and accessed at the SQL command level, using <TT CLASS="COMMAND" >PREPARE</TT > and <TT CLASS="COMMAND" >EXECUTE</TT >. </P ><P > Once a prepared statement exists, it can be readied for execution using a Bind message. The Bind message gives the name of the source prepared statement (empty string denotes the unnamed prepared statement), the name of the destination portal (empty string denotes the unnamed portal), and the values to use for any parameter placeholders present in the prepared statement. The supplied parameter set must match those needed by the prepared statement. (If you declared any <TT CLASS="TYPE" >void</TT > parameters in the Parse message, pass NULL values for them in the Bind message.) Bind also specifies the format to use for any data returned by the query; the format can be specified overall, or per-column. The response is either BindComplete or ErrorResponse. </P ><DIV CLASS="NOTE" ><BLOCKQUOTE CLASS="NOTE" ><P ><B >Note: </B > The choice between text and binary output is determined by the format codes given in Bind, regardless of the SQL command involved. The <TT CLASS="LITERAL" >BINARY</TT > attribute in cursor declarations is irrelevant when using extended query protocol. </P ></BLOCKQUOTE ></DIV ><P > Query planning typically occurs when the Bind message is processed. If the prepared statement has no parameters, or is executed repeatedly, the server might save the created plan and re-use it during subsequent Bind messages for the same prepared statement. However, it will do so only if it finds that a generic plan can be created that is not much less efficient than a plan that depends on the specific parameter values supplied. This happens transparently so far as the protocol is concerned. </P ><P > If successfully created, a named portal object lasts till the end of the current transaction, unless explicitly destroyed. An unnamed portal is destroyed at the end of the transaction, or as soon as the next Bind statement specifying the unnamed portal as destination is issued. (Note that a simple Query message also destroys the unnamed portal.) Named portals must be explicitly closed before they can be redefined by another Bind message, but this is not required for the unnamed portal. Named portals can also be created and accessed at the SQL command level, using <TT CLASS="COMMAND" >DECLARE CURSOR</TT > and <TT CLASS="COMMAND" >FETCH</TT >. </P ><P > Once a portal exists, it can be executed using an Execute message. The Execute message specifies the portal name (empty string denotes the unnamed portal) and a maximum result-row count (zero meaning <SPAN CLASS="QUOTE" >"fetch all rows"</SPAN >). The result-row count is only meaningful for portals containing commands that return row sets; in other cases the command is always executed to completion, and the row count is ignored. The possible responses to Execute are the same as those described above for queries issued via simple query protocol, except that Execute doesn't cause ReadyForQuery or RowDescription to be issued. </P ><P > If Execute terminates before completing the execution of a portal (due to reaching a nonzero result-row count), it will send a PortalSuspended message; the appearance of this message tells the frontend that another Execute should be issued against the same portal to complete the operation. The CommandComplete message indicating completion of the source SQL command is not sent until the portal's execution is completed. Therefore, an Execute phase is always terminated by the appearance of exactly one of these messages: CommandComplete, EmptyQueryResponse (if the portal was created from an empty query string), ErrorResponse, or PortalSuspended. </P ><P > At completion of each series of extended-query messages, the frontend should issue a Sync message. This parameterless message causes the backend to close the current transaction if it's not inside a <TT CLASS="COMMAND" >BEGIN</TT >/<TT CLASS="COMMAND" >COMMIT</TT > transaction block (<SPAN CLASS="QUOTE" >"close"</SPAN > meaning to commit if no error, or roll back if error). Then a ReadyForQuery response is issued. The purpose of Sync is to provide a resynchronization point for error recovery. When an error is detected while processing any extended-query message, the backend issues ErrorResponse, then reads and discards messages until a Sync is reached, then issues ReadyForQuery and returns to normal message processing. (But note that no skipping occurs if an error is detected <SPAN CLASS="emphasis" ><I CLASS="EMPHASIS" >while</I ></SPAN > processing Sync — this ensures that there is one and only one ReadyForQuery sent for each Sync.) </P ><DIV CLASS="NOTE" ><BLOCKQUOTE CLASS="NOTE" ><P ><B >Note: </B > Sync does not cause a transaction block opened with <TT CLASS="COMMAND" >BEGIN</TT > to be closed. It is possible to detect this situation since the ReadyForQuery message includes transaction status information. </P ></BLOCKQUOTE ></DIV ><P > In addition to these fundamental, required operations, there are several optional operations that can be used with extended-query protocol. </P ><P > The Describe message (portal variant) specifies the name of an existing portal (or an empty string for the unnamed portal). The response is a RowDescription message describing the rows that will be returned by executing the portal; or a NoData message if the portal does not contain a query that will return rows; or ErrorResponse if there is no such portal. </P ><P > The Describe message (statement variant) specifies the name of an existing prepared statement (or an empty string for the unnamed prepared statement). The response is a ParameterDescription message describing the parameters needed by the statement, followed by a RowDescription message describing the rows that will be returned when the statement is eventually executed (or a NoData message if the statement will not return rows). ErrorResponse is issued if there is no such prepared statement. Note that since Bind has not yet been issued, the formats to be used for returned columns are not yet known to the backend; the format code fields in the RowDescription message will be zeroes in this case. </P ><DIV CLASS="TIP" ><BLOCKQUOTE CLASS="TIP" ><P ><B >Tip: </B > In most scenarios the frontend should issue one or the other variant of Describe before issuing Execute, to ensure that it knows how to interpret the results it will get back. </P ></BLOCKQUOTE ></DIV ><P > The Close message closes an existing prepared statement or portal and releases resources. It is not an error to issue Close against a nonexistent statement or portal name. The response is normally CloseComplete, but could be ErrorResponse if some difficulty is encountered while releasing resources. Note that closing a prepared statement implicitly closes any open portals that were constructed from that statement. </P ><P > The Flush message does not cause any specific output to be generated, but forces the backend to deliver any data pending in its output buffers. A Flush must be sent after any extended-query command except Sync, if the frontend wishes to examine the results of that command before issuing more commands. Without Flush, messages returned by the backend will be combined into the minimum possible number of packets to minimize network overhead. </P ><DIV CLASS="NOTE" ><BLOCKQUOTE CLASS="NOTE" ><P ><B >Note: </B > The simple Query message is approximately equivalent to the series Parse, Bind, portal Describe, Execute, Close, Sync, using the unnamed prepared statement and portal objects and no parameters. One difference is that it will accept multiple SQL statements in the query string, automatically performing the bind/describe/execute sequence for each one in succession. Another difference is that it will not return ParseComplete, BindComplete, CloseComplete, or NoData messages. </P ></BLOCKQUOTE ></DIV ></DIV ><DIV CLASS="SECT2" ><H2 CLASS="SECT2" ><A NAME="AEN95963" >46.2.4. Function Call</A ></H2 ><P > The Function Call sub-protocol allows the client to request a direct call of any function that exists in the database's <TT CLASS="STRUCTNAME" >pg_proc</TT > system catalog. The client must have execute permission for the function. </P ><DIV CLASS="NOTE" ><BLOCKQUOTE CLASS="NOTE" ><P ><B >Note: </B > The Function Call sub-protocol is a legacy feature that is probably best avoided in new code. Similar results can be accomplished by setting up a prepared statement that does <TT CLASS="LITERAL" >SELECT function($1, ...)</TT >. The Function Call cycle can then be replaced with Bind/Execute. </P ></BLOCKQUOTE ></DIV ><P > A Function Call cycle is initiated by the frontend sending a FunctionCall message to the backend. The backend then sends one or more response messages depending on the results of the function call, and finally a ReadyForQuery response message. ReadyForQuery informs the frontend that it can safely send a new query or function call. </P ><P > The possible response messages from the backend are: <P ></P ></P><DIV CLASS="VARIABLELIST" ><DL ><DT >ErrorResponse</DT ><DD ><P > An error has occurred. </P ></DD ><DT >FunctionCallResponse</DT ><DD ><P > The function call was completed and returned the result given in the message. (Note that the Function Call protocol can only handle a single scalar result, not a row type or set of results.) </P ></DD ><DT >ReadyForQuery</DT ><DD ><P > Processing of the function call is complete. ReadyForQuery will always be sent, whether processing terminates successfully or with an error. </P ></DD ><DT >NoticeResponse</DT ><DD ><P > A warning message has been issued in relation to the function call. Notices are in addition to other responses, i.e., the backend will continue processing the command. </P ></DD ></DL ></DIV ><P> </P ></DIV ><DIV CLASS="SECT2" ><H2 CLASS="SECT2" ><A NAME="PROTOCOL-COPY" >46.2.5. COPY Operations</A ></H2 ><P > The <TT CLASS="COMMAND" >COPY</TT > command allows high-speed bulk data transfer to or from the server. Copy-in and copy-out operations each switch the connection into a distinct sub-protocol, which lasts until the operation is completed. </P ><P > Copy-in mode (data transfer to the server) is initiated when the backend executes a <TT CLASS="COMMAND" >COPY FROM STDIN</TT > SQL statement. The backend sends a CopyInResponse message to the frontend. The frontend should then send zero or more CopyData messages, forming a stream of input data. (The message boundaries are not required to have anything to do with row boundaries, although that is often a reasonable choice.) The frontend can terminate the copy-in mode by sending either a CopyDone message (allowing successful termination) or a CopyFail message (which will cause the <TT CLASS="COMMAND" >COPY</TT > SQL statement to fail with an error). The backend then reverts to the command-processing mode it was in before the <TT CLASS="COMMAND" >COPY</TT > started, which will be either simple or extended query protocol. It will next send either CommandComplete (if successful) or ErrorResponse (if not). </P ><P > In the event of a backend-detected error during copy-in mode (including receipt of a CopyFail message), the backend will issue an ErrorResponse message. If the <TT CLASS="COMMAND" >COPY</TT > command was issued via an extended-query message, the backend will now discard frontend messages until a Sync message is received, then it will issue ReadyForQuery and return to normal processing. If the <TT CLASS="COMMAND" >COPY</TT > command was issued in a simple Query message, the rest of that message is discarded and ReadyForQuery is issued. In either case, any subsequent CopyData, CopyDone, or CopyFail messages issued by the frontend will simply be dropped. </P ><P > The backend will ignore Flush and Sync messages received during copy-in mode. Receipt of any other non-copy message type constitutes an error that will abort the copy-in state as described above. (The exception for Flush and Sync is for the convenience of client libraries that always send Flush or Sync after an Execute message, without checking whether the command to be executed is a <TT CLASS="COMMAND" >COPY FROM STDIN</TT >.) </P ><P > Copy-out mode (data transfer from the server) is initiated when the backend executes a <TT CLASS="COMMAND" >COPY TO STDOUT</TT > SQL statement. The backend sends a CopyOutResponse message to the frontend, followed by zero or more CopyData messages (always one per row), followed by CopyDone. The backend then reverts to the command-processing mode it was in before the <TT CLASS="COMMAND" >COPY</TT > started, and sends CommandComplete. The frontend cannot abort the transfer (except by closing the connection or issuing a Cancel request), but it can discard unwanted CopyData and CopyDone messages. </P ><P > In the event of a backend-detected error during copy-out mode, the backend will issue an ErrorResponse message and revert to normal processing. The frontend should treat receipt of ErrorResponse as terminating the copy-out mode. </P ><P > It is possible for NoticeResponse and ParameterStatus messages to be interspersed between CopyData messages; frontends must handle these cases, and should be prepared for other asynchronous message types as well (see <A HREF="protocol-flow.html#PROTOCOL-ASYNC" >Section 46.2.6</A >). Otherwise, any message type other than CopyData or CopyDone may be treated as terminating copy-out mode. </P ><P > There is another Copy-related mode called Copy-both, which allows high-speed bulk data transfer to <SPAN CLASS="emphasis" ><I CLASS="EMPHASIS" >and</I ></SPAN > from the server. Copy-both mode is initiated when a backend in walsender mode executes a <TT CLASS="COMMAND" >START_REPLICATION</TT > statement. The backend sends a CopyBothResponse message to the frontend. Both the backend and the frontend may then send CopyData messages until the connection is terminated. See <A HREF="protocol-replication.html" >Section 46.3</A >. </P ><P > The CopyInResponse, CopyOutResponse and CopyBothResponse messages include fields that inform the frontend of the number of columns per row and the format codes being used for each column. (As of the present implementation, all columns in a given <TT CLASS="COMMAND" >COPY</TT > operation will use the same format, but the message design does not assume this.) </P ></DIV ><DIV CLASS="SECT2" ><H2 CLASS="SECT2" ><A NAME="PROTOCOL-ASYNC" >46.2.6. Asynchronous Operations</A ></H2 ><P > There are several cases in which the backend will send messages that are not specifically prompted by the frontend's command stream. Frontends must be prepared to deal with these messages at any time, even when not engaged in a query. At minimum, one should check for these cases before beginning to read a query response. </P ><P > It is possible for NoticeResponse messages to be generated due to outside activity; for example, if the database administrator commands a <SPAN CLASS="QUOTE" >"fast"</SPAN > database shutdown, the backend will send a NoticeResponse indicating this fact before closing the connection. Accordingly, frontends should always be prepared to accept and display NoticeResponse messages, even when the connection is nominally idle. </P ><P > ParameterStatus messages will be generated whenever the active value changes for any of the parameters the backend believes the frontend should know about. Most commonly this occurs in response to a <TT CLASS="COMMAND" >SET</TT > SQL command executed by the frontend, and this case is effectively synchronous — but it is also possible for parameter status changes to occur because the administrator changed a configuration file and then sent the <SPAN CLASS="SYSTEMITEM" >SIGHUP</SPAN > signal to the server. Also, if a <TT CLASS="COMMAND" >SET</TT > command is rolled back, an appropriate ParameterStatus message will be generated to report the current effective value. </P ><P > At present there is a hard-wired set of parameters for which ParameterStatus will be generated: they are <TT CLASS="VARNAME" >server_version</TT >, <TT CLASS="VARNAME" >server_encoding</TT >, <TT CLASS="VARNAME" >client_encoding</TT >, <TT CLASS="VARNAME" >application_name</TT >, <TT CLASS="VARNAME" >is_superuser</TT >, <TT CLASS="VARNAME" >session_authorization</TT >, <TT CLASS="VARNAME" >DateStyle</TT >, <TT CLASS="VARNAME" >IntervalStyle</TT >, <TT CLASS="VARNAME" >TimeZone</TT >, <TT CLASS="VARNAME" >integer_datetimes</TT >, and <TT CLASS="VARNAME" >standard_conforming_strings</TT >. (<TT CLASS="VARNAME" >server_encoding</TT >, <TT CLASS="VARNAME" >TimeZone</TT >, and <TT CLASS="VARNAME" >integer_datetimes</TT > were not reported by releases before 8.0; <TT CLASS="VARNAME" >standard_conforming_strings</TT > was not reported by releases before 8.1; <TT CLASS="VARNAME" >IntervalStyle</TT > was not reported by releases before 8.4; <TT CLASS="VARNAME" >application_name</TT > was not reported by releases before 9.0.) Note that <TT CLASS="VARNAME" >server_version</TT >, <TT CLASS="VARNAME" >server_encoding</TT > and <TT CLASS="VARNAME" >integer_datetimes</TT > are pseudo-parameters that cannot change after startup. This set might change in the future, or even become configurable. Accordingly, a frontend should simply ignore ParameterStatus for parameters that it does not understand or care about. </P ><P > If a frontend issues a <TT CLASS="COMMAND" >LISTEN</TT > command, then the backend will send a NotificationResponse message (not to be confused with NoticeResponse!) whenever a <TT CLASS="COMMAND" >NOTIFY</TT > command is executed for the same channel name. </P ><DIV CLASS="NOTE" ><BLOCKQUOTE CLASS="NOTE" ><P ><B >Note: </B > At present, NotificationResponse can only be sent outside a transaction, and thus it will not occur in the middle of a command-response series, though it might occur just before ReadyForQuery. It is unwise to design frontend logic that assumes that, however. Good practice is to be able to accept NotificationResponse at any point in the protocol. </P ></BLOCKQUOTE ></DIV ></DIV ><DIV CLASS="SECT2" ><H2 CLASS="SECT2" ><A NAME="AEN96049" >46.2.7. Canceling Requests in Progress</A ></H2 ><P > During the processing of a query, the frontend might request cancellation of the query. The cancel request is not sent directly on the open connection to the backend for reasons of implementation efficiency: we don't want to have the backend constantly checking for new input from the frontend during query processing. Cancel requests should be relatively infrequent, so we make them slightly cumbersome in order to avoid a penalty in the normal case. </P ><P > To issue a cancel request, the frontend opens a new connection to the server and sends a CancelRequest message, rather than the StartupMessage message that would ordinarily be sent across a new connection. The server will process this request and then close the connection. For security reasons, no direct reply is made to the cancel request message. </P ><P > A CancelRequest message will be ignored unless it contains the same key data (PID and secret key) passed to the frontend during connection start-up. If the request matches the PID and secret key for a currently executing backend, the processing of the current query is aborted. (In the existing implementation, this is done by sending a special signal to the backend process that is processing the query.) </P ><P > The cancellation signal might or might not have any effect — for example, if it arrives after the backend has finished processing the query, then it will have no effect. If the cancellation is effective, it results in the current command being terminated early with an error message. </P ><P > The upshot of all this is that for reasons of both security and efficiency, the frontend has no direct way to tell whether a cancel request has succeeded. It must continue to wait for the backend to respond to the query. Issuing a cancel simply improves the odds that the current query will finish soon, and improves the odds that it will fail with an error message instead of succeeding. </P ><P > Since the cancel request is sent across a new connection to the server and not across the regular frontend/backend communication link, it is possible for the cancel request to be issued by any process, not just the frontend whose query is to be canceled. This might provide additional flexibility when building multiple-process applications. It also introduces a security risk, in that unauthorized persons might try to cancel queries. The security risk is addressed by requiring a dynamically generated secret key to be supplied in cancel requests. </P ></DIV ><DIV CLASS="SECT2" ><H2 CLASS="SECT2" ><A NAME="AEN96057" >46.2.8. Termination</A ></H2 ><P > The normal, graceful termination procedure is that the frontend sends a Terminate message and immediately closes the connection. On receipt of this message, the backend closes the connection and terminates. </P ><P > In rare cases (such as an administrator-commanded database shutdown) the backend might disconnect without any frontend request to do so. In such cases the backend will attempt to send an error or notice message giving the reason for the disconnection before it closes the connection. </P ><P > Other termination scenarios arise from various failure cases, such as core dump at one end or the other, loss of the communications link, loss of message-boundary synchronization, etc. If either frontend or backend sees an unexpected closure of the connection, it should clean up and terminate. The frontend has the option of launching a new backend by recontacting the server if it doesn't want to terminate itself. Closing the connection is also advisable if an unrecognizable message type is received, since this probably indicates loss of message-boundary sync. </P ><P > For either normal or abnormal termination, any open transaction is rolled back, not committed. One should note however that if a frontend disconnects while a non-<TT CLASS="COMMAND" >SELECT</TT > query is being processed, the backend will probably finish the query before noticing the disconnection. If the query is outside any transaction block (<TT CLASS="COMMAND" >BEGIN</TT > ... <TT CLASS="COMMAND" >COMMIT</TT > sequence) then its results might be committed before the disconnection is recognized. </P ></DIV ><DIV CLASS="SECT2" ><H2 CLASS="SECT2" ><A NAME="AEN96066" >46.2.9. <ACRONYM CLASS="ACRONYM" >SSL</ACRONYM > Session Encryption</A ></H2 ><P > If <SPAN CLASS="PRODUCTNAME" >PostgreSQL</SPAN > was built with <ACRONYM CLASS="ACRONYM" >SSL</ACRONYM > support, frontend/backend communications can be encrypted using <ACRONYM CLASS="ACRONYM" >SSL</ACRONYM >. This provides communication security in environments where attackers might be able to capture the session traffic. For more information on encrypting <SPAN CLASS="PRODUCTNAME" >PostgreSQL</SPAN > sessions with <ACRONYM CLASS="ACRONYM" >SSL</ACRONYM >, see <A HREF="ssl-tcp.html" >Section 17.9</A >. </P ><P > To initiate an <ACRONYM CLASS="ACRONYM" >SSL</ACRONYM >-encrypted connection, the frontend initially sends an SSLRequest message rather than a StartupMessage. The server then responds with a single byte containing <TT CLASS="LITERAL" >S</TT > or <TT CLASS="LITERAL" >N</TT >, indicating that it is willing or unwilling to perform <ACRONYM CLASS="ACRONYM" >SSL</ACRONYM >, respectively. The frontend might close the connection at this point if it is dissatisfied with the response. To continue after <TT CLASS="LITERAL" >S</TT >, perform an <ACRONYM CLASS="ACRONYM" >SSL</ACRONYM > startup handshake (not described here, part of the <ACRONYM CLASS="ACRONYM" >SSL</ACRONYM > specification) with the server. If this is successful, continue with sending the usual StartupMessage. In this case the StartupMessage and all subsequent data will be <ACRONYM CLASS="ACRONYM" >SSL</ACRONYM >-encrypted. To continue after <TT CLASS="LITERAL" >N</TT >, send the usual StartupMessage and proceed without encryption. </P ><P > The frontend should also be prepared to handle an ErrorMessage response to SSLRequest from the server. This would only occur if the server predates the addition of <ACRONYM CLASS="ACRONYM" >SSL</ACRONYM > support to <SPAN CLASS="PRODUCTNAME" >PostgreSQL</SPAN >. (Such servers are now very ancient, and likely do not exist in the wild anymore.) In this case the connection must be closed, but the frontend might choose to open a fresh connection and proceed without requesting <ACRONYM CLASS="ACRONYM" >SSL</ACRONYM >. </P ><P > An initial SSLRequest can also be used in a connection that is being opened to send a CancelRequest message. </P ><P > While the protocol itself does not provide a way for the server to force <ACRONYM CLASS="ACRONYM" >SSL</ACRONYM > encryption, the administrator can configure the server to reject unencrypted sessions as a byproduct of authentication checking. </P ></DIV ></DIV ><DIV CLASS="NAVFOOTER" ><HR ALIGN="LEFT" WIDTH="100%"><TABLE SUMMARY="Footer navigation table" WIDTH="100%" BORDER="0" CELLPADDING="0" CELLSPACING="0" ><TR ><TD WIDTH="33%" ALIGN="left" VALIGN="top" ><A HREF="protocol-overview.html" ACCESSKEY="P" >Prev</A ></TD ><TD WIDTH="34%" ALIGN="center" VALIGN="top" ><A HREF="index.html" ACCESSKEY="H" >Home</A ></TD ><TD WIDTH="33%" ALIGN="right" VALIGN="top" ><A HREF="protocol-replication.html" ACCESSKEY="N" >Next</A ></TD ></TR ><TR ><TD WIDTH="33%" ALIGN="left" VALIGN="top" >Overview</TD ><TD WIDTH="34%" ALIGN="center" VALIGN="top" ><A HREF="protocol.html" ACCESSKEY="U" >Up</A ></TD ><TD WIDTH="33%" ALIGN="right" VALIGN="top" >Streaming Replication Protocol</TD ></TR ></TABLE ></DIV ></BODY ></HTML >