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