]> begriffs open source - ai-pg/blob - full-docs/html/protocol-flow.html
Include links to all subsection html pages, with shorter paths too
[ai-pg] / full-docs / html / protocol-flow.html
1 <?xml version="1.0" encoding="UTF-8" standalone="no"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /><title>54.2. Message Flow</title><link rel="stylesheet" type="text/css" href="stylesheet.css" /><link rev="made" href="pgsql-docs@lists.postgresql.org" /><meta name="generator" content="DocBook XSL Stylesheets Vsnapshot" /><link rel="prev" href="protocol-overview.html" title="54.1. Overview" /><link rel="next" href="sasl-authentication.html" title="54.3. SASL Authentication" /></head><body id="docContent" class="container-fluid col-10"><div class="navheader"><table width="100%" summary="Navigation header"><tr><th colspan="5" align="center">54.2. Message Flow</th></tr><tr><td width="10%" align="left"><a accesskey="p" href="protocol-overview.html" title="54.1. Overview">Prev</a> </td><td width="10%" align="left"><a accesskey="u" href="protocol.html" title="Chapter 54. Frontend/Backend Protocol">Up</a></td><th width="60%" align="center">Chapter 54. Frontend/Backend Protocol</th><td width="10%" align="right"><a accesskey="h" href="index.html" title="PostgreSQL 18.0 Documentation">Home</a></td><td width="10%" align="right"> <a accesskey="n" href="sasl-authentication.html" title="54.3. SASL Authentication">Next</a></td></tr></table><hr /></div><div class="sect1" id="PROTOCOL-FLOW"><div class="titlepage"><div><div><h2 class="title" style="clear: both">54.2. Message Flow <a href="#PROTOCOL-FLOW" class="id_link">#</a></h2></div></div></div><div class="toc"><dl class="toc"><dt><span class="sect2"><a href="protocol-flow.html#PROTOCOL-FLOW-START-UP">54.2.1. Start-up</a></span></dt><dt><span class="sect2"><a href="protocol-flow.html#PROTOCOL-FLOW-SIMPLE-QUERY">54.2.2. Simple Query</a></span></dt><dt><span class="sect2"><a href="protocol-flow.html#PROTOCOL-FLOW-EXT-QUERY">54.2.3. Extended Query</a></span></dt><dt><span class="sect2"><a href="protocol-flow.html#PROTOCOL-FLOW-PIPELINING">54.2.4. Pipelining</a></span></dt><dt><span class="sect2"><a href="protocol-flow.html#PROTOCOL-FLOW-FUNCTION-CALL">54.2.5. Function Call</a></span></dt><dt><span class="sect2"><a href="protocol-flow.html#PROTOCOL-COPY">54.2.6. COPY Operations</a></span></dt><dt><span class="sect2"><a href="protocol-flow.html#PROTOCOL-ASYNC">54.2.7. Asynchronous Operations</a></span></dt><dt><span class="sect2"><a href="protocol-flow.html#PROTOCOL-FLOW-CANCELING-REQUESTS">54.2.8. Canceling Requests in Progress</a></span></dt><dt><span class="sect2"><a href="protocol-flow.html#PROTOCOL-FLOW-TERMINATION">54.2.9. Termination</a></span></dt><dt><span class="sect2"><a href="protocol-flow.html#PROTOCOL-FLOW-SSL">54.2.10. <acronym class="acronym">SSL</acronym> Session Encryption</a></span></dt><dt><span class="sect2"><a href="protocol-flow.html#PROTOCOL-FLOW-GSSAPI">54.2.11. <acronym class="acronym">GSSAPI</acronym> Session Encryption</a></span></dt></dl></div><p>
3    This section describes the message flow and the semantics of each
4    message type.  (Details of the exact representation of each message
5    appear in <a class="xref" href="protocol-message-formats.html" title="54.7. Message Formats">Section 54.7</a>.)  There are
6    several different sub-protocols depending on the state of the
7    connection: start-up, query, function call,
8    <code class="command">COPY</code>, and termination.  There are also special
9    provisions for asynchronous operations (including notification
10    responses and command cancellation), which can occur at any time
11    after the start-up phase.
12   </p><div class="sect2" id="PROTOCOL-FLOW-START-UP"><div class="titlepage"><div><div><h3 class="title">54.2.1. Start-up <a href="#PROTOCOL-FLOW-START-UP" class="id_link">#</a></h3></div></div></div><p>
13     To begin a session, a frontend opens a connection to the server and sends
14     a startup message.  This message includes the names of the user and of the
15     database the user wants to connect to; it also identifies the particular
16     protocol version to be used.  (Optionally, the startup message can include
17     additional settings for run-time parameters.)
18     The server then uses this information and
19     the contents of its configuration files (such as
20     <code class="filename">pg_hba.conf</code>) to determine
21     whether the connection is provisionally acceptable, and what additional
22     authentication is required (if any).
23    </p><p>
24     The server then sends an appropriate authentication request message,
25     to which the frontend must reply with an appropriate authentication
26     response message (such as a password).
27     For all authentication methods except GSSAPI, SSPI and SASL, there is at
28     most one request and one response. In some methods, no response
29     at all is needed from the frontend, and so no authentication request
30     occurs. For GSSAPI, SSPI and SASL, multiple exchanges of packets may be
31     needed to complete the authentication.
32    </p><p>
33     The authentication cycle ends with the server either rejecting the
34     connection attempt (ErrorResponse), or sending AuthenticationOk.
35    </p><p>
36     The possible messages from the server in this phase are:
37
38     </p><div class="variablelist"><dl class="variablelist"><dt><span class="term">ErrorResponse</span></dt><dd><p>
39         The connection attempt has been rejected.
40         The server then immediately closes the connection.
41        </p></dd><dt><span class="term">AuthenticationOk</span></dt><dd><p>
42         The authentication exchange is successfully completed.
43        </p></dd><dt><span class="term">AuthenticationKerberosV5</span></dt><dd><p>
44         The frontend must now take part in a Kerberos V5
45         authentication dialog (not described here, part of the
46         Kerberos specification) with the server.  If this is
47         successful, the server responds with an AuthenticationOk,
48         otherwise it responds with an ErrorResponse. This is no
49         longer supported.
50        </p></dd><dt><span class="term">AuthenticationCleartextPassword</span></dt><dd><p>
51         The frontend must now send a PasswordMessage containing the
52         password in clear-text form.  If
53         this is the correct password, the server responds with an
54         AuthenticationOk, otherwise it responds with an ErrorResponse.
55        </p></dd><dt><span class="term">AuthenticationMD5Password</span></dt><dd><p>
56         The frontend must now send a PasswordMessage containing the
57         password (with user name) encrypted via MD5, then encrypted
58         again using the 4-byte random salt specified in the
59         AuthenticationMD5Password message.  If this is the correct
60         password, the server responds with an AuthenticationOk,
61         otherwise it responds with an ErrorResponse.  The actual
62         PasswordMessage can be computed in SQL as <code class="literal">concat('md5',
63         md5(concat(md5(concat(password, username)), random-salt)))</code>.
64         (Keep in mind the <code class="function">md5()</code> function returns its
65         result as a hex string.)
66        </p><div class="warning"><h3 class="title">Warning</h3><p>
67           Support for MD5-encrypted passwords is deprecated and will be removed
68           in a future release of <span class="productname">PostgreSQL</span>.  Refer
69           to <a class="xref" href="auth-password.html" title="20.5. Password Authentication">Section 20.5</a> for details about migrating to
70           another password type.
71          </p></div></dd><dt><span class="term">AuthenticationGSS</span></dt><dd><p>
72         The frontend must now initiate a GSSAPI negotiation. The frontend
73         will send a GSSResponse message with the first part of the GSSAPI
74         data stream in response to this. If further messages are needed,
75         the server will respond with AuthenticationGSSContinue.
76        </p></dd><dt><span class="term">AuthenticationSSPI</span></dt><dd><p>
77         The frontend must now initiate an SSPI negotiation. The frontend
78         will send a GSSResponse with the first part of the SSPI
79         data stream in response to this. If further messages are needed,
80         the server will respond with AuthenticationGSSContinue.
81        </p></dd><dt><span class="term">AuthenticationGSSContinue</span></dt><dd><p>
82         This message contains the response data from the previous step
83         of GSSAPI or SSPI negotiation (AuthenticationGSS, AuthenticationSSPI
84         or a previous AuthenticationGSSContinue). If the GSSAPI
85         or SSPI data in this message
86         indicates more data is needed to complete the authentication,
87         the frontend must send that data as another GSSResponse message. If
88         GSSAPI or SSPI authentication is completed by this message, the server
89         will next send AuthenticationOk to indicate successful authentication
90         or ErrorResponse to indicate failure.
91        </p></dd><dt><span class="term">AuthenticationSASL</span></dt><dd><p>
92         The frontend must now initiate a SASL negotiation, using one of the
93         SASL mechanisms listed in the message. The frontend will send a
94         SASLInitialResponse with the name of the selected mechanism, and the
95         first part of the SASL data stream in response to this. If further
96         messages are needed, the server will respond with
97         AuthenticationSASLContinue. See <a class="xref" href="sasl-authentication.html" title="54.3. SASL Authentication">Section 54.3</a>
98         for details.
99        </p></dd><dt><span class="term">AuthenticationSASLContinue</span></dt><dd><p>
100         This message contains challenge data from the previous step of SASL
101         negotiation (AuthenticationSASL, or a previous
102         AuthenticationSASLContinue). The frontend must respond with a
103         SASLResponse message.
104        </p></dd><dt><span class="term">AuthenticationSASLFinal</span></dt><dd><p>
105         SASL authentication has completed with additional mechanism-specific
106         data for the client. The server will next send AuthenticationOk to
107         indicate successful authentication, or an ErrorResponse to indicate
108         failure. This message is sent only if the SASL mechanism specifies
109         additional data to be sent from server to client at completion.
110        </p></dd><dt><span class="term">NegotiateProtocolVersion</span></dt><dd><p>
111         The server does not support the minor protocol version requested
112         by the client, but does support an earlier version of the protocol;
113         this message indicates the highest supported minor version.  This
114         message will also be sent if the client requested unsupported protocol
115         options (i.e., beginning with <code class="literal">_pq_.</code>) in the
116         startup packet.
117        </p><p>
118         After this message, the authentication will continue using the version
119         indicated by the server.  If the client does not support the older
120         version, it should immediately close the connection.  If the server
121         does not send this message, it supports the client's requested
122         protocol version and all the protocol options.
123        </p></dd></dl></div><p>
124    </p><p>
125     If the frontend does not support the authentication method
126     requested by the server, then it should immediately close the
127     connection.
128    </p><p>
129     After having received AuthenticationOk, the frontend must wait
130     for further messages from the server.  In this phase a backend process
131     is being started, and the frontend is just an interested bystander.
132     It is still possible for the startup attempt
133     to fail (ErrorResponse) or the server to decline support for the requested
134     minor protocol version (NegotiateProtocolVersion), but in the normal case
135     the backend will send some ParameterStatus messages, BackendKeyData, and
136     finally ReadyForQuery.
137    </p><p>
138     During this phase the backend will attempt to apply any additional
139     run-time parameter settings that were given in the startup message.
140     If successful, these values become session defaults.  An error causes
141     ErrorResponse and exit.
142    </p><p>
143     The possible messages from the backend in this phase are:
144
145     </p><div class="variablelist"><dl class="variablelist"><dt><span class="term">BackendKeyData</span></dt><dd><p>
146         This message provides secret-key data that the frontend must
147         save if it wants to be able to issue cancel requests later.
148         The frontend should not respond to this message, but should
149         continue listening for a ReadyForQuery message.
150        </p><p>
151         The <span class="productname">PostgreSQL</span> server will always send this
152         message, but some third party backend implementations of the protocol
153         that don't support query cancellation are known not to.
154        </p></dd><dt><span class="term">ParameterStatus</span></dt><dd><p>
155         This message informs the frontend about the current (initial)
156          setting of backend parameters, such as <a class="xref" href="runtime-config-client.html#GUC-CLIENT-ENCODING">client_encoding</a> or <a class="xref" href="runtime-config-client.html#GUC-DATESTYLE">DateStyle</a>.
157          The frontend can ignore this message, or record the settings
158          for its future use; see <a class="xref" href="protocol-flow.html#PROTOCOL-ASYNC" title="54.2.7. Asynchronous Operations">Section 54.2.7</a> for
159          more details.  The frontend should not respond to this
160          message, but should continue listening for a ReadyForQuery
161          message.
162        </p></dd><dt><span class="term">ReadyForQuery</span></dt><dd><p>
163         Start-up is completed.  The frontend can now issue commands.
164        </p></dd><dt><span class="term">ErrorResponse</span></dt><dd><p>
165         Start-up failed.  The connection is closed after sending this
166         message.
167        </p></dd><dt><span class="term">NoticeResponse</span></dt><dd><p>
168         A warning message has been issued.  The frontend should
169         display the message but continue listening for ReadyForQuery
170         or ErrorResponse.
171        </p></dd></dl></div><p>
172    </p><p>
173     The ReadyForQuery message is the same one that the backend will
174     issue after each command cycle.  Depending on the coding needs of
175     the frontend, it is reasonable to consider ReadyForQuery as
176     starting a command cycle, or to consider ReadyForQuery as ending the
177     start-up phase and each subsequent command cycle.
178    </p></div><div class="sect2" id="PROTOCOL-FLOW-SIMPLE-QUERY"><div class="titlepage"><div><div><h3 class="title">54.2.2. Simple Query <a href="#PROTOCOL-FLOW-SIMPLE-QUERY" class="id_link">#</a></h3></div></div></div><p>
179     A simple query cycle is initiated by the frontend sending a Query message
180     to the backend.  The message includes an SQL command (or commands)
181     expressed as a text string.
182     The backend then sends one or more response
183     messages depending on the contents of the query command string,
184     and finally a ReadyForQuery response message.  ReadyForQuery
185     informs the frontend that it can safely send a new command.
186     (It is not actually necessary for the frontend to wait for
187     ReadyForQuery before issuing another command, but the frontend must
188     then take responsibility for figuring out what happens if the earlier
189     command fails and already-issued later commands succeed.)
190    </p><p>
191     The possible response messages from the backend are:
192
193     </p><div class="variablelist"><dl class="variablelist"><dt><span class="term">CommandComplete</span></dt><dd><p>
194         An SQL command completed normally.
195        </p></dd><dt><span class="term">CopyInResponse</span></dt><dd><p>
196         The backend is ready to copy data from the frontend to a
197         table; see <a class="xref" href="protocol-flow.html#PROTOCOL-COPY" title="54.2.6. COPY Operations">Section 54.2.6</a>.
198        </p></dd><dt><span class="term">CopyOutResponse</span></dt><dd><p>
199         The backend is ready to copy data from a table to the
200         frontend; see <a class="xref" href="protocol-flow.html#PROTOCOL-COPY" title="54.2.6. COPY Operations">Section 54.2.6</a>.
201        </p></dd><dt><span class="term">RowDescription</span></dt><dd><p>
202         Indicates that rows are about to be returned in response to
203         a <code class="command">SELECT</code>, <code class="command">FETCH</code>, etc. query.
204         The contents of this message describe the column layout of the rows.
205         This will be followed by a DataRow message for each row being returned
206         to the frontend.
207        </p></dd><dt><span class="term">DataRow</span></dt><dd><p>
208         One of the set of rows returned by
209         a <code class="command">SELECT</code>, <code class="command">FETCH</code>, etc. query.
210        </p></dd><dt><span class="term">EmptyQueryResponse</span></dt><dd><p>
211         An empty query string was recognized.
212        </p></dd><dt><span class="term">ErrorResponse</span></dt><dd><p>
213         An error has occurred.
214        </p></dd><dt><span class="term">ReadyForQuery</span></dt><dd><p>
215         Processing of the query string is complete.  A separate
216         message is sent to indicate this because the query string might
217         contain multiple SQL commands.  (CommandComplete marks the
218         end of processing one SQL command, not the whole string.)
219         ReadyForQuery will always be sent, whether processing
220         terminates successfully or with an error.
221        </p></dd><dt><span class="term">NoticeResponse</span></dt><dd><p>
222         A warning message has been issued in relation to the query.
223         Notices are in addition to other responses, i.e., the backend
224         will continue processing the command.
225        </p></dd></dl></div><p>
226    </p><p>
227     The response to a <code class="command">SELECT</code> query (or other queries that
228     return row sets, such as <code class="command">EXPLAIN</code> or <code class="command">SHOW</code>)
229     normally consists of RowDescription, zero or more
230     DataRow messages, and then CommandComplete.
231     <code class="command">COPY</code> to or from the frontend invokes special protocol
232     as described in <a class="xref" href="protocol-flow.html#PROTOCOL-COPY" title="54.2.6. COPY Operations">Section 54.2.6</a>.
233     All other query types normally produce only
234     a CommandComplete message.
235    </p><p>
236     Since a query string could contain several queries (separated by
237     semicolons), there might be several such response sequences before the
238     backend finishes processing the query string.  ReadyForQuery is issued
239     when the entire string has been processed and the backend is ready to
240     accept a new query string.
241    </p><p>
242     If a completely empty (no contents other than whitespace) query string
243     is received, the response is EmptyQueryResponse followed by ReadyForQuery.
244    </p><p>
245     In the event of an error, ErrorResponse is issued followed by
246     ReadyForQuery.  All further processing of the query string is aborted by
247     ErrorResponse (even if more queries remained in it).  Note that this
248     might occur partway through the sequence of messages generated by an
249     individual query.
250    </p><p>
251     In simple Query mode, the format of retrieved values is always text,
252     except when the given command is a <code class="command">FETCH</code> from a cursor
253     declared with the <code class="literal">BINARY</code> option.  In that case, the
254     retrieved values are in binary format.  The format codes given in
255     the RowDescription message tell which format is being used.
256    </p><p>
257     A frontend must be prepared to accept ErrorResponse and
258     NoticeResponse messages whenever it is expecting any other type of
259     message.  See also <a class="xref" href="protocol-flow.html#PROTOCOL-ASYNC" title="54.2.7. Asynchronous Operations">Section 54.2.7</a> concerning messages
260     that the backend might generate due to outside events.
261    </p><p>
262     Recommended practice is to code frontends in a state-machine style
263     that will accept any message type at any time that it could make sense,
264     rather than wiring in assumptions about the exact sequence of messages.
265    </p><div class="sect3" id="PROTOCOL-FLOW-MULTI-STATEMENT"><div class="titlepage"><div><div><h4 class="title">54.2.2.1. Multiple Statements in a Simple Query <a href="#PROTOCOL-FLOW-MULTI-STATEMENT" class="id_link">#</a></h4></div></div></div><p>
266      When a simple Query message contains more than one SQL statement
267      (separated by semicolons), those statements are executed as a single
268      transaction, unless explicit transaction control commands are included
269      to force a different behavior.  For example, if the message contains
270 </p><pre class="programlisting">
271 INSERT INTO mytable VALUES(1);
272 SELECT 1/0;
273 INSERT INTO mytable VALUES(2);
274 </pre><p>
275      then the divide-by-zero failure in the <code class="command">SELECT</code> will force
276      rollback of the first <code class="command">INSERT</code>.  Furthermore, because
277      execution of the message is abandoned at the first error, the second
278      <code class="command">INSERT</code> is never attempted at all.
279     </p><p>
280      If instead the message contains
281 </p><pre class="programlisting">
282 BEGIN;
283 INSERT INTO mytable VALUES(1);
284 COMMIT;
285 INSERT INTO mytable VALUES(2);
286 SELECT 1/0;
287 </pre><p>
288      then the first <code class="command">INSERT</code> is committed by the
289      explicit <code class="command">COMMIT</code> command.  The second <code class="command">INSERT</code>
290      and the <code class="command">SELECT</code> are still treated as a single transaction,
291      so that the divide-by-zero failure will roll back the
292      second <code class="command">INSERT</code>, but not the first one.
293     </p><p>
294      This behavior is implemented by running the statements in a
295      multi-statement Query message in an <em class="firstterm">implicit transaction
296      block</em> unless there is some explicit transaction block for them to
297      run in.  The main difference between an implicit transaction block and
298      a regular one is that an implicit block is closed automatically at the
299      end of the Query message, either by an implicit commit if there was no
300      error, or an implicit rollback if there was an error.  This is similar
301      to the implicit commit or rollback that happens for a statement
302      executed by itself (when not in a transaction block).
303     </p><p>
304      If the session is already in a transaction block, as a result of
305      a <code class="command">BEGIN</code> in some previous message, then the Query message
306      simply continues that transaction block, whether the message contains
307      one statement or several.  However, if the Query message contains
308      a <code class="command">COMMIT</code> or <code class="command">ROLLBACK</code> closing the existing
309      transaction block, then any following statements are executed in an
310      implicit transaction block.
311      Conversely, if a <code class="command">BEGIN</code> appears in a multi-statement Query
312      message, then it starts a regular transaction block that will only be
313      terminated by an explicit <code class="command">COMMIT</code> or <code class="command">ROLLBACK</code>,
314      whether that appears in this Query message or a later one.
315      If the <code class="command">BEGIN</code> follows some statements that were executed as
316      an implicit transaction block, those statements are not immediately
317      committed; in effect, they are retroactively included into the new
318      regular transaction block.
319     </p><p>
320      A <code class="command">COMMIT</code> or <code class="command">ROLLBACK</code> appearing in an implicit
321      transaction block is executed as normal, closing the implicit block;
322      however, a warning will be issued since a <code class="command">COMMIT</code>
323      or <code class="command">ROLLBACK</code> without a previous <code class="command">BEGIN</code> might
324      represent a mistake.  If more statements follow, a new implicit
325      transaction block will be started for them.
326     </p><p>
327      Savepoints are not allowed in an implicit transaction block, since
328      they would conflict with the behavior of automatically closing the
329      block upon any error.
330     </p><p>
331      Remember that, regardless of any transaction control commands that may
332      be present, execution of the Query message stops at the first error.
333      Thus for example given
334 </p><pre class="programlisting">
335 BEGIN;
336 SELECT 1/0;
337 ROLLBACK;
338 </pre><p>
339      in a single Query message, the session will be left inside a failed
340      regular transaction block, since the <code class="command">ROLLBACK</code> is not
341      reached after the divide-by-zero error.  Another <code class="command">ROLLBACK</code>
342      will be needed to restore the session to a usable state.
343     </p><p>
344      Another behavior of note is that initial lexical and syntactic
345      analysis is done on the entire query string before any of it is
346      executed.  Thus simple errors (such as a misspelled keyword) in later
347      statements can prevent execution of any of the statements.  This
348      is normally invisible to users since the statements would all roll
349      back anyway when done as an implicit transaction block.  However,
350      it can be visible when attempting to do multiple transactions within a
351      multi-statement Query.  For instance, if a typo turned our previous
352      example into
353 </p><pre class="programlisting">
354 BEGIN;
355 INSERT INTO mytable VALUES(1);
356 COMMIT;
357 INSERT INTO mytable VALUES(2);
358 SELCT 1/0;
359 </pre><p>
360      then none of the statements would get run, resulting in the visible
361      difference that the first <code class="command">INSERT</code> is not committed.
362      Errors detected at semantic analysis or later, such as a misspelled
363      table or column name, do not have this effect.
364     </p><p>
365      Lastly, note that all the statements within the Query message will
366      observe the same value of <code class="function">statement_timestamp()</code>,
367      since that timestamp is updated only upon receipt of the Query
368      message.  This will result in them all observing the same
369      value of <code class="function">transaction_timestamp()</code> as well,
370      except in cases where the query string ends a previously-started
371      transaction and begins a new one.
372     </p></div></div><div class="sect2" id="PROTOCOL-FLOW-EXT-QUERY"><div class="titlepage"><div><div><h3 class="title">54.2.3. Extended Query <a href="#PROTOCOL-FLOW-EXT-QUERY" class="id_link">#</a></h3></div></div></div><p>
373     The extended query protocol breaks down the above-described simple
374     query protocol into multiple steps.  The results of preparatory
375     steps can be re-used multiple times for improved efficiency.
376     Furthermore, additional features are available, such as the possibility
377     of supplying data values as separate parameters instead of having to
378     insert them directly into a query string.
379    </p><p>
380     In the extended protocol, the frontend first sends a Parse message,
381     which contains a textual query string, optionally some information
382     about data types of parameter placeholders, and the
383     name of a destination prepared-statement object (an empty string
384     selects the unnamed prepared statement).  The response is
385     either ParseComplete or ErrorResponse.  Parameter data types can be
386     specified by OID; if not given, the parser attempts to infer the
387     data types in the same way as it would do for untyped literal string
388     constants.
389    </p><div class="note"><h3 class="title">Note</h3><p>
390      A parameter data type can be left unspecified by setting it to zero,
391      or by making the array of parameter type OIDs shorter than the
392      number of parameter symbols (<code class="literal">$</code><em class="replaceable"><code>n</code></em>)
393      used in the query string.  Another special case is that a parameter's
394      type can be specified as <code class="type">void</code> (that is, the OID of the
395      <code class="type">void</code> pseudo-type).  This is meant to allow parameter symbols
396      to be used for function parameters that are actually OUT parameters.
397      Ordinarily there is no context in which a <code class="type">void</code> parameter
398      could be used, but if such a parameter symbol appears in a function's
399      parameter list, it is effectively ignored.  For example, a function
400      call such as <code class="literal">foo($1,$2,$3,$4)</code> could match a function with
401      two IN and two OUT arguments, if <code class="literal">$3</code> and <code class="literal">$4</code>
402      are specified as having type <code class="type">void</code>.
403     </p></div><div class="note"><h3 class="title">Note</h3><p>
404      The query string contained in a Parse message cannot include more
405      than one SQL statement; else a syntax error is reported.  This
406      restriction does not exist in the simple-query protocol, but it
407      does exist in the extended protocol, because allowing prepared
408      statements or portals to contain multiple commands would complicate
409      the protocol unduly.
410     </p></div><p>
411     If successfully created, a named prepared-statement object lasts till
412     the end of the current session, unless explicitly destroyed.  An unnamed
413     prepared statement lasts only until the next Parse statement specifying
414     the unnamed statement as destination is issued.  (Note that a simple
415     Query message also destroys the unnamed statement.)  Named prepared
416     statements must be explicitly closed before they can be redefined by
417     another Parse message, but this is not required for the unnamed statement.
418     Named prepared statements can also be created and accessed at the SQL
419     command level, using <code class="command">PREPARE</code> and <code class="command">EXECUTE</code>.
420    </p><p>
421     Once a prepared statement exists, it can be readied for execution using a
422     Bind message.  The Bind message gives the name of the source prepared
423     statement (empty string denotes the unnamed prepared statement), the name
424     of the destination portal (empty string denotes the unnamed portal), and
425     the values to use for any parameter placeholders present in the prepared
426     statement.  The
427     supplied parameter set must match those needed by the prepared statement.
428     (If you declared any <code class="type">void</code> parameters in the Parse message,
429     pass NULL values for them in the Bind message.)
430     Bind also specifies the format to use for any data returned
431     by the query; the format can be specified overall, or per-column.
432     The response is either BindComplete or ErrorResponse.
433    </p><div class="note"><h3 class="title">Note</h3><p>
434      The choice between text and binary output is determined by the format
435      codes given in Bind, regardless of the SQL command involved.  The
436      <code class="literal">BINARY</code> attribute in cursor declarations is irrelevant when
437      using extended query protocol.
438     </p></div><p>
439     Query planning typically occurs when the Bind message is processed.
440     If the prepared statement has no parameters, or is executed repeatedly,
441     the server might save the created plan and re-use it during subsequent
442     Bind messages for the same prepared statement.  However, it will do so
443     only if it finds that a generic plan can be created that is not much
444     less efficient than a plan that depends on the specific parameter values
445     supplied.  This happens transparently so far as the protocol is concerned.
446    </p><p>
447     If successfully created, a named portal object lasts till the end of the
448     current transaction, unless explicitly destroyed.  An unnamed portal is
449     destroyed at the end of the transaction, or as soon as the next Bind
450     statement specifying the unnamed portal as destination is issued.  (Note
451     that a simple Query message also destroys the unnamed portal.)  Named
452     portals must be explicitly closed before they can be redefined by another
453     Bind message, but this is not required for the unnamed portal.
454     Named portals can also be created and accessed at the SQL
455     command level, using <code class="command">DECLARE CURSOR</code> and <code class="command">FETCH</code>.
456    </p><p>
457     Once a portal exists, it can be executed using an Execute message.
458     The Execute message specifies the portal name (empty string denotes the
459     unnamed portal) and
460     a maximum result-row count (zero meaning <span class="quote">“<span class="quote">fetch all rows</span>”</span>).
461     The result-row count is only meaningful for portals
462     containing commands that return row sets; in other cases the command is
463     always executed to completion, and the row count is ignored.
464     The possible
465     responses to Execute are the same as those described above for queries
466     issued via simple query protocol, except that Execute doesn't cause
467     ReadyForQuery or RowDescription to be issued.
468    </p><p>
469     If Execute terminates before completing the execution of a portal
470     (due to reaching a nonzero result-row count), it will send a
471     PortalSuspended message; the appearance of this message tells the frontend
472     that another Execute should be issued against the same portal to
473     complete the operation.  The CommandComplete message indicating
474     completion of the source SQL command is not sent until
475     the portal's execution is completed.  Therefore, an Execute phase is
476     always terminated by the appearance of exactly one of these messages:
477     CommandComplete, EmptyQueryResponse (if the portal was created from
478     an empty query string), ErrorResponse, or PortalSuspended.
479    </p><p>
480     At completion of each series of extended-query messages, the frontend
481     should issue a Sync message.  This parameterless message causes the
482     backend to close the current transaction if it's not inside a
483     <code class="command">BEGIN</code>/<code class="command">COMMIT</code> transaction block (<span class="quote">“<span class="quote">close</span>”</span>
484     meaning to commit if no error, or roll back if error).  Then a
485     ReadyForQuery response is issued.  The purpose of Sync is to provide
486     a resynchronization point for error recovery.  When an error is detected
487     while processing any extended-query message, the backend issues
488     ErrorResponse, then reads and discards messages until a Sync is reached,
489     then issues ReadyForQuery and returns to normal message processing.
490     (But note that no skipping occurs if an error is detected
491     <span class="emphasis"><em>while</em></span> processing Sync — this ensures that there is one
492     and only one ReadyForQuery sent for each Sync.)
493    </p><div class="note"><h3 class="title">Note</h3><p>
494      Sync does not cause a transaction block opened with <code class="command">BEGIN</code>
495      to be closed.  It is possible to detect this situation since the
496      ReadyForQuery message includes transaction status information.
497     </p></div><p>
498     In addition to these fundamental, required operations, there are several
499     optional operations that can be used with extended-query protocol.
500    </p><p>
501     The Describe message (portal variant) specifies the name of an existing
502     portal (or an empty string for the unnamed portal).  The response is a
503     RowDescription message describing the rows that will be returned by
504     executing the portal; or a NoData message if the portal does not contain a
505     query that will return rows; or ErrorResponse if there is no such portal.
506    </p><p>
507     The Describe message (statement variant) specifies the name of an existing
508     prepared statement (or an empty string for the unnamed prepared
509     statement).  The response is a ParameterDescription message describing the
510     parameters needed by the statement, followed by a RowDescription message
511     describing the rows that will be returned when the statement is eventually
512     executed (or a NoData message if the statement will not return rows).
513     ErrorResponse is issued if there is no such prepared statement.  Note that
514     since Bind has not yet been issued, the formats to be used for returned
515     columns are not yet known to the backend; the format code fields in the
516     RowDescription message will be zeroes in this case.
517    </p><div class="tip"><h3 class="title">Tip</h3><p>
518      In most scenarios the frontend should issue one or the other variant
519      of Describe before issuing Execute, to ensure that it knows how to
520      interpret the results it will get back.
521     </p></div><p>
522     The Close message closes an existing prepared statement or portal
523     and releases resources.  It is not an error to issue Close against
524     a nonexistent statement or portal name.  The response is normally
525     CloseComplete, but could be ErrorResponse if some difficulty is
526     encountered while releasing resources.  Note that closing a prepared
527     statement implicitly closes any open portals that were constructed
528     from that statement.
529    </p><p>
530     The Flush message does not cause any specific output to be generated,
531     but forces the backend to deliver any data pending in its output
532     buffers.  A Flush must be sent after any extended-query command except
533     Sync, if the frontend wishes to examine the results of that command before
534     issuing more commands.  Without Flush, messages returned by the backend
535     will be combined into the minimum possible number of packets to minimize
536     network overhead.
537    </p><div class="note"><h3 class="title">Note</h3><p>
538      The simple Query message is approximately equivalent to the series Parse,
539      Bind, portal Describe, Execute, Close, Sync, using the unnamed prepared
540      statement and portal objects and no parameters.  One difference is that
541      it will accept multiple SQL statements in the query string, automatically
542      performing the bind/describe/execute sequence for each one in succession.
543      Another difference is that it will not return ParseComplete, BindComplete,
544      CloseComplete, or NoData messages.
545     </p></div></div><div class="sect2" id="PROTOCOL-FLOW-PIPELINING"><div class="titlepage"><div><div><h3 class="title">54.2.4. Pipelining <a href="#PROTOCOL-FLOW-PIPELINING" class="id_link">#</a></h3></div></div></div><a id="id-1.10.6.7.6.2" class="indexterm"></a><p>
546     Use of the extended query protocol
547     allows <em class="firstterm">pipelining</em>, which means sending a series
548     of queries without waiting for earlier ones to complete.  This reduces
549     the number of network round trips needed to complete a given series of
550     operations.  However, the user must carefully consider the required
551     behavior if one of the steps fails, since later queries will already
552     be in flight to the server.
553    </p><p>
554     One way to deal with that is to make the whole query series be a
555     single transaction, that is wrap it in <code class="command">BEGIN</code> ...
556     <code class="command">COMMIT</code>.  However, this does not help if one wishes
557     for some of the commands to commit independently of others.
558    </p><p>
559     The extended query protocol provides another way to manage this
560     concern, which is to omit sending Sync messages between steps that
561     are dependent.  Since, after an error, the backend will skip command
562     messages until it finds Sync, this allows later commands in a pipeline
563     to be skipped automatically when an earlier one fails, without the
564     client having to manage that explicitly with <code class="command">BEGIN</code>
565     and <code class="command">COMMIT</code>.  Independently-committable segments
566     of the pipeline can be separated by Sync messages.
567    </p><p>
568     If the client has not issued an explicit <code class="command">BEGIN</code>,
569     then an implicit transaction block is started and each Sync ordinarily
570     causes an implicit <code class="command">COMMIT</code> if the preceding step(s)
571     succeeded, or an implicit <code class="command">ROLLBACK</code> if they failed.
572     This implicit transaction block will only be detected by the server
573     when the first command ends without a sync.  There are a few DDL
574     commands (such as <code class="command">CREATE DATABASE</code>) that cannot be
575     executed inside a transaction block. If one of these is executed in a
576     pipeline, it will fail unless it is the first command after a Sync.
577     Furthermore, upon success it will force an immediate commit to preserve
578     database consistency. Thus a Sync immediately following one of these
579     commands has no effect except to respond with ReadyForQuery.
580    </p><p>
581     When using this method, completion of the pipeline must be determined
582     by counting ReadyForQuery messages and waiting for that to reach the
583     number of Syncs sent.  Counting command completion responses is
584     unreliable, since some of the commands may be skipped and thus not
585     produce a completion message.
586    </p></div><div class="sect2" id="PROTOCOL-FLOW-FUNCTION-CALL"><div class="titlepage"><div><div><h3 class="title">54.2.5. Function Call <a href="#PROTOCOL-FLOW-FUNCTION-CALL" class="id_link">#</a></h3></div></div></div><p>
587     The Function Call sub-protocol allows the client to request a direct
588     call of any function that exists in the database's
589     <code class="structname">pg_proc</code> system catalog.  The client must have
590     execute permission for the function.
591    </p><div class="note"><h3 class="title">Note</h3><p>
592      The Function Call sub-protocol is a legacy feature that is probably best
593      avoided in new code.  Similar results can be accomplished by setting up
594      a prepared statement that does <code class="literal">SELECT function($1, ...)</code>.
595      The Function Call cycle can then be replaced with Bind/Execute.
596     </p></div><p>
597     A Function Call cycle is initiated by the frontend sending a
598     FunctionCall message to the backend.  The backend then sends one
599     or more response messages depending on the results of the function
600     call, and finally a ReadyForQuery response message.  ReadyForQuery
601     informs the frontend that it can safely send a new query or
602     function call.
603    </p><p>
604     The possible response messages from the backend are:
605
606     </p><div class="variablelist"><dl class="variablelist"><dt><span class="term">ErrorResponse</span></dt><dd><p>
607         An error has occurred.
608        </p></dd><dt><span class="term">FunctionCallResponse</span></dt><dd><p>
609         The function call was completed and returned the result given
610         in the message.
611         (Note that the Function Call protocol can only handle a single
612         scalar result, not a row type or set of results.)
613        </p></dd><dt><span class="term">ReadyForQuery</span></dt><dd><p>
614         Processing of the function call is complete.  ReadyForQuery
615         will always be sent, whether processing terminates
616         successfully or with an error.
617        </p></dd><dt><span class="term">NoticeResponse</span></dt><dd><p>
618         A warning message has been issued in relation to the function
619         call.  Notices are in addition to other responses, i.e., the
620         backend will continue processing the command.
621        </p></dd></dl></div><p>
622    </p></div><div class="sect2" id="PROTOCOL-COPY"><div class="titlepage"><div><div><h3 class="title">54.2.6. COPY Operations <a href="#PROTOCOL-COPY" class="id_link">#</a></h3></div></div></div><p>
623     The <code class="command">COPY</code> command allows high-speed bulk data transfer
624     to or from the server.  Copy-in and copy-out operations each switch
625     the connection into a distinct sub-protocol, which lasts until the
626     operation is completed.
627    </p><p>
628     Copy-in mode (data transfer to the server) is initiated when the
629     backend executes a <code class="command">COPY FROM STDIN</code> SQL statement.  The backend
630     sends a CopyInResponse message to the frontend.  The frontend should
631     then send zero or more CopyData messages, forming a stream of input
632     data.  (The message boundaries are not required to have anything to do
633     with row boundaries, although that is often a reasonable choice.)
634     The frontend can terminate the copy-in mode by sending either a CopyDone
635     message (allowing successful termination) or a CopyFail message (which
636     will cause the <code class="command">COPY</code> SQL statement to fail with an
637     error).  The backend then reverts to the command-processing mode it was
638     in before the <code class="command">COPY</code> started, which will be either simple or
639     extended query protocol.  It will next send either CommandComplete
640     (if successful) or ErrorResponse (if not).
641    </p><p>
642     In the event of a backend-detected error during copy-in mode (including
643     receipt of a CopyFail message), the backend will issue an ErrorResponse
644     message.  If the <code class="command">COPY</code> command was issued via an extended-query
645     message, the backend will now discard frontend messages until a Sync
646     message is received, then it will issue ReadyForQuery and return to normal
647     processing.  If the <code class="command">COPY</code> command was issued in a simple
648     Query message, the rest of that message is discarded and ReadyForQuery
649     is issued.  In either case, any subsequent CopyData, CopyDone, or CopyFail
650     messages issued by the frontend will simply be dropped.
651    </p><p>
652     The backend will ignore Flush and Sync messages received during copy-in
653     mode.  Receipt of any other non-copy message type constitutes an error
654     that will abort the copy-in state as described above.  (The exception for
655     Flush and Sync is for the convenience of client libraries that always
656     send Flush or Sync after an Execute message, without checking whether
657     the command to be executed is a <code class="command">COPY FROM STDIN</code>.)
658    </p><p>
659     Copy-out mode (data transfer from the server) is initiated when the
660     backend executes a <code class="command">COPY TO STDOUT</code> SQL statement.  The backend
661     sends a CopyOutResponse message to the frontend, followed by
662     zero or more CopyData messages (always one per row), followed by CopyDone.
663     The backend then reverts to the command-processing mode it was
664     in before the <code class="command">COPY</code> started, and sends CommandComplete.
665     The frontend cannot abort the transfer (except by closing the connection
666     or issuing a Cancel request),
667     but it can discard unwanted CopyData and CopyDone messages.
668    </p><p>
669     In the event of a backend-detected error during copy-out mode,
670     the backend will issue an ErrorResponse message and revert to normal
671     processing.  The frontend should treat receipt of ErrorResponse as
672     terminating the copy-out mode.
673    </p><p>
674     It is possible for NoticeResponse and ParameterStatus messages to be
675     interspersed between CopyData messages; frontends must handle these cases,
676     and should be prepared for other asynchronous message types as well (see
677     <a class="xref" href="protocol-flow.html#PROTOCOL-ASYNC" title="54.2.7. Asynchronous Operations">Section 54.2.7</a>).  Otherwise, any message type other than
678     CopyData or CopyDone may be treated as terminating copy-out mode.
679    </p><p>
680     There is another Copy-related mode called copy-both, which allows
681     high-speed bulk data transfer to <span class="emphasis"><em>and</em></span> from the server.
682     Copy-both mode is initiated when a backend in walsender mode
683     executes a <code class="command">START_REPLICATION</code> statement.  The
684     backend sends a CopyBothResponse message to the frontend.  Both
685     the backend and the frontend may then send CopyData messages
686     until either end sends a CopyDone message. After the client
687     sends a CopyDone message, the connection goes from copy-both mode to
688     copy-out mode, and the client may not send any more CopyData messages.
689     Similarly, when the server sends a CopyDone message, the connection
690     goes into copy-in mode, and the server may not send any more CopyData
691     messages. After both sides have sent a CopyDone message, the copy mode
692     is terminated, and the backend reverts to the command-processing mode.
693     In the event of a backend-detected error during copy-both mode,
694     the backend will issue an ErrorResponse message, discard frontend messages
695     until a Sync message is received, and then issue ReadyForQuery and return
696     to normal processing.  The frontend should treat receipt of ErrorResponse
697     as terminating the copy in both directions; no CopyDone should be sent
698     in this case.  See <a class="xref" href="protocol-replication.html" title="54.4. Streaming Replication Protocol">Section 54.4</a> for more
699     information on the subprotocol transmitted over copy-both mode.
700    </p><p>
701     The CopyInResponse, CopyOutResponse and CopyBothResponse messages
702     include fields that inform the frontend of the number of columns
703     per row and the format codes being used for each column.  (As of
704     the present implementation, all columns in a given <code class="command">COPY</code>
705     operation will use the same format, but the message design does not
706     assume this.)
707    </p></div><div class="sect2" id="PROTOCOL-ASYNC"><div class="titlepage"><div><div><h3 class="title">54.2.7. Asynchronous Operations <a href="#PROTOCOL-ASYNC" class="id_link">#</a></h3></div></div></div><p>
708     There are several cases in which the backend will send messages that
709     are not specifically prompted by the frontend's command stream.
710     Frontends must be prepared to deal with these messages at any time,
711     even when not engaged in a query.
712     At minimum, one should check for these cases before beginning to
713     read a query response.
714    </p><p>
715     It is possible for NoticeResponse messages to be generated due to
716     outside activity; for example, if the database administrator commands
717     a <span class="quote">“<span class="quote">fast</span>”</span> database shutdown, the backend will send a NoticeResponse
718     indicating this fact before closing the connection.  Accordingly,
719     frontends should always be prepared to accept and display NoticeResponse
720     messages, even when the connection is nominally idle.
721    </p><p>
722     ParameterStatus messages will be generated whenever the active
723     value changes for any of the parameters the backend believes the
724     frontend should know about.  Most commonly this occurs in response
725     to a <code class="command">SET</code> SQL command executed by the frontend, and
726     this case is effectively synchronous — but it is also possible
727     for parameter status changes to occur because the administrator
728     changed a configuration file and then sent the
729     <span class="systemitem">SIGHUP</span> signal to the server.  Also,
730     if a <code class="command">SET</code> command is rolled back, an appropriate
731     ParameterStatus message will be generated to report the current
732     effective value.
733    </p><p>
734     At present there is a hard-wired set of parameters for which
735     ParameterStatus will be generated.  They are:
736     </p><table border="0" summary="Simple list" class="simplelist"><tr><td><code class="varname">application_name</code></td><td><code class="varname">scram_iterations</code></td></tr><tr><td><code class="varname">client_encoding</code></td><td><code class="varname">search_path</code></td></tr><tr><td><code class="varname">DateStyle</code></td><td><code class="varname">server_encoding</code></td></tr><tr><td><code class="varname">default_transaction_read_only</code></td><td><code class="varname">server_version</code></td></tr><tr><td><code class="varname">in_hot_standby</code></td><td><code class="varname">session_authorization</code></td></tr><tr><td><code class="varname">integer_datetimes</code></td><td><code class="varname">standard_conforming_strings</code></td></tr><tr><td><code class="varname">IntervalStyle</code></td><td><code class="varname">TimeZone</code></td></tr><tr><td><code class="varname">is_superuser</code></td><td> </td></tr></table><p>
737     (<code class="varname">default_transaction_read_only</code> and
738     <code class="varname">in_hot_standby</code> were not reported by releases before
739     14; <code class="varname">scram_iterations</code> was not reported by releases
740     before 16; <code class="varname">search_path</code> was not reported by releases
741     before 18.)
742     Note that
743     <code class="varname">server_version</code>,
744     <code class="varname">server_encoding</code> and
745     <code class="varname">integer_datetimes</code>
746     are pseudo-parameters that cannot change after startup.
747     This set might change in the future, or even become configurable.
748     Accordingly, a frontend should simply ignore ParameterStatus for
749     parameters that it does not understand or care about.
750    </p><p>
751     If a frontend issues a <code class="command">LISTEN</code> command, then the
752     backend will send a NotificationResponse message (not to be
753     confused with NoticeResponse!)  whenever a
754     <code class="command">NOTIFY</code> command is executed for the same
755     channel name.
756    </p><div class="note"><h3 class="title">Note</h3><p>
757      At present, NotificationResponse can only be sent outside a
758      transaction, and thus it will not occur in the middle of a
759      command-response series, though it might occur just before ReadyForQuery.
760      It is unwise to design frontend logic that assumes that, however.
761      Good practice is to be able to accept NotificationResponse at any
762      point in the protocol.
763     </p></div></div><div class="sect2" id="PROTOCOL-FLOW-CANCELING-REQUESTS"><div class="titlepage"><div><div><h3 class="title">54.2.8. Canceling Requests in Progress <a href="#PROTOCOL-FLOW-CANCELING-REQUESTS" class="id_link">#</a></h3></div></div></div><p>
764     During the processing of a query, the frontend might request
765     cancellation of the query.  The cancel request is not sent
766     directly on the open connection to the backend for reasons of
767     implementation efficiency: we don't want to have the backend
768     constantly checking for new input from the frontend during query
769     processing.  Cancel requests should be relatively infrequent, so
770     we make them slightly cumbersome in order to avoid a penalty in
771     the normal case.
772    </p><p>
773     To issue a cancel request, the frontend opens a new connection to
774     the server and sends a CancelRequest message, rather than the
775     StartupMessage message that would ordinarily be sent across a new
776     connection.  The server will process this request and then close
777     the connection.  For security reasons, no direct reply is made to
778     the cancel request message.
779    </p><p>
780     A CancelRequest message will be ignored unless it contains the
781     same key data (PID and secret key) passed to the frontend during
782     connection start-up.  If the request matches the PID and secret
783     key for a currently executing backend, the processing of the
784     current query is aborted.  (In the existing implementation, this is
785     done by sending a special signal to the backend process that is
786     processing the query.)
787    </p><p>
788     The cancellation signal might or might not have any effect — for
789     example, if it arrives after the backend has finished processing
790     the query, then it will have no effect.  If the cancellation is
791     effective, it results in the current command being terminated
792     early with an error message.
793    </p><p>
794     The upshot of all this is that for reasons of both security and
795     efficiency, the frontend has no direct way to tell whether a
796     cancel request has succeeded.  It must continue to wait for the
797     backend to respond to the query.  Issuing a cancel simply improves
798     the odds that the current query will finish soon, and improves the
799     odds that it will fail with an error message instead of
800     succeeding.
801    </p><p>
802     Since the cancel request is sent across a new connection to the
803     server and not across the regular frontend/backend communication
804     link, it is possible for the cancel request to be issued by any
805     process, not just the frontend whose query is to be canceled.
806     This might provide additional flexibility when building
807     multiple-process applications.  It also introduces a security
808     risk, in that unauthorized persons might try to cancel queries.
809     The security risk is addressed by requiring a dynamically
810     generated secret key to be supplied in cancel requests.
811    </p></div><div class="sect2" id="PROTOCOL-FLOW-TERMINATION"><div class="titlepage"><div><div><h3 class="title">54.2.9. Termination <a href="#PROTOCOL-FLOW-TERMINATION" class="id_link">#</a></h3></div></div></div><p>
812     The normal, graceful termination procedure is that the frontend
813     sends a Terminate message and immediately closes the connection.
814     On receipt of this message, the backend closes the connection and
815     terminates.
816    </p><p>
817     In rare cases (such as an administrator-commanded database shutdown)
818     the backend might disconnect without any frontend request to do so.
819     In such cases the backend will attempt to send an error or notice message
820     giving the reason for the disconnection before it closes the connection.
821    </p><p>
822     Other termination scenarios arise from various failure cases, such as core
823     dump at one end or the other, loss of the communications link, loss of
824     message-boundary synchronization, etc.  If either frontend or backend sees
825     an unexpected closure of the connection, it should clean
826     up and terminate.  The frontend has the option of launching a new backend
827     by recontacting the server if it doesn't want to terminate itself.
828     Closing the connection is also advisable if an unrecognizable message type
829     is received, since this probably indicates loss of message-boundary sync.
830    </p><p>
831     For either normal or abnormal termination, any open transaction is
832     rolled back, not committed.  One should note however that if a
833     frontend disconnects while a non-<code class="command">SELECT</code> query
834     is being processed, the backend will probably finish the query
835     before noticing the disconnection.  If the query is outside any
836     transaction block (<code class="command">BEGIN</code> ... <code class="command">COMMIT</code>
837     sequence) then its results might be committed before the
838     disconnection is recognized.
839    </p></div><div class="sect2" id="PROTOCOL-FLOW-SSL"><div class="titlepage"><div><div><h3 class="title">54.2.10. <acronym class="acronym">SSL</acronym> Session Encryption <a href="#PROTOCOL-FLOW-SSL" class="id_link">#</a></h3></div></div></div><p>
840     If <span class="productname">PostgreSQL</span> was built with
841     <acronym class="acronym">SSL</acronym> support, frontend/backend communications
842     can be encrypted using <acronym class="acronym">SSL</acronym>.  This provides
843     communication security in environments where attackers might be
844     able to capture the session traffic. For more information on
845     encrypting <span class="productname">PostgreSQL</span> sessions with
846     <acronym class="acronym">SSL</acronym>, see <a class="xref" href="ssl-tcp.html" title="18.9. Secure TCP/IP Connections with SSL">Section 18.9</a>.
847    </p><p>
848     To initiate an <acronym class="acronym">SSL</acronym>-encrypted connection, the
849     frontend initially sends an SSLRequest message rather than a
850     StartupMessage.  The server then responds with a single byte
851     containing <code class="literal">S</code> or <code class="literal">N</code>, indicating that it is
852     willing or unwilling to perform <acronym class="acronym">SSL</acronym>,
853     respectively.  The frontend might close the connection at this point
854     if it is dissatisfied with the response.  To continue after
855     <code class="literal">S</code>, perform an <acronym class="acronym">SSL</acronym> startup handshake
856     (not described here, part of the <acronym class="acronym">SSL</acronym>
857     specification) with the server.  If this is successful, continue
858     with sending the usual StartupMessage.  In this case the
859     StartupMessage and all subsequent data will be
860     <acronym class="acronym">SSL</acronym>-encrypted.  To continue after
861     <code class="literal">N</code>, send the usual StartupMessage and proceed without
862     encryption.
863     (Alternatively, it is permissible to issue a GSSENCRequest message
864     after an <code class="literal">N</code> response to try to
865     use <acronym class="acronym">GSSAPI</acronym> encryption instead
866     of <acronym class="acronym">SSL</acronym>.)
867    </p><p>
868     The frontend should also be prepared to handle an ErrorMessage
869     response to SSLRequest from the server. The frontend should not display
870     this error message to the user/application, since the server has not been
871     authenticated
872     (<a class="ulink" href="https://www.postgresql.org/support/security/CVE-2024-10977/" target="_top">CVE-2024-10977</a>).
873     In this case the connection must
874     be closed, but the frontend might choose to open a fresh connection
875     and proceed without requesting <acronym class="acronym">SSL</acronym>.
876    </p><p>
877     When <acronym class="acronym">SSL</acronym> encryption can be performed, the server
878     is expected to send only the single <code class="literal">S</code> byte and then
879     wait for the frontend to initiate an <acronym class="acronym">SSL</acronym> handshake.
880     If additional bytes are available to read at this point, it likely
881     means that a man-in-the-middle is attempting to perform a
882     buffer-stuffing attack
883     (<a class="ulink" href="https://www.postgresql.org/support/security/CVE-2021-23222/" target="_top">CVE-2021-23222</a>).
884     Frontends should be coded either to read exactly one byte from the
885     socket before turning the socket over to their SSL library, or to
886     treat it as a protocol violation if they find they have read additional
887     bytes.
888    </p><p>
889      Likewise the server expects the client to not begin
890      the <acronym class="acronym">SSL</acronym> negotiation until it receives the server's
891      single byte response to the <acronym class="acronym">SSL</acronym> request.  If the
892      client begins the <acronym class="acronym">SSL</acronym> negotiation immediately without
893      waiting for the server response to be received it can reduce connection
894      latency by one round-trip.  However this comes at the cost of not being
895      able to handle the case where the server sends a negative response to the
896      <acronym class="acronym">SSL</acronym> request.  In that case instead of continuing with either GSSAPI or an
897      unencrypted connection or a protocol error the server will simply
898      disconnect.
899    </p><p>
900     An initial SSLRequest can also be used in a connection that is being
901     opened to send a CancelRequest message.
902    </p><p>
903      A second alternate way to initiate <acronym class="acronym">SSL</acronym> encryption is
904      available.  The server will recognize connections which immediately
905      begin <acronym class="acronym">SSL</acronym> negotiation without any previous SSLRequest
906      packets.  Once the <acronym class="acronym">SSL</acronym> connection is established the
907      server will expect a normal startup-request packet and continue
908      negotiation over the encrypted channel.  In this case any other requests
909      for encryption will be refused.  This method is not preferred for general
910      purpose tools as it cannot negotiate the best connection encryption
911      available or handle unencrypted connections.  However it is useful for
912      environments where both the server and client are controlled together.
913      In that case it avoids one round trip of latency and allows the use of
914      network tools that depend on standard <acronym class="acronym">SSL</acronym> connections.
915      When using <acronym class="acronym">SSL</acronym> connections in this style the client is
916      required to use the ALPN extension defined
917      by <a class="ulink" href="https://tools.ietf.org/html/rfc7301" target="_top">RFC 7301</a> to
918      protect against protocol confusion attacks.
919      The <span class="productname">PostgreSQL</span> protocol is "postgresql" as
920      registered
921      at <a class="ulink" href="https://www.iana.org/assignments/tls-extensiontype-values/tls-extensiontype-values.xhtml#alpn-protocol-ids" target="_top">IANA
922      TLS ALPN Protocol IDs</a> registry.
923    </p><p>
924     While the protocol itself does not provide a way for the server to
925     force <acronym class="acronym">SSL</acronym> encryption, the administrator can
926     configure the server to reject unencrypted sessions as a byproduct
927     of authentication checking.
928    </p></div><div class="sect2" id="PROTOCOL-FLOW-GSSAPI"><div class="titlepage"><div><div><h3 class="title">54.2.11. <acronym class="acronym">GSSAPI</acronym> Session Encryption <a href="#PROTOCOL-FLOW-GSSAPI" class="id_link">#</a></h3></div></div></div><p>
929     If <span class="productname">PostgreSQL</span> was built with
930     <acronym class="acronym">GSSAPI</acronym> support, frontend/backend communications
931     can be encrypted using <acronym class="acronym">GSSAPI</acronym>.  This provides
932     communication security in environments where attackers might be
933     able to capture the session traffic. For more information on
934     encrypting <span class="productname">PostgreSQL</span> sessions with
935     <acronym class="acronym">GSSAPI</acronym>, see <a class="xref" href="gssapi-enc.html" title="18.10. Secure TCP/IP Connections with GSSAPI Encryption">Section 18.10</a>.
936    </p><p>
937     To initiate a <acronym class="acronym">GSSAPI</acronym>-encrypted connection, the
938     frontend initially sends a GSSENCRequest message rather than a
939     StartupMessage.  The server then responds with a single byte
940     containing <code class="literal">G</code> or <code class="literal">N</code>, indicating that it
941     is willing or unwilling to perform <acronym class="acronym">GSSAPI</acronym> encryption,
942     respectively.  The frontend might close the connection at this point
943     if it is dissatisfied with the response.  To continue after
944     <code class="literal">G</code>, using the GSSAPI C bindings as discussed in
945     <a class="ulink" href="https://datatracker.ietf.org/doc/html/rfc2744" target="_top">RFC 2744</a>
946     or equivalent, perform a <acronym class="acronym">GSSAPI</acronym> initialization by
947     calling <code class="function">gss_init_sec_context()</code> in a loop and sending
948     the result to the server, starting with an empty input and then with each
949     result from the server, until it returns no output.  When sending the
950     results of <code class="function">gss_init_sec_context()</code> to the server,
951     prepend the length of the message as a four byte integer in network byte
952     order.
953     To continue after
954     <code class="literal">N</code>, send the usual StartupMessage and proceed without
955     encryption.
956     (Alternatively, it is permissible to issue an SSLRequest message
957     after an <code class="literal">N</code> response to try to
958     use <acronym class="acronym">SSL</acronym> encryption instead
959     of <acronym class="acronym">GSSAPI</acronym>.)
960    </p><p>
961     The frontend should also be prepared to handle an ErrorMessage
962     response to GSSENCRequest from the server.  The frontend should not display
963     this error message to the user/application, since the server has not been
964     authenticated
965     (<a class="ulink" href="https://www.postgresql.org/support/security/CVE-2024-10977/" target="_top">CVE-2024-10977</a>).
966     In this case the connection must be closed, but the frontend might choose
967     to open a fresh connection and proceed without requesting
968     <acronym class="acronym">GSSAPI</acronym> encryption.
969    </p><p>
970     When <acronym class="acronym">GSSAPI</acronym> encryption can be performed, the server
971     is expected to send only the single <code class="literal">G</code> byte and then
972     wait for the frontend to initiate a <acronym class="acronym">GSSAPI</acronym> handshake.
973     If additional bytes are available to read at this point, it likely
974     means that a man-in-the-middle is attempting to perform a
975     buffer-stuffing attack
976     (<a class="ulink" href="https://www.postgresql.org/support/security/CVE-2021-23222/" target="_top">CVE-2021-23222</a>).
977     Frontends should be coded either to read exactly one byte from the
978     socket before turning the socket over to their GSSAPI library, or to
979     treat it as a protocol violation if they find they have read additional
980     bytes.
981    </p><p>
982     An initial GSSENCRequest can also be used in a connection that is being
983     opened to send a CancelRequest message.
984    </p><p>
985     Once <acronym class="acronym">GSSAPI</acronym> encryption has been successfully
986     established, use <code class="function">gss_wrap()</code> to
987     encrypt the usual StartupMessage and all subsequent data, prepending the
988     length of the result from <code class="function">gss_wrap()</code> as a four byte
989     integer in network byte order to the actual encrypted payload.  Note that
990     the server will only accept encrypted packets from the client which are less
991     than 16kB; <code class="function">gss_wrap_size_limit()</code> should be used by the
992     client to determine the size of the unencrypted message which will fit
993     within this limit and larger messages should be broken up into multiple
994     <code class="function">gss_wrap()</code> calls.  Typical segments are 8kB of
995     unencrypted data, resulting in encrypted packets of slightly larger than 8kB
996     but well within the 16kB maximum.  The server can be expected to not send
997     encrypted packets of larger than 16kB to the client.
998    </p><p>
999     While the protocol itself does not provide a way for the server to
1000     force <acronym class="acronym">GSSAPI</acronym> encryption, the administrator can
1001     configure the server to reject unencrypted sessions as a byproduct
1002     of authentication checking.
1003    </p></div></div><div class="navfooter"><hr /><table width="100%" summary="Navigation footer"><tr><td width="40%" align="left"><a accesskey="p" href="protocol-overview.html" title="54.1. Overview">Prev</a> </td><td width="20%" align="center"><a accesskey="u" href="protocol.html" title="Chapter 54. Frontend/Backend Protocol">Up</a></td><td width="40%" align="right"> <a accesskey="n" href="sasl-authentication.html" title="54.3. SASL Authentication">Next</a></td></tr><tr><td width="40%" align="left" valign="top">54.1. Overview </td><td width="20%" align="center"><a accesskey="h" href="index.html" title="PostgreSQL 18.0 Documentation">Home</a></td><td width="40%" align="right" valign="top"> 54.3. SASL Authentication</td></tr></table></div></body></html>