1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794
|
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>43.2.Message Flow</title>
<link rel="stylesheet" href="stylesheet.css" type="text/css">
<link rev="made" href="pgsql-docs@postgresql.org">
<meta name="generator" content="DocBook XSL Stylesheets V1.70.0">
<link rel="start" href="index.html" title="PostgreSQL 8.1.4 Documentation">
<link rel="up" href="protocol.html" title="Chapter43.Frontend/Backend Protocol">
<link rel="prev" href="protocol.html" title="Chapter43.Frontend/Backend Protocol">
<link rel="next" href="protocol-message-types.html" title="43.3.Message Data Types">
<link rel="copyright" href="ln-legalnotice.html" title="Legal Notice">
</head>
<body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF"><div class="sect1" lang="en">
<div class="titlepage"><div><div><h2 class="title" style="clear: both">
<a name="protocol-flow"></a>43.2.Message Flow</h2></div></div></div>
<p> This section describes the message flow and the semantics of each
message type. (Details of the exact representation of each message
appear in <a href="protocol-message-formats.html" title="43.4.Message Formats">Section43.4, “Message Formats”</a>.) There are
several different sub-protocols depending on the state of the
connection: start-up, query, function call,
<code class="command">COPY</code>, and termination. There are also special
provisions for asynchronous operations (including notification
responses and command cancellation), which can occur at any time
after the start-up phase.
</p>
<div class="sect2" lang="en">
<div class="titlepage"><div><div><h3 class="title">
<a name="id834234"></a>43.2.1.Start-Up</h3></div></div></div>
<p> To begin a session, a frontend opens a connection to the server and sends
a startup message. This message includes the names of the user and of the
database the user wants to connect to; it also identifies the particular
protocol version to be used. (Optionally, the startup message can include
additional settings for run-time parameters.)
The server then uses this information and
the contents of its configuration files (such as
<code class="filename">pg_hba.conf</code>) to determine
whether the connection is provisionally acceptable, and what additional
authentication is required (if any).
</p>
<p> The server then sends an appropriate authentication request message,
to which the frontend must reply with an appropriate authentication
response message (such as a password).
In principle the authentication request/response cycle could require
multiple iterations, but none of the present authentication methods
use more than one request and response. In some methods, no response
at all is needed from the frontend, and so no authentication request
occurs.
</p>
<p> The authentication cycle ends with the server either rejecting the
connection attempt (ErrorResponse), or sending AuthenticationOk.
</p>
<p> The possible messages from the server in this phase are:
</p>
<div class="variablelist"><dl>
<dt><span class="term">ErrorResponse</span></dt>
<dd><p> The connection attempt has been rejected.
The server then immediately closes the connection.
</p></dd>
<dt><span class="term">AuthenticationOk</span></dt>
<dd><p> The authentication exchange is successfully completed.
</p></dd>
<dt><span class="term">AuthenticationKerberosV5</span></dt>
<dd><p> The frontend must now take part in a Kerberos V5
authentication dialog (not described here, part of the
Kerberos specification) with the server. If this is
successful, the server responds with an AuthenticationOk,
otherwise it responds with an ErrorResponse.
</p></dd>
<dt><span class="term">AuthenticationCleartextPassword</span></dt>
<dd><p> The frontend must now send a PasswordMessage containing the
password in clear-text form. If
this is the correct password, the server responds with an
AuthenticationOk, otherwise it responds with an ErrorResponse.
</p></dd>
<dt><span class="term">AuthenticationCryptPassword</span></dt>
<dd><p> The frontend must now send a PasswordMessage containing the
password encrypted via crypt(3), using the 2-character salt
specified in the AuthenticationCryptPassword message. If
this is the correct password, the server responds with an
AuthenticationOk, otherwise it responds with an ErrorResponse.
</p></dd>
<dt><span class="term">AuthenticationMD5Password</span></dt>
<dd><p> The frontend must now send a PasswordMessage containing the
password encrypted via MD5, using the 4-character salt
specified in the AuthenticationMD5Password message. If
this is the correct password, the server responds with an
AuthenticationOk, otherwise it responds with an ErrorResponse.
</p></dd>
<dt><span class="term">AuthenticationSCMCredential</span></dt>
<dd><p> This response is only possible for local Unix-domain connections
on platforms that support SCM credential messages. The frontend
must issue an SCM credential message and then send a single data
byte. (The contents of the data byte are uninteresting; it's
only used to ensure that the server waits long enough to receive
the credential message.) If the credential is acceptable,
the server responds with an
AuthenticationOk, otherwise it responds with an ErrorResponse.
</p></dd>
</dl></div>
<p>
</p>
<p> If the frontend does not support the authentication method
requested by the server, then it should immediately close the
connection.
</p>
<p> After having received AuthenticationOk, the frontend must wait
for further messages from the server. In this phase a backend process
is being started, and the frontend is just an interested bystander.
It is still possible for the startup attempt
to fail (ErrorResponse), but in the normal case the backend will send
some ParameterStatus messages, BackendKeyData, and finally ReadyForQuery.
</p>
<p> During this phase the backend will attempt to apply any additional
run-time parameter settings that were given in the startup message.
If successful, these values become session defaults. An error causes
ErrorResponse and exit.
</p>
<p> The possible messages from the backend in this phase are:
</p>
<div class="variablelist"><dl>
<dt><span class="term">BackendKeyData</span></dt>
<dd><p> This message provides secret-key data that the frontend must
save if it wants to be able to issue cancel requests later.
The frontend should not respond to this message, but should
continue listening for a ReadyForQuery message.
</p></dd>
<dt><span class="term">ParameterStatus</span></dt>
<dd><p> This message informs the frontend about the current (initial)
setting of backend parameters, such as <a href="runtime-config-client.html#guc-client-encoding">client_encoding</a> or <a href="runtime-config-client.html#guc-datestyle">DateStyle</a>.
The frontend may ignore this message, or record the settings
for its future use; see <a href="protocol-flow.html#protocol-async" title="43.2.6.Asynchronous Operations">Section43.2.6, “Asynchronous Operations”</a> for
more details. The frontend should not respond to this
message, but should continue listening for a ReadyForQuery
message.
</p></dd>
<dt><span class="term">ReadyForQuery</span></dt>
<dd><p> Start-up is completed. The frontend may now issue commands.
</p></dd>
<dt><span class="term">ErrorResponse</span></dt>
<dd><p> Start-up failed. The connection is closed after sending this
message.
</p></dd>
<dt><span class="term">NoticeResponse</span></dt>
<dd><p> A warning message has been issued. The frontend should
display the message but continue listening for ReadyForQuery
or ErrorResponse.
</p></dd>
</dl></div>
<p>
</p>
<p> The ReadyForQuery message is the same one that the backend will
issue after each command cycle. Depending on the coding needs of
the frontend, it is reasonable to consider ReadyForQuery as
starting a command cycle, or to consider ReadyForQuery as ending the
start-up phase and each subsequent command cycle.
</p>
</div>
<div class="sect2" lang="en">
<div class="titlepage"><div><div><h3 class="title">
<a name="id834480"></a>43.2.2.Simple Query</h3></div></div></div>
<p> A simple query cycle is initiated by the frontend sending a Query message
to the backend. The message includes an SQL command (or commands)
expressed as a text string.
The backend then sends one or more response
messages depending on the contents of the query command string,
and finally a ReadyForQuery response message. ReadyForQuery
informs the frontend that it may safely send a new command.
(It is not actually necessary for the frontend to wait for
ReadyForQuery before issuing another command, but the frontend must
then take responsibility for figuring out what happens if the earlier
command fails and already-issued later commands succeed.)
</p>
<p> The possible response messages from the backend are:
</p>
<div class="variablelist"><dl>
<dt><span class="term">CommandComplete</span></dt>
<dd><p> An SQL command completed normally.
</p></dd>
<dt><span class="term">CopyInResponse</span></dt>
<dd><p> The backend is ready to copy data from the frontend to a
table; see <a href="protocol-flow.html#protocol-copy" title="43.2.5.COPY Operations">Section43.2.5, “COPY Operations”</a>.
</p></dd>
<dt><span class="term">CopyOutResponse</span></dt>
<dd><p> The backend is ready to copy data from a table to the
frontend; see <a href="protocol-flow.html#protocol-copy" title="43.2.5.COPY Operations">Section43.2.5, “COPY Operations”</a>.
</p></dd>
<dt><span class="term">RowDescription</span></dt>
<dd><p> Indicates that rows are about to be returned in response to
a <code class="command">SELECT</code>, <code class="command">FETCH</code>, etc query.
The contents of this message describe the column layout of the rows.
This will be followed by a DataRow message for each row being returned
to the frontend.
</p></dd>
<dt><span class="term">DataRow</span></dt>
<dd><p> One of the set of rows returned by
a <code class="command">SELECT</code>, <code class="command">FETCH</code>, etc query.
</p></dd>
<dt><span class="term">EmptyQueryResponse</span></dt>
<dd><p> An empty query string was recognized.
</p></dd>
<dt><span class="term">ErrorResponse</span></dt>
<dd><p> An error has occurred.
</p></dd>
<dt><span class="term">ReadyForQuery</span></dt>
<dd><p> Processing of the query string is complete. A separate
message is sent to indicate this because the query string may
contain multiple SQL commands. (CommandComplete marks the
end of processing one SQL command, not the whole string.)
ReadyForQuery will always be sent, whether processing
terminates successfully or with an error.
</p></dd>
<dt><span class="term">NoticeResponse</span></dt>
<dd><p> A warning message has been issued in relation to the query.
Notices are in addition to other responses, i.e., the backend
will continue processing the command.
</p></dd>
</dl></div>
<p>
</p>
<p> The response to a <code class="command">SELECT</code> query (or other queries that
return row sets, such as <code class="command">EXPLAIN</code> or <code class="command">SHOW</code>)
normally consists of RowDescription, zero or more
DataRow messages, and then CommandComplete.
<code class="command">COPY</code> to or from the frontend invokes special protocol
as described in <a href="protocol-flow.html#protocol-copy" title="43.2.5.COPY Operations">Section43.2.5, “COPY Operations”</a>.
All other query types normally produce only
a CommandComplete message.
</p>
<p> Since a query string could contain several queries (separated by
semicolons), there might be several such response sequences before the
backend finishes processing the query string. ReadyForQuery is issued
when the entire string has been processed and the backend is ready to
accept a new query string.
</p>
<p> If a completely empty (no contents other than whitespace) query string
is received, the response is EmptyQueryResponse followed by ReadyForQuery.
</p>
<p> In the event of an error, ErrorResponse is issued followed by
ReadyForQuery. All further processing of the query string is aborted by
ErrorResponse (even if more queries remained in it). Note that this
may occur partway through the sequence of messages generated by an
individual query.
</p>
<p> In simple Query mode, the format of retrieved values is always text,
except when the given command is a <code class="command">FETCH</code> from a cursor
declared with the <code class="literal">BINARY</code> option. In that case, the
retrieved values are in binary format. The format codes given in
the RowDescription message tell which format is being used.
</p>
<p> A frontend must be prepared to accept ErrorResponse and
NoticeResponse messages whenever it is expecting any other type of
message. See also <a href="protocol-flow.html#protocol-async" title="43.2.6.Asynchronous Operations">Section43.2.6, “Asynchronous Operations”</a> concerning messages
that the backend may generate due to outside events.
</p>
<p> Recommended practice is to code frontends in a state-machine style
that will accept any message type at any time that it could make sense,
rather than wiring in assumptions about the exact sequence of messages.
</p>
</div>
<div class="sect2" lang="en">
<div class="titlepage"><div><div><h3 class="title">
<a name="id834738"></a>43.2.3.Extended Query</h3></div></div></div>
<p> The extended query protocol breaks down the above-described simple
query protocol into multiple steps. The results of preparatory
steps can be re-used multiple times for improved efficiency.
Furthermore, additional features are available, such as the possibility
of supplying data values as separate parameters instead of having to
insert them directly into a query string.
</p>
<p> In the extended protocol, the frontend first sends a Parse message,
which contains a textual query string, optionally some information
about data types of parameter placeholders, and the
name of a destination prepared-statement object (an empty string
selects the unnamed prepared statement). The response is
either ParseComplete or ErrorResponse. Parameter data types may be
specified by OID; if not given, the parser attempts to infer the
data types in the same way as it would do for untyped literal string
constants.
</p>
<div class="note" style="margin-left: 0.5in; margin-right: 0.5in;">
<h3 class="title">Note</h3>
<p> A parameter data type can be left unspecified by setting it to zero,
or by making the array of parameter type OIDs shorter than the
number of parameter symbols (<code class="literal">$</code><em class="replaceable"><code>n</code></em>)
used in the query string. Another special case is that a parameter's
type can be specified as <code class="type">void</code> (that is, the OID of the
<code class="type">void</code> pseudotype). This is meant to allow parameter symbols
to be used for function parameters that are actually OUT parameters.
Ordinarily there is no context in which a <code class="type">void</code> parameter
could be used, but if such a parameter symbol appears in a function's
parameter list, it is effectively ignored. For example, a function
call such as <code class="literal">foo($1,$2,$3,$4)</code> could match a function with
two IN and two OUT arguments, if <code class="literal">$3</code> and <code class="literal">$4</code>
are specified as having type <code class="type">void</code>.
</p>
</div>
<div class="note" style="margin-left: 0.5in; margin-right: 0.5in;">
<h3 class="title">Note</h3>
<p> The query string contained in a Parse message cannot include more
than one SQL statement; else a syntax error is reported. This
restriction does not exist in the simple-query protocol, but it
does exist in the extended protocol, because allowing prepared
statements or portals to contain multiple commands would complicate
the protocol unduly.
</p>
</div>
<p> If successfully created, a named prepared-statement object lasts till
the end of the current session, unless explicitly destroyed. An unnamed
prepared statement lasts only until the next Parse statement specifying
the unnamed statement as destination is issued. (Note that a simple
Query message also destroys the unnamed statement.) Named prepared
statements must be explicitly closed before they can be redefined by
a Parse message, but this is not required for the unnamed statement.
Named prepared statements can also be created and accessed at the SQL
command level, using <code class="command">PREPARE</code> and <code class="command">EXECUTE</code>.
</p>
<p> Once a prepared statement exists, it can be readied for execution using a
Bind message. The Bind message gives the name of the source prepared
statement (empty string denotes the unnamed prepared statement), the name
of the destination portal (empty string denotes the unnamed portal), and
the values to use for any parameter placeholders present in the prepared
statement. The
supplied parameter set must match those needed by the prepared statement.
(If you declared any <code class="type">void</code> parameters in the Parse message,
pass NULL values for them in the Bind message.)
Bind also specifies the format to use for any data returned
by the query; the format can be specified overall, or per-column.
The response is either BindComplete or ErrorResponse.
</p>
<div class="note" style="margin-left: 0.5in; margin-right: 0.5in;">
<h3 class="title">Note</h3>
<p> The choice between text and binary output is determined by the format
codes given in Bind, regardless of the SQL command involved. The
<code class="literal">BINARY</code> attribute in cursor declarations is irrelevant when
using extended query protocol.
</p>
</div>
<p> Query planning for named prepared-statement objects occurs when the Parse
message is received. If a query will be repeatedly executed with
different parameters, it may be beneficial to send a single Parse message
containing a parameterized query, followed by multiple Bind
and Execute messages. This will avoid replanning the query on each
execution.
</p>
<p> The unnamed prepared statement is likewise planned during Parse processing
if the Parse message defines no parameters. But if there are parameters,
query planning is delayed until the first Bind message for the statement
is received. The planner will consider the actual values of the parameters
provided in the Bind message when planning the query.
</p>
<div class="note" style="margin-left: 0.5in; margin-right: 0.5in;">
<h3 class="title">Note</h3>
<p> Query plans generated from a parameterized query may be less
efficient than query plans generated from an equivalent query with actual
parameter values substituted. The query planner cannot make decisions
based on actual parameter values (for example, index selectivity) when
planning a parameterized query assigned to a named prepared-statement
object. This possible penalty is avoided when using the unnamed
statement, since it is not planned until actual parameter values are
available.
</p>
<p> If a second or subsequent Bind referencing the unnamed prepared-statement
object is received without an intervening Parse, the query is
not replanned. The parameter values used in the first Bind message may
produce a query plan that is only efficient for a subset of possible
parameter values. To force replanning of the query for a fresh set of
parameters, send another Parse message to replace the unnamed
prepared-statement object.
</p>
</div>
<p> If successfully created, a named portal object lasts till the end of the
current transaction, unless explicitly destroyed. An unnamed portal is
destroyed at the end of the transaction, or as soon as the next Bind
statement specifying the unnamed portal as destination is issued. (Note
that a simple Query message also destroys the unnamed portal.) Named
portals must be explicitly closed before they can be redefined by a Bind
message, but this is not required for the unnamed portal.
Named portals can also be created and accessed at the SQL
command level, using <code class="command">DECLARE CURSOR</code> and <code class="command">FETCH</code>.
</p>
<p> Once a portal exists, it can be executed using an Execute message.
The Execute message specifies the portal name (empty string denotes the
unnamed portal) and
a maximum result-row count (zero meaning “<span class="quote">fetch all rows</span>”).
The result-row count is only meaningful for portals
containing commands that return row sets; in other cases the command is
always executed to completion, and the row count is ignored.
The possible
responses to Execute are the same as those described above for queries
issued via simple query protocol, except that Execute doesn't cause
ReadyForQuery or RowDescription to be issued.
</p>
<p> If Execute terminates before completing the execution of a portal
(due to reaching a nonzero result-row count), it will send a
PortalSuspended message; the appearance of this message tells the frontend
that another Execute should be issued against the same portal to
complete the operation. The CommandComplete message indicating
completion of the source SQL command is not sent until
the portal's execution is completed. Therefore, an Execute phase is
always terminated by the appearance of exactly one of these messages:
CommandComplete, EmptyQueryResponse (if the portal was created from
an empty query string), ErrorResponse, or PortalSuspended.
</p>
<p> At completion of each series of extended-query messages, the frontend
should issue a Sync message. This parameterless message causes the
backend to close the current transaction if it's not inside a
<code class="command">BEGIN</code>/<code class="command">COMMIT</code> transaction block (“<span class="quote">close</span>”
meaning to commit if no error, or roll back if error). Then a
ReadyForQuery response is issued. The purpose of Sync is to provide
a resynchronization point for error recovery. When an error is detected
while processing any extended-query message, the backend issues
ErrorResponse, then reads and discards messages until a Sync is reached,
then issues ReadyForQuery and returns to normal message processing.
(But note that no skipping occurs if an error is detected
<span class="emphasis"><em>while</em></span> processing Sync [mdash ] this ensures that there is one
and only one ReadyForQuery sent for each Sync.)
</p>
<div class="note" style="margin-left: 0.5in; margin-right: 0.5in;">
<h3 class="title">Note</h3>
<p> Sync does not cause a transaction block opened with <code class="command">BEGIN</code>
to be closed. It is possible to detect this situation since the
ReadyForQuery message includes transaction status information.
</p>
</div>
<p> In addition to these fundamental, required operations, there are several
optional operations that can be used with extended-query protocol.
</p>
<p> The Describe message (portal variant) specifies the name of an existing
portal (or an empty string for the unnamed portal). The response is a
RowDescription message describing the rows that will be returned by
executing the portal; or a NoData message if the portal does not contain a
query that will return rows; or ErrorResponse if there is no such portal.
</p>
<p> The Describe message (statement variant) specifies the name of an existing
prepared statement (or an empty string for the unnamed prepared
statement). The response is a ParameterDescription message describing the
parameters needed by the statement, followed by a RowDescription message
describing the rows that will be returned when the statement is eventually
executed (or a NoData message if the statement will not return rows).
ErrorResponse is issued if there is no such prepared statement. Note that
since Bind has not yet been issued, the formats to be used for returned
columns are not yet known to the backend; the format code fields in the
RowDescription message will be zeroes in this case.
</p>
<div class="tip" style="margin-left: 0.5in; margin-right: 0.5in;">
<h3 class="title">Tip</h3>
<p> In most scenarios the frontend should issue one or the other variant
of Describe before issuing Execute, to ensure that it knows how to
interpret the results it will get back.
</p>
</div>
<p> The Close message closes an existing prepared statement or portal
and releases resources. It is not an error to issue Close against
a nonexistent statement or portal name. The response is normally
CloseComplete, but could be ErrorResponse if some difficulty is
encountered while releasing resources. Note that closing a prepared
statement implicitly closes any open portals that were constructed
from that statement.
</p>
<p> The Flush message does not cause any specific output to be generated,
but forces the backend to deliver any data pending in its output
buffers. A Flush must be sent after any extended-query command except
Sync, if the frontend wishes to examine the results of that command before
issuing more commands. Without Flush, messages returned by the backend
will be combined into the minimum possible number of packets to minimize
network overhead.
</p>
<div class="note" style="margin-left: 0.5in; margin-right: 0.5in;">
<h3 class="title">Note</h3>
<p> The simple Query message is approximately equivalent to the series Parse,
Bind, portal Describe, Execute, Close, Sync, using the unnamed prepared
statement and portal objects and no parameters. One difference is that
it will accept multiple SQL statements in the query string, automatically
performing the bind/describe/execute sequence for each one in succession.
Another difference is that it will not return ParseComplete, BindComplete,
CloseComplete, or NoData messages.
</p>
</div>
</div>
<div class="sect2" lang="en">
<div class="titlepage"><div><div><h3 class="title">
<a name="id835121"></a>43.2.4.Function Call</h3></div></div></div>
<p> The Function Call sub-protocol allows the client to request a direct
call of any function that exists in the database's
<code class="structname">pg_proc</code> system catalog. The client must have
execute permission for the function.
</p>
<div class="note" style="margin-left: 0.5in; margin-right: 0.5in;">
<h3 class="title">Note</h3>
<p> The Function Call sub-protocol is a legacy feature that is probably best
avoided in new code. Similar results can be accomplished by setting up
a prepared statement that does <code class="literal">SELECT function($1, ...)</code>.
The Function Call cycle can then be replaced with Bind/Execute.
</p>
</div>
<p> A Function Call cycle is initiated by the frontend sending a
FunctionCall message to the backend. The backend then sends one
or more response messages depending on the results of the function
call, and finally a ReadyForQuery response message. ReadyForQuery
informs the frontend that it may safely send a new query or
function call.
</p>
<p> The possible response messages from the backend are:
</p>
<div class="variablelist"><dl>
<dt><span class="term">ErrorResponse</span></dt>
<dd><p> An error has occurred.
</p></dd>
<dt><span class="term">FunctionCallResponse</span></dt>
<dd><p> The function call was completed and returned the result given
in the message.
(Note that the Function Call protocol can only handle a single
scalar result, not a row type or set of results.)
</p></dd>
<dt><span class="term">ReadyForQuery</span></dt>
<dd><p> Processing of the function call is complete. ReadyForQuery
will always be sent, whether processing terminates
successfully or with an error.
</p></dd>
<dt><span class="term">NoticeResponse</span></dt>
<dd><p> A warning message has been issued in relation to the function
call. Notices are in addition to other responses, i.e., the
backend will continue processing the command.
</p></dd>
</dl></div>
<p>
</p>
</div>
<div class="sect2" lang="en">
<div class="titlepage"><div><div><h3 class="title">
<a name="protocol-copy"></a>43.2.5.COPY Operations</h3></div></div></div>
<p> The <code class="command">COPY</code> command allows high-speed bulk data transfer
to or from the server. Copy-in and copy-out operations each switch
the connection into a distinct sub-protocol, which lasts until the
operation is completed.
</p>
<p> Copy-in mode (data transfer to the server) is initiated when the
backend executes a <code class="command">COPY FROM STDIN</code> SQL statement. The backend
sends a CopyInResponse message to the frontend. The frontend should
then send zero or more CopyData messages, forming a stream of input
data. (The message boundaries are not required to have anything to do
with row boundaries, although that is often a reasonable choice.)
The frontend can terminate the copy-in mode by sending either a CopyDone
message (allowing successful termination) or a CopyFail message (which
will cause the <code class="command">COPY</code> SQL statement to fail with an
error). The backend then reverts to the command-processing mode it was
in before the <code class="command">COPY</code> started, which will be either simple or
extended query protocol. It will next send either CommandComplete
(if successful) or ErrorResponse (if not).
</p>
<p> In the event of a backend-detected error during copy-in mode (including
receipt of a CopyFail message), the backend will issue an ErrorResponse
message. If the <code class="command">COPY</code> command was issued via an extended-query
message, the backend will now discard frontend messages until a Sync
message is received, then it will issue ReadyForQuery and return to normal
processing. If the <code class="command">COPY</code> command was issued in a simple
Query message, the rest of that message is discarded and ReadyForQuery
is issued. In either case, any subsequent CopyData, CopyDone, or CopyFail
messages issued by the frontend will simply be dropped.
</p>
<p> The backend will ignore Flush and Sync messages received during copy-in
mode. Receipt of any other non-copy message type constitutes an error
that will abort the copy-in state as described above. (The exception for
Flush and Sync is for the convenience of client libraries that always
send Flush or Sync after an Execute message, without checking whether
the command to be executed is a <code class="command">COPY FROM STDIN</code>.)
</p>
<p> Copy-out mode (data transfer from the server) is initiated when the
backend executes a <code class="command">COPY TO STDOUT</code> SQL statement. The backend
sends a CopyOutResponse message to the frontend, followed by
zero or more CopyData messages (always one per row), followed by CopyDone.
The backend then reverts to the command-processing mode it was
in before the <code class="command">COPY</code> started, and sends CommandComplete.
The frontend cannot abort the transfer (except by closing the connection
or issuing a Cancel request),
but it can discard unwanted CopyData and CopyDone messages.
</p>
<p> In the event of a backend-detected error during copy-out mode,
the backend will issue an ErrorResponse message and revert to normal
processing. The frontend should treat receipt of ErrorResponse (or
indeed any message type other than CopyData or CopyDone) as terminating
the copy-out mode.
</p>
<p> The CopyInResponse and CopyOutResponse messages include fields that
inform the frontend of the number of columns per row and the format
codes being used for each column. (As of the present implementation,
all columns in a given <code class="command">COPY</code> operation will use the same
format, but the message design does not assume this.)
</p>
</div>
<div class="sect2" lang="en">
<div class="titlepage"><div><div><h3 class="title">
<a name="protocol-async"></a>43.2.6.Asynchronous Operations</h3></div></div></div>
<p> There are several cases in which the backend will send messages that
are not specifically prompted by the frontend's command stream.
Frontends must be prepared to deal with these messages at any time,
even when not engaged in a query.
At minimum, one should check for these cases before beginning to
read a query response.
</p>
<p> It is possible for NoticeResponse messages to be generated due to
outside activity; for example, if the database administrator commands
a “<span class="quote">fast</span>” database shutdown, the backend will send a NoticeResponse
indicating this fact before closing the connection. Accordingly,
frontends should always be prepared to accept and display NoticeResponse
messages, even when the connection is nominally idle.
</p>
<p> ParameterStatus messages will be generated whenever the active
value changes for any of the parameters the backend believes the
frontend should know about. Most commonly this occurs in response
to a <code class="command">SET</code> SQL command executed by the frontend, and
this case is effectively synchronous [mdash ] but it is also possible
for parameter status changes to occur because the administrator
changed a configuration file and then sent the
<span class="systemitem">SIGHUP</span> signal to the postmaster. Also,
if a <code class="command">SET</code> command is rolled back, an appropriate
ParameterStatus message will be generated to report the current
effective value.
</p>
<p> At present there is a hard-wired set of parameters for which
ParameterStatus will be generated: they are
<code class="literal">server_version</code>,
<code class="literal">server_encoding</code>,
<code class="literal">client_encoding</code>,
<code class="literal">is_superuser</code>,
<code class="literal">session_authorization</code>,
<code class="literal">DateStyle</code>,
<code class="literal">TimeZone</code>,
<code class="literal">integer_datetimes</code>, and
<code class="literal">standard_conforming_strings</code>.
(<code class="literal">server_encoding</code>, <code class="literal">TimeZone</code>, and
<code class="literal">integer_datetimes</code> were not reported by releases before 8.0;
<code class="literal">standard_conforming_strings</code> was not reported by releases
before 8.1.)
Note that
<code class="literal">server_version</code>,
<code class="literal">server_encoding</code> and
<code class="literal">integer_datetimes</code>
are pseudo-parameters that cannot change after startup.
This set might change in the future, or even become configurable.
Accordingly, a frontend should simply ignore ParameterStatus for
parameters that it does not understand or care about.
</p>
<p> If a frontend issues a <code class="command">LISTEN</code> command, then the
backend will send a NotificationResponse message (not to be
confused with NoticeResponse!) whenever a
<code class="command">NOTIFY</code> command is executed for the same
notification name.
</p>
<div class="note" style="margin-left: 0.5in; margin-right: 0.5in;">
<h3 class="title">Note</h3>
<p> At present, NotificationResponse can only be sent outside a
transaction, and thus it will not occur in the middle of a
command-response series, though it may occur just before ReadyForQuery.
It is unwise to design frontend logic that assumes that, however.
Good practice is to be able to accept NotificationResponse at any
point in the protocol.
</p>
</div>
</div>
<div class="sect2" lang="en">
<div class="titlepage"><div><div><h3 class="title">
<a name="id835564"></a>43.2.7.Cancelling Requests in Progress</h3></div></div></div>
<p> During the processing of a query, the frontend may request
cancellation of the query. The cancel request is not sent
directly on the open connection to the backend for reasons of
implementation efficiency: we don't want to have the backend
constantly checking for new input from the frontend during query
processing. Cancel requests should be relatively infrequent, so
we make them slightly cumbersome in order to avoid a penalty in
the normal case.
</p>
<p> To issue a cancel request, the frontend opens a new connection to
the server and sends a CancelRequest message, rather than the
StartupMessage message that would ordinarily be sent across a new
connection. The server will process this request and then close
the connection. For security reasons, no direct reply is made to
the cancel request message.
</p>
<p> A CancelRequest message will be ignored unless it contains the
same key data (PID and secret key) passed to the frontend during
connection start-up. If the request matches the PID and secret
key for a currently executing backend, the processing of the
current query is aborted. (In the existing implementation, this is
done by sending a special signal to the backend process that is
processing the query.)
</p>
<p> The cancellation signal may or may not have any effect [mdash ] for
example, if it arrives after the backend has finished processing
the query, then it will have no effect. If the cancellation is
effective, it results in the current command being terminated
early with an error message.
</p>
<p> The upshot of all this is that for reasons of both security and
efficiency, the frontend has no direct way to tell whether a
cancel request has succeeded. It must continue to wait for the
backend to respond to the query. Issuing a cancel simply improves
the odds that the current query will finish soon, and improves the
odds that it will fail with an error message instead of
succeeding.
</p>
<p> Since the cancel request is sent across a new connection to the
server and not across the regular frontend/backend communication
link, it is possible for the cancel request to be issued by any
process, not just the frontend whose query is to be canceled.
This may have some benefits of flexibility in building
multiple-process applications. It also introduces a security
risk, in that unauthorized persons might try to cancel queries.
The security risk is addressed by requiring a dynamically
generated secret key to be supplied in cancel requests.
</p>
</div>
<div class="sect2" lang="en">
<div class="titlepage"><div><div><h3 class="title">
<a name="id835628"></a>43.2.8.Termination</h3></div></div></div>
<p> The normal, graceful termination procedure is that the frontend
sends a Terminate message and immediately closes the connection.
On receipt of this message, the backend closes the connection and
terminates.
</p>
<p> In rare cases (such as an administrator-commanded database shutdown)
the backend may disconnect without any frontend request to do so.
In such cases the backend will attempt to send an error or notice message
giving the reason for the disconnection before it closes the connection.
</p>
<p> Other termination scenarios arise from various failure cases, such as core
dump at one end or the other, loss of the communications link, loss of
message-boundary synchronization, etc. If either frontend or backend sees
an unexpected closure of the connection, it should clean
up and terminate. The frontend has the option of launching a new backend
by recontacting the server if it doesn't want to terminate itself.
Closing the connection is also advisable if an unrecognizable message type
is received, since this probably indicates loss of message-boundary sync.
</p>
<p> For either normal or abnormal termination, any open transaction is
rolled back, not committed. One should note however that if a
frontend disconnects while a non-<code class="command">SELECT</code> query
is being processed, the backend will probably finish the query
before noticing the disconnection. If the query is outside any
transaction block (<code class="command">BEGIN</code> ... <code class="command">COMMIT</code>
sequence) then its results may be committed before the
disconnection is recognized.
</p>
</div>
<div class="sect2" lang="en">
<div class="titlepage"><div><div><h3 class="title">
<a name="id835688"></a>43.2.9.<acronym class="acronym">SSL</acronym> Session Encryption</h3></div></div></div>
<p> If <span class="productname">PostgreSQL</span> was built with
<acronym class="acronym">SSL</acronym> support, frontend/backend communications
can be encrypted using <acronym class="acronym">SSL</acronym>. This provides
communication security in environments where attackers might be
able to capture the session traffic. For more information on
encrypting <span class="productname">PostgreSQL</span> sessions with
<acronym class="acronym">SSL</acronym>, see <a href="ssl-tcp.html" title="16.7.Secure TCP/IP Connections with SSL">Section16.7, “Secure TCP/IP Connections with SSL”</a>.
</p>
<p> To initiate an <acronym class="acronym">SSL</acronym>-encrypted connection, the
frontend initially sends an SSLRequest message rather than a
StartupMessage. The server then responds with a single byte
containing <code class="literal">S</code> or <code class="literal">N</code>, indicating that it is
willing or unwilling to perform <acronym class="acronym">SSL</acronym>,
respectively. The frontend may close the connection at this point
if it is dissatisfied with the response. To continue after
<code class="literal">S</code>, perform an <acronym class="acronym">SSL</acronym> startup handshake
(not described here, part of the <acronym class="acronym">SSL</acronym>
specification) with the server. If this is successful, continue
with sending the usual StartupMessage. In this case the
StartupMessage and all subsequent data will be
<acronym class="acronym">SSL</acronym>-encrypted. To continue after
<code class="literal">N</code>, send the usual StartupMessage and proceed without
encryption.
</p>
<p> The frontend should also be prepared to handle an ErrorMessage
response to SSLRequest from the server. This would only occur if
the server predates the addition of <acronym class="acronym">SSL</acronym> support
to <span class="productname">PostgreSQL</span>. In this case the connection must
be closed, but the frontend may choose to open a fresh connection
and proceed without requesting <acronym class="acronym">SSL</acronym>.
</p>
<p> An initial SSLRequest may also be used in a connection that is being
opened to send a CancelRequest message.
</p>
<p> While the protocol itself does not provide a way for the server to
force <acronym class="acronym">SSL</acronym> encryption, the administrator may
configure the server to reject unencrypted sessions as a byproduct
of authentication checking.
</p>
</div>
</div></body>
</html>
|