1<!-- doc/src/sgml/libpq.sgml --> 2 3<chapter id="libpq"> 4 <title><application>libpq</application> - C Library</title> 5 6 <indexterm zone="libpq"> 7 <primary>libpq</primary> 8 </indexterm> 9 10 <indexterm zone="libpq"> 11 <primary>C</primary> 12 </indexterm> 13 14 <para> 15 <application>libpq</application> is the <acronym>C</acronym> 16 application programmer's interface to <productname>PostgreSQL</productname>. 17 <application>libpq</application> is a set of library functions that allow 18 client programs to pass queries to the <productname>PostgreSQL</productname> 19 backend server and to receive the results of these queries. 20 </para> 21 22 <para> 23 <application>libpq</application> is also the underlying engine for several 24 other <productname>PostgreSQL</productname> application interfaces, including 25 those written for C++, Perl, Python, Tcl and <application>ECPG</application>. 26 So some aspects of <application>libpq</application>'s behavior will be 27 important to you if you use one of those packages. In particular, 28 <xref linkend="libpq-envars"/>, 29 <xref linkend="libpq-pgpass"/> and 30 <xref linkend="libpq-ssl"/> 31 describe behavior that is visible to the user of any application 32 that uses <application>libpq</application>. 33 </para> 34 35 <para> 36 Some short programs are included at the end of this chapter (<xref linkend="libpq-example"/>) to show how 37 to write programs that use <application>libpq</application>. There are also several 38 complete examples of <application>libpq</application> applications in the 39 directory <filename>src/test/examples</filename> in the source code distribution. 40 </para> 41 42 <para> 43 Client programs that use <application>libpq</application> must 44 include the header file 45 <filename>libpq-fe.h</filename><indexterm><primary>libpq-fe.h</primary></indexterm> 46 and must link with the <application>libpq</application> library. 47 </para> 48 49 <sect1 id="libpq-connect"> 50 <title>Database Connection Control Functions</title> 51 52 <para> 53 The following functions deal with making a connection to a 54 <productname>PostgreSQL</productname> backend server. An 55 application program can have several backend connections open at 56 one time. (One reason to do that is to access more than one 57 database.) Each connection is represented by a 58 <structname>PGconn</structname><indexterm><primary>PGconn</primary></indexterm> object, which 59 is obtained from the function <function>PQconnectdb</function>, 60 <function>PQconnectdbParams</function>, or 61 <function>PQsetdbLogin</function>. Note that these functions will always 62 return a non-null object pointer, unless perhaps there is too 63 little memory even to allocate the <structname>PGconn</structname> object. 64 The <function>PQstatus</function> function should be called to check 65 the return value for a successful connection before queries are sent 66 via the connection object. 67 68 <warning> 69 <para> 70 If untrusted users have access to a database that has not adopted a 71 <link linkend="ddl-schemas-patterns">secure schema usage pattern</link>, 72 begin each session by removing publicly-writable schemas from 73 <varname>search_path</varname>. One can set parameter key 74 word <literal>options</literal> to 75 value <literal>-csearch_path=</literal>. Alternately, one can 76 issue <literal>PQexec(<replaceable>conn</replaceable>, "SELECT 77 pg_catalog.set_config('search_path', '', false)")</literal> after 78 connecting. This consideration is not specific 79 to <application>libpq</application>; it applies to every interface for 80 executing arbitrary SQL commands. 81 </para> 82 </warning> 83 84 <warning> 85 <para> 86 On Unix, forking a process with open libpq connections can lead to 87 unpredictable results because the parent and child processes share 88 the same sockets and operating system resources. For this reason, 89 such usage is not recommended, though doing an <function>exec</function> from 90 the child process to load a new executable is safe. 91 </para> 92 </warning> 93 94 <variablelist> 95 <varlistentry id="libpq-pqconnectdbparams"> 96 <term><function>PQconnectdbParams</function><indexterm><primary>PQconnectdbParams</primary></indexterm></term> 97 <listitem> 98 <para> 99 Makes a new connection to the database server. 100 101<synopsis> 102PGconn *PQconnectdbParams(const char * const *keywords, 103 const char * const *values, 104 int expand_dbname); 105</synopsis> 106 </para> 107 108 <para> 109 This function opens a new database connection using the parameters taken 110 from two <symbol>NULL</symbol>-terminated arrays. The first, 111 <literal>keywords</literal>, is defined as an array of strings, each one 112 being a key word. The second, <literal>values</literal>, gives the value 113 for each key word. Unlike <function>PQsetdbLogin</function> below, the parameter 114 set can be extended without changing the function signature, so use of 115 this function (or its nonblocking analogs <function>PQconnectStartParams</function> 116 and <function>PQconnectPoll</function>) is preferred for new application 117 programming. 118 </para> 119 120 <para> 121 The currently recognized parameter key words are listed in 122 <xref linkend="libpq-paramkeywords"/>. 123 </para> 124 125 <para> 126 The passed arrays can be empty to use all default parameters, or can 127 contain one or more parameter settings. They must be matched in length. 128 Processing will stop at the first <symbol>NULL</symbol> entry 129 in the <literal>keywords</literal> array. 130 Also, if the <literal>values</literal> entry associated with a 131 non-<symbol>NULL</symbol> <literal>keywords</literal> entry is 132 <symbol>NULL</symbol> or an empty string, that entry is ignored and 133 processing continues with the next pair of array entries. 134 </para> 135 136 <para> 137 When <literal>expand_dbname</literal> is non-zero, the value for 138 the first <parameter>dbname</parameter> key word is checked to see 139 if it is a <firstterm>connection string</firstterm>. If so, it 140 is <quote>expanded</quote> into the individual connection 141 parameters extracted from the string. The value is considered to 142 be a connection string, rather than just a database name, if it 143 contains an equal sign (<literal>=</literal>) or it begins with a 144 URI scheme designator. (More details on connection string formats 145 appear in <xref linkend="libpq-connstring"/>.) Only the first 146 occurrence of <parameter>dbname</parameter> is treated in this way; 147 any subsequent <parameter>dbname</parameter> parameter is processed 148 as a plain database name. 149 </para> 150 151 <para> 152 In general the parameter arrays are processed from start to end. 153 If any key word is repeated, the last value (that is 154 not <symbol>NULL</symbol> or empty) is used. This rule applies in 155 particular when a key word found in a connection string conflicts 156 with one appearing in the <literal>keywords</literal> array. Thus, 157 the programmer may determine whether array entries can override or 158 be overridden by values taken from a connection string. Array 159 entries appearing before an expanded <parameter>dbname</parameter> 160 entry can be overridden by fields of the connection string, and in 161 turn those fields are overridden by array entries appearing 162 after <parameter>dbname</parameter> (but, again, only if those 163 entries supply non-empty values). 164 </para> 165 166 <para> 167 After processing all the array entries and any expanded connection 168 string, any connection parameters that remain unset are filled with 169 default values. If an unset parameter's corresponding environment 170 variable (see <xref linkend="libpq-envars"/>) is set, its value is 171 used. If the environment variable is not set either, then the 172 parameter's built-in default value is used. 173 </para> 174 175 </listitem> 176 </varlistentry> 177 178 <varlistentry id="libpq-pqconnectdb"> 179 <term><function>PQconnectdb</function><indexterm><primary>PQconnectdb</primary></indexterm></term> 180 <listitem> 181 <para> 182 Makes a new connection to the database server. 183 184<synopsis> 185PGconn *PQconnectdb(const char *conninfo); 186</synopsis> 187 </para> 188 189 <para> 190 This function opens a new database connection using the parameters taken 191 from the string <literal>conninfo</literal>. 192 </para> 193 194 <para> 195 The passed string can be empty to use all default parameters, or it can 196 contain one or more parameter settings separated by whitespace, 197 or it can contain a <acronym>URI</acronym>. 198 See <xref linkend="libpq-connstring"/> for details. 199 </para> 200 201 202 </listitem> 203 </varlistentry> 204 205 <varlistentry id="libpq-pqsetdblogin"> 206 <term><function>PQsetdbLogin</function><indexterm><primary>PQsetdbLogin</primary></indexterm></term> 207 <listitem> 208 <para> 209 Makes a new connection to the database server. 210<synopsis> 211PGconn *PQsetdbLogin(const char *pghost, 212 const char *pgport, 213 const char *pgoptions, 214 const char *pgtty, 215 const char *dbName, 216 const char *login, 217 const char *pwd); 218</synopsis> 219 </para> 220 221 <para> 222 This is the predecessor of <function>PQconnectdb</function> with a fixed 223 set of parameters. It has the same functionality except that the 224 missing parameters will always take on default values. Write <symbol>NULL</symbol> or an 225 empty string for any one of the fixed parameters that is to be defaulted. 226 </para> 227 228 <para> 229 If the <parameter>dbName</parameter> contains 230 an <symbol>=</symbol> sign or has a valid connection <acronym>URI</acronym> prefix, it 231 is taken as a <parameter>conninfo</parameter> string in exactly the same way as 232 if it had been passed to <function>PQconnectdb</function>, and the remaining 233 parameters are then applied as specified for <function>PQconnectdbParams</function>. 234 </para> 235 </listitem> 236 </varlistentry> 237 238 <varlistentry id="libpq-pqsetdb"> 239 <term><function>PQsetdb</function><indexterm><primary>PQsetdb</primary></indexterm></term> 240 <listitem> 241 <para> 242 Makes a new connection to the database server. 243<synopsis> 244PGconn *PQsetdb(char *pghost, 245 char *pgport, 246 char *pgoptions, 247 char *pgtty, 248 char *dbName); 249</synopsis> 250 </para> 251 252 <para> 253 This is a macro that calls <function>PQsetdbLogin</function> with null pointers 254 for the <parameter>login</parameter> and <parameter>pwd</parameter> parameters. It is provided 255 for backward compatibility with very old programs. 256 </para> 257 </listitem> 258 </varlistentry> 259 260 <varlistentry id="libpq-pqconnectstartparams"> 261 <term><function>PQconnectStartParams</function><indexterm><primary>PQconnectStartParams</primary></indexterm></term> 262 <term><function>PQconnectStart</function><indexterm><primary>PQconnectStart</primary></indexterm></term> 263 <term><function>PQconnectPoll</function><indexterm><primary>PQconnectPoll</primary></indexterm></term> 264 <listitem> 265 <para> 266 <indexterm><primary>nonblocking connection</primary></indexterm> 267 Make a connection to the database server in a nonblocking manner. 268 269<synopsis> 270PGconn *PQconnectStartParams(const char * const *keywords, 271 const char * const *values, 272 int expand_dbname); 273 274PGconn *PQconnectStart(const char *conninfo); 275 276PostgresPollingStatusType PQconnectPoll(PGconn *conn); 277</synopsis> 278 </para> 279 280 <para> 281 These three functions are used to open a connection to a database server such 282 that your application's thread of execution is not blocked on remote I/O 283 whilst doing so. The point of this approach is that the waits for I/O to 284 complete can occur in the application's main loop, rather than down inside 285 <function>PQconnectdbParams</function> or <function>PQconnectdb</function>, and so the 286 application can manage this operation in parallel with other activities. 287 </para> 288 289 <para> 290 With <function>PQconnectStartParams</function>, the database connection is made 291 using the parameters taken from the <literal>keywords</literal> and 292 <literal>values</literal> arrays, and controlled by <literal>expand_dbname</literal>, 293 as described above for <function>PQconnectdbParams</function>. 294 </para> 295 296 <para> 297 With <function>PQconnectStart</function>, the database connection is made 298 using the parameters taken from the string <literal>conninfo</literal> as 299 described above for <function>PQconnectdb</function>. 300 </para> 301 302 <para> 303 Neither <function>PQconnectStartParams</function> nor <function>PQconnectStart</function> 304 nor <function>PQconnectPoll</function> will block, so long as a number of 305 restrictions are met: 306 <itemizedlist> 307 <listitem> 308 <para> 309 The <literal>hostaddr</literal> parameter must be used appropriately 310 to prevent DNS queries from being made. See the documentation of 311 this parameter in <xref linkend="libpq-paramkeywords"/> for details. 312 </para> 313 </listitem> 314 315 <listitem> 316 <para> 317 If you call <function>PQtrace</function>, ensure that the stream object 318 into which you trace will not block. 319 </para> 320 </listitem> 321 322 <listitem> 323 <para> 324 You must ensure that the socket is in the appropriate state 325 before calling <function>PQconnectPoll</function>, as described below. 326 </para> 327 </listitem> 328 </itemizedlist> 329 </para> 330 331 <para> 332 To begin a nonblocking connection request, 333 call <function>PQconnectStart</function> 334 or <function>PQconnectStartParams</function>. If the result is null, 335 then <application>libpq</application> has been unable to allocate a 336 new <structname>PGconn</structname> structure. Otherwise, a 337 valid <structname>PGconn</structname> pointer is returned (though not 338 yet representing a valid connection to the database). Next 339 call <literal>PQstatus(conn)</literal>. If the result 340 is <symbol>CONNECTION_BAD</symbol>, the connection attempt has already 341 failed, typically because of invalid connection parameters. 342 </para> 343 344 <para> 345 If <function>PQconnectStart</function> 346 or <function>PQconnectStartParams</function> succeeds, the next stage 347 is to poll <application>libpq</application> so that it can proceed with 348 the connection sequence. 349 Use <function>PQsocket(conn)</function> to obtain the descriptor of the 350 socket underlying the database connection. 351 (Caution: do not assume that the socket remains the same 352 across <function>PQconnectPoll</function> calls.) 353 Loop thus: If <function>PQconnectPoll(conn)</function> last returned 354 <symbol>PGRES_POLLING_READING</symbol>, wait until the socket is ready to 355 read (as indicated by <function>select()</function>, <function>poll()</function>, or 356 similar system function). 357 Then call <function>PQconnectPoll(conn)</function> again. 358 Conversely, if <function>PQconnectPoll(conn)</function> last returned 359 <symbol>PGRES_POLLING_WRITING</symbol>, wait until the socket is ready 360 to write, then call <function>PQconnectPoll(conn)</function> again. 361 On the first iteration, i.e., if you have yet to call 362 <function>PQconnectPoll</function>, behave as if it last returned 363 <symbol>PGRES_POLLING_WRITING</symbol>. Continue this loop until 364 <function>PQconnectPoll(conn)</function> returns 365 <symbol>PGRES_POLLING_FAILED</symbol>, indicating the connection procedure 366 has failed, or <symbol>PGRES_POLLING_OK</symbol>, indicating the connection 367 has been successfully made. 368 </para> 369 370 <para> 371 At any time during connection, the status of the connection can be 372 checked by calling <function>PQstatus</function>. If this call returns <symbol>CONNECTION_BAD</symbol>, then the 373 connection procedure has failed; if the call returns <function>CONNECTION_OK</function>, then the 374 connection is ready. Both of these states are equally detectable 375 from the return value of <function>PQconnectPoll</function>, described above. Other states might also occur 376 during (and only during) an asynchronous connection procedure. These 377 indicate the current stage of the connection procedure and might be useful 378 to provide feedback to the user for example. These statuses are: 379 380 <variablelist> 381 <varlistentry id="libpq-connection-started"> 382 <term><symbol>CONNECTION_STARTED</symbol></term> 383 <listitem> 384 <para> 385 Waiting for connection to be made. 386 </para> 387 </listitem> 388 </varlistentry> 389 390 <varlistentry id="libpq-connection-made"> 391 <term><symbol>CONNECTION_MADE</symbol></term> 392 <listitem> 393 <para> 394 Connection OK; waiting to send. 395 </para> 396 </listitem> 397 </varlistentry> 398 399 <varlistentry id="libpq-connection-awaiting-response"> 400 <term><symbol>CONNECTION_AWAITING_RESPONSE</symbol></term> 401 <listitem> 402 <para> 403 Waiting for a response from the server. 404 </para> 405 </listitem> 406 </varlistentry> 407 408 <varlistentry id="libpq-connection-auth-ok"> 409 <term><symbol>CONNECTION_AUTH_OK</symbol></term> 410 <listitem> 411 <para> 412 Received authentication; waiting for backend start-up to finish. 413 </para> 414 </listitem> 415 </varlistentry> 416 417 <varlistentry id="libpq-connection-ssl-startup"> 418 <term><symbol>CONNECTION_SSL_STARTUP</symbol></term> 419 <listitem> 420 <para> 421 Negotiating SSL encryption. 422 </para> 423 </listitem> 424 </varlistentry> 425 426 <varlistentry id="libpq-connection-setenv"> 427 <term><symbol>CONNECTION_SETENV</symbol></term> 428 <listitem> 429 <para> 430 Negotiating environment-driven parameter settings. 431 </para> 432 </listitem> 433 </varlistentry> 434 435 <varlistentry id="libpq-connection-check-writable"> 436 <term><symbol>CONNECTION_CHECK_WRITABLE</symbol></term> 437 <listitem> 438 <para> 439 Checking if connection is able to handle write transactions. 440 </para> 441 </listitem> 442 </varlistentry> 443 444 <varlistentry id="libpq-connection-consume"> 445 <term><symbol>CONNECTION_CONSUME</symbol></term> 446 <listitem> 447 <para> 448 Consuming any remaining response messages on connection. 449 </para> 450 </listitem> 451 </varlistentry> 452 </variablelist> 453 454 Note that, although these constants will remain (in order to maintain 455 compatibility), an application should never rely upon these occurring in a 456 particular order, or at all, or on the status always being one of these 457 documented values. An application might do something like this: 458<programlisting> 459switch(PQstatus(conn)) 460{ 461 case CONNECTION_STARTED: 462 feedback = "Connecting..."; 463 break; 464 465 case CONNECTION_MADE: 466 feedback = "Connected to server..."; 467 break; 468. 469. 470. 471 default: 472 feedback = "Connecting..."; 473} 474</programlisting> 475 </para> 476 477 <para> 478 The <literal>connect_timeout</literal> connection parameter is ignored 479 when using <function>PQconnectPoll</function>; it is the application's 480 responsibility to decide whether an excessive amount of time has elapsed. 481 Otherwise, <function>PQconnectStart</function> followed by a 482 <function>PQconnectPoll</function> loop is equivalent to 483 <function>PQconnectdb</function>. 484 </para> 485 486 <para> 487 Note that when <function>PQconnectStart</function> 488 or <function>PQconnectStartParams</function> returns a non-null 489 pointer, you must call <function>PQfinish</function> when you are 490 finished with it, in order to dispose of the structure and any 491 associated memory blocks. This must be done even if the connection 492 attempt fails or is abandoned. 493 </para> 494 </listitem> 495 </varlistentry> 496 497 <varlistentry id="libpq-pqconndefaults"> 498 <term><function>PQconndefaults</function><indexterm><primary>PQconndefaults</primary></indexterm></term> 499 <listitem> 500 <para> 501 Returns the default connection options. 502<synopsis> 503PQconninfoOption *PQconndefaults(void); 504 505typedef struct 506{ 507 char *keyword; /* The keyword of the option */ 508 char *envvar; /* Fallback environment variable name */ 509 char *compiled; /* Fallback compiled in default value */ 510 char *val; /* Option's current value, or NULL */ 511 char *label; /* Label for field in connect dialog */ 512 char *dispchar; /* Indicates how to display this field 513 in a connect dialog. Values are: 514 "" Display entered value as is 515 "*" Password field - hide value 516 "D" Debug option - don't show by default */ 517 int dispsize; /* Field size in characters for dialog */ 518} PQconninfoOption; 519</synopsis> 520 </para> 521 522 <para> 523 Returns a connection options array. This can be used to determine 524 all possible <function>PQconnectdb</function> options and their 525 current default values. The return value points to an array of 526 <structname>PQconninfoOption</structname> structures, which ends 527 with an entry having a null <structfield>keyword</structfield> pointer. The 528 null pointer is returned if memory could not be allocated. Note that 529 the current default values (<structfield>val</structfield> fields) 530 will depend on environment variables and other context. A 531 missing or invalid service file will be silently ignored. Callers 532 must treat the connection options data as read-only. 533 </para> 534 535 <para> 536 After processing the options array, free it by passing it to 537 <function>PQconninfoFree</function>. If this is not done, a small amount of memory 538 is leaked for each call to <function>PQconndefaults</function>. 539 </para> 540 541 </listitem> 542 </varlistentry> 543 544 <varlistentry id="libpq-pqconninfo"> 545 <term><function>PQconninfo</function><indexterm><primary>PQconninfo</primary></indexterm></term> 546 <listitem> 547 <para> 548 Returns the connection options used by a live connection. 549<synopsis> 550PQconninfoOption *PQconninfo(PGconn *conn); 551</synopsis> 552 </para> 553 554 <para> 555 Returns a connection options array. This can be used to determine 556 all possible <function>PQconnectdb</function> options and the 557 values that were used to connect to the server. The return 558 value points to an array of <structname>PQconninfoOption</structname> 559 structures, which ends with an entry having a null <structfield>keyword</structfield> 560 pointer. All notes above for <function>PQconndefaults</function> also 561 apply to the result of <function>PQconninfo</function>. 562 </para> 563 564 </listitem> 565 </varlistentry> 566 567 568 <varlistentry id="libpq-pqconninfoparse"> 569 <term><function>PQconninfoParse</function><indexterm><primary>PQconninfoParse</primary></indexterm></term> 570 <listitem> 571 <para> 572 Returns parsed connection options from the provided connection string. 573 574<synopsis> 575PQconninfoOption *PQconninfoParse(const char *conninfo, char **errmsg); 576</synopsis> 577 </para> 578 579 <para> 580 Parses a connection string and returns the resulting options as an 581 array; or returns <symbol>NULL</symbol> if there is a problem with the connection 582 string. This function can be used to extract 583 the <function>PQconnectdb</function> options in the provided 584 connection string. The return value points to an array of 585 <structname>PQconninfoOption</structname> structures, which ends 586 with an entry having a null <structfield>keyword</structfield> pointer. 587 </para> 588 589 <para> 590 All legal options will be present in the result array, but the 591 <literal>PQconninfoOption</literal> for any option not present 592 in the connection string will have <literal>val</literal> set to 593 <literal>NULL</literal>; default values are not inserted. 594 </para> 595 596 <para> 597 If <literal>errmsg</literal> is not <symbol>NULL</symbol>, then <literal>*errmsg</literal> is set 598 to <symbol>NULL</symbol> on success, else to a <function>malloc</function>'d error string explaining 599 the problem. (It is also possible for <literal>*errmsg</literal> to be 600 set to <symbol>NULL</symbol> and the function to return <symbol>NULL</symbol>; 601 this indicates an out-of-memory condition.) 602 </para> 603 604 <para> 605 After processing the options array, free it by passing it to 606 <function>PQconninfoFree</function>. If this is not done, some memory 607 is leaked for each call to <function>PQconninfoParse</function>. 608 Conversely, if an error occurs and <literal>errmsg</literal> is not <symbol>NULL</symbol>, 609 be sure to free the error string using <function>PQfreemem</function>. 610 </para> 611 612 </listitem> 613 </varlistentry> 614 615 <varlistentry id="libpq-pqfinish"> 616 <term><function>PQfinish</function><indexterm><primary>PQfinish</primary></indexterm></term> 617 <listitem> 618 <para> 619 Closes the connection to the server. Also frees 620 memory used by the <structname>PGconn</structname> object. 621<synopsis> 622void PQfinish(PGconn *conn); 623</synopsis> 624 </para> 625 626 <para> 627 Note that even if the server connection attempt fails (as 628 indicated by <function>PQstatus</function>), the application should call <function>PQfinish</function> 629 to free the memory used by the <structname>PGconn</structname> object. 630 The <structname>PGconn</structname> pointer must not be used again after 631 <function>PQfinish</function> has been called. 632 </para> 633 </listitem> 634 </varlistentry> 635 636 <varlistentry id="libpq-pqreset"> 637 <term><function>PQreset</function><indexterm><primary>PQreset</primary></indexterm></term> 638 <listitem> 639 <para> 640 Resets the communication channel to the server. 641<synopsis> 642void PQreset(PGconn *conn); 643</synopsis> 644 </para> 645 646 <para> 647 This function will close the connection 648 to the server and attempt to establish a new 649 connection, using all the same 650 parameters previously used. This might be useful for 651 error recovery if a working connection is lost. 652 </para> 653 </listitem> 654 </varlistentry> 655 656 <varlistentry id="libpq-pqresetstart"> 657 <term><function>PQresetStart</function><indexterm><primary>PQresetStart</primary></indexterm></term> 658 <term><function>PQresetPoll</function><indexterm><primary>PQresetPoll</primary></indexterm></term> 659 <listitem> 660 <para> 661 Reset the communication channel to the server, in a nonblocking manner. 662 663<synopsis> 664int PQresetStart(PGconn *conn); 665 666PostgresPollingStatusType PQresetPoll(PGconn *conn); 667</synopsis> 668 </para> 669 670 <para> 671 These functions will close the connection to the server and attempt to 672 establish a new connection, using all the same 673 parameters previously used. This can be useful for error recovery if a 674 working connection is lost. They differ from <function>PQreset</function> (above) in that they 675 act in a nonblocking manner. These functions suffer from the same 676 restrictions as <function>PQconnectStartParams</function>, <function>PQconnectStart</function> 677 and <function>PQconnectPoll</function>. 678 </para> 679 680 <para> 681 To initiate a connection reset, call 682 <function>PQresetStart</function>. If it returns 0, the reset has 683 failed. If it returns 1, poll the reset using 684 <function>PQresetPoll</function> in exactly the same way as you 685 would create the connection using <function>PQconnectPoll</function>. 686 </para> 687 </listitem> 688 </varlistentry> 689 690 <varlistentry id="libpq-pqpingparams"> 691 <term><function>PQpingParams</function><indexterm><primary>PQpingParams</primary></indexterm></term> 692 <listitem> 693 <para> 694 <function>PQpingParams</function> reports the status of the 695 server. It accepts connection parameters identical to those of 696 <function>PQconnectdbParams</function>, described above. It is not 697 necessary to supply correct user name, password, or database name 698 values to obtain the server status; however, if incorrect values 699 are provided, the server will log a failed connection attempt. 700 701<synopsis> 702PGPing PQpingParams(const char * const *keywords, 703 const char * const *values, 704 int expand_dbname); 705</synopsis> 706 707 The function returns one of the following values: 708 709 <variablelist> 710 <varlistentry id="libpq-pqpingparams-pqping-ok"> 711 <term><literal>PQPING_OK</literal></term> 712 <listitem> 713 <para> 714 The server is running and appears to be accepting connections. 715 </para> 716 </listitem> 717 </varlistentry> 718 719 <varlistentry id="libpq-pqpingparams-pqping-reject"> 720 <term><literal>PQPING_REJECT</literal></term> 721 <listitem> 722 <para> 723 The server is running but is in a state that disallows connections 724 (startup, shutdown, or crash recovery). 725 </para> 726 </listitem> 727 </varlistentry> 728 729 <varlistentry id="libpq-pqpingparams-pqping-no-response"> 730 <term><literal>PQPING_NO_RESPONSE</literal></term> 731 <listitem> 732 <para> 733 The server could not be contacted. This might indicate that the 734 server is not running, or that there is something wrong with the 735 given connection parameters (for example, wrong port number), or 736 that there is a network connectivity problem (for example, a 737 firewall blocking the connection request). 738 </para> 739 </listitem> 740 </varlistentry> 741 742 <varlistentry id="libpq-pqpingparams-pqping-no-attempt"> 743 <term><literal>PQPING_NO_ATTEMPT</literal></term> 744 <listitem> 745 <para> 746 No attempt was made to contact the server, because the supplied 747 parameters were obviously incorrect or there was some client-side 748 problem (for example, out of memory). 749 </para> 750 </listitem> 751 </varlistentry> 752 </variablelist> 753 754 </para> 755 756 </listitem> 757 </varlistentry> 758 759 <varlistentry id="libpq-pqping"> 760 <term><function>PQping</function><indexterm><primary>PQping</primary></indexterm></term> 761 <listitem> 762 <para> 763 <function>PQping</function> reports the status of the 764 server. It accepts connection parameters identical to those of 765 <function>PQconnectdb</function>, described above. It is not 766 necessary to supply correct user name, password, or database name 767 values to obtain the server status; however, if incorrect values 768 are provided, the server will log a failed connection attempt. 769 770<synopsis> 771PGPing PQping(const char *conninfo); 772</synopsis> 773 </para> 774 775 <para> 776 The return values are the same as for <function>PQpingParams</function>. 777 </para> 778 779 </listitem> 780 </varlistentry> 781 782 </variablelist> 783 </para> 784 785 <sect2 id="libpq-connstring"> 786 <title>Connection Strings</title> 787 788 <indexterm zone="libpq-connstring"> 789 <primary><literal>conninfo</literal></primary> 790 </indexterm> 791 792 <indexterm zone="libpq-connstring"> 793 <primary><literal>URI</literal></primary> 794 </indexterm> 795 796 <para> 797 Several <application>libpq</application> functions parse a user-specified string to obtain 798 connection parameters. There are two accepted formats for these strings: 799 plain keyword/value strings 800 and URIs. URIs generally follow 801 <ulink url="https://tools.ietf.org/html/rfc3986">RFC 802 3986</ulink>, except that multi-host connection strings are allowed 803 as further described below. 804 </para> 805 806 <sect3> 807 <title>Keyword/Value Connection Strings</title> 808 809 <para> 810 In the keyword/value format, each parameter setting is in the form 811 <replaceable>keyword</replaceable> <literal>=</literal> 812 <replaceable>value</replaceable>, with space(s) between settings. 813 Spaces around a setting's equal sign are 814 optional. To write an empty value, or a value containing spaces, surround it 815 with single quotes, for example <literal>keyword = 'a value'</literal>. 816 Single quotes and backslashes within 817 a value must be escaped with a backslash, i.e., <literal>\'</literal> and 818 <literal>\\</literal>. 819 </para> 820 821 <para> 822 Example: 823<programlisting> 824host=localhost port=5432 dbname=mydb connect_timeout=10 825</programlisting> 826 </para> 827 828 <para> 829 The recognized parameter key words are listed in <xref 830 linkend="libpq-paramkeywords"/>. 831 </para> 832 </sect3> 833 834 <sect3> 835 <title>Connection URIs</title> 836 837 <para> 838 The general form for a connection <acronym>URI</acronym> is: 839<synopsis> 840postgresql://<optional><replaceable>userspec</replaceable>@</optional><optional><replaceable>hostspec</replaceable></optional><optional>/<replaceable>dbname</replaceable></optional><optional>?<replaceable>paramspec</replaceable></optional> 841 842<phrase>where <replaceable>userspec</replaceable> is:</phrase> 843 844<replaceable>user</replaceable><optional>:<replaceable>password</replaceable></optional> 845 846<phrase>and <replaceable>hostspec</replaceable> is:</phrase> 847 848<optional><replaceable>host</replaceable></optional><optional>:<replaceable>port</replaceable></optional><optional>,...</optional> 849 850<phrase>and <replaceable>paramspec</replaceable> is:</phrase> 851 852<replaceable>name</replaceable>=<replaceable>value</replaceable><optional>&...</optional> 853</synopsis> 854 </para> 855 856 <para> 857 The <acronym>URI</acronym> scheme designator can be either 858 <literal>postgresql://</literal> or <literal>postgres://</literal>. Each 859 of the remaining <acronym>URI</acronym> parts is optional. The 860 following examples illustrate valid <acronym>URI</acronym> syntax: 861<programlisting> 862postgresql:// 863postgresql://localhost 864postgresql://localhost:5433 865postgresql://localhost/mydb 866postgresql://user@localhost 867postgresql://user:secret@localhost 868postgresql://other@localhost/otherdb?connect_timeout=10&application_name=myapp 869postgresql://host1:123,host2:456/somedb?target_session_attrs=any&application_name=myapp 870</programlisting> 871 Values that would normally appear in the hierarchical part of 872 the <acronym>URI</acronym> can alternatively be given as named 873 parameters. For example: 874<programlisting> 875postgresql:///mydb?host=localhost&port=5433 876</programlisting> 877 All named parameters must match key words listed in 878 <xref linkend="libpq-paramkeywords"/>, except that for compatibility 879 with JDBC connection <acronym>URI</acronym>s, instances 880 of <literal>ssl=true</literal> are translated into 881 <literal>sslmode=require</literal>. 882 </para> 883 884 <para> 885 Percent-encoding may be used to include symbols with special meaning in any 886 of the <acronym>URI</acronym> parts, e.g., replace <literal>=</literal> with 887 <literal>%3D</literal>. 888 889 </para> 890 891 <para> 892 The host part may be either a host name or an IP address. To specify an 893 IPv6 address, enclose it in square brackets: 894<synopsis> 895postgresql://[2001:db8::1234]/database 896</synopsis> 897 </para> 898 899 <para> 900 The host part is interpreted as described for the parameter <xref 901 linkend="libpq-connect-host"/>. In particular, a Unix-domain socket 902 connection is chosen if the host part is either empty or looks like an 903 absolute path name, 904 otherwise a TCP/IP connection is initiated. Note, however, that the 905 slash is a reserved character in the hierarchical part of the URI. So, to 906 specify a non-standard Unix-domain socket directory, either omit the host 907 part of the URI and specify the host as a named parameter, or 908 percent-encode the path in the host part of the URI: 909<programlisting> 910postgresql:///dbname?host=/var/lib/postgresql 911postgresql://%2Fvar%2Flib%2Fpostgresql/dbname 912</programlisting> 913 </para> 914 915 <para> 916 It is possible to specify multiple host components, each with an optional 917 port component, in a single URI. A URI of the form 918 <literal>postgresql://host1:port1,host2:port2,host3:port3/</literal> 919 is equivalent to a connection string of the form 920 <literal>host=host1,host2,host3 port=port1,port2,port3</literal>. 921 As further described below, each 922 host will be tried in turn until a connection is successfully established. 923 </para> 924 </sect3> 925 926 <sect3 id="libpq-multiple-hosts"> 927 <title>Specifying Multiple Hosts</title> 928 929 <para> 930 It is possible to specify multiple hosts to connect to, so that they are 931 tried in the given order. In the Keyword/Value format, the <literal>host</literal>, 932 <literal>hostaddr</literal>, and <literal>port</literal> options accept comma-separated 933 lists of values. The same number of elements must be given in each 934 option that is specified, such 935 that e.g., the first <literal>hostaddr</literal> corresponds to the first host name, 936 the second <literal>hostaddr</literal> corresponds to the second host name, and so 937 forth. As an exception, if only one <literal>port</literal> is specified, it 938 applies to all the hosts. 939 </para> 940 941 <para> 942 In the connection URI format, you can list multiple <literal>host:port</literal> pairs 943 separated by commas in the <literal>host</literal> component of the URI. 944 </para> 945 946 <para> 947 In either format, a single host name can translate to multiple network 948 addresses. A common example of this is a host that has both an IPv4 and 949 an IPv6 address. 950 </para> 951 952 <para> 953 When multiple hosts are specified, or when a single host name is 954 translated to multiple addresses, all the hosts and addresses will be 955 tried in order, until one succeeds. If none of the hosts can be reached, 956 the connection fails. If a connection is established successfully, but 957 authentication fails, the remaining hosts in the list are not tried. 958 </para> 959 960 <para> 961 If a password file is used, you can have different passwords for 962 different hosts. All the other connection options are the same for every 963 host in the list; it is not possible to e.g., specify different 964 usernames for different hosts. 965 </para> 966 </sect3> 967 </sect2> 968 969 <sect2 id="libpq-paramkeywords"> 970 <title>Parameter Key Words</title> 971 972 <para> 973 The currently recognized parameter key words are: 974 975 <variablelist> 976 <varlistentry id="libpq-connect-host" xreflabel="host"> 977 <term><literal>host</literal></term> 978 <listitem> 979 <para> 980 Name of host to connect to.<indexterm><primary>host name</primary></indexterm> 981 If a host name begins with a slash, it specifies Unix-domain 982 communication rather than TCP/IP communication; the value is the 983 name of the directory in which the socket file is stored. 984 The default behavior when <literal>host</literal> is 985 not specified, or is empty, is to connect to a Unix-domain 986 socket<indexterm><primary>Unix domain socket</primary></indexterm> in 987 <filename>/tmp</filename> (or whatever socket directory was specified 988 when <productname>PostgreSQL</productname> was built). On machines without 989 Unix-domain sockets, the default is to connect to <literal>localhost</literal>. 990 </para> 991 <para> 992 A comma-separated list of host names is also accepted, in which case 993 each host name in the list is tried in order; an empty item in the 994 list selects the default behavior as explained above. See 995 <xref linkend="libpq-multiple-hosts"/> for details. 996 </para> 997 </listitem> 998 </varlistentry> 999 1000 <varlistentry id="libpq-connect-hostaddr" xreflabel="hostaddr"> 1001 <term><literal>hostaddr</literal></term> 1002 <listitem> 1003 <para> 1004 Numeric IP address of host to connect to. This should be in the 1005 standard IPv4 address format, e.g., <literal>172.28.40.9</literal>. If 1006 your machine supports IPv6, you can also use those addresses. 1007 TCP/IP communication is 1008 always used when a nonempty string is specified for this parameter. 1009 </para> 1010 1011 <para> 1012 Using <literal>hostaddr</literal> instead of <literal>host</literal> allows the 1013 application to avoid a host name look-up, which might be important 1014 in applications with time constraints. However, a host name is 1015 required for GSSAPI or SSPI authentication 1016 methods, as well as for <literal>verify-full</literal> SSL 1017 certificate verification. The following rules are used: 1018 <itemizedlist> 1019 <listitem> 1020 <para> 1021 If <literal>host</literal> is specified 1022 without <literal>hostaddr</literal>, a host name lookup occurs. 1023 (When using <function>PQconnectPoll</function>, the lookup occurs 1024 when <function>PQconnectPoll</function> first considers this host 1025 name, and it may cause <function>PQconnectPoll</function> to block 1026 for a significant amount of time.) 1027 </para> 1028 </listitem> 1029 <listitem> 1030 <para> 1031 If <literal>hostaddr</literal> is specified without <literal>host</literal>, 1032 the value for <literal>hostaddr</literal> gives the server network address. 1033 The connection attempt will fail if the authentication 1034 method requires a host name. 1035 </para> 1036 </listitem> 1037 <listitem> 1038 <para> 1039 If both <literal>host</literal> and <literal>hostaddr</literal> are specified, 1040 the value for <literal>hostaddr</literal> gives the server network address. 1041 The value for <literal>host</literal> is ignored unless the 1042 authentication method requires it, in which case it will be 1043 used as the host name. 1044 </para> 1045 </listitem> 1046 </itemizedlist> 1047 Note that authentication is likely to fail if <literal>host</literal> 1048 is not the name of the server at network address <literal>hostaddr</literal>. 1049 Also, when both <literal>host</literal> and <literal>hostaddr</literal> 1050 are specified, <literal>host</literal> 1051 is used to identify the connection in a password file (see 1052 <xref linkend="libpq-pgpass"/>). 1053 </para> 1054 1055 <para> 1056 A comma-separated list of <literal>hostaddr</literal> values is also 1057 accepted, in which case each host in the list is tried in order. 1058 An empty item in the list causes the corresponding host name to be 1059 used, or the default host name if that is empty as well. See 1060 <xref linkend="libpq-multiple-hosts"/> for details. 1061 </para> 1062 <para> 1063 Without either a host name or host address, 1064 <application>libpq</application> will connect using a 1065 local Unix-domain socket; or on machines without Unix-domain 1066 sockets, it will attempt to connect to <literal>localhost</literal>. 1067 </para> 1068 </listitem> 1069 </varlistentry> 1070 1071 <varlistentry id="libpq-connect-port" xreflabel="port"> 1072 <term><literal>port</literal></term> 1073 <listitem> 1074 <para> 1075 Port number to connect to at the server host, or socket file 1076 name extension for Unix-domain 1077 connections.<indexterm><primary>port</primary></indexterm> 1078 If multiple hosts were given in the <literal>host</literal> or 1079 <literal>hostaddr</literal> parameters, this parameter may specify a 1080 comma-separated list of ports of the same length as the host list, or 1081 it may specify a single port number to be used for all hosts. 1082 An empty string, or an empty item in a comma-separated list, 1083 specifies the default port number established 1084 when <productname>PostgreSQL</productname> was built. 1085 </para> 1086 </listitem> 1087 </varlistentry> 1088 1089 <varlistentry id="libpq-connect-dbname" xreflabel="dbname"> 1090 <term><literal>dbname</literal></term> 1091 <listitem> 1092 <para> 1093 The database name. Defaults to be the same as the user name. 1094 In certain contexts, the value is checked for extended 1095 formats; see <xref linkend="libpq-connstring"/> for more details on 1096 those. 1097 </para> 1098 </listitem> 1099 </varlistentry> 1100 1101 <varlistentry id="libpq-connect-user" xreflabel="user"> 1102 <term><literal>user</literal></term> 1103 <listitem> 1104 <para> 1105 <productname>PostgreSQL</productname> user name to connect as. 1106 Defaults to be the same as the operating system name of the user 1107 running the application. 1108 </para> 1109 </listitem> 1110 </varlistentry> 1111 1112 <varlistentry id="libpq-connect-password" xreflabel="password"> 1113 <term><literal>password</literal></term> 1114 <listitem> 1115 <para> 1116 Password to be used if the server demands password authentication. 1117 </para> 1118 </listitem> 1119 </varlistentry> 1120 1121 <varlistentry id="libpq-connect-passfile" xreflabel="passfile"> 1122 <term><literal>passfile</literal></term> 1123 <listitem> 1124 <para> 1125 Specifies the name of the file used to store passwords 1126 (see <xref linkend="libpq-pgpass"/>). 1127 Defaults to <filename>~/.pgpass</filename>, or 1128 <filename>%APPDATA%\postgresql\pgpass.conf</filename> on Microsoft Windows. 1129 (No error is reported if this file does not exist.) 1130 </para> 1131 </listitem> 1132 </varlistentry> 1133 1134 <varlistentry id="libpq-connect-connect-timeout" xreflabel="connect_timeout"> 1135 <term><literal>connect_timeout</literal></term> 1136 <listitem> 1137 <para> 1138 Maximum wait for connection, in seconds (write as a decimal integer, 1139 e.g., <literal>10</literal>). Zero, negative, or not specified means 1140 wait indefinitely. The minimum allowed timeout is 2 seconds, therefore 1141 a value of <literal>1</literal> is interpreted as <literal>2</literal>. 1142 This timeout applies separately to each host name or IP address. 1143 For example, if you specify two hosts and <literal>connect_timeout</literal> 1144 is 5, each host will time out if no connection is made within 5 1145 seconds, so the total time spent waiting for a connection might be 1146 up to 10 seconds. 1147 </para> 1148 </listitem> 1149 </varlistentry> 1150 1151 <varlistentry id="libpq-connect-client-encoding" xreflabel="client_encoding"> 1152 <term><literal>client_encoding</literal></term> 1153 <listitem> 1154 <para> 1155 This sets the <varname>client_encoding</varname> 1156 configuration parameter for this connection. In addition to 1157 the values accepted by the corresponding server option, you 1158 can use <literal>auto</literal> to determine the right 1159 encoding from the current locale in the client 1160 (<envar>LC_CTYPE</envar> environment variable on Unix 1161 systems). 1162 </para> 1163 </listitem> 1164 </varlistentry> 1165 1166 <varlistentry id="libpq-connect-options" xreflabel="options"> 1167 <term><literal>options</literal></term> 1168 <listitem> 1169 <para> 1170 Specifies command-line options to send to the server at connection 1171 start. For example, setting this to <literal>-c geqo=off</literal> sets the 1172 session's value of the <varname>geqo</varname> parameter to 1173 <literal>off</literal>. Spaces within this string are considered to 1174 separate command-line arguments, unless escaped with a backslash 1175 (<literal>\</literal>); write <literal>\\</literal> to represent a literal 1176 backslash. For a detailed discussion of the available 1177 options, consult <xref linkend="runtime-config"/>. 1178 </para> 1179 </listitem> 1180 </varlistentry> 1181 1182 <varlistentry id="libpq-connect-application-name" xreflabel="application_name"> 1183 <term><literal>application_name</literal></term> 1184 <listitem> 1185 <para> 1186 Specifies a value for the <xref linkend="guc-application-name"/> 1187 configuration parameter. 1188 </para> 1189 </listitem> 1190 </varlistentry> 1191 1192 <varlistentry id="libpq-connect-fallback-application-name" xreflabel="fallback_application_name"> 1193 <term><literal>fallback_application_name</literal></term> 1194 <listitem> 1195 <para> 1196 Specifies a fallback value for the <xref 1197 linkend="guc-application-name"/> configuration parameter. 1198 This value will be used if no value has been given for 1199 <literal>application_name</literal> via a connection parameter or the 1200 <envar>PGAPPNAME</envar> environment variable. Specifying 1201 a fallback name is useful in generic utility programs that 1202 wish to set a default application name but allow it to be 1203 overridden by the user. 1204 </para> 1205 </listitem> 1206 </varlistentry> 1207 1208 <varlistentry id="libpq-keepalives" xreflabel="keepalives"> 1209 <term><literal>keepalives</literal></term> 1210 <listitem> 1211 <para> 1212 Controls whether client-side TCP keepalives are used. The default 1213 value is 1, meaning on, but you can change this to 0, meaning off, 1214 if keepalives are not wanted. This parameter is ignored for 1215 connections made via a Unix-domain socket. 1216 </para> 1217 </listitem> 1218 </varlistentry> 1219 1220 <varlistentry id="libpq-keepalives-idle" xreflabel="keepalives_idle"> 1221 <term><literal>keepalives_idle</literal></term> 1222 <listitem> 1223 <para> 1224 Controls the number of seconds of inactivity after which TCP should 1225 send a keepalive message to the server. A value of zero uses the 1226 system default. This parameter is ignored for connections made via a 1227 Unix-domain socket, or if keepalives are disabled. 1228 It is only supported on systems where <symbol>TCP_KEEPIDLE</symbol> or 1229 an equivalent socket option is available, and on Windows; on other 1230 systems, it has no effect. 1231 </para> 1232 </listitem> 1233 </varlistentry> 1234 1235 <varlistentry id="libpq-keepalives-interval" xreflabel="keepalives_interval"> 1236 <term><literal>keepalives_interval</literal></term> 1237 <listitem> 1238 <para> 1239 Controls the number of seconds after which a TCP keepalive message 1240 that is not acknowledged by the server should be retransmitted. A 1241 value of zero uses the system default. This parameter is ignored for 1242 connections made via a Unix-domain socket, or if keepalives are disabled. 1243 It is only supported on systems where <symbol>TCP_KEEPINTVL</symbol> or 1244 an equivalent socket option is available, and on Windows; on other 1245 systems, it has no effect. 1246 </para> 1247 </listitem> 1248 </varlistentry> 1249 1250 <varlistentry id="libpq-keepalives-count" xreflabel="keepalives_count"> 1251 <term><literal>keepalives_count</literal></term> 1252 <listitem> 1253 <para> 1254 Controls the number of TCP keepalives that can be lost before the 1255 client's connection to the server is considered dead. A value of 1256 zero uses the system default. This parameter is ignored for 1257 connections made via a Unix-domain socket, or if keepalives are disabled. 1258 It is only supported on systems where <symbol>TCP_KEEPCNT</symbol> or 1259 an equivalent socket option is available; on other systems, it has no 1260 effect. 1261 </para> 1262 </listitem> 1263 </varlistentry> 1264 1265 <varlistentry id="libpq-tcp-user-timeout" xreflabel="tcp_user_timeout"> 1266 <term><literal>tcp_user_timeout</literal></term> 1267 <listitem> 1268 <para> 1269 Controls the number of milliseconds that transmitted data may 1270 remain unacknowledged before a connection is forcibly closed. 1271 A value of zero uses the system default. This parameter is 1272 ignored for connections made via a Unix-domain socket. 1273 It is only supported on systems where <symbol>TCP_USER_TIMEOUT</symbol> 1274 is available; on other systems, it has no effect. 1275 </para> 1276 </listitem> 1277 </varlistentry> 1278 1279 <varlistentry id="libpq-connect-tty" xreflabel="tty"> 1280 <term><literal>tty</literal></term> 1281 <listitem> 1282 <para> 1283 Ignored (formerly, this specified where to send server debug output). 1284 </para> 1285 </listitem> 1286 </varlistentry> 1287 1288 <varlistentry id="libpq-connect-replication" xreflabel="replication"> 1289 <term><literal>replication</literal></term> 1290 <listitem> 1291 <para> 1292 This option determines whether the connection should use the 1293 replication protocol instead of the normal protocol. This is what 1294 PostgreSQL replication connections as well as tools such as 1295 <application>pg_basebackup</application> use internally, but it can 1296 also be used by third-party applications. For a description of the 1297 replication protocol, consult <xref linkend="protocol-replication"/>. 1298 </para> 1299 1300 <para> 1301 The following values, which are case-insensitive, are supported: 1302 <variablelist> 1303 <varlistentry> 1304 <term> 1305 <literal>true</literal>, <literal>on</literal>, 1306 <literal>yes</literal>, <literal>1</literal> 1307 </term> 1308 <listitem> 1309 <para> 1310 The connection goes into physical replication mode. 1311 </para> 1312 </listitem> 1313 </varlistentry> 1314 1315 <varlistentry> 1316 <term><literal>database</literal></term> 1317 <listitem> 1318 <para> 1319 The connection goes into logical replication mode, connecting to 1320 the database specified in the <literal>dbname</literal> parameter. 1321 </para> 1322 </listitem> 1323 </varlistentry> 1324 1325 <varlistentry> 1326 <term> 1327 <literal>false</literal>, <literal>off</literal>, 1328 <literal>no</literal>, <literal>0</literal> 1329 </term> 1330 <listitem> 1331 <para> 1332 The connection is a regular one, which is the default behavior. 1333 </para> 1334 </listitem> 1335 </varlistentry> 1336 </variablelist> 1337 </para> 1338 1339 <para> 1340 In physical or logical replication mode, only the simple query protocol 1341 can be used. 1342 </para> 1343 </listitem> 1344 </varlistentry> 1345 1346 <varlistentry id="libpq-connect-gssencmode" xreflabel="gssencmode"> 1347 <term><literal>gssencmode</literal></term> 1348 <listitem> 1349 <para> 1350 This option determines whether or with what priority a secure 1351 <acronym>GSS</acronym> TCP/IP connection will be negotiated with the 1352 server. There are three modes: 1353 1354 <variablelist> 1355 <varlistentry> 1356 <term><literal>disable</literal></term> 1357 <listitem> 1358 <para> 1359 only try a non-<acronym>GSSAPI</acronym>-encrypted connection 1360 </para> 1361 </listitem> 1362 </varlistentry> 1363 1364 <varlistentry> 1365 <term><literal>prefer</literal> (default)</term> 1366 <listitem> 1367 <para> 1368 if there are <acronym>GSSAPI</acronym> credentials present (i.e., 1369 in a credentials cache), first try 1370 a <acronym>GSSAPI</acronym>-encrypted connection; if that fails or 1371 there are no credentials, try a 1372 non-<acronym>GSSAPI</acronym>-encrypted connection. This is the 1373 default when <productname>PostgreSQL</productname> has been 1374 compiled with <acronym>GSSAPI</acronym> support. 1375 </para> 1376 </listitem> 1377 </varlistentry> 1378 1379 <varlistentry> 1380 <term><literal>require</literal></term> 1381 <listitem> 1382 <para> 1383 only try a <acronym>GSSAPI</acronym>-encrypted connection 1384 </para> 1385 </listitem> 1386 </varlistentry> 1387 </variablelist> 1388 </para> 1389 1390 <para> 1391 <literal>gssencmode</literal> is ignored for Unix domain socket 1392 communication. If <productname>PostgreSQL</productname> is compiled 1393 without GSSAPI support, using the <literal>require</literal> option 1394 will cause an error, while <literal>prefer</literal> will be accepted 1395 but <application>libpq</application> will not actually attempt 1396 a <acronym>GSSAPI</acronym>-encrypted 1397 connection.<indexterm><primary>GSSAPI</primary><secondary sortas="libpq">with 1398 libpq</secondary></indexterm> 1399 </para> 1400 </listitem> 1401 </varlistentry> 1402 1403 <varlistentry id="libpq-connect-sslmode" xreflabel="sslmode"> 1404 <term><literal>sslmode</literal></term> 1405 <listitem> 1406 <para> 1407 This option determines whether or with what priority a secure 1408 <acronym>SSL</acronym> TCP/IP connection will be negotiated with the 1409 server. There are six modes: 1410 1411 <variablelist> 1412 <varlistentry> 1413 <term><literal>disable</literal></term> 1414 <listitem> 1415 <para> 1416 only try a non-<acronym>SSL</acronym> connection 1417 </para> 1418 </listitem> 1419 </varlistentry> 1420 1421 <varlistentry> 1422 <term><literal>allow</literal></term> 1423 <listitem> 1424 <para> 1425 first try a non-<acronym>SSL</acronym> connection; if that 1426 fails, try an <acronym>SSL</acronym> connection 1427 </para> 1428 </listitem> 1429 </varlistentry> 1430 1431 <varlistentry> 1432 <term><literal>prefer</literal> (default)</term> 1433 <listitem> 1434 <para> 1435 first try an <acronym>SSL</acronym> connection; if that fails, 1436 try a non-<acronym>SSL</acronym> connection 1437 </para> 1438 </listitem> 1439 </varlistentry> 1440 1441 <varlistentry> 1442 <term><literal>require</literal></term> 1443 <listitem> 1444 <para> 1445 only try an <acronym>SSL</acronym> connection. If a root CA 1446 file is present, verify the certificate in the same way as 1447 if <literal>verify-ca</literal> was specified 1448 </para> 1449 </listitem> 1450 </varlistentry> 1451 1452 <varlistentry> 1453 <term><literal>verify-ca</literal></term> 1454 <listitem> 1455 <para> 1456 only try an <acronym>SSL</acronym> connection, and verify that 1457 the server certificate is issued by a trusted 1458 certificate authority (<acronym>CA</acronym>) 1459 </para> 1460 </listitem> 1461 </varlistentry> 1462 1463 <varlistentry> 1464 <term><literal>verify-full</literal></term> 1465 <listitem> 1466 <para> 1467 only try an <acronym>SSL</acronym> connection, verify that the 1468 server certificate is issued by a 1469 trusted <acronym>CA</acronym> and that the requested server host name 1470 matches that in the certificate 1471 </para> 1472 </listitem> 1473 </varlistentry> 1474 </variablelist> 1475 1476 See <xref linkend="libpq-ssl"/> for a detailed description of how 1477 these options work. 1478 </para> 1479 1480 <para> 1481 <literal>sslmode</literal> is ignored for Unix domain socket 1482 communication. 1483 If <productname>PostgreSQL</productname> is compiled without SSL support, 1484 using options <literal>require</literal>, <literal>verify-ca</literal>, or 1485 <literal>verify-full</literal> will cause an error, while 1486 options <literal>allow</literal> and <literal>prefer</literal> will be 1487 accepted but <application>libpq</application> will not actually attempt 1488 an <acronym>SSL</acronym> 1489 connection.<indexterm><primary>SSL</primary><secondary 1490 sortas="libpq">with libpq</secondary></indexterm> 1491 </para> 1492 1493 <para> 1494 Note that if <acronym>GSSAPI</acronym> encryption is possible, 1495 that will be used in preference to <acronym>SSL</acronym> 1496 encryption, regardless of the value of <literal>sslmode</literal>. 1497 To force use of <acronym>SSL</acronym> encryption in an 1498 environment that has working <acronym>GSSAPI</acronym> 1499 infrastructure (such as a Kerberos server), also 1500 set <literal>gssencmode</literal> to <literal>disable</literal>. 1501 </para> 1502 </listitem> 1503 </varlistentry> 1504 1505 <varlistentry id="libpq-connect-requiressl" xreflabel="requiressl"> 1506 <term><literal>requiressl</literal></term> 1507 <listitem> 1508 <para> 1509 This option is deprecated in favor of the <literal>sslmode</literal> 1510 setting. 1511 </para> 1512 1513 <para> 1514 If set to 1, an <acronym>SSL</acronym> connection to the server 1515 is required (this is equivalent to <literal>sslmode</literal> 1516 <literal>require</literal>). <application>libpq</application> will then refuse 1517 to connect if the server does not accept an 1518 <acronym>SSL</acronym> connection. If set to 0 (default), 1519 <application>libpq</application> will negotiate the connection type with 1520 the server (equivalent to <literal>sslmode</literal> 1521 <literal>prefer</literal>). This option is only available if 1522 <productname>PostgreSQL</productname> is compiled with SSL support. 1523 </para> 1524 </listitem> 1525 </varlistentry> 1526 1527 <varlistentry id="libpq-connect-sslcompression" xreflabel="sslcompression"> 1528 <term><literal>sslcompression</literal></term> 1529 <listitem> 1530 <para> 1531 If set to 1, data sent over SSL connections will be compressed. If 1532 set to 0, compression will be disabled. The default is 0. This 1533 parameter is ignored if a connection without SSL is made. 1534 </para> 1535 1536 <para> 1537 SSL compression is nowadays considered insecure and its use is no 1538 longer recommended. <productname>OpenSSL</productname> 1.1.0 disables 1539 compression by default, and many operating system distributions 1540 disable it in prior versions as well, so setting this parameter to on 1541 will not have any effect if the server does not accept compression. 1542 On the other hand, <productname>OpenSSL</productname> before 1.0.0 1543 does not support disabling compression, so this parameter is ignored 1544 with those versions, and whether compression is used depends on the 1545 server. 1546 </para> 1547 1548 <para> 1549 If security is not a primary concern, compression can improve 1550 throughput if the network is the bottleneck. Disabling compression 1551 can improve response time and throughput if CPU performance is the 1552 limiting factor. 1553 </para> 1554 </listitem> 1555 </varlistentry> 1556 1557 <varlistentry id="libpq-connect-sslcert" xreflabel="sslcert"> 1558 <term><literal>sslcert</literal></term> 1559 <listitem> 1560 <para> 1561 This parameter specifies the file name of the client SSL 1562 certificate, replacing the default 1563 <filename>~/.postgresql/postgresql.crt</filename>. 1564 This parameter is ignored if an SSL connection is not made. 1565 </para> 1566 </listitem> 1567 </varlistentry> 1568 1569 <varlistentry id="libpq-connect-sslkey" xreflabel="sslkey"> 1570 <term><literal>sslkey</literal></term> 1571 <listitem> 1572 <para> 1573 This parameter specifies the location for the secret key used for 1574 the client certificate. It can either specify a file name that will 1575 be used instead of the default 1576 <filename>~/.postgresql/postgresql.key</filename>, or it can specify a key 1577 obtained from an external <quote>engine</quote> (engines are 1578 <productname>OpenSSL</productname> loadable modules). An external engine 1579 specification should consist of a colon-separated engine name and 1580 an engine-specific key identifier. This parameter is ignored if an 1581 SSL connection is not made. 1582 </para> 1583 </listitem> 1584 </varlistentry> 1585 1586 <varlistentry id="libpq-connect-sslrootcert" xreflabel="sslrootcert"> 1587 <term><literal>sslrootcert</literal></term> 1588 <listitem> 1589 <para> 1590 This parameter specifies the name of a file containing SSL 1591 certificate authority (<acronym>CA</acronym>) certificate(s). 1592 If the file exists, the server's certificate will be verified 1593 to be signed by one of these authorities. The default is 1594 <filename>~/.postgresql/root.crt</filename>. 1595 </para> 1596 </listitem> 1597 </varlistentry> 1598 1599 <varlistentry id="libpq-connect-sslcrl" xreflabel="sslcrl"> 1600 <term><literal>sslcrl</literal></term> 1601 <listitem> 1602 <para> 1603 This parameter specifies the file name of the SSL certificate 1604 revocation list (CRL). Certificates listed in this file, if it 1605 exists, will be rejected while attempting to authenticate the 1606 server's certificate. The default is 1607 <filename>~/.postgresql/root.crl</filename>. 1608 </para> 1609 </listitem> 1610 </varlistentry> 1611 1612 <varlistentry id="libpq-connect-requirepeer" xreflabel="requirepeer"> 1613 <term><literal>requirepeer</literal></term> 1614 <listitem> 1615 <para> 1616 This parameter specifies the operating-system user name of the 1617 server, for example <literal>requirepeer=postgres</literal>. 1618 When making a Unix-domain socket connection, if this 1619 parameter is set, the client checks at the beginning of the 1620 connection that the server process is running under the specified 1621 user name; if it is not, the connection is aborted with an error. 1622 This parameter can be used to provide server authentication similar 1623 to that available with SSL certificates on TCP/IP connections. 1624 (Note that if the Unix-domain socket is in 1625 <filename>/tmp</filename> or another publicly writable location, 1626 any user could start a server listening there. Use this parameter 1627 to ensure that you are connected to a server run by a trusted user.) 1628 This option is only supported on platforms for which the 1629 <literal>peer</literal> authentication method is implemented; see 1630 <xref linkend="auth-peer"/>. 1631 </para> 1632 </listitem> 1633 </varlistentry> 1634 1635 <varlistentry id="libpq-connect-krbsrvname" xreflabel="krbsrvname"> 1636 <term><literal>krbsrvname</literal></term> 1637 <listitem> 1638 <para> 1639 Kerberos service name to use when authenticating with GSSAPI. 1640 This must match the service name specified in the server 1641 configuration for Kerberos authentication to succeed. (See also 1642 <xref linkend="gssapi-auth"/>.) 1643 The default value is normally <literal>postgres</literal>, 1644 but that can be changed when 1645 building <productname>PostgreSQL</productname> via 1646 the <option>--with-krb-srvnam</option> option 1647 of <application>configure</application>. 1648 In most environments, this parameter never needs to be changed. 1649 Some Kerberos implementations might require a different service name, 1650 such as Microsoft Active Directory which requires the service name 1651 to be in upper case (<literal>POSTGRES</literal>). 1652 </para> 1653 </listitem> 1654 </varlistentry> 1655 1656 <varlistentry id="libpq-connect-gsslib" xreflabel="gsslib"> 1657 <term><literal>gsslib</literal></term> 1658 <listitem> 1659 <para> 1660 GSS library to use for GSSAPI authentication. 1661 Currently this is disregarded except on Windows builds that include 1662 both GSSAPI and SSPI support. In that case, set 1663 this to <literal>gssapi</literal> to cause libpq to use the GSSAPI 1664 library for authentication instead of the default SSPI. 1665 </para> 1666 </listitem> 1667 </varlistentry> 1668 1669 <varlistentry id="libpq-connect-service" xreflabel="service"> 1670 <term><literal>service</literal></term> 1671 <listitem> 1672 <para> 1673 Service name to use for additional parameters. It specifies a service 1674 name in <filename>pg_service.conf</filename> that holds additional connection parameters. 1675 This allows applications to specify only a service name so connection parameters 1676 can be centrally maintained. See <xref linkend="libpq-pgservice"/>. 1677 </para> 1678 </listitem> 1679 </varlistentry> 1680 1681 <varlistentry id="libpq-connect-target-session-attrs" xreflabel="target_session_attrs"> 1682 <term><literal>target_session_attrs</literal></term> 1683 <listitem> 1684 <para> 1685 If this parameter is set to <literal>read-write</literal>, only a 1686 connection in which read-write transactions are accepted by default 1687 is considered acceptable. The query 1688 <literal>SHOW transaction_read_only</literal> will be sent upon any 1689 successful connection; if it returns <literal>on</literal>, the connection 1690 will be closed. If multiple hosts were specified in the connection 1691 string, any remaining servers will be tried just as if the connection 1692 attempt had failed. The default value of this parameter, 1693 <literal>any</literal>, regards all connections as acceptable. 1694 </para> 1695 </listitem> 1696 </varlistentry> 1697 </variablelist> 1698 </para> 1699 </sect2> 1700 </sect1> 1701 1702 <sect1 id="libpq-status"> 1703 <title>Connection Status Functions</title> 1704 1705 <para> 1706 These functions can be used to interrogate the status 1707 of an existing database connection object. 1708 </para> 1709 1710 <tip> 1711 <para> 1712 <indexterm><primary>libpq-fe.h</primary></indexterm> 1713 <indexterm><primary>libpq-int.h</primary></indexterm> 1714 <application>libpq</application> application programmers should be careful to 1715 maintain the <structname>PGconn</structname> abstraction. Use the accessor 1716 functions described below to get at the contents of <structname>PGconn</structname>. 1717 Reference to internal <structname>PGconn</structname> fields using 1718 <filename>libpq-int.h</filename> is not recommended because they are subject to change 1719 in the future. 1720 </para> 1721 </tip> 1722 1723 <para> 1724 The following functions return parameter values established at connection. 1725 These values are fixed for the life of the connection. If a multi-host 1726 connection string is used, the values of <function>PQhost</function>, 1727 <function>PQport</function>, and <function>PQpass</function> can change if a new connection 1728 is established using the same <structname>PGconn</structname> object. Other values 1729 are fixed for the lifetime of the <structname>PGconn</structname> object. 1730 1731 <variablelist> 1732 <varlistentry id="libpq-pqdb"> 1733 <term> 1734 <function>PQdb</function> 1735 <indexterm> 1736 <primary>PQdb</primary> 1737 </indexterm> 1738 </term> 1739 1740 <listitem> 1741 <para> 1742 Returns the database name of the connection. 1743<synopsis> 1744char *PQdb(const PGconn *conn); 1745</synopsis> 1746 </para> 1747 </listitem> 1748 </varlistentry> 1749 1750 <varlistentry id="libpq-pquser"> 1751 <term> 1752 <function>PQuser</function> 1753 <indexterm> 1754 <primary>PQuser</primary> 1755 </indexterm> 1756 </term> 1757 1758 <listitem> 1759 <para> 1760 Returns the user name of the connection. 1761<synopsis> 1762char *PQuser(const PGconn *conn); 1763</synopsis> 1764 </para> 1765 </listitem> 1766 </varlistentry> 1767 1768 <varlistentry id="libpq-pqpass"> 1769 <term> 1770 <function>PQpass</function> 1771 <indexterm> 1772 <primary>PQpass</primary> 1773 </indexterm> 1774 </term> 1775 1776 <listitem> 1777 <para> 1778 Returns the password of the connection. 1779<synopsis> 1780char *PQpass(const PGconn *conn); 1781</synopsis> 1782 </para> 1783 1784 <para> 1785 <function>PQpass</function> will return either the password specified 1786 in the connection parameters, or if there was none and the password 1787 was obtained from the <link linkend="libpq-pgpass">password 1788 file</link>, it will return that. In the latter case, 1789 if multiple hosts were specified in the connection parameters, it is 1790 not possible to rely on the result of <function>PQpass</function> until 1791 the connection is established. The status of the connection can be 1792 checked using the function <function>PQstatus</function>. 1793 </para> 1794 </listitem> 1795 </varlistentry> 1796 1797 <varlistentry id="libpq-pqhost"> 1798 <term> 1799 <function>PQhost</function> 1800 <indexterm> 1801 <primary>PQhost</primary> 1802 </indexterm> 1803 </term> 1804 1805 <listitem> 1806 <para> 1807 Returns the server host name of the active connection. 1808 This can be a host name, an IP address, or a directory path if the 1809 connection is via Unix socket. (The path case can be distinguished 1810 because it will always be an absolute path, beginning 1811 with <literal>/</literal>.) 1812<synopsis> 1813char *PQhost(const PGconn *conn); 1814</synopsis> 1815 </para> 1816 1817 <para> 1818 If the connection parameters specified both <literal>host</literal> and 1819 <literal>hostaddr</literal>, then <function>PQhost</function> will 1820 return the <literal>host</literal> information. If only 1821 <literal>hostaddr</literal> was specified, then that is returned. 1822 If multiple hosts were specified in the connection parameters, 1823 <function>PQhost</function> returns the host actually connected to. 1824 </para> 1825 1826 <para> 1827 <function>PQhost</function> returns <symbol>NULL</symbol> if the 1828 <parameter>conn</parameter> argument is <symbol>NULL</symbol>. 1829 Otherwise, if there is an error producing the host information (perhaps 1830 if the connection has not been fully established or there was an 1831 error), it returns an empty string. 1832 </para> 1833 1834 <para> 1835 If multiple hosts were specified in the connection parameters, it is 1836 not possible to rely on the result of <function>PQhost</function> until 1837 the connection is established. The status of the connection can be 1838 checked using the function <function>PQstatus</function>. 1839 </para> 1840 </listitem> 1841 </varlistentry> 1842 1843 1844 <varlistentry id="libpq-pqhostaddr"> 1845 <term> 1846 <function>PQhostaddr</function> 1847 <indexterm> 1848 <primary>PQhostaddr</primary> 1849 </indexterm> 1850 </term> 1851 1852 <listitem> 1853 <para> 1854 Returns the server IP address of the active connection. 1855 This can be the address that a host name resolved to, 1856 or an IP address provided through the <literal>hostaddr</literal> 1857 parameter. 1858<synopsis> 1859char *PQhostaddr(const PGconn *conn); 1860</synopsis> 1861 </para> 1862 1863 <para> 1864 <function>PQhostaddr</function> returns <symbol>NULL</symbol> if the 1865 <parameter>conn</parameter> argument is <symbol>NULL</symbol>. 1866 Otherwise, if there is an error producing the host information 1867 (perhaps if the connection has not been fully established or 1868 there was an error), it returns an empty string. 1869 </para> 1870 </listitem> 1871 </varlistentry> 1872 1873 <varlistentry id="libpq-pqport"> 1874 <term> 1875 <function>PQport</function> 1876 <indexterm> 1877 <primary>PQport</primary> 1878 </indexterm> 1879 </term> 1880 1881 <listitem> 1882 <para> 1883 Returns the port of the active connection. 1884 1885<synopsis> 1886char *PQport(const PGconn *conn); 1887</synopsis> 1888 </para> 1889 1890 <para> 1891 If multiple ports were specified in the connection parameters, 1892 <function>PQport</function> returns the port actually connected to. 1893 </para> 1894 1895 <para> 1896 <function>PQport</function> returns <symbol>NULL</symbol> if the 1897 <parameter>conn</parameter> argument is <symbol>NULL</symbol>. 1898 Otherwise, if there is an error producing the port information (perhaps 1899 if the connection has not been fully established or there was an 1900 error), it returns an empty string. 1901 </para> 1902 1903 <para> 1904 If multiple ports were specified in the connection parameters, it is 1905 not possible to rely on the result of <function>PQport</function> until 1906 the connection is established. The status of the connection can be 1907 checked using the function <function>PQstatus</function>. 1908 </para> 1909 </listitem> 1910 </varlistentry> 1911 1912 <varlistentry id="libpq-pqtty"> 1913 <term> 1914 <function>PQtty</function> 1915 <indexterm> 1916 <primary>PQtty</primary> 1917 </indexterm> 1918 </term> 1919 1920 <listitem> 1921 <para> 1922 Returns the debug <acronym>TTY</acronym> of the connection. 1923 (This is obsolete, since the server no longer pays attention 1924 to the <acronym>TTY</acronym> setting, but the function remains 1925 for backward compatibility.) 1926 1927<synopsis> 1928char *PQtty(const PGconn *conn); 1929</synopsis> 1930 </para> 1931 </listitem> 1932 </varlistentry> 1933 1934 <varlistentry id="libpq-pqoptions"> 1935 <term> 1936 <function>PQoptions</function> 1937 <indexterm> 1938 <primary>PQoptions</primary> 1939 </indexterm> 1940 </term> 1941 1942 <listitem> 1943 <para> 1944 Returns the command-line options passed in the connection request. 1945<synopsis> 1946char *PQoptions(const PGconn *conn); 1947</synopsis> 1948 </para> 1949 </listitem> 1950 </varlistentry> 1951 </variablelist> 1952 </para> 1953 1954 <para> 1955 The following functions return status data that can change as operations 1956 are executed on the <structname>PGconn</structname> object. 1957 1958 <variablelist> 1959 <varlistentry id="libpq-pqstatus"> 1960 <term> 1961 <function>PQstatus</function> 1962 <indexterm> 1963 <primary>PQstatus</primary> 1964 </indexterm> 1965 </term> 1966 1967 <listitem> 1968 <para> 1969 Returns the status of the connection. 1970<synopsis> 1971ConnStatusType PQstatus(const PGconn *conn); 1972</synopsis> 1973 </para> 1974 1975 <para> 1976 The status can be one of a number of values. However, only two of 1977 these are seen outside of an asynchronous connection procedure: 1978 <literal>CONNECTION_OK</literal> and 1979 <literal>CONNECTION_BAD</literal>. A good connection to the database 1980 has the status <literal>CONNECTION_OK</literal>. A failed 1981 connection attempt is signaled by status 1982 <literal>CONNECTION_BAD</literal>. Ordinarily, an OK status will 1983 remain so until <function>PQfinish</function>, but a communications 1984 failure might result in the status changing to 1985 <literal>CONNECTION_BAD</literal> prematurely. In that case the 1986 application could try to recover by calling 1987 <function>PQreset</function>. 1988 </para> 1989 1990 <para> 1991 See the entry for <function>PQconnectStartParams</function>, <function>PQconnectStart</function> 1992 and <function>PQconnectPoll</function> with regards to other status codes that 1993 might be returned. 1994 </para> 1995 </listitem> 1996 </varlistentry> 1997 1998 <varlistentry id="libpq-pqtransactionstatus"> 1999 <term> 2000 <function>PQtransactionStatus</function> 2001 <indexterm> 2002 <primary>PQtransactionStatus</primary> 2003 </indexterm> 2004 </term> 2005 2006 <listitem> 2007 <para> 2008 Returns the current in-transaction status of the server. 2009 2010<synopsis> 2011PGTransactionStatusType PQtransactionStatus(const PGconn *conn); 2012</synopsis> 2013 2014 The status can be <literal>PQTRANS_IDLE</literal> (currently idle), 2015 <literal>PQTRANS_ACTIVE</literal> (a command is in progress), 2016 <literal>PQTRANS_INTRANS</literal> (idle, in a valid transaction block), 2017 or <literal>PQTRANS_INERROR</literal> (idle, in a failed transaction block). 2018 <literal>PQTRANS_UNKNOWN</literal> is reported if the connection is bad. 2019 <literal>PQTRANS_ACTIVE</literal> is reported only when a query 2020 has been sent to the server and not yet completed. 2021 </para> 2022 </listitem> 2023 </varlistentry> 2024 2025 <varlistentry id="libpq-pqparameterstatus"> 2026 <term> 2027 <function>PQparameterStatus</function> 2028 <indexterm> 2029 <primary>PQparameterStatus</primary> 2030 </indexterm> 2031 </term> 2032 2033 <listitem> 2034 <para> 2035 Looks up a current parameter setting of the server. 2036 2037<synopsis> 2038const char *PQparameterStatus(const PGconn *conn, const char *paramName); 2039</synopsis> 2040 2041 Certain parameter values are reported by the server automatically at 2042 connection startup or whenever their values change. 2043 <function>PQparameterStatus</function> can be used to interrogate these settings. 2044 It returns the current value of a parameter if known, or <symbol>NULL</symbol> 2045 if the parameter is not known. 2046 </para> 2047 2048 <para> 2049 Parameters reported as of the current release include 2050 <varname>server_version</varname>, 2051 <varname>server_encoding</varname>, 2052 <varname>client_encoding</varname>, 2053 <varname>application_name</varname>, 2054 <varname>is_superuser</varname>, 2055 <varname>session_authorization</varname>, 2056 <varname>DateStyle</varname>, 2057 <varname>IntervalStyle</varname>, 2058 <varname>TimeZone</varname>, 2059 <varname>integer_datetimes</varname>, and 2060 <varname>standard_conforming_strings</varname>. 2061 (<varname>server_encoding</varname>, <varname>TimeZone</varname>, and 2062 <varname>integer_datetimes</varname> were not reported by releases before 8.0; 2063 <varname>standard_conforming_strings</varname> was not reported by releases 2064 before 8.1; 2065 <varname>IntervalStyle</varname> was not reported by releases before 8.4; 2066 <varname>application_name</varname> was not reported by releases before 9.0.) 2067 Note that 2068 <varname>server_version</varname>, 2069 <varname>server_encoding</varname> and 2070 <varname>integer_datetimes</varname> 2071 cannot change after startup. 2072 </para> 2073 2074 <para> 2075 Pre-3.0-protocol servers do not report parameter settings, but 2076 <application>libpq</application> includes logic to obtain values for 2077 <varname>server_version</varname> and <varname>client_encoding</varname> anyway. 2078 Applications are encouraged to use <function>PQparameterStatus</function> 2079 rather than <foreignphrase>ad hoc</foreignphrase> code to determine these values. 2080 (Beware however that on a pre-3.0 connection, changing 2081 <varname>client_encoding</varname> via <command>SET</command> after connection 2082 startup will not be reflected by <function>PQparameterStatus</function>.) 2083 For <varname>server_version</varname>, see also 2084 <function>PQserverVersion</function>, which returns the information in a 2085 numeric form that is much easier to compare against. 2086 </para> 2087 2088 <para> 2089 If no value for <varname>standard_conforming_strings</varname> is reported, 2090 applications can assume it is <literal>off</literal>, that is, backslashes 2091 are treated as escapes in string literals. Also, the presence of 2092 this parameter can be taken as an indication that the escape string 2093 syntax (<literal>E'...'</literal>) is accepted. 2094 </para> 2095 2096 <para> 2097 Although the returned pointer is declared <literal>const</literal>, it in fact 2098 points to mutable storage associated with the <literal>PGconn</literal> structure. 2099 It is unwise to assume the pointer will remain valid across queries. 2100 </para> 2101 </listitem> 2102 </varlistentry> 2103 2104 <varlistentry id="libpq-pqprotocolversion"> 2105 <term> 2106 <function>PQprotocolVersion</function> 2107 <indexterm> 2108 <primary>PQprotocolVersion</primary> 2109 </indexterm> 2110 </term> 2111 2112 <listitem> 2113 <para> 2114 Interrogates the frontend/backend protocol being used. 2115<synopsis> 2116int PQprotocolVersion(const PGconn *conn); 2117</synopsis> 2118 Applications might wish to use this function to determine whether certain 2119 features are supported. Currently, the possible values are 2 (2.0 2120 protocol), 3 (3.0 protocol), or zero (connection bad). The 2121 protocol version will 2122 not change after connection startup is complete, but it could 2123 theoretically change during a connection reset. The 3.0 protocol 2124 will normally be used when communicating with 2125 <productname>PostgreSQL</productname> 7.4 or later servers; pre-7.4 servers 2126 support only protocol 2.0. (Protocol 1.0 is obsolete and not 2127 supported by <application>libpq</application>.) 2128 </para> 2129 </listitem> 2130 </varlistentry> 2131 2132 <varlistentry id="libpq-pqserverversion"> 2133 <term> 2134 <function>PQserverVersion</function> 2135 <indexterm> 2136 <primary>PQserverVersion</primary> 2137 </indexterm> 2138 </term> 2139 2140 <listitem> 2141 <para> 2142 Returns an integer representing the server version. 2143<synopsis> 2144int PQserverVersion(const PGconn *conn); 2145</synopsis> 2146 </para> 2147 2148 <para> 2149 Applications might use this function to determine the version of the 2150 database server they are connected to. The result is formed by 2151 multiplying the server's major version number by 10000 and adding 2152 the minor version number. For example, version 10.1 will be 2153 returned as 100001, and version 11.0 will be returned as 110000. 2154 Zero is returned if the connection is bad. 2155 </para> 2156 2157 <para> 2158 Prior to major version 10, <productname>PostgreSQL</productname> used 2159 three-part version numbers in which the first two parts together 2160 represented the major version. For those 2161 versions, <function>PQserverVersion</function> uses two digits for each 2162 part; for example version 9.1.5 will be returned as 90105, and 2163 version 9.2.0 will be returned as 90200. 2164 </para> 2165 2166 <para> 2167 Therefore, for purposes of determining feature compatibility, 2168 applications should divide the result of <function>PQserverVersion</function> 2169 by 100 not 10000 to determine a logical major version number. 2170 In all release series, only the last two digits differ between 2171 minor releases (bug-fix releases). 2172 </para> 2173 </listitem> 2174 </varlistentry> 2175 2176 <varlistentry id="libpq-pqerrormessage"> 2177 <term> 2178 <function>PQerrorMessage</function> 2179 <indexterm> 2180 <primary>PQerrorMessage</primary> 2181 </indexterm> 2182 </term> 2183 2184 <listitem> 2185 <para> 2186 <indexterm><primary>error message</primary></indexterm> Returns the error message 2187 most recently generated by an operation on the connection. 2188 2189<synopsis> 2190char *PQerrorMessage(const PGconn *conn); 2191</synopsis> 2192 2193 </para> 2194 2195 <para> 2196 Nearly all <application>libpq</application> functions will set a message for 2197 <function>PQerrorMessage</function> if they fail. Note that by 2198 <application>libpq</application> convention, a nonempty 2199 <function>PQerrorMessage</function> result can consist of multiple lines, 2200 and will include a trailing newline. The caller should not free 2201 the result directly. It will be freed when the associated 2202 <structname>PGconn</structname> handle is passed to 2203 <function>PQfinish</function>. The result string should not be 2204 expected to remain the same across operations on the 2205 <literal>PGconn</literal> structure. 2206 </para> 2207 </listitem> 2208 </varlistentry> 2209 2210 <varlistentry id="libpq-pqsocket"> 2211 <term><function>PQsocket</function><indexterm><primary>PQsocket</primary></indexterm></term> 2212 <listitem> 2213 <para> 2214 Obtains the file descriptor number of the connection socket to 2215 the server. A valid descriptor will be greater than or equal 2216 to 0; a result of -1 indicates that no server connection is 2217 currently open. (This will not change during normal operation, 2218 but could change during connection setup or reset.) 2219 2220<synopsis> 2221int PQsocket(const PGconn *conn); 2222</synopsis> 2223 2224 </para> 2225 </listitem> 2226 </varlistentry> 2227 2228 <varlistentry id="libpq-pqbackendpid"> 2229 <term><function>PQbackendPID</function><indexterm><primary>PQbackendPID</primary></indexterm></term> 2230 <listitem> 2231 <para> 2232 Returns the process <acronym>ID</acronym> (PID)<indexterm> 2233 <primary>PID</primary> 2234 <secondary>determining PID of server process</secondary> 2235 <tertiary>in libpq</tertiary> 2236 </indexterm> 2237 of the backend process handling this connection. 2238 2239<synopsis> 2240int PQbackendPID(const PGconn *conn); 2241</synopsis> 2242 </para> 2243 2244 <para> 2245 The backend <acronym>PID</acronym> is useful for debugging 2246 purposes and for comparison to <command>NOTIFY</command> 2247 messages (which include the <acronym>PID</acronym> of the 2248 notifying backend process). Note that the 2249 <acronym>PID</acronym> belongs to a process executing on the 2250 database server host, not the local host! 2251 </para> 2252 </listitem> 2253 </varlistentry> 2254 2255 <varlistentry id="libpq-pqconnectionneedspassword"> 2256 <term><function>PQconnectionNeedsPassword</function><indexterm><primary>PQconnectionNeedsPassword</primary></indexterm></term> 2257 <listitem> 2258 <para> 2259 Returns true (1) if the connection authentication method 2260 required a password, but none was available. 2261 Returns false (0) if not. 2262 2263<synopsis> 2264int PQconnectionNeedsPassword(const PGconn *conn); 2265</synopsis> 2266 </para> 2267 2268 <para> 2269 This function can be applied after a failed connection attempt 2270 to decide whether to prompt the user for a password. 2271 </para> 2272 </listitem> 2273 </varlistentry> 2274 2275 <varlistentry id="libpq-pqconnectionusedpassword"> 2276 <term><function>PQconnectionUsedPassword</function><indexterm><primary>PQconnectionUsedPassword</primary></indexterm></term> 2277 <listitem> 2278 <para> 2279 Returns true (1) if the connection authentication method 2280 used a password. Returns false (0) if not. 2281 2282<synopsis> 2283int PQconnectionUsedPassword(const PGconn *conn); 2284</synopsis> 2285 </para> 2286 2287 <para> 2288 This function can be applied after either a failed or successful 2289 connection attempt to detect whether the server demanded a password. 2290 </para> 2291 </listitem> 2292 </varlistentry> 2293 </variablelist> 2294 </para> 2295 2296 <para> 2297 The following functions return information related to SSL. This information 2298 usually doesn't change after a connection is established. 2299 2300 <variablelist> 2301 <varlistentry id="libpq-pqsslinuse"> 2302 <term><function>PQsslInUse</function><indexterm><primary>PQsslInUse</primary></indexterm></term> 2303 <listitem> 2304 <para> 2305 Returns true (1) if the connection uses SSL, false (0) if not. 2306 2307<synopsis> 2308int PQsslInUse(const PGconn *conn); 2309</synopsis> 2310 </para> 2311 2312 </listitem> 2313 </varlistentry> 2314 2315 <varlistentry id="libpq-pqsslattribute"> 2316 <term><function>PQsslAttribute</function><indexterm><primary>PQsslAttribute</primary></indexterm></term> 2317 <listitem> 2318 <para> 2319 Returns SSL-related information about the connection. 2320 2321<synopsis> 2322const char *PQsslAttribute(const PGconn *conn, const char *attribute_name); 2323</synopsis> 2324 </para> 2325 2326 <para> 2327 The list of available attributes varies depending on the SSL library 2328 being used, and the type of connection. If an attribute is not 2329 available, returns NULL. 2330 </para> 2331 2332 <para> 2333 The following attributes are commonly available: 2334 <variablelist> 2335 <varlistentry> 2336 <term><literal>library</literal></term> 2337 <listitem> 2338 <para> 2339 Name of the SSL implementation in use. (Currently, only 2340 <literal>"OpenSSL"</literal> is implemented) 2341 </para> 2342 </listitem> 2343 </varlistentry> 2344 <varlistentry> 2345 <term><literal>protocol</literal></term> 2346 <listitem> 2347 <para> 2348 SSL/TLS version in use. Common values 2349 are <literal>"TLSv1"</literal>, <literal>"TLSv1.1"</literal> 2350 and <literal>"TLSv1.2"</literal>, but an implementation may 2351 return other strings if some other protocol is used. 2352 </para> 2353 </listitem> 2354 </varlistentry> 2355 <varlistentry> 2356 <term><literal>key_bits</literal></term> 2357 <listitem> 2358 <para> 2359 Number of key bits used by the encryption algorithm. 2360 </para> 2361 </listitem> 2362 </varlistentry> 2363 <varlistentry> 2364 <term><literal>cipher</literal></term> 2365 <listitem> 2366 <para> 2367 A short name of the ciphersuite used, e.g., 2368 <literal>"DHE-RSA-DES-CBC3-SHA"</literal>. The names are specific 2369 to each SSL implementation. 2370 </para> 2371 </listitem> 2372 </varlistentry> 2373 <varlistentry> 2374 <term><literal>compression</literal></term> 2375 <listitem> 2376 <para> 2377 If SSL compression is in use, returns the name of the compression 2378 algorithm, or "on" if compression is used but the algorithm is 2379 not known. If compression is not in use, returns "off". 2380 </para> 2381 </listitem> 2382 </varlistentry> 2383 </variablelist> 2384 </para> 2385 </listitem> 2386 </varlistentry> 2387 2388 <varlistentry id="libpq-pqsslattributenames"> 2389 <term><function>PQsslAttributeNames</function><indexterm><primary>PQsslAttributeNames</primary></indexterm></term> 2390 <listitem> 2391 <para> 2392 Return an array of SSL attribute names available. The array is terminated by a NULL pointer. 2393<synopsis> 2394const char * const * PQsslAttributeNames(const PGconn *conn); 2395</synopsis> 2396 </para> 2397 </listitem> 2398 </varlistentry> 2399 2400 <varlistentry id="libpq-pqsslstruct"> 2401 <term><function>PQsslStruct</function><indexterm><primary>PQsslStruct</primary></indexterm></term> 2402 <listitem> 2403 <para> 2404 Return a pointer to an SSL-implementation-specific object describing 2405 the connection. 2406<synopsis> 2407void *PQsslStruct(const PGconn *conn, const char *struct_name); 2408</synopsis> 2409 </para> 2410 <para> 2411 The struct(s) available depend on the SSL implementation in use. 2412 For OpenSSL, there is one struct, available under the name "OpenSSL", 2413 and it returns a pointer to the OpenSSL <literal>SSL</literal> struct. 2414 To use this function, code along the following lines could be used: 2415<programlisting><![CDATA[ 2416#include <libpq-fe.h> 2417#include <openssl/ssl.h> 2418 2419... 2420 2421 SSL *ssl; 2422 2423 dbconn = PQconnectdb(...); 2424 ... 2425 2426 ssl = PQsslStruct(dbconn, "OpenSSL"); 2427 if (ssl) 2428 { 2429 /* use OpenSSL functions to access ssl */ 2430 } 2431]]></programlisting> 2432 </para> 2433 <para> 2434 This structure can be used to verify encryption levels, check server 2435 certificates, and more. Refer to the <productname>OpenSSL</productname> 2436 documentation for information about this structure. 2437 </para> 2438 </listitem> 2439 </varlistentry> 2440 2441 <varlistentry id="libpq-pqgetssl"> 2442 <term><function>PQgetssl</function><indexterm><primary>PQgetssl</primary></indexterm></term> 2443 <listitem> 2444 <para> 2445 <indexterm><primary>SSL</primary><secondary sortas="libpq">in libpq</secondary></indexterm> 2446 Returns the SSL structure used in the connection, or null 2447 if SSL is not in use. 2448 2449<synopsis> 2450void *PQgetssl(const PGconn *conn); 2451</synopsis> 2452 </para> 2453 2454 <para> 2455 This function is equivalent to <literal>PQsslStruct(conn, "OpenSSL")</literal>. It should 2456 not be used in new applications, because the returned struct is 2457 specific to OpenSSL and will not be available if another SSL 2458 implementation is used. To check if a connection uses SSL, call 2459 <function>PQsslInUse</function> instead, and for more details about the 2460 connection, use <function>PQsslAttribute</function>. 2461 </para> 2462 </listitem> 2463 </varlistentry> 2464 2465 </variablelist> 2466 </para> 2467 2468 </sect1> 2469 2470 <sect1 id="libpq-exec"> 2471 <title>Command Execution Functions</title> 2472 2473 <para> 2474 Once a connection to a database server has been successfully 2475 established, the functions described here are used to perform 2476 SQL queries and commands. 2477 </para> 2478 2479 <sect2 id="libpq-exec-main"> 2480 <title>Main Functions</title> 2481 2482 <para> 2483 <variablelist> 2484 <varlistentry id="libpq-pqexec"> 2485 <term> 2486 <function>PQexec</function> 2487 <indexterm> 2488 <primary>PQexec</primary> 2489 </indexterm> 2490 </term> 2491 2492 <listitem> 2493 <para> 2494 Submits a command to the server and waits for the result. 2495 2496<synopsis> 2497PGresult *PQexec(PGconn *conn, const char *command); 2498</synopsis> 2499 </para> 2500 2501 <para> 2502 Returns a <structname>PGresult</structname> pointer or possibly a null 2503 pointer. A non-null pointer will generally be returned except in 2504 out-of-memory conditions or serious errors such as inability to send 2505 the command to the server. The <function>PQresultStatus</function> function 2506 should be called to check the return value for any errors (including 2507 the value of a null pointer, in which case it will return 2508 <symbol>PGRES_FATAL_ERROR</symbol>). Use 2509 <function>PQerrorMessage</function> to get more information about such 2510 errors. 2511 </para> 2512 </listitem> 2513 </varlistentry> 2514 </variablelist> 2515 2516 The command string can include multiple SQL commands 2517 (separated by semicolons). Multiple queries sent in a single 2518 <function>PQexec</function> call are processed in a single transaction, unless 2519 there are explicit <command>BEGIN</command>/<command>COMMIT</command> 2520 commands included in the query string to divide it into multiple 2521 transactions. (See <xref linkend="protocol-flow-multi-statement"/> 2522 for more details about how the server handles multi-query strings.) 2523 Note however that the returned 2524 <structname>PGresult</structname> structure describes only the result 2525 of the last command executed from the string. Should one of the 2526 commands fail, processing of the string stops with it and the returned 2527 <structname>PGresult</structname> describes the error condition. 2528 </para> 2529 2530 <para> 2531 <variablelist> 2532 <varlistentry id="libpq-pqexecparams"> 2533 <term> 2534 <function>PQexecParams</function> 2535 <indexterm> 2536 <primary>PQexecParams</primary> 2537 </indexterm> 2538 </term> 2539 2540 <listitem> 2541 <para> 2542 Submits a command to the server and waits for the result, 2543 with the ability to pass parameters separately from the SQL 2544 command text. 2545 2546<synopsis> 2547PGresult *PQexecParams(PGconn *conn, 2548 const char *command, 2549 int nParams, 2550 const Oid *paramTypes, 2551 const char * const *paramValues, 2552 const int *paramLengths, 2553 const int *paramFormats, 2554 int resultFormat); 2555</synopsis> 2556 </para> 2557 2558 <para> 2559 <function>PQexecParams</function> is like <function>PQexec</function>, but offers additional 2560 functionality: parameter values can be specified separately from the command 2561 string proper, and query results can be requested in either text or binary 2562 format. <function>PQexecParams</function> is supported only in protocol 3.0 and later 2563 connections; it will fail when using protocol 2.0. 2564 </para> 2565 2566 <para> 2567 The function arguments are: 2568 2569 <variablelist> 2570 <varlistentry> 2571 <term><parameter>conn</parameter></term> 2572 2573 <listitem> 2574 <para> 2575 The connection object to send the command through. 2576 </para> 2577 </listitem> 2578 </varlistentry> 2579 2580 <varlistentry> 2581 <term><parameter>command</parameter></term> 2582 <listitem> 2583 <para> 2584 The SQL command string to be executed. If parameters are used, 2585 they are referred to in the command string as <literal>$1</literal>, 2586 <literal>$2</literal>, etc. 2587 </para> 2588 </listitem> 2589 </varlistentry> 2590 2591 <varlistentry> 2592 <term><parameter>nParams</parameter></term> 2593 <listitem> 2594 <para> 2595 The number of parameters supplied; it is the length of the arrays 2596 <parameter>paramTypes[]</parameter>, <parameter>paramValues[]</parameter>, 2597 <parameter>paramLengths[]</parameter>, and <parameter>paramFormats[]</parameter>. (The 2598 array pointers can be <symbol>NULL</symbol> when <parameter>nParams</parameter> 2599 is zero.) 2600 </para> 2601 </listitem> 2602 </varlistentry> 2603 2604 <varlistentry> 2605 <term><parameter>paramTypes[]</parameter></term> 2606 <listitem> 2607 <para> 2608 Specifies, by OID, the data types to be assigned to the 2609 parameter symbols. If <parameter>paramTypes</parameter> is 2610 <symbol>NULL</symbol>, or any particular element in the array 2611 is zero, the server infers a data type for the parameter symbol 2612 in the same way it would do for an untyped literal string. 2613 </para> 2614 </listitem> 2615 </varlistentry> 2616 2617 <varlistentry> 2618 <term><parameter>paramValues[]</parameter></term> 2619 <listitem> 2620 <para> 2621 Specifies the actual values of the parameters. A null pointer 2622 in this array means the corresponding parameter is null; 2623 otherwise the pointer points to a zero-terminated text string 2624 (for text format) or binary data in the format expected by the 2625 server (for binary format). 2626 </para> 2627 </listitem> 2628 </varlistentry> 2629 2630 <varlistentry> 2631 <term><parameter>paramLengths[]</parameter></term> 2632 <listitem> 2633 <para> 2634 Specifies the actual data lengths of binary-format parameters. 2635 It is ignored for null parameters and text-format parameters. 2636 The array pointer can be null when there are no binary parameters. 2637 </para> 2638 </listitem> 2639 </varlistentry> 2640 2641 <varlistentry> 2642 <term><parameter>paramFormats[]</parameter></term> 2643 <listitem> 2644 <para> 2645 Specifies whether parameters are text (put a zero in the 2646 array entry for the corresponding parameter) or binary (put 2647 a one in the array entry for the corresponding parameter). 2648 If the array pointer is null then all parameters are presumed 2649 to be text strings. 2650 </para> 2651 <para> 2652 Values passed in binary format require knowledge of 2653 the internal representation expected by the backend. 2654 For example, integers must be passed in network byte 2655 order. Passing <type>numeric</type> values requires 2656 knowledge of the server storage format, as implemented 2657 in 2658 <filename>src/backend/utils/adt/numeric.c::numeric_send()</filename> and 2659 <filename>src/backend/utils/adt/numeric.c::numeric_recv()</filename>. 2660 </para> 2661 </listitem> 2662 </varlistentry> 2663 2664 <varlistentry> 2665 <term><parameter>resultFormat</parameter></term> 2666 <listitem> 2667 <para> 2668 Specify zero to obtain results in text format, or one to obtain 2669 results in binary format. (There is not currently a provision 2670 to obtain different result columns in different formats, 2671 although that is possible in the underlying protocol.) 2672 </para> 2673 </listitem> 2674 </varlistentry> 2675 </variablelist> 2676 </para> 2677 </listitem> 2678 </varlistentry> 2679 </variablelist> 2680 </para> 2681 2682 <para> 2683 The primary advantage of <function>PQexecParams</function> over 2684 <function>PQexec</function> is that parameter values can be separated from the 2685 command string, thus avoiding the need for tedious and error-prone 2686 quoting and escaping. 2687 </para> 2688 2689 <para> 2690 Unlike <function>PQexec</function>, <function>PQexecParams</function> allows at most 2691 one SQL command in the given string. (There can be semicolons in it, 2692 but not more than one nonempty command.) This is a limitation of the 2693 underlying protocol, but has some usefulness as an extra defense against 2694 SQL-injection attacks. 2695 </para> 2696 2697 <tip> 2698 <para> 2699 Specifying parameter types via OIDs is tedious, particularly if you prefer 2700 not to hard-wire particular OID values into your program. However, you can 2701 avoid doing so even in cases where the server by itself cannot determine the 2702 type of the parameter, or chooses a different type than you want. In the 2703 SQL command text, attach an explicit cast to the parameter symbol to show what 2704 data type you will send. For example: 2705<programlisting> 2706SELECT * FROM mytable WHERE x = $1::bigint; 2707</programlisting> 2708 This forces parameter <literal>$1</literal> to be treated as <type>bigint</type>, whereas 2709 by default it would be assigned the same type as <literal>x</literal>. Forcing the 2710 parameter type decision, either this way or by specifying a numeric type OID, 2711 is strongly recommended when sending parameter values in binary format, because 2712 binary format has less redundancy than text format and so there is less chance 2713 that the server will detect a type mismatch mistake for you. 2714 </para> 2715 </tip> 2716 2717 <para> 2718 <variablelist> 2719 <varlistentry id="libpq-pqprepare"> 2720 <term><function>PQprepare</function> 2721 <indexterm> 2722 <primary>PQprepare</primary> 2723 </indexterm> 2724 </term> 2725 2726 <listitem> 2727 <para> 2728 Submits a request to create a prepared statement with the 2729 given parameters, and waits for completion. 2730<synopsis> 2731PGresult *PQprepare(PGconn *conn, 2732 const char *stmtName, 2733 const char *query, 2734 int nParams, 2735 const Oid *paramTypes); 2736</synopsis> 2737 </para> 2738 2739 <para> 2740 <function>PQprepare</function> creates a prepared statement for later 2741 execution with <function>PQexecPrepared</function>. This feature allows 2742 commands to be executed repeatedly without being parsed and 2743 planned each time; see <xref linkend="sql-prepare"/> for details. 2744 <function>PQprepare</function> is supported only in protocol 3.0 and later 2745 connections; it will fail when using protocol 2.0. 2746 </para> 2747 2748 <para> 2749 The function creates a prepared statement named 2750 <parameter>stmtName</parameter> from the <parameter>query</parameter> string, which 2751 must contain a single SQL command. <parameter>stmtName</parameter> can be 2752 <literal>""</literal> to create an unnamed statement, in which case any 2753 pre-existing unnamed statement is automatically replaced; otherwise 2754 it is an error if the statement name is already defined in the 2755 current session. If any parameters are used, they are referred 2756 to in the query as <literal>$1</literal>, <literal>$2</literal>, etc. 2757 <parameter>nParams</parameter> is the number of parameters for which types 2758 are pre-specified in the array <parameter>paramTypes[]</parameter>. (The 2759 array pointer can be <symbol>NULL</symbol> when 2760 <parameter>nParams</parameter> is zero.) <parameter>paramTypes[]</parameter> 2761 specifies, by OID, the data types to be assigned to the parameter 2762 symbols. If <parameter>paramTypes</parameter> is <symbol>NULL</symbol>, 2763 or any particular element in the array is zero, the server assigns 2764 a data type to the parameter symbol in the same way it would do 2765 for an untyped literal string. Also, the query can use parameter 2766 symbols with numbers higher than <parameter>nParams</parameter>; data types 2767 will be inferred for these symbols as well. (See 2768 <function>PQdescribePrepared</function> for a means to find out 2769 what data types were inferred.) 2770 </para> 2771 2772 <para> 2773 As with <function>PQexec</function>, the result is normally a 2774 <structname>PGresult</structname> object whose contents indicate 2775 server-side success or failure. A null result indicates 2776 out-of-memory or inability to send the command at all. Use 2777 <function>PQerrorMessage</function> to get more information about 2778 such errors. 2779 </para> 2780 </listitem> 2781 </varlistentry> 2782 </variablelist> 2783 2784 Prepared statements for use with <function>PQexecPrepared</function> can also 2785 be created by executing SQL <xref linkend="sql-prepare"/> 2786 statements. Also, although there is no <application>libpq</application> 2787 function for deleting a prepared statement, the SQL <xref 2788 linkend="sql-deallocate"/> statement 2789 can be used for that purpose. 2790 </para> 2791 2792 <para> 2793 <variablelist> 2794 <varlistentry id="libpq-pqexecprepared"> 2795 <term> 2796 <function>PQexecPrepared</function> 2797 <indexterm> 2798 <primary>PQexecPrepared</primary> 2799 </indexterm> 2800 </term> 2801 2802 <listitem> 2803 <para> 2804 Sends a request to execute a prepared statement with given 2805 parameters, and waits for the result. 2806<synopsis> 2807PGresult *PQexecPrepared(PGconn *conn, 2808 const char *stmtName, 2809 int nParams, 2810 const char * const *paramValues, 2811 const int *paramLengths, 2812 const int *paramFormats, 2813 int resultFormat); 2814</synopsis> 2815 </para> 2816 2817 <para> 2818 <function>PQexecPrepared</function> is like <function>PQexecParams</function>, 2819 but the command to be executed is specified by naming a 2820 previously-prepared statement, instead of giving a query string. 2821 This feature allows commands that will be used repeatedly to be 2822 parsed and planned just once, rather than each time they are 2823 executed. The statement must have been prepared previously in 2824 the current session. <function>PQexecPrepared</function> is supported 2825 only in protocol 3.0 and later connections; it will fail when 2826 using protocol 2.0. 2827 </para> 2828 2829 <para> 2830 The parameters are identical to <function>PQexecParams</function>, except that the 2831 name of a prepared statement is given instead of a query string, and the 2832 <parameter>paramTypes[]</parameter> parameter is not present (it is not needed since 2833 the prepared statement's parameter types were determined when it was created). 2834 </para> 2835 </listitem> 2836 </varlistentry> 2837 2838 <varlistentry id="libpq-pqdescribeprepared"> 2839 <term> 2840 <function>PQdescribePrepared</function> 2841 <indexterm> 2842 <primary>PQdescribePrepared</primary> 2843 </indexterm> 2844 </term> 2845 2846 <listitem> 2847 <para> 2848 Submits a request to obtain information about the specified 2849 prepared statement, and waits for completion. 2850<synopsis> 2851PGresult *PQdescribePrepared(PGconn *conn, const char *stmtName); 2852</synopsis> 2853 </para> 2854 2855 <para> 2856 <function>PQdescribePrepared</function> allows an application to obtain 2857 information about a previously prepared statement. 2858 <function>PQdescribePrepared</function> is supported only in protocol 3.0 2859 and later connections; it will fail when using protocol 2.0. 2860 </para> 2861 2862 <para> 2863 <parameter>stmtName</parameter> can be <literal>""</literal> or <symbol>NULL</symbol> to reference 2864 the unnamed statement, otherwise it must be the name of an existing 2865 prepared statement. On success, a <structname>PGresult</structname> with 2866 status <literal>PGRES_COMMAND_OK</literal> is returned. The 2867 functions <function>PQnparams</function> and 2868 <function>PQparamtype</function> can be applied to this 2869 <structname>PGresult</structname> to obtain information about the parameters 2870 of the prepared statement, and the functions 2871 <function>PQnfields</function>, <function>PQfname</function>, 2872 <function>PQftype</function>, etc provide information about the 2873 result columns (if any) of the statement. 2874 </para> 2875 </listitem> 2876 </varlistentry> 2877 2878 <varlistentry id="libpq-pqdescribeportal"> 2879 <term> 2880 <function>PQdescribePortal</function> 2881 <indexterm> 2882 <primary>PQdescribePortal</primary> 2883 </indexterm> 2884 </term> 2885 2886 <listitem> 2887 <para> 2888 Submits a request to obtain information about the specified 2889 portal, and waits for completion. 2890<synopsis> 2891PGresult *PQdescribePortal(PGconn *conn, const char *portalName); 2892</synopsis> 2893 </para> 2894 2895 <para> 2896 <function>PQdescribePortal</function> allows an application to obtain 2897 information about a previously created portal. 2898 (<application>libpq</application> does not provide any direct access to 2899 portals, but you can use this function to inspect the properties 2900 of a cursor created with a <command>DECLARE CURSOR</command> SQL command.) 2901 <function>PQdescribePortal</function> is supported only in protocol 3.0 2902 and later connections; it will fail when using protocol 2.0. 2903 </para> 2904 2905 <para> 2906 <parameter>portalName</parameter> can be <literal>""</literal> or <symbol>NULL</symbol> to reference 2907 the unnamed portal, otherwise it must be the name of an existing 2908 portal. On success, a <structname>PGresult</structname> with status 2909 <literal>PGRES_COMMAND_OK</literal> is returned. The functions 2910 <function>PQnfields</function>, <function>PQfname</function>, 2911 <function>PQftype</function>, etc can be applied to the 2912 <structname>PGresult</structname> to obtain information about the result 2913 columns (if any) of the portal. 2914 </para> 2915 </listitem> 2916 </varlistentry> 2917 </variablelist> 2918 </para> 2919 2920 <para> 2921 The <structname>PGresult</structname><indexterm><primary>PGresult</primary></indexterm> 2922 structure encapsulates the result returned by the server. 2923 <application>libpq</application> application programmers should be 2924 careful to maintain the <structname>PGresult</structname> abstraction. 2925 Use the accessor functions below to get at the contents of 2926 <structname>PGresult</structname>. Avoid directly referencing the 2927 fields of the <structname>PGresult</structname> structure because they 2928 are subject to change in the future. 2929 2930 <variablelist> 2931 <varlistentry id="libpq-pqresultstatus"> 2932 <term> 2933 <function>PQresultStatus</function> 2934 <indexterm> 2935 <primary>PQresultStatus</primary> 2936 </indexterm> 2937 </term> 2938 2939 <listitem> 2940 <para> 2941 Returns the result status of the command. 2942<synopsis> 2943ExecStatusType PQresultStatus(const PGresult *res); 2944</synopsis> 2945 </para> 2946 2947 <para> 2948 <function>PQresultStatus</function> can return one of the following values: 2949 2950 <variablelist> 2951 <varlistentry id="libpq-pgres-empty-query"> 2952 <term><literal>PGRES_EMPTY_QUERY</literal></term> 2953 <listitem> 2954 <para> 2955 The string sent to the server was empty. 2956 </para> 2957 </listitem> 2958 </varlistentry> 2959 2960 <varlistentry id="libpq-pgres-command-ok"> 2961 <term><literal>PGRES_COMMAND_OK</literal></term> 2962 <listitem> 2963 <para> 2964 Successful completion of a command returning no data. 2965 </para> 2966 </listitem> 2967 </varlistentry> 2968 2969 <varlistentry id="libpq-pgres-tuples-ok"> 2970 <term><literal>PGRES_TUPLES_OK</literal></term> 2971 <listitem> 2972 <para> 2973 Successful completion of a command returning data (such as 2974 a <command>SELECT</command> or <command>SHOW</command>). 2975 </para> 2976 </listitem> 2977 </varlistentry> 2978 2979 <varlistentry id="libpq-pgres-copy-out"> 2980 <term><literal>PGRES_COPY_OUT</literal></term> 2981 <listitem> 2982 <para> 2983 Copy Out (from server) data transfer started. 2984 </para> 2985 </listitem> 2986 </varlistentry> 2987 2988 <varlistentry id="libpq-pgres-copy-in"> 2989 <term><literal>PGRES_COPY_IN</literal></term> 2990 <listitem> 2991 <para> 2992 Copy In (to server) data transfer started. 2993 </para> 2994 </listitem> 2995 </varlistentry> 2996 2997 <varlistentry id="libpq-pgres-bad-response"> 2998 <term><literal>PGRES_BAD_RESPONSE</literal></term> 2999 <listitem> 3000 <para> 3001 The server's response was not understood. 3002 </para> 3003 </listitem> 3004 </varlistentry> 3005 3006 <varlistentry id="libpq-pgres-nonfatal-error"> 3007 <term><literal>PGRES_NONFATAL_ERROR</literal></term> 3008 <listitem> 3009 <para> 3010 A nonfatal error (a notice or warning) occurred. 3011 </para> 3012 </listitem> 3013 </varlistentry> 3014 3015 <varlistentry id="libpq-pgres-fatal-error"> 3016 <term><literal>PGRES_FATAL_ERROR</literal></term> 3017 <listitem> 3018 <para> 3019 A fatal error occurred. 3020 </para> 3021 </listitem> 3022 </varlistentry> 3023 3024 <varlistentry id="libpq-pgres-copy-both"> 3025 <term><literal>PGRES_COPY_BOTH</literal></term> 3026 <listitem> 3027 <para> 3028 Copy In/Out (to and from server) data transfer started. This 3029 feature is currently used only for streaming replication, 3030 so this status should not occur in ordinary applications. 3031 </para> 3032 </listitem> 3033 </varlistentry> 3034 3035 <varlistentry id="libpq-pgres-single-tuple"> 3036 <term><literal>PGRES_SINGLE_TUPLE</literal></term> 3037 <listitem> 3038 <para> 3039 The <structname>PGresult</structname> contains a single result tuple 3040 from the current command. This status occurs only when 3041 single-row mode has been selected for the query 3042 (see <xref linkend="libpq-single-row-mode"/>). 3043 </para> 3044 </listitem> 3045 </varlistentry> 3046 </variablelist> 3047 3048 If the result status is <literal>PGRES_TUPLES_OK</literal> or 3049 <literal>PGRES_SINGLE_TUPLE</literal>, then 3050 the functions described below can be used to retrieve the rows 3051 returned by the query. Note that a <command>SELECT</command> 3052 command that happens to retrieve zero rows still shows 3053 <literal>PGRES_TUPLES_OK</literal>. 3054 <literal>PGRES_COMMAND_OK</literal> is for commands that can never 3055 return rows (<command>INSERT</command> or <command>UPDATE</command> 3056 without a <literal>RETURNING</literal> clause, 3057 etc.). A response of <literal>PGRES_EMPTY_QUERY</literal> might 3058 indicate a bug in the client software. 3059 </para> 3060 3061 <para> 3062 A result of status <symbol>PGRES_NONFATAL_ERROR</symbol> will 3063 never be returned directly by <function>PQexec</function> or other 3064 query execution functions; results of this kind are instead passed 3065 to the notice processor (see <xref 3066 linkend="libpq-notice-processing"/>). 3067 </para> 3068 </listitem> 3069 </varlistentry> 3070 3071 <varlistentry id="libpq-pqresstatus"> 3072 <term> 3073 <function>PQresStatus</function> 3074 <indexterm> 3075 <primary>PQresStatus</primary> 3076 </indexterm> 3077 </term> 3078 3079 <listitem> 3080 <para> 3081 Converts the enumerated type returned by 3082 <function>PQresultStatus</function> into a string constant describing the 3083 status code. The caller should not free the result. 3084 3085<synopsis> 3086char *PQresStatus(ExecStatusType status); 3087</synopsis> 3088 </para> 3089 </listitem> 3090 </varlistentry> 3091 3092 <varlistentry id="libpq-pqresulterrormessage"> 3093 <term> 3094 <function>PQresultErrorMessage</function> 3095 <indexterm> 3096 <primary>PQresultErrorMessage</primary> 3097 </indexterm> 3098 </term> 3099 3100 <listitem> 3101 <para> 3102 Returns the error message associated with the command, or an empty string 3103 if there was no error. 3104<synopsis> 3105char *PQresultErrorMessage(const PGresult *res); 3106</synopsis> 3107 If there was an error, the returned string will include a trailing 3108 newline. The caller should not free the result directly. It will 3109 be freed when the associated <structname>PGresult</structname> handle is 3110 passed to <function>PQclear</function>. 3111 </para> 3112 3113 <para> 3114 Immediately following a <function>PQexec</function> or 3115 <function>PQgetResult</function> call, 3116 <function>PQerrorMessage</function> (on the connection) will return 3117 the same string as <function>PQresultErrorMessage</function> (on 3118 the result). However, a <structname>PGresult</structname> will 3119 retain its error message until destroyed, whereas the connection's 3120 error message will change when subsequent operations are done. 3121 Use <function>PQresultErrorMessage</function> when you want to 3122 know the status associated with a particular 3123 <structname>PGresult</structname>; use 3124 <function>PQerrorMessage</function> when you want to know the 3125 status from the latest operation on the connection. 3126 </para> 3127 </listitem> 3128 </varlistentry> 3129 3130 <varlistentry id="libpq-pqresultverboseerrormessage"> 3131 <term> 3132 <function>PQresultVerboseErrorMessage</function> 3133 <indexterm> 3134 <primary>PQresultVerboseErrorMessage</primary> 3135 </indexterm> 3136 </term> 3137 3138 <listitem> 3139 <para> 3140 Returns a reformatted version of the error message associated with 3141 a <structname>PGresult</structname> object. 3142<synopsis> 3143char *PQresultVerboseErrorMessage(const PGresult *res, 3144 PGVerbosity verbosity, 3145 PGContextVisibility show_context); 3146</synopsis> 3147 In some situations a client might wish to obtain a more detailed 3148 version of a previously-reported error. 3149 <function>PQresultVerboseErrorMessage</function> addresses this need 3150 by computing the message that would have been produced 3151 by <function>PQresultErrorMessage</function> if the specified 3152 verbosity settings had been in effect for the connection when the 3153 given <structname>PGresult</structname> was generated. If 3154 the <structname>PGresult</structname> is not an error result, 3155 <quote>PGresult is not an error result</quote> is reported instead. 3156 The returned string includes a trailing newline. 3157 </para> 3158 3159 <para> 3160 Unlike most other functions for extracting data from 3161 a <structname>PGresult</structname>, the result of this function is a freshly 3162 allocated string. The caller must free it 3163 using <function>PQfreemem()</function> when the string is no longer needed. 3164 </para> 3165 3166 <para> 3167 A NULL return is possible if there is insufficient memory. 3168 </para> 3169 </listitem> 3170 </varlistentry> 3171 3172 <varlistentry id="libpq-pqresulterrorfield"> 3173 <term><function>PQresultErrorField</function><indexterm><primary>PQresultErrorField</primary></indexterm></term> 3174 <listitem> 3175 <para> 3176 Returns an individual field of an error report. 3177<synopsis> 3178char *PQresultErrorField(const PGresult *res, int fieldcode); 3179</synopsis> 3180 <parameter>fieldcode</parameter> is an error field identifier; see the symbols 3181 listed below. <symbol>NULL</symbol> is returned if the 3182 <structname>PGresult</structname> is not an error or warning result, 3183 or does not include the specified field. Field values will normally 3184 not include a trailing newline. The caller should not free the 3185 result directly. It will be freed when the 3186 associated <structname>PGresult</structname> handle is passed to 3187 <function>PQclear</function>. 3188 </para> 3189 3190 <para> 3191 The following field codes are available: 3192 <variablelist> 3193 <varlistentry id="libpq-pg-diag-severity"> 3194 <term><symbol>PG_DIAG_SEVERITY</symbol></term> 3195 <listitem> 3196 <para> 3197 The severity; the field contents are <literal>ERROR</literal>, 3198 <literal>FATAL</literal>, or <literal>PANIC</literal> (in an error message), 3199 or <literal>WARNING</literal>, <literal>NOTICE</literal>, <literal>DEBUG</literal>, 3200 <literal>INFO</literal>, or <literal>LOG</literal> (in a notice message), or 3201 a localized translation of one of these. Always present. 3202 </para> 3203 </listitem> 3204 </varlistentry> 3205 3206 <varlistentry id="libpq-pg-diag-severity-nonlocalized"> 3207 <term><symbol>PG_DIAG_SEVERITY_NONLOCALIZED</symbol></term> 3208 <listitem> 3209 <para> 3210 The severity; the field contents are <literal>ERROR</literal>, 3211 <literal>FATAL</literal>, or <literal>PANIC</literal> (in an error message), 3212 or <literal>WARNING</literal>, <literal>NOTICE</literal>, <literal>DEBUG</literal>, 3213 <literal>INFO</literal>, or <literal>LOG</literal> (in a notice message). 3214 This is identical to the <symbol>PG_DIAG_SEVERITY</symbol> field except 3215 that the contents are never localized. This is present only in 3216 reports generated by <productname>PostgreSQL</productname> versions 9.6 3217 and later. 3218 </para> 3219 </listitem> 3220 </varlistentry> 3221 3222 <varlistentry id="libpq-pg-diag-sqlstate"> 3223 <term> 3224 <symbol>PG_DIAG_SQLSTATE</symbol> 3225 <indexterm> 3226 <primary>error codes</primary> 3227 <secondary>libpq</secondary> 3228 </indexterm> 3229 </term> 3230 <listitem> 3231 <para> 3232 The SQLSTATE code for the error. The SQLSTATE code identifies 3233 the type of error that has occurred; it can be used by 3234 front-end applications to perform specific operations (such 3235 as error handling) in response to a particular database error. 3236 For a list of the possible SQLSTATE codes, see <xref 3237 linkend="errcodes-appendix"/>. This field is not localizable, 3238 and is always present. 3239 </para> 3240 </listitem> 3241 </varlistentry> 3242 3243 <varlistentry id="libpq-pg-diag-message-primary"> 3244 <term><symbol>PG_DIAG_MESSAGE_PRIMARY</symbol></term> 3245 <listitem> 3246 <para> 3247 The primary human-readable error message (typically one line). 3248 Always present. 3249 </para> 3250 </listitem> 3251 </varlistentry> 3252 3253 <varlistentry id="libpq-pg-diag-message-detail"> 3254 <term><symbol>PG_DIAG_MESSAGE_DETAIL</symbol></term> 3255 <listitem> 3256 <para> 3257 Detail: an optional secondary error message carrying more 3258 detail about the problem. Might run to multiple lines. 3259 </para> 3260 </listitem> 3261 </varlistentry> 3262 3263 <varlistentry id="libpq-pg-diag-message-hint"> 3264 <term><symbol>PG_DIAG_MESSAGE_HINT</symbol></term> 3265 <listitem> 3266 <para> 3267 Hint: an optional suggestion what to do about the problem. 3268 This is intended to differ from detail in that it offers advice 3269 (potentially inappropriate) rather than hard facts. Might 3270 run to multiple lines. 3271 </para> 3272 </listitem> 3273 </varlistentry> 3274 3275 <varlistentry id="libpq-pg-diag-statement-position"> 3276 <term><symbol>PG_DIAG_STATEMENT_POSITION</symbol></term> 3277 <listitem> 3278 <para> 3279 A string containing a decimal integer indicating an error cursor 3280 position as an index into the original statement string. The 3281 first character has index 1, and positions are measured in 3282 characters not bytes. 3283 </para> 3284 </listitem> 3285 </varlistentry> 3286 3287 <varlistentry id="libpq-pg-diag-internal-position"> 3288 <term><symbol>PG_DIAG_INTERNAL_POSITION</symbol></term> 3289 <listitem> 3290 <para> 3291 This is defined the same as the 3292 <symbol>PG_DIAG_STATEMENT_POSITION</symbol> field, but it is used 3293 when the cursor position refers to an internally generated 3294 command rather than the one submitted by the client. The 3295 <symbol>PG_DIAG_INTERNAL_QUERY</symbol> field will always appear when 3296 this field appears. 3297 </para> 3298 </listitem> 3299 </varlistentry> 3300 3301 <varlistentry id="libpq-pg-diag-internal-query"> 3302 <term><symbol>PG_DIAG_INTERNAL_QUERY</symbol></term> 3303 <listitem> 3304 <para> 3305 The text of a failed internally-generated command. This could 3306 be, for example, a SQL query issued by a PL/pgSQL function. 3307 </para> 3308 </listitem> 3309 </varlistentry> 3310 3311 <varlistentry id="libpq-pg-diag-context"> 3312 <term><symbol>PG_DIAG_CONTEXT</symbol></term> 3313 <listitem> 3314 <para> 3315 An indication of the context in which the error occurred. 3316 Presently this includes a call stack traceback of active 3317 procedural language functions and internally-generated queries. 3318 The trace is one entry per line, most recent first. 3319 </para> 3320 </listitem> 3321 </varlistentry> 3322 3323 <varlistentry id="libpq-pg-diag-schema-name"> 3324 <term><symbol>PG_DIAG_SCHEMA_NAME</symbol></term> 3325 <listitem> 3326 <para> 3327 If the error was associated with a specific database object, 3328 the name of the schema containing that object, if any. 3329 </para> 3330 </listitem> 3331 </varlistentry> 3332 3333 <varlistentry id="libpq-pg-diag-table-name"> 3334 <term><symbol>PG_DIAG_TABLE_NAME</symbol></term> 3335 <listitem> 3336 <para> 3337 If the error was associated with a specific table, the name of the 3338 table. (Refer to the schema name field for the name of the 3339 table's schema.) 3340 </para> 3341 </listitem> 3342 </varlistentry> 3343 3344 <varlistentry id="libpq-pg-diag-column-name"> 3345 <term><symbol>PG_DIAG_COLUMN_NAME</symbol></term> 3346 <listitem> 3347 <para> 3348 If the error was associated with a specific table column, the name 3349 of the column. (Refer to the schema and table name fields to 3350 identify the table.) 3351 </para> 3352 </listitem> 3353 </varlistentry> 3354 3355 <varlistentry id="libpq-pg-diag-datatype-name"> 3356 <term><symbol>PG_DIAG_DATATYPE_NAME</symbol></term> 3357 <listitem> 3358 <para> 3359 If the error was associated with a specific data type, the name of 3360 the data type. (Refer to the schema name field for the name of 3361 the data type's schema.) 3362 </para> 3363 </listitem> 3364 </varlistentry> 3365 3366 <varlistentry id="libpq-pg-diag-constraint-name"> 3367 <term><symbol>PG_DIAG_CONSTRAINT_NAME</symbol></term> 3368 <listitem> 3369 <para> 3370 If the error was associated with a specific constraint, the name 3371 of the constraint. Refer to fields listed above for the 3372 associated table or domain. (For this purpose, indexes are 3373 treated as constraints, even if they weren't created with 3374 constraint syntax.) 3375 </para> 3376 </listitem> 3377 </varlistentry> 3378 3379 <varlistentry id="libpq-pg-diag-source-file"> 3380 <term><symbol>PG_DIAG_SOURCE_FILE</symbol></term> 3381 <listitem> 3382 <para> 3383 The file name of the source-code location where the error was 3384 reported. 3385 </para> 3386 </listitem> 3387 </varlistentry> 3388 3389 <varlistentry id="libpq-pg-diag-source-line"> 3390 <term><symbol>PG_DIAG_SOURCE_LINE</symbol></term> 3391 <listitem> 3392 <para> 3393 The line number of the source-code location where the error 3394 was reported. 3395 </para> 3396 </listitem> 3397 </varlistentry> 3398 3399 <varlistentry id="libpq-pg-diag-source-function"> 3400 <term><symbol>PG_DIAG_SOURCE_FUNCTION</symbol></term> 3401 <listitem> 3402 <para> 3403 The name of the source-code function reporting the error. 3404 </para> 3405 </listitem> 3406 </varlistentry> 3407 </variablelist> 3408 </para> 3409 3410 <note> 3411 <para> 3412 The fields for schema name, table name, column name, data type name, 3413 and constraint name are supplied only for a limited number of error 3414 types; see <xref linkend="errcodes-appendix"/>. Do not assume that 3415 the presence of any of these fields guarantees the presence of 3416 another field. Core error sources observe the interrelationships 3417 noted above, but user-defined functions may use these fields in other 3418 ways. In the same vein, do not assume that these fields denote 3419 contemporary objects in the current database. 3420 </para> 3421 </note> 3422 3423 <para> 3424 The client is responsible for formatting displayed information to meet 3425 its needs; in particular it should break long lines as needed. 3426 Newline characters appearing in the error message fields should be 3427 treated as paragraph breaks, not line breaks. 3428 </para> 3429 3430 <para> 3431 Errors generated internally by <application>libpq</application> will 3432 have severity and primary message, but typically no other fields. 3433 Errors returned by a pre-3.0-protocol server will include severity and 3434 primary message, and sometimes a detail message, but no other fields. 3435 </para> 3436 3437 <para> 3438 Note that error fields are only available from 3439 <structname>PGresult</structname> objects, not 3440 <structname>PGconn</structname> objects; there is no 3441 <function>PQerrorField</function> function. 3442 </para> 3443 </listitem> 3444 </varlistentry> 3445 3446 <varlistentry id="libpq-pqclear"> 3447 <term><function>PQclear</function><indexterm><primary>PQclear</primary></indexterm></term> 3448 <listitem> 3449 <para> 3450 Frees the storage associated with a 3451 <structname>PGresult</structname>. Every command result should be 3452 freed via <function>PQclear</function> when it is no longer 3453 needed. 3454 3455<synopsis> 3456void PQclear(PGresult *res); 3457</synopsis> 3458 </para> 3459 3460 <para> 3461 You can keep a <structname>PGresult</structname> object around for 3462 as long as you need it; it does not go away when you issue a new 3463 command, nor even if you close the connection. To get rid of it, 3464 you must call <function>PQclear</function>. Failure to do this 3465 will result in memory leaks in your application. 3466 </para> 3467 </listitem> 3468 </varlistentry> 3469 </variablelist> 3470 </para> 3471 </sect2> 3472 3473 <sect2 id="libpq-exec-select-info"> 3474 <title>Retrieving Query Result Information</title> 3475 3476 <para> 3477 These functions are used to extract information from a 3478 <structname>PGresult</structname> object that represents a successful 3479 query result (that is, one that has status 3480 <literal>PGRES_TUPLES_OK</literal> or <literal>PGRES_SINGLE_TUPLE</literal>). 3481 They can also be used to extract 3482 information from a successful Describe operation: a Describe's result 3483 has all the same column information that actual execution of the query 3484 would provide, but it has zero rows. For objects with other status values, 3485 these functions will act as though the result has zero rows and zero columns. 3486 </para> 3487 3488 <variablelist> 3489 <varlistentry id="libpq-pqntuples"> 3490 <term> 3491 <function>PQntuples</function> 3492 <indexterm> 3493 <primary>PQntuples</primary> 3494 </indexterm> 3495 </term> 3496 3497 <listitem> 3498 <para> 3499 Returns the number of rows (tuples) in the query result. 3500 (Note that <structname>PGresult</structname> objects are limited to no more 3501 than <literal>INT_MAX</literal> rows, so an <type>int</type> result is 3502 sufficient.) 3503 3504<synopsis> 3505int PQntuples(const PGresult *res); 3506</synopsis> 3507 3508 </para> 3509 </listitem> 3510 </varlistentry> 3511 3512 <varlistentry id="libpq-pqnfields"> 3513 <term> 3514 <function>PQnfields</function> 3515 <indexterm> 3516 <primary>PQnfields</primary> 3517 </indexterm> 3518 </term> 3519 3520 <listitem> 3521 <para> 3522 Returns the number of columns (fields) in each row of the query 3523 result. 3524 3525<synopsis> 3526int PQnfields(const PGresult *res); 3527</synopsis> 3528 </para> 3529 </listitem> 3530 </varlistentry> 3531 3532 <varlistentry id="libpq-pqfname"> 3533 <term> 3534 <function>PQfname</function> 3535 <indexterm> 3536 <primary>PQfname</primary> 3537 </indexterm> 3538 </term> 3539 3540 <listitem> 3541 <para> 3542 Returns the column name associated with the given column number. 3543 Column numbers start at 0. The caller should not free the result 3544 directly. It will be freed when the associated 3545 <structname>PGresult</structname> handle is passed to 3546 <function>PQclear</function>. 3547<synopsis> 3548char *PQfname(const PGresult *res, 3549 int column_number); 3550</synopsis> 3551 </para> 3552 3553 <para> 3554 <symbol>NULL</symbol> is returned if the column number is out of range. 3555 </para> 3556 </listitem> 3557 </varlistentry> 3558 3559 <varlistentry id="libpq-pqfnumber"> 3560 <term> 3561 <function>PQfnumber</function> 3562 <indexterm> 3563 <primary>PQfnumber</primary> 3564 </indexterm> 3565 </term> 3566 3567 <listitem> 3568 <para> 3569 Returns the column number associated with the given column name. 3570<synopsis> 3571int PQfnumber(const PGresult *res, 3572 const char *column_name); 3573</synopsis> 3574 </para> 3575 3576 <para> 3577 -1 is returned if the given name does not match any column. 3578 </para> 3579 3580 <para> 3581 The given name is treated like an identifier in an SQL command, 3582 that is, it is downcased unless double-quoted. For example, given 3583 a query result generated from the SQL command: 3584<programlisting> 3585SELECT 1 AS FOO, 2 AS "BAR"; 3586</programlisting> 3587 we would have the results: 3588<programlisting> 3589PQfname(res, 0) <lineannotation>foo</lineannotation> 3590PQfname(res, 1) <lineannotation>BAR</lineannotation> 3591PQfnumber(res, "FOO") <lineannotation>0</lineannotation> 3592PQfnumber(res, "foo") <lineannotation>0</lineannotation> 3593PQfnumber(res, "BAR") <lineannotation>-1</lineannotation> 3594PQfnumber(res, "\"BAR\"") <lineannotation>1</lineannotation> 3595</programlisting> 3596 </para> 3597 </listitem> 3598 </varlistentry> 3599 3600 <varlistentry id="libpq-pqftable"> 3601 <term> 3602 <function>PQftable</function> 3603 <indexterm> 3604 <primary>PQftable</primary> 3605 </indexterm> 3606 </term> 3607 3608 <listitem> 3609 <para> 3610 Returns the OID of the table from which the given column was 3611 fetched. Column numbers start at 0. 3612<synopsis> 3613Oid PQftable(const PGresult *res, 3614 int column_number); 3615</synopsis> 3616 </para> 3617 3618 <para> 3619 <literal>InvalidOid</literal> is returned if the column number is out of range, 3620 or if the specified column is not a simple reference to a table column, 3621 or when using pre-3.0 protocol. 3622 You can query the system table <literal>pg_class</literal> to determine 3623 exactly which table is referenced. 3624 </para> 3625 3626 <para> 3627 The type <type>Oid</type> and the constant 3628 <literal>InvalidOid</literal> will be defined when you include 3629 the <application>libpq</application> header file. They will both 3630 be some integer type. 3631 </para> 3632 </listitem> 3633 </varlistentry> 3634 3635 <varlistentry id="libpq-pqftablecol"> 3636 <term> 3637 <function>PQftablecol</function> 3638 <indexterm> 3639 <primary>PQftablecol</primary> 3640 </indexterm> 3641 </term> 3642 3643 <listitem> 3644 <para> 3645 Returns the column number (within its table) of the column making 3646 up the specified query result column. Query-result column numbers 3647 start at 0, but table columns have nonzero numbers. 3648<synopsis> 3649int PQftablecol(const PGresult *res, 3650 int column_number); 3651</synopsis> 3652 </para> 3653 3654 <para> 3655 Zero is returned if the column number is out of range, or if the 3656 specified column is not a simple reference to a table column, or 3657 when using pre-3.0 protocol. 3658 </para> 3659 </listitem> 3660 </varlistentry> 3661 3662 <varlistentry id="libpq-pqfformat"> 3663 <term> 3664 <function>PQfformat</function> 3665 <indexterm> 3666 <primary>PQfformat</primary> 3667 </indexterm> 3668 </term> 3669 3670 <listitem> 3671 <para> 3672 Returns the format code indicating the format of the given 3673 column. Column numbers start at 0. 3674<synopsis> 3675int PQfformat(const PGresult *res, 3676 int column_number); 3677</synopsis> 3678 </para> 3679 3680 <para> 3681 Format code zero indicates textual data representation, while format 3682 code one indicates binary representation. (Other codes are reserved 3683 for future definition.) 3684 </para> 3685 </listitem> 3686 </varlistentry> 3687 3688 <varlistentry id="libpq-pqftype"> 3689 <term> 3690 <function>PQftype</function> 3691 <indexterm> 3692 <primary>PQftype</primary> 3693 </indexterm> 3694 </term> 3695 3696 <listitem> 3697 <para> 3698 Returns the data type associated with the given column number. 3699 The integer returned is the internal OID number of the type. 3700 Column numbers start at 0. 3701<synopsis> 3702Oid PQftype(const PGresult *res, 3703 int column_number); 3704</synopsis> 3705 </para> 3706 3707 <para> 3708 You can query the system table <literal>pg_type</literal> to 3709 obtain the names and properties of the various data types. The 3710 <acronym>OID</acronym>s of the built-in data types are defined 3711 in the file <filename>include/server/catalog/pg_type_d.h</filename> 3712 in the install directory. 3713 </para> 3714 </listitem> 3715 </varlistentry> 3716 3717 <varlistentry id="libpq-pqfmod"> 3718 <term> 3719 <function>PQfmod</function> 3720 <indexterm> 3721 <primary>PQfmod</primary> 3722 </indexterm> 3723 </term> 3724 3725 <listitem> 3726 <para> 3727 Returns the type modifier of the column associated with the 3728 given column number. Column numbers start at 0. 3729<synopsis> 3730int PQfmod(const PGresult *res, 3731 int column_number); 3732</synopsis> 3733 </para> 3734 3735 <para> 3736 The interpretation of modifier values is type-specific; they 3737 typically indicate precision or size limits. The value -1 is 3738 used to indicate <quote>no information available</quote>. Most data 3739 types do not use modifiers, in which case the value is always 3740 -1. 3741 </para> 3742 </listitem> 3743 </varlistentry> 3744 3745 <varlistentry id="libpq-pqfsize"> 3746 <term> 3747 <function>PQfsize</function> 3748 <indexterm> 3749 <primary>PQfsize</primary> 3750 </indexterm> 3751 </term> 3752 3753 <listitem> 3754 <para> 3755 Returns the size in bytes of the column associated with the 3756 given column number. Column numbers start at 0. 3757<synopsis> 3758int PQfsize(const PGresult *res, 3759 int column_number); 3760</synopsis> 3761 </para> 3762 3763 <para> 3764 <function>PQfsize</function> returns the space allocated for this column 3765 in a database row, in other words the size of the server's 3766 internal representation of the data type. (Accordingly, it is 3767 not really very useful to clients.) A negative value indicates 3768 the data type is variable-length. 3769 </para> 3770 </listitem> 3771 </varlistentry> 3772 3773 <varlistentry id="libpq-pqbinarytuples"> 3774 <term> 3775 <function>PQbinaryTuples</function> 3776 <indexterm> 3777 <primary>PQbinaryTuples</primary> 3778 </indexterm> 3779 </term> 3780 3781 <listitem> 3782 <para> 3783 Returns 1 if the <structname>PGresult</structname> contains binary data 3784 and 0 if it contains text data. 3785<synopsis> 3786int PQbinaryTuples(const PGresult *res); 3787</synopsis> 3788 </para> 3789 3790 <para> 3791 This function is deprecated (except for its use in connection with 3792 <command>COPY</command>), because it is possible for a single 3793 <structname>PGresult</structname> to contain text data in some columns and 3794 binary data in others. <function>PQfformat</function> is preferred. 3795 <function>PQbinaryTuples</function> returns 1 only if all columns of the 3796 result are binary (format 1). 3797 </para> 3798 </listitem> 3799 </varlistentry> 3800 3801 <varlistentry id="libpq-pqgetvalue"> 3802 <term> 3803 <function>PQgetvalue</function> 3804 <indexterm> 3805 <primary>PQgetvalue</primary> 3806 </indexterm> 3807 </term> 3808 3809 <listitem> 3810 <para> 3811 Returns a single field value of one row of a 3812 <structname>PGresult</structname>. Row and column numbers start 3813 at 0. The caller should not free the result directly. It will 3814 be freed when the associated <structname>PGresult</structname> handle is 3815 passed to <function>PQclear</function>. 3816<synopsis> 3817char *PQgetvalue(const PGresult *res, 3818 int row_number, 3819 int column_number); 3820</synopsis> 3821 </para> 3822 3823 <para> 3824 For data in text format, the value returned by 3825 <function>PQgetvalue</function> is a null-terminated character 3826 string representation of the field value. For data in binary 3827 format, the value is in the binary representation determined by 3828 the data type's <function>typsend</function> and <function>typreceive</function> 3829 functions. (The value is actually followed by a zero byte in 3830 this case too, but that is not ordinarily useful, since the 3831 value is likely to contain embedded nulls.) 3832 </para> 3833 3834 <para> 3835 An empty string is returned if the field value is null. See 3836 <function>PQgetisnull</function> to distinguish null values from 3837 empty-string values. 3838 </para> 3839 3840 <para> 3841 The pointer returned by <function>PQgetvalue</function> points 3842 to storage that is part of the <structname>PGresult</structname> 3843 structure. One should not modify the data it points to, and one 3844 must explicitly copy the data into other storage if it is to be 3845 used past the lifetime of the <structname>PGresult</structname> 3846 structure itself. 3847 </para> 3848 </listitem> 3849 </varlistentry> 3850 3851 <varlistentry id="libpq-pqgetisnull"> 3852 <term> 3853 <function>PQgetisnull</function> 3854 <indexterm> 3855 <primary>PQgetisnull</primary> 3856 </indexterm> 3857 <indexterm> 3858 <primary>null value</primary> 3859 <secondary sortas="libpq">in libpq</secondary> 3860 </indexterm> 3861 </term> 3862 3863 <listitem> 3864 <para> 3865 Tests a field for a null value. Row and column numbers start 3866 at 0. 3867<synopsis> 3868int PQgetisnull(const PGresult *res, 3869 int row_number, 3870 int column_number); 3871</synopsis> 3872 </para> 3873 3874 <para> 3875 This function returns 1 if the field is null and 0 if it 3876 contains a non-null value. (Note that 3877 <function>PQgetvalue</function> will return an empty string, 3878 not a null pointer, for a null field.) 3879 </para> 3880 </listitem> 3881 </varlistentry> 3882 3883 <varlistentry id="libpq-pqgetlength"> 3884 <term> 3885 <function>PQgetlength</function> 3886 <indexterm> 3887 <primary>PQgetlength</primary> 3888 </indexterm></term> 3889 3890 <listitem> 3891 <para> 3892 Returns the actual length of a field value in bytes. Row and 3893 column numbers start at 0. 3894<synopsis> 3895int PQgetlength(const PGresult *res, 3896 int row_number, 3897 int column_number); 3898</synopsis> 3899 </para> 3900 3901 <para> 3902 This is the actual data length for the particular data value, 3903 that is, the size of the object pointed to by 3904 <function>PQgetvalue</function>. For text data format this is 3905 the same as <function>strlen()</function>. For binary format this is 3906 essential information. Note that one should <emphasis>not</emphasis> 3907 rely on <function>PQfsize</function> to obtain the actual data 3908 length. 3909 </para> 3910 </listitem> 3911 </varlistentry> 3912 3913 <varlistentry id="libpq-pqnparams"> 3914 <term> 3915 <function>PQnparams</function> 3916 <indexterm> 3917 <primary>PQnparams</primary> 3918 </indexterm> 3919 </term> 3920 3921 <listitem> 3922 <para> 3923 Returns the number of parameters of a prepared statement. 3924<synopsis> 3925int PQnparams(const PGresult *res); 3926</synopsis> 3927 </para> 3928 3929 <para> 3930 This function is only useful when inspecting the result of 3931 <function>PQdescribePrepared</function>. For other types of queries it 3932 will return zero. 3933 </para> 3934 </listitem> 3935 </varlistentry> 3936 3937 <varlistentry id="libpq-pqparamtype"> 3938 <term> 3939 <function>PQparamtype</function> 3940 <indexterm> 3941 <primary>PQparamtype</primary> 3942 </indexterm> 3943 </term> 3944 3945 <listitem> 3946 <para> 3947 Returns the data type of the indicated statement parameter. 3948 Parameter numbers start at 0. 3949<synopsis> 3950Oid PQparamtype(const PGresult *res, int param_number); 3951</synopsis> 3952 </para> 3953 3954 <para> 3955 This function is only useful when inspecting the result of 3956 <function>PQdescribePrepared</function>. For other types of queries it 3957 will return zero. 3958 </para> 3959 </listitem> 3960 </varlistentry> 3961 3962 <varlistentry id="libpq-pqprint"> 3963 <term> 3964 <function>PQprint</function> 3965 <indexterm> 3966 <primary>PQprint</primary> 3967 </indexterm> 3968 </term> 3969 3970 <listitem> 3971 <para> 3972 Prints out all the rows and, optionally, the column names to 3973 the specified output stream. 3974<synopsis> 3975void PQprint(FILE *fout, /* output stream */ 3976 const PGresult *res, 3977 const PQprintOpt *po); 3978typedef struct 3979{ 3980 pqbool header; /* print output field headings and row count */ 3981 pqbool align; /* fill align the fields */ 3982 pqbool standard; /* old brain dead format */ 3983 pqbool html3; /* output HTML tables */ 3984 pqbool expanded; /* expand tables */ 3985 pqbool pager; /* use pager for output if needed */ 3986 char *fieldSep; /* field separator */ 3987 char *tableOpt; /* attributes for HTML table element */ 3988 char *caption; /* HTML table caption */ 3989 char **fieldName; /* null-terminated array of replacement field names */ 3990} PQprintOpt; 3991</synopsis> 3992 </para> 3993 3994 <para> 3995 This function was formerly used by <application>psql</application> 3996 to print query results, but this is no longer the case. Note 3997 that it assumes all the data is in text format. 3998 </para> 3999 </listitem> 4000 </varlistentry> 4001 </variablelist> 4002 </sect2> 4003 4004 <sect2 id="libpq-exec-nonselect"> 4005 <title>Retrieving Other Result Information</title> 4006 4007 <para> 4008 These functions are used to extract other information from 4009 <structname>PGresult</structname> objects. 4010 </para> 4011 4012 <variablelist> 4013 <varlistentry id="libpq-pqcmdstatus"> 4014 <term> 4015 <function>PQcmdStatus</function> 4016 <indexterm> 4017 <primary>PQcmdStatus</primary> 4018 </indexterm> 4019 </term> 4020 4021 <listitem> 4022 <para> 4023 Returns the command status tag from the SQL command that generated 4024 the <structname>PGresult</structname>. 4025<synopsis> 4026char *PQcmdStatus(PGresult *res); 4027</synopsis> 4028 </para> 4029 4030 <para> 4031 Commonly this is just the name of the command, but it might include 4032 additional data such as the number of rows processed. The caller 4033 should not free the result directly. It will be freed when the 4034 associated <structname>PGresult</structname> handle is passed to 4035 <function>PQclear</function>. 4036 </para> 4037 </listitem> 4038 </varlistentry> 4039 4040 <varlistentry id="libpq-pqcmdtuples"> 4041 <term> 4042 <function>PQcmdTuples</function> 4043 <indexterm> 4044 <primary>PQcmdTuples</primary> 4045 </indexterm> 4046 </term> 4047 4048 <listitem> 4049 <para> 4050 Returns the number of rows affected by the SQL command. 4051<synopsis> 4052char *PQcmdTuples(PGresult *res); 4053</synopsis> 4054 </para> 4055 4056 <para> 4057 This function returns a string containing the number of rows 4058 affected by the <acronym>SQL</acronym> statement that generated the 4059 <structname>PGresult</structname>. This function can only be used following 4060 the execution of a <command>SELECT</command>, <command>CREATE TABLE AS</command>, 4061 <command>INSERT</command>, <command>UPDATE</command>, <command>DELETE</command>, 4062 <command>MOVE</command>, <command>FETCH</command>, or <command>COPY</command> statement, 4063 or an <command>EXECUTE</command> of a prepared query that contains an 4064 <command>INSERT</command>, <command>UPDATE</command>, or <command>DELETE</command> statement. 4065 If the command that generated the <structname>PGresult</structname> was anything 4066 else, <function>PQcmdTuples</function> returns an empty string. The caller 4067 should not free the return value directly. It will be freed when 4068 the associated <structname>PGresult</structname> handle is passed to 4069 <function>PQclear</function>. 4070 </para> 4071 </listitem> 4072 </varlistentry> 4073 4074 <varlistentry id="libpq-pqoidvalue"> 4075 <term> 4076 <function>PQoidValue</function> 4077 <indexterm> 4078 <primary>PQoidValue</primary> 4079 </indexterm> 4080 </term> 4081 4082 <listitem> 4083 <para> 4084 Returns the OID<indexterm><primary>OID</primary><secondary>in libpq</secondary></indexterm> 4085 of the inserted row, if the <acronym>SQL</acronym> command was an 4086 <command>INSERT</command> that inserted exactly one row into a table that 4087 has OIDs, or a <command>EXECUTE</command> of a prepared query containing 4088 a suitable <command>INSERT</command> statement. Otherwise, this function 4089 returns <literal>InvalidOid</literal>. This function will also 4090 return <literal>InvalidOid</literal> if the table affected by the 4091 <command>INSERT</command> statement does not contain OIDs. 4092<synopsis> 4093Oid PQoidValue(const PGresult *res); 4094</synopsis> 4095 </para> 4096 </listitem> 4097 </varlistentry> 4098 4099 <varlistentry id="libpq-pqoidstatus"> 4100 <term> 4101 <function>PQoidStatus</function> 4102 <indexterm> 4103 <primary>PQoidStatus</primary> 4104 </indexterm> 4105 </term> 4106 4107 <listitem> 4108 <para> 4109 This function is deprecated in favor of 4110 <function>PQoidValue</function> and is not thread-safe. 4111 It returns a string with the OID of the inserted row, while 4112 <function>PQoidValue</function> returns the OID value. 4113<synopsis> 4114char *PQoidStatus(const PGresult *res); 4115</synopsis> 4116 </para> 4117 4118 </listitem> 4119 </varlistentry> 4120 </variablelist> 4121 4122 </sect2> 4123 4124 <sect2 id="libpq-exec-escape-string"> 4125 <title>Escaping Strings for Inclusion in SQL Commands</title> 4126 4127 <indexterm zone="libpq-exec-escape-string"> 4128 <primary>escaping strings</primary> 4129 <secondary>in libpq</secondary> 4130 </indexterm> 4131 4132 <variablelist> 4133 <varlistentry id="libpq-pqescapeliteral"> 4134 <term> 4135 <function>PQescapeLiteral</function> 4136 <indexterm> 4137 <primary>PQescapeLiteral</primary> 4138 </indexterm> 4139 </term> 4140 4141 <listitem> 4142 <para> 4143<synopsis> 4144char *PQescapeLiteral(PGconn *conn, const char *str, size_t length); 4145</synopsis> 4146 </para> 4147 4148 <para> 4149 <function>PQescapeLiteral</function> escapes a string for 4150 use within an SQL command. This is useful when inserting data 4151 values as literal constants in SQL commands. Certain characters 4152 (such as quotes and backslashes) must be escaped to prevent them 4153 from being interpreted specially by the SQL parser. 4154 <function>PQescapeLiteral</function> performs this operation. 4155 </para> 4156 4157 <para> 4158 <function>PQescapeLiteral</function> returns an escaped version of the 4159 <parameter>str</parameter> parameter in memory allocated with 4160 <function>malloc()</function>. This memory should be freed using 4161 <function>PQfreemem()</function> when the result is no longer needed. 4162 A terminating zero byte is not required, and should not be 4163 counted in <parameter>length</parameter>. (If a terminating zero byte is found 4164 before <parameter>length</parameter> bytes are processed, 4165 <function>PQescapeLiteral</function> stops at the zero; the behavior is 4166 thus rather like <function>strncpy</function>.) The 4167 return string has all special characters replaced so that they can 4168 be properly processed by the <productname>PostgreSQL</productname> 4169 string literal parser. A terminating zero byte is also added. The 4170 single quotes that must surround <productname>PostgreSQL</productname> 4171 string literals are included in the result string. 4172 </para> 4173 4174 <para> 4175 On error, <function>PQescapeLiteral</function> returns <symbol>NULL</symbol> and a suitable 4176 message is stored in the <parameter>conn</parameter> object. 4177 </para> 4178 4179 <tip> 4180 <para> 4181 It is especially important to do proper escaping when handling 4182 strings that were received from an untrustworthy source. 4183 Otherwise there is a security risk: you are vulnerable to 4184 <quote>SQL injection</quote> attacks wherein unwanted SQL commands are 4185 fed to your database. 4186 </para> 4187 </tip> 4188 4189 <para> 4190 Note that it is neither necessary nor correct to do escaping when a data 4191 value is passed as a separate parameter in <function>PQexecParams</function> or 4192 its sibling routines. 4193 </para> 4194 </listitem> 4195 </varlistentry> 4196 4197 <varlistentry id="libpq-pqescapeidentifier"> 4198 <term> 4199 <function>PQescapeIdentifier</function> 4200 <indexterm> 4201 <primary>PQescapeIdentifier</primary> 4202 </indexterm> 4203 </term> 4204 4205 <listitem> 4206 <para> 4207<synopsis> 4208char *PQescapeIdentifier(PGconn *conn, const char *str, size_t length); 4209</synopsis> 4210 </para> 4211 4212 <para> 4213 <function>PQescapeIdentifier</function> escapes a string for 4214 use as an SQL identifier, such as a table, column, or function name. 4215 This is useful when a user-supplied identifier might contain 4216 special characters that would otherwise not be interpreted as part 4217 of the identifier by the SQL parser, or when the identifier might 4218 contain upper case characters whose case should be preserved. 4219 </para> 4220 4221 <para> 4222 <function>PQescapeIdentifier</function> returns a version of the 4223 <parameter>str</parameter> parameter escaped as an SQL identifier 4224 in memory allocated with <function>malloc()</function>. This memory must be 4225 freed using <function>PQfreemem()</function> when the result is no longer 4226 needed. A terminating zero byte is not required, and should not be 4227 counted in <parameter>length</parameter>. (If a terminating zero byte is found 4228 before <parameter>length</parameter> bytes are processed, 4229 <function>PQescapeIdentifier</function> stops at the zero; the behavior is 4230 thus rather like <function>strncpy</function>.) The 4231 return string has all special characters replaced so that it 4232 will be properly processed as an SQL identifier. A terminating zero byte 4233 is also added. The return string will also be surrounded by double 4234 quotes. 4235 </para> 4236 4237 <para> 4238 On error, <function>PQescapeIdentifier</function> returns <symbol>NULL</symbol> and a suitable 4239 message is stored in the <parameter>conn</parameter> object. 4240 </para> 4241 4242 <tip> 4243 <para> 4244 As with string literals, to prevent SQL injection attacks, 4245 SQL identifiers must be escaped when they are received from an 4246 untrustworthy source. 4247 </para> 4248 </tip> 4249 </listitem> 4250 </varlistentry> 4251 4252 <varlistentry id="libpq-pqescapestringconn"> 4253 <term> 4254 <function>PQescapeStringConn</function> 4255 <indexterm> 4256 <primary>PQescapeStringConn</primary> 4257 </indexterm> 4258 </term> 4259 4260 <listitem> 4261 <para> 4262<synopsis> 4263size_t PQescapeStringConn(PGconn *conn, 4264 char *to, const char *from, size_t length, 4265 int *error); 4266</synopsis> 4267 </para> 4268 4269 <para> 4270 <function>PQescapeStringConn</function> escapes string literals, much like 4271 <function>PQescapeLiteral</function>. Unlike <function>PQescapeLiteral</function>, 4272 the caller is responsible for providing an appropriately sized buffer. 4273 Furthermore, <function>PQescapeStringConn</function> does not generate the 4274 single quotes that must surround <productname>PostgreSQL</productname> string 4275 literals; they should be provided in the SQL command that the 4276 result is inserted into. The parameter <parameter>from</parameter> points to 4277 the first character of the string that is to be escaped, and the 4278 <parameter>length</parameter> parameter gives the number of bytes in this 4279 string. A terminating zero byte is not required, and should not be 4280 counted in <parameter>length</parameter>. (If a terminating zero byte is found 4281 before <parameter>length</parameter> bytes are processed, 4282 <function>PQescapeStringConn</function> stops at the zero; the behavior is 4283 thus rather like <function>strncpy</function>.) <parameter>to</parameter> shall point 4284 to a buffer that is able to hold at least one more byte than twice 4285 the value of <parameter>length</parameter>, otherwise the behavior is undefined. 4286 Behavior is likewise undefined if the <parameter>to</parameter> and 4287 <parameter>from</parameter> strings overlap. 4288 </para> 4289 4290 <para> 4291 If the <parameter>error</parameter> parameter is not <symbol>NULL</symbol>, then 4292 <literal>*error</literal> is set to zero on success, nonzero on error. 4293 Presently the only possible error conditions involve invalid multibyte 4294 encoding in the source string. The output string is still generated 4295 on error, but it can be expected that the server will reject it as 4296 malformed. On error, a suitable message is stored in the 4297 <parameter>conn</parameter> object, whether or not <parameter>error</parameter> is <symbol>NULL</symbol>. 4298 </para> 4299 4300 <para> 4301 <function>PQescapeStringConn</function> returns the number of bytes written 4302 to <parameter>to</parameter>, not including the terminating zero byte. 4303 </para> 4304 </listitem> 4305 </varlistentry> 4306 4307 <varlistentry id="libpq-pqescapestring"> 4308 <term> 4309 <function>PQescapeString</function> 4310 <indexterm> 4311 <primary>PQescapeString</primary> 4312 </indexterm> 4313 </term> 4314 4315 <listitem> 4316 <para> 4317 <function>PQescapeString</function> is an older, deprecated version of 4318 <function>PQescapeStringConn</function>. 4319<synopsis> 4320size_t PQescapeString (char *to, const char *from, size_t length); 4321</synopsis> 4322 </para> 4323 4324 <para> 4325 The only difference from <function>PQescapeStringConn</function> is that 4326 <function>PQescapeString</function> does not take <structname>PGconn</structname> 4327 or <parameter>error</parameter> parameters. 4328 Because of this, it cannot adjust its behavior depending on the 4329 connection properties (such as character encoding) and therefore 4330 <emphasis>it might give the wrong results</emphasis>. Also, it has no way 4331 to report error conditions. 4332 </para> 4333 4334 <para> 4335 <function>PQescapeString</function> can be used safely in 4336 client programs that work with only one <productname>PostgreSQL</productname> 4337 connection at a time (in this case it can find out what it needs to 4338 know <quote>behind the scenes</quote>). In other contexts it is a security 4339 hazard and should be avoided in favor of 4340 <function>PQescapeStringConn</function>. 4341 </para> 4342 </listitem> 4343 </varlistentry> 4344 4345 <varlistentry id="libpq-pqescapebyteaconn"> 4346 <term> 4347 <function>PQescapeByteaConn</function> 4348 <indexterm> 4349 <primary>PQescapeByteaConn</primary> 4350 </indexterm> 4351 </term> 4352 4353 <listitem> 4354 <para> 4355 Escapes binary data for use within an SQL command with the type 4356 <type>bytea</type>. As with <function>PQescapeStringConn</function>, 4357 this is only used when inserting data directly into an SQL command string. 4358<synopsis> 4359unsigned char *PQescapeByteaConn(PGconn *conn, 4360 const unsigned char *from, 4361 size_t from_length, 4362 size_t *to_length); 4363</synopsis> 4364 </para> 4365 4366 <para> 4367 Certain byte values must be escaped when used as part of a 4368 <type>bytea</type> literal in an <acronym>SQL</acronym> statement. 4369 <function>PQescapeByteaConn</function> escapes bytes using 4370 either hex encoding or backslash escaping. See <xref 4371 linkend="datatype-binary"/> for more information. 4372 </para> 4373 4374 <para> 4375 The <parameter>from</parameter> parameter points to the first 4376 byte of the string that is to be escaped, and the 4377 <parameter>from_length</parameter> parameter gives the number of 4378 bytes in this binary string. (A terminating zero byte is 4379 neither necessary nor counted.) The <parameter>to_length</parameter> 4380 parameter points to a variable that will hold the resultant 4381 escaped string length. This result string length includes the terminating 4382 zero byte of the result. 4383 </para> 4384 4385 <para> 4386 <function>PQescapeByteaConn</function> returns an escaped version of the 4387 <parameter>from</parameter> parameter binary string in memory 4388 allocated with <function>malloc()</function>. This memory should be freed using 4389 <function>PQfreemem()</function> when the result is no longer needed. The 4390 return string has all special characters replaced so that they can 4391 be properly processed by the <productname>PostgreSQL</productname> 4392 string literal parser, and the <type>bytea</type> input function. A 4393 terminating zero byte is also added. The single quotes that must 4394 surround <productname>PostgreSQL</productname> string literals are 4395 not part of the result string. 4396 </para> 4397 4398 <para> 4399 On error, a null pointer is returned, and a suitable error message 4400 is stored in the <parameter>conn</parameter> object. Currently, the only 4401 possible error is insufficient memory for the result string. 4402 </para> 4403 </listitem> 4404 </varlistentry> 4405 4406 <varlistentry id="libpq-pqescapebytea"> 4407 <term> 4408 <function>PQescapeBytea</function> 4409 <indexterm> 4410 <primary>PQescapeBytea</primary> 4411 </indexterm> 4412 </term> 4413 4414 <listitem> 4415 <para> 4416 <function>PQescapeBytea</function> is an older, deprecated version of 4417 <function>PQescapeByteaConn</function>. 4418<synopsis> 4419unsigned char *PQescapeBytea(const unsigned char *from, 4420 size_t from_length, 4421 size_t *to_length); 4422</synopsis> 4423 </para> 4424 4425 <para> 4426 The only difference from <function>PQescapeByteaConn</function> is that 4427 <function>PQescapeBytea</function> does not take a <structname>PGconn</structname> 4428 parameter. Because of this, <function>PQescapeBytea</function> can 4429 only be used safely in client programs that use a single 4430 <productname>PostgreSQL</productname> connection at a time (in this case 4431 it can find out what it needs to know <quote>behind the 4432 scenes</quote>). It <emphasis>might give the wrong results</emphasis> if 4433 used in programs that use multiple database connections (use 4434 <function>PQescapeByteaConn</function> in such cases). 4435 </para> 4436 </listitem> 4437 </varlistentry> 4438 4439 <varlistentry id="libpq-pqunescapebytea"> 4440 <term> 4441 <function>PQunescapeBytea</function> 4442 <indexterm> 4443 <primary>PQunescapeBytea</primary> 4444 </indexterm> 4445 </term> 4446 4447 <listitem> 4448 <para> 4449 Converts a string representation of binary data into binary data 4450 — the reverse of <function>PQescapeBytea</function>. This 4451 is needed when retrieving <type>bytea</type> data in text format, 4452 but not when retrieving it in binary format. 4453 4454<synopsis> 4455unsigned char *PQunescapeBytea(const unsigned char *from, size_t *to_length); 4456</synopsis> 4457 </para> 4458 4459 <para> 4460 The <parameter>from</parameter> parameter points to a string 4461 such as might be returned by <function>PQgetvalue</function> when applied 4462 to a <type>bytea</type> column. <function>PQunescapeBytea</function> 4463 converts this string representation into its binary representation. 4464 It returns a pointer to a buffer allocated with 4465 <function>malloc()</function>, or <symbol>NULL</symbol> on error, and puts the size of 4466 the buffer in <parameter>to_length</parameter>. The result must be 4467 freed using <function>PQfreemem</function> when it is no longer needed. 4468 </para> 4469 4470 <para> 4471 This conversion is not exactly the inverse of 4472 <function>PQescapeBytea</function>, because the string is not expected 4473 to be <quote>escaped</quote> when received from <function>PQgetvalue</function>. 4474 In particular this means there is no need for string quoting considerations, 4475 and so no need for a <structname>PGconn</structname> parameter. 4476 </para> 4477 </listitem> 4478 </varlistentry> 4479 </variablelist> 4480 4481 </sect2> 4482 4483 </sect1> 4484 4485 <sect1 id="libpq-async"> 4486 <title>Asynchronous Command Processing</title> 4487 4488 <indexterm zone="libpq-async"> 4489 <primary>nonblocking connection</primary> 4490 </indexterm> 4491 4492 <para> 4493 The <function>PQexec</function> function is adequate for submitting 4494 commands in normal, synchronous applications. It has a few 4495 deficiencies, however, that can be of importance to some users: 4496 4497 <itemizedlist> 4498 <listitem> 4499 <para> 4500 <function>PQexec</function> waits for the command to be completed. 4501 The application might have other work to do (such as maintaining a 4502 user interface), in which case it won't want to block waiting for 4503 the response. 4504 </para> 4505 </listitem> 4506 4507 <listitem> 4508 <para> 4509 Since the execution of the client application is suspended while it 4510 waits for the result, it is hard for the application to decide that 4511 it would like to try to cancel the ongoing command. (It can be done 4512 from a signal handler, but not otherwise.) 4513 </para> 4514 </listitem> 4515 4516 <listitem> 4517 <para> 4518 <function>PQexec</function> can return only one 4519 <structname>PGresult</structname> structure. If the submitted command 4520 string contains multiple <acronym>SQL</acronym> commands, all but 4521 the last <structname>PGresult</structname> are discarded by 4522 <function>PQexec</function>. 4523 </para> 4524 </listitem> 4525 4526 <listitem> 4527 <para> 4528 <function>PQexec</function> always collects the command's entire result, 4529 buffering it in a single <structname>PGresult</structname>. While 4530 this simplifies error-handling logic for the application, it can be 4531 impractical for results containing many rows. 4532 </para> 4533 </listitem> 4534 </itemizedlist> 4535 </para> 4536 4537 <para> 4538 Applications that do not like these limitations can instead use the 4539 underlying functions that <function>PQexec</function> is built from: 4540 <function>PQsendQuery</function> and <function>PQgetResult</function>. 4541 There are also 4542 <function>PQsendQueryParams</function>, 4543 <function>PQsendPrepare</function>, 4544 <function>PQsendQueryPrepared</function>, 4545 <function>PQsendDescribePrepared</function>, and 4546 <function>PQsendDescribePortal</function>, 4547 which can be used with <function>PQgetResult</function> to duplicate 4548 the functionality of 4549 <function>PQexecParams</function>, 4550 <function>PQprepare</function>, 4551 <function>PQexecPrepared</function>, 4552 <function>PQdescribePrepared</function>, and 4553 <function>PQdescribePortal</function> 4554 respectively. 4555 4556 <variablelist> 4557 <varlistentry id="libpq-pqsendquery"> 4558 <term> 4559 <function>PQsendQuery</function> 4560 <indexterm> 4561 <primary>PQsendQuery</primary> 4562 </indexterm> 4563 </term> 4564 4565 <listitem> 4566 <para> 4567 Submits a command to the server without waiting for the result(s). 4568 1 is returned if the command was successfully dispatched and 0 if 4569 not (in which case, use <function>PQerrorMessage</function> to get more 4570 information about the failure). 4571<synopsis> 4572int PQsendQuery(PGconn *conn, const char *command); 4573</synopsis> 4574 4575 After successfully calling <function>PQsendQuery</function>, call 4576 <function>PQgetResult</function> one or more times to obtain the 4577 results. <function>PQsendQuery</function> cannot be called again 4578 (on the same connection) until <function>PQgetResult</function> 4579 has returned a null pointer, indicating that the command is done. 4580 </para> 4581 </listitem> 4582 </varlistentry> 4583 4584 <varlistentry id="libpq-pqsendqueryparams"> 4585 <term> 4586 <function>PQsendQueryParams</function> 4587 <indexterm> 4588 <primary>PQsendQueryParams</primary> 4589 </indexterm> 4590 </term> 4591 4592 <listitem> 4593 <para> 4594 Submits a command and separate parameters to the server without 4595 waiting for the result(s). 4596<synopsis> 4597int PQsendQueryParams(PGconn *conn, 4598 const char *command, 4599 int nParams, 4600 const Oid *paramTypes, 4601 const char * const *paramValues, 4602 const int *paramLengths, 4603 const int *paramFormats, 4604 int resultFormat); 4605</synopsis> 4606 4607 This is equivalent to <function>PQsendQuery</function> except that 4608 query parameters can be specified separately from the query string. 4609 The function's parameters are handled identically to 4610 <function>PQexecParams</function>. Like 4611 <function>PQexecParams</function>, it will not work on 2.0-protocol 4612 connections, and it allows only one command in the query string. 4613 </para> 4614 </listitem> 4615 </varlistentry> 4616 4617 <varlistentry id="libpq-pqsendprepare"> 4618 <term> 4619 <function>PQsendPrepare</function> 4620 <indexterm> 4621 <primary>PQsendPrepare</primary> 4622 </indexterm> 4623 </term> 4624 4625 <listitem> 4626 <para> 4627 Sends a request to create a prepared statement with the given 4628 parameters, without waiting for completion. 4629<synopsis> 4630int PQsendPrepare(PGconn *conn, 4631 const char *stmtName, 4632 const char *query, 4633 int nParams, 4634 const Oid *paramTypes); 4635</synopsis> 4636 4637 This is an asynchronous version of <function>PQprepare</function>: it 4638 returns 1 if it was able to dispatch the request, and 0 if not. 4639 After a successful call, call <function>PQgetResult</function> to 4640 determine whether the server successfully created the prepared 4641 statement. The function's parameters are handled identically to 4642 <function>PQprepare</function>. Like 4643 <function>PQprepare</function>, it will not work on 2.0-protocol 4644 connections. 4645 </para> 4646 </listitem> 4647 </varlistentry> 4648 4649 <varlistentry id="libpq-pqsendqueryprepared"> 4650 <term> 4651 <function>PQsendQueryPrepared</function> 4652 <indexterm> 4653 <primary>PQsendQueryPrepared</primary> 4654 </indexterm> 4655 </term> 4656 4657 <listitem> 4658 <para> 4659 Sends a request to execute a prepared statement with given 4660 parameters, without waiting for the result(s). 4661<synopsis> 4662int PQsendQueryPrepared(PGconn *conn, 4663 const char *stmtName, 4664 int nParams, 4665 const char * const *paramValues, 4666 const int *paramLengths, 4667 const int *paramFormats, 4668 int resultFormat); 4669</synopsis> 4670 4671 This is similar to <function>PQsendQueryParams</function>, but 4672 the command to be executed is specified by naming a 4673 previously-prepared statement, instead of giving a query string. 4674 The function's parameters are handled identically to 4675 <function>PQexecPrepared</function>. Like 4676 <function>PQexecPrepared</function>, it will not work on 4677 2.0-protocol connections. 4678 </para> 4679 </listitem> 4680 </varlistentry> 4681 4682 <varlistentry id="libpq-pqsenddescribeprepared"> 4683 <term> 4684 <function>PQsendDescribePrepared</function> 4685 <indexterm> 4686 <primary>PQsendDescribePrepared</primary> 4687 </indexterm> 4688 </term> 4689 4690 <listitem> 4691 <para> 4692 Submits a request to obtain information about the specified 4693 prepared statement, without waiting for completion. 4694<synopsis> 4695int PQsendDescribePrepared(PGconn *conn, const char *stmtName); 4696</synopsis> 4697 4698 This is an asynchronous version of <function>PQdescribePrepared</function>: 4699 it returns 1 if it was able to dispatch the request, and 0 if not. 4700 After a successful call, call <function>PQgetResult</function> to 4701 obtain the results. The function's parameters are handled 4702 identically to <function>PQdescribePrepared</function>. Like 4703 <function>PQdescribePrepared</function>, it will not work on 4704 2.0-protocol connections. 4705 </para> 4706 </listitem> 4707 </varlistentry> 4708 4709 <varlistentry id="libpq-pqsenddescribeportal"> 4710 <term> 4711 <function>PQsendDescribePortal</function> 4712 <indexterm> 4713 <primary>PQsendDescribePortal</primary> 4714 </indexterm> 4715 </term> 4716 4717 <listitem> 4718 <para> 4719 Submits a request to obtain information about the specified 4720 portal, without waiting for completion. 4721<synopsis> 4722int PQsendDescribePortal(PGconn *conn, const char *portalName); 4723</synopsis> 4724 4725 This is an asynchronous version of <function>PQdescribePortal</function>: 4726 it returns 1 if it was able to dispatch the request, and 0 if not. 4727 After a successful call, call <function>PQgetResult</function> to 4728 obtain the results. The function's parameters are handled 4729 identically to <function>PQdescribePortal</function>. Like 4730 <function>PQdescribePortal</function>, it will not work on 4731 2.0-protocol connections. 4732 </para> 4733 </listitem> 4734 </varlistentry> 4735 4736 <varlistentry id="libpq-pqgetresult"> 4737 <term> 4738 <function>PQgetResult</function> 4739 <indexterm> 4740 <primary>PQgetResult</primary> 4741 </indexterm> 4742 </term> 4743 4744 <listitem> 4745 <para> 4746 Waits for the next result from a prior 4747 <function>PQsendQuery</function>, 4748 <function>PQsendQueryParams</function>, 4749 <function>PQsendPrepare</function>, 4750 <function>PQsendQueryPrepared</function>, 4751 <function>PQsendDescribePrepared</function>, or 4752 <function>PQsendDescribePortal</function> 4753 call, and returns it. 4754 A null pointer is returned when the command is complete and there 4755 will be no more results. 4756<synopsis> 4757PGresult *PQgetResult(PGconn *conn); 4758</synopsis> 4759 </para> 4760 4761 <para> 4762 <function>PQgetResult</function> must be called repeatedly until 4763 it returns a null pointer, indicating that the command is done. 4764 (If called when no command is active, 4765 <function>PQgetResult</function> will just return a null pointer 4766 at once.) Each non-null result from 4767 <function>PQgetResult</function> should be processed using the 4768 same <structname>PGresult</structname> accessor functions previously 4769 described. Don't forget to free each result object with 4770 <function>PQclear</function> when done with it. Note that 4771 <function>PQgetResult</function> will block only if a command is 4772 active and the necessary response data has not yet been read by 4773 <function>PQconsumeInput</function>. 4774 </para> 4775 4776 <note> 4777 <para> 4778 Even when <function>PQresultStatus</function> indicates a fatal 4779 error, <function>PQgetResult</function> should be called until it 4780 returns a null pointer, to allow <application>libpq</application> to 4781 process the error information completely. 4782 </para> 4783 </note> 4784 </listitem> 4785 </varlistentry> 4786 </variablelist> 4787 </para> 4788 4789 <para> 4790 Using <function>PQsendQuery</function> and 4791 <function>PQgetResult</function> solves one of 4792 <function>PQexec</function>'s problems: If a command string contains 4793 multiple <acronym>SQL</acronym> commands, the results of those commands 4794 can be obtained individually. (This allows a simple form of overlapped 4795 processing, by the way: the client can be handling the results of one 4796 command while the server is still working on later queries in the same 4797 command string.) 4798 </para> 4799 4800 <para> 4801 Another frequently-desired feature that can be obtained with 4802 <function>PQsendQuery</function> and <function>PQgetResult</function> 4803 is retrieving large query results a row at a time. This is discussed 4804 in <xref linkend="libpq-single-row-mode"/>. 4805 </para> 4806 4807 <para> 4808 By itself, calling <function>PQgetResult</function> 4809 will still cause the client to block until the server completes the 4810 next <acronym>SQL</acronym> command. This can be avoided by proper 4811 use of two more functions: 4812 4813 <variablelist> 4814 <varlistentry id="libpq-pqconsumeinput"> 4815 <term> 4816 <function>PQconsumeInput</function> 4817 <indexterm> 4818 <primary>PQconsumeInput</primary> 4819 </indexterm> 4820 </term> 4821 4822 <listitem> 4823 <para> 4824 If input is available from the server, consume it. 4825<synopsis> 4826int PQconsumeInput(PGconn *conn); 4827</synopsis> 4828 </para> 4829 4830 <para> 4831 <function>PQconsumeInput</function> normally returns 1 indicating 4832 <quote>no error</quote>, but returns 0 if there was some kind of 4833 trouble (in which case <function>PQerrorMessage</function> can be 4834 consulted). Note that the result does not say whether any input 4835 data was actually collected. After calling 4836 <function>PQconsumeInput</function>, the application can check 4837 <function>PQisBusy</function> and/or 4838 <function>PQnotifies</function> to see if their state has changed. 4839 </para> 4840 4841 <para> 4842 <function>PQconsumeInput</function> can be called even if the 4843 application is not prepared to deal with a result or notification 4844 just yet. The function will read available data and save it in 4845 a buffer, thereby causing a <function>select()</function> 4846 read-ready indication to go away. The application can thus use 4847 <function>PQconsumeInput</function> to clear the 4848 <function>select()</function> condition immediately, and then 4849 examine the results at leisure. 4850 </para> 4851 </listitem> 4852 </varlistentry> 4853 4854 <varlistentry id="libpq-pqisbusy"> 4855 <term> 4856 <function>PQisBusy</function> 4857 <indexterm> 4858 <primary>PQisBusy</primary> 4859 </indexterm> 4860 </term> 4861 4862 <listitem> 4863 <para> 4864 Returns 1 if a command is busy, that is, 4865 <function>PQgetResult</function> would block waiting for input. 4866 A 0 return indicates that <function>PQgetResult</function> can be 4867 called with assurance of not blocking. 4868<synopsis> 4869int PQisBusy(PGconn *conn); 4870</synopsis> 4871 </para> 4872 4873 <para> 4874 <function>PQisBusy</function> will not itself attempt to read data 4875 from the server; therefore <function>PQconsumeInput</function> 4876 must be invoked first, or the busy state will never end. 4877 </para> 4878 </listitem> 4879 </varlistentry> 4880 </variablelist> 4881 </para> 4882 4883 <para> 4884 A typical application using these functions will have a main loop that 4885 uses <function>select()</function> or <function>poll()</function> to wait for 4886 all the conditions that it must respond to. One of the conditions 4887 will be input available from the server, which in terms of 4888 <function>select()</function> means readable data on the file 4889 descriptor identified by <function>PQsocket</function>. When the main 4890 loop detects input ready, it should call 4891 <function>PQconsumeInput</function> to read the input. It can then 4892 call <function>PQisBusy</function>, followed by 4893 <function>PQgetResult</function> if <function>PQisBusy</function> 4894 returns false (0). It can also call <function>PQnotifies</function> 4895 to detect <command>NOTIFY</command> messages (see <xref 4896 linkend="libpq-notify"/>). 4897 </para> 4898 4899 <para> 4900 A client that uses 4901 <function>PQsendQuery</function>/<function>PQgetResult</function> 4902 can also attempt to cancel a command that is still being processed 4903 by the server; see <xref linkend="libpq-cancel"/>. But regardless of 4904 the return value of <function>PQcancel</function>, the application 4905 must continue with the normal result-reading sequence using 4906 <function>PQgetResult</function>. A successful cancellation will 4907 simply cause the command to terminate sooner than it would have 4908 otherwise. 4909 </para> 4910 4911 <para> 4912 By using the functions described above, it is possible to avoid 4913 blocking while waiting for input from the database server. However, 4914 it is still possible that the application will block waiting to send 4915 output to the server. This is relatively uncommon but can happen if 4916 very long SQL commands or data values are sent. (It is much more 4917 probable if the application sends data via <command>COPY IN</command>, 4918 however.) To prevent this possibility and achieve completely 4919 nonblocking database operation, the following additional functions 4920 can be used. 4921 4922 <variablelist> 4923 <varlistentry id="libpq-pqsetnonblocking"> 4924 <term> 4925 <function>PQsetnonblocking</function> 4926 <indexterm> 4927 <primary>PQsetnonblocking</primary> 4928 </indexterm> 4929 </term> 4930 4931 <listitem> 4932 <para> 4933 Sets the nonblocking status of the connection. 4934<synopsis> 4935int PQsetnonblocking(PGconn *conn, int arg); 4936</synopsis> 4937 </para> 4938 4939 <para> 4940 Sets the state of the connection to nonblocking if 4941 <parameter>arg</parameter> is 1, or blocking if 4942 <parameter>arg</parameter> is 0. Returns 0 if OK, -1 if error. 4943 </para> 4944 4945 <para> 4946 In the nonblocking state, calls to 4947 <function>PQsendQuery</function>, <function>PQputline</function>, 4948 <function>PQputnbytes</function>, <function>PQputCopyData</function>, 4949 and <function>PQendcopy</function> will not block but instead return 4950 an error if they need to be called again. 4951 </para> 4952 4953 <para> 4954 Note that <function>PQexec</function> does not honor nonblocking 4955 mode; if it is called, it will act in blocking fashion anyway. 4956 </para> 4957 </listitem> 4958 </varlistentry> 4959 4960 <varlistentry id="libpq-pqisnonblocking"> 4961 <term> 4962 <function>PQisnonblocking</function> 4963 <indexterm> 4964 <primary>PQisnonblocking</primary> 4965 </indexterm> 4966 </term> 4967 4968 <listitem> 4969 <para> 4970 Returns the blocking status of the database connection. 4971<synopsis> 4972int PQisnonblocking(const PGconn *conn); 4973</synopsis> 4974 </para> 4975 4976 <para> 4977 Returns 1 if the connection is set to nonblocking mode and 0 if 4978 blocking. 4979 </para> 4980 </listitem> 4981 </varlistentry> 4982 4983 <varlistentry id="libpq-pqflush"> 4984 <term> 4985 <function>PQflush</function> 4986 <indexterm> 4987 <primary>PQflush</primary> 4988 </indexterm> 4989 </term> 4990 4991 <listitem> 4992 <para> 4993 Attempts to flush any queued output data to the server. Returns 4994 0 if successful (or if the send queue is empty), -1 if it failed 4995 for some reason, or 1 if it was unable to send all the data in 4996 the send queue yet (this case can only occur if the connection 4997 is nonblocking). 4998<synopsis> 4999int PQflush(PGconn *conn); 5000</synopsis> 5001 </para> 5002 </listitem> 5003 </varlistentry> 5004 </variablelist> 5005 </para> 5006 5007 <para> 5008 After sending any command or data on a nonblocking connection, call 5009 <function>PQflush</function>. If it returns 1, wait for the socket 5010 to become read- or write-ready. If it becomes write-ready, call 5011 <function>PQflush</function> again. If it becomes read-ready, call 5012 <function>PQconsumeInput</function>, then call 5013 <function>PQflush</function> again. Repeat until 5014 <function>PQflush</function> returns 0. (It is necessary to check for 5015 read-ready and drain the input with <function>PQconsumeInput</function>, 5016 because the server can block trying to send us data, e.g., NOTICE 5017 messages, and won't read our data until we read its.) Once 5018 <function>PQflush</function> returns 0, wait for the socket to be 5019 read-ready and then read the response as described above. 5020 </para> 5021 5022 </sect1> 5023 5024 <sect1 id="libpq-single-row-mode"> 5025 <title>Retrieving Query Results Row-by-Row</title> 5026 5027 <indexterm zone="libpq-single-row-mode"> 5028 <primary>libpq</primary> 5029 <secondary>single-row mode</secondary> 5030 </indexterm> 5031 5032 <para> 5033 Ordinarily, <application>libpq</application> collects a SQL command's 5034 entire result and returns it to the application as a single 5035 <structname>PGresult</structname>. This can be unworkable for commands 5036 that return a large number of rows. For such cases, applications can use 5037 <function>PQsendQuery</function> and <function>PQgetResult</function> in 5038 <firstterm>single-row mode</firstterm>. In this mode, the result row(s) are 5039 returned to the application one at a time, as they are received from the 5040 server. 5041 </para> 5042 5043 <para> 5044 To enter single-row mode, call <function>PQsetSingleRowMode</function> 5045 immediately after a successful call of <function>PQsendQuery</function> 5046 (or a sibling function). This mode selection is effective only for the 5047 currently executing query. Then call <function>PQgetResult</function> 5048 repeatedly, until it returns null, as documented in <xref 5049 linkend="libpq-async"/>. If the query returns any rows, they are returned 5050 as individual <structname>PGresult</structname> objects, which look like 5051 normal query results except for having status code 5052 <literal>PGRES_SINGLE_TUPLE</literal> instead of 5053 <literal>PGRES_TUPLES_OK</literal>. After the last row, or immediately if 5054 the query returns zero rows, a zero-row object with status 5055 <literal>PGRES_TUPLES_OK</literal> is returned; this is the signal that no 5056 more rows will arrive. (But note that it is still necessary to continue 5057 calling <function>PQgetResult</function> until it returns null.) All of 5058 these <structname>PGresult</structname> objects will contain the same row 5059 description data (column names, types, etc) that an ordinary 5060 <structname>PGresult</structname> object for the query would have. 5061 Each object should be freed with <function>PQclear</function> as usual. 5062 </para> 5063 5064 <para> 5065 <variablelist> 5066 <varlistentry id="libpq-pqsetsinglerowmode"> 5067 <term> 5068 <function>PQsetSingleRowMode</function> 5069 <indexterm> 5070 <primary>PQsetSingleRowMode</primary> 5071 </indexterm> 5072 </term> 5073 5074 <listitem> 5075 <para> 5076 Select single-row mode for the currently-executing query. 5077 5078<synopsis> 5079int PQsetSingleRowMode(PGconn *conn); 5080</synopsis> 5081 </para> 5082 5083 <para> 5084 This function can only be called immediately after 5085 <function>PQsendQuery</function> or one of its sibling functions, 5086 before any other operation on the connection such as 5087 <function>PQconsumeInput</function> or 5088 <function>PQgetResult</function>. If called at the correct time, 5089 the function activates single-row mode for the current query and 5090 returns 1. Otherwise the mode stays unchanged and the function 5091 returns 0. In any case, the mode reverts to normal after 5092 completion of the current query. 5093 </para> 5094 </listitem> 5095 </varlistentry> 5096 </variablelist> 5097 </para> 5098 5099 <caution> 5100 <para> 5101 While processing a query, the server may return some rows and then 5102 encounter an error, causing the query to be aborted. Ordinarily, 5103 <application>libpq</application> discards any such rows and reports only the 5104 error. But in single-row mode, those rows will have already been 5105 returned to the application. Hence, the application will see some 5106 <literal>PGRES_SINGLE_TUPLE</literal> <structname>PGresult</structname> 5107 objects followed by a <literal>PGRES_FATAL_ERROR</literal> object. For 5108 proper transactional behavior, the application must be designed to 5109 discard or undo whatever has been done with the previously-processed 5110 rows, if the query ultimately fails. 5111 </para> 5112 </caution> 5113 5114 </sect1> 5115 5116 <sect1 id="libpq-cancel"> 5117 <title>Canceling Queries in Progress</title> 5118 5119 <indexterm zone="libpq-cancel"> 5120 <primary>canceling</primary> 5121 <secondary>SQL command</secondary> 5122 </indexterm> 5123 5124 <para> 5125 A client application can request cancellation of a command that is 5126 still being processed by the server, using the functions described in 5127 this section. 5128 5129 <variablelist> 5130 <varlistentry id="libpq-pqgetcancel"> 5131 <term> 5132 <function>PQgetCancel</function> 5133 <indexterm> 5134 <primary>PQgetCancel</primary> 5135 </indexterm> 5136 </term> 5137 5138 <listitem> 5139 <para> 5140 Creates a data structure containing the information needed to cancel 5141 a command issued through a particular database connection. 5142<synopsis> 5143PGcancel *PQgetCancel(PGconn *conn); 5144</synopsis> 5145 </para> 5146 5147 <para> 5148 <function>PQgetCancel</function> creates a 5149 <structname>PGcancel</structname><indexterm><primary>PGcancel</primary></indexterm> object 5150 given a <structname>PGconn</structname> connection object. It will return 5151 <symbol>NULL</symbol> if the given <parameter>conn</parameter> is <symbol>NULL</symbol> or an invalid 5152 connection. The <structname>PGcancel</structname> object is an opaque 5153 structure that is not meant to be accessed directly by the 5154 application; it can only be passed to <function>PQcancel</function> 5155 or <function>PQfreeCancel</function>. 5156 </para> 5157 </listitem> 5158 </varlistentry> 5159 5160 <varlistentry id="libpq-pqfreecancel"> 5161 <term> 5162 <function>PQfreeCancel</function> 5163 <indexterm> 5164 <primary>PQfreeCancel</primary> 5165 </indexterm> 5166 </term> 5167 5168 <listitem> 5169 <para> 5170 Frees a data structure created by <function>PQgetCancel</function>. 5171<synopsis> 5172void PQfreeCancel(PGcancel *cancel); 5173</synopsis> 5174 </para> 5175 5176 <para> 5177 <function>PQfreeCancel</function> frees a data object previously created 5178 by <function>PQgetCancel</function>. 5179 </para> 5180 </listitem> 5181 </varlistentry> 5182 5183 <varlistentry id="libpq-pqcancel"> 5184 <term> 5185 <function>PQcancel</function> 5186 <indexterm> 5187 <primary>PQcancel</primary> 5188 </indexterm> 5189 </term> 5190 5191 <listitem> 5192 <para> 5193 Requests that the server abandon processing of the current command. 5194<synopsis> 5195int PQcancel(PGcancel *cancel, char *errbuf, int errbufsize); 5196</synopsis> 5197 </para> 5198 5199 <para> 5200 The return value is 1 if the cancel request was successfully 5201 dispatched and 0 if not. If not, <parameter>errbuf</parameter> is filled 5202 with an explanatory error message. <parameter>errbuf</parameter> 5203 must be a char array of size <parameter>errbufsize</parameter> (the 5204 recommended size is 256 bytes). 5205 </para> 5206 5207 <para> 5208 Successful dispatch is no guarantee that the request will have 5209 any effect, however. If the cancellation is effective, the current 5210 command will terminate early and return an error result. If the 5211 cancellation fails (say, because the server was already done 5212 processing the command), then there will be no visible result at 5213 all. 5214 </para> 5215 5216 <para> 5217 <function>PQcancel</function> can safely be invoked from a signal 5218 handler, if the <parameter>errbuf</parameter> is a local variable in the 5219 signal handler. The <structname>PGcancel</structname> object is read-only 5220 as far as <function>PQcancel</function> is concerned, so it can 5221 also be invoked from a thread that is separate from the one 5222 manipulating the <structname>PGconn</structname> object. 5223 </para> 5224 </listitem> 5225 </varlistentry> 5226 </variablelist> 5227 5228 <variablelist> 5229 <varlistentry id="libpq-pqrequestcancel"> 5230 <term> 5231 <function>PQrequestCancel</function> 5232 <indexterm> 5233 <primary>PQrequestCancel</primary> 5234 </indexterm> 5235 </term> 5236 5237 <listitem> 5238 <para> 5239 <function>PQrequestCancel</function> is a deprecated variant of 5240 <function>PQcancel</function>. 5241<synopsis> 5242int PQrequestCancel(PGconn *conn); 5243</synopsis> 5244 </para> 5245 5246 <para> 5247 Requests that the server abandon processing of the current 5248 command. It operates directly on the 5249 <structname>PGconn</structname> object, and in case of failure stores the 5250 error message in the <structname>PGconn</structname> object (whence it can 5251 be retrieved by <function>PQerrorMessage</function>). Although 5252 the functionality is the same, this approach creates hazards for 5253 multiple-thread programs and signal handlers, since it is possible 5254 that overwriting the <structname>PGconn</structname>'s error message will 5255 mess up the operation currently in progress on the connection. 5256 </para> 5257 </listitem> 5258 </varlistentry> 5259 </variablelist> 5260 </para> 5261 5262 </sect1> 5263 5264 <sect1 id="libpq-fastpath"> 5265 <title>The Fast-Path Interface</title> 5266 5267 <indexterm zone="libpq-fastpath"> 5268 <primary>fast path</primary> 5269 </indexterm> 5270 5271 <para> 5272 <productname>PostgreSQL</productname> provides a fast-path interface 5273 to send simple function calls to the server. 5274 </para> 5275 5276 <tip> 5277 <para> 5278 This interface is somewhat obsolete, as one can achieve similar 5279 performance and greater functionality by setting up a prepared 5280 statement to define the function call. Then, executing the statement 5281 with binary transmission of parameters and results substitutes for a 5282 fast-path function call. 5283 </para> 5284 </tip> 5285 5286 <para> 5287 The function <function>PQfn</function><indexterm><primary>PQfn</primary></indexterm> 5288 requests execution of a server function via the fast-path interface: 5289<synopsis> 5290PGresult *PQfn(PGconn *conn, 5291 int fnid, 5292 int *result_buf, 5293 int *result_len, 5294 int result_is_int, 5295 const PQArgBlock *args, 5296 int nargs); 5297 5298typedef struct 5299{ 5300 int len; 5301 int isint; 5302 union 5303 { 5304 int *ptr; 5305 int integer; 5306 } u; 5307} PQArgBlock; 5308</synopsis> 5309 </para> 5310 5311 <para> 5312 The <parameter>fnid</parameter> argument is the OID of the function to be 5313 executed. <parameter>args</parameter> and <parameter>nargs</parameter> define the 5314 parameters to be passed to the function; they must match the declared 5315 function argument list. When the <parameter>isint</parameter> field of a 5316 parameter structure is true, the <parameter>u.integer</parameter> value is sent 5317 to the server as an integer of the indicated length (this must be 5318 2 or 4 bytes); proper byte-swapping occurs. When <parameter>isint</parameter> 5319 is false, the indicated number of bytes at <parameter>*u.ptr</parameter> are 5320 sent with no processing; the data must be in the format expected by 5321 the server for binary transmission of the function's argument data 5322 type. (The declaration of <parameter>u.ptr</parameter> as being of 5323 type <type>int *</type> is historical; it would be better to consider 5324 it <type>void *</type>.) 5325 <parameter>result_buf</parameter> points to the buffer in which to place 5326 the function's return value. The caller must have allocated sufficient 5327 space to store the return value. (There is no check!) The actual result 5328 length in bytes will be returned in the integer pointed to by 5329 <parameter>result_len</parameter>. If a 2- or 4-byte integer result 5330 is expected, set <parameter>result_is_int</parameter> to 1, otherwise 5331 set it to 0. Setting <parameter>result_is_int</parameter> to 1 causes 5332 <application>libpq</application> to byte-swap the value if necessary, so that it 5333 is delivered as a proper <type>int</type> value for the client machine; 5334 note that a 4-byte integer is delivered into <parameter>*result_buf</parameter> 5335 for either allowed result size. 5336 When <parameter>result_is_int</parameter> is 0, the binary-format byte string 5337 sent by the server is returned unmodified. (In this case it's better 5338 to consider <parameter>result_buf</parameter> as being of 5339 type <type>void *</type>.) 5340 </para> 5341 5342 <para> 5343 <function>PQfn</function> always returns a valid 5344 <structname>PGresult</structname> pointer, with 5345 status <literal>PGRES_COMMAND_OK</literal> for success 5346 or <literal>PGRES_FATAL_ERROR</literal> if some problem was encountered. 5347 The result status should be 5348 checked before the result is used. The caller is responsible for 5349 freeing the <structname>PGresult</structname> with 5350 <function>PQclear</function> when it is no longer needed. 5351 </para> 5352 5353 <para> 5354 To pass a NULL argument to the function, set 5355 the <parameter>len</parameter> field of that parameter structure 5356 to <literal>-1</literal>; the <parameter>isint</parameter> 5357 and <parameter>u</parameter> fields are then irrelevant. 5358 (But this works only in protocol 3.0 and later connections.) 5359 </para> 5360 5361 <para> 5362 If the function returns NULL, <parameter>*result_len</parameter> is set 5363 to <literal>-1</literal>, and <parameter>*result_buf</parameter> is not 5364 modified. (This works only in protocol 3.0 and later connections; in 5365 protocol 2.0, neither <parameter>*result_len</parameter> 5366 nor <parameter>*result_buf</parameter> are modified.) 5367 </para> 5368 5369 <para> 5370 Note that it is not possible to handle set-valued results when using 5371 this interface. Also, the function must be a plain function, not an 5372 aggregate, window function, or procedure. 5373 </para> 5374 5375 </sect1> 5376 5377 <sect1 id="libpq-notify"> 5378 <title>Asynchronous Notification</title> 5379 5380 <indexterm zone="libpq-notify"> 5381 <primary>NOTIFY</primary> 5382 <secondary>in libpq</secondary> 5383 </indexterm> 5384 5385 <para> 5386 <productname>PostgreSQL</productname> offers asynchronous notification 5387 via the <command>LISTEN</command> and <command>NOTIFY</command> 5388 commands. A client session registers its interest in a particular 5389 notification channel with the <command>LISTEN</command> command (and 5390 can stop listening with the <command>UNLISTEN</command> command). All 5391 sessions listening on a particular channel will be notified 5392 asynchronously when a <command>NOTIFY</command> command with that 5393 channel name is executed by any session. A <quote>payload</quote> string can 5394 be passed to communicate additional data to the listeners. 5395 </para> 5396 5397 <para> 5398 <application>libpq</application> applications submit 5399 <command>LISTEN</command>, <command>UNLISTEN</command>, 5400 and <command>NOTIFY</command> commands as 5401 ordinary SQL commands. The arrival of <command>NOTIFY</command> 5402 messages can subsequently be detected by calling 5403 <function>PQnotifies</function>.<indexterm><primary>PQnotifies</primary></indexterm> 5404 </para> 5405 5406 <para> 5407 The function <function>PQnotifies</function> returns the next notification 5408 from a list of unhandled notification messages received from the server. 5409 It returns a null pointer if there are no pending notifications. Once a 5410 notification is returned from <function>PQnotifies</function>, it is considered 5411 handled and will be removed from the list of notifications. 5412 5413<synopsis> 5414PGnotify *PQnotifies(PGconn *conn); 5415 5416typedef struct pgNotify 5417{ 5418 char *relname; /* notification channel name */ 5419 int be_pid; /* process ID of notifying server process */ 5420 char *extra; /* notification payload string */ 5421} PGnotify; 5422</synopsis> 5423 5424 After processing a <structname>PGnotify</structname> object returned 5425 by <function>PQnotifies</function>, be sure to free it with 5426 <function>PQfreemem</function>. It is sufficient to free the 5427 <structname>PGnotify</structname> pointer; the 5428 <structfield>relname</structfield> and <structfield>extra</structfield> 5429 fields do not represent separate allocations. (The names of these fields 5430 are historical; in particular, channel names need not have anything to 5431 do with relation names.) 5432 </para> 5433 5434 <para> 5435 <xref linkend="libpq-example-2"/> gives a sample program that illustrates 5436 the use of asynchronous notification. 5437 </para> 5438 5439 <para> 5440 <function>PQnotifies</function> does not actually read data from the 5441 server; it just returns messages previously absorbed by another 5442 <application>libpq</application> function. In ancient releases of 5443 <application>libpq</application>, the only way to ensure timely receipt 5444 of <command>NOTIFY</command> messages was to constantly submit commands, even 5445 empty ones, and then check <function>PQnotifies</function> after each 5446 <function>PQexec</function>. While this still works, it is deprecated 5447 as a waste of processing power. 5448 </para> 5449 5450 <para> 5451 A better way to check for <command>NOTIFY</command> messages when you have no 5452 useful commands to execute is to call 5453 <function>PQconsumeInput</function>, then check 5454 <function>PQnotifies</function>. You can use 5455 <function>select()</function> to wait for data to arrive from the 5456 server, thereby using no <acronym>CPU</acronym> power unless there is 5457 something to do. (See <function>PQsocket</function> to obtain the file 5458 descriptor number to use with <function>select()</function>.) Note that 5459 this will work OK whether you submit commands with 5460 <function>PQsendQuery</function>/<function>PQgetResult</function> or 5461 simply use <function>PQexec</function>. You should, however, remember 5462 to check <function>PQnotifies</function> after each 5463 <function>PQgetResult</function> or <function>PQexec</function>, to 5464 see if any notifications came in during the processing of the command. 5465 </para> 5466 5467 </sect1> 5468 5469 <sect1 id="libpq-copy"> 5470 <title>Functions Associated with the <command>COPY</command> Command</title> 5471 5472 <indexterm zone="libpq-copy"> 5473 <primary>COPY</primary> 5474 <secondary>with libpq</secondary> 5475 </indexterm> 5476 5477 <para> 5478 The <command>COPY</command> command in 5479 <productname>PostgreSQL</productname> has options to read from or write 5480 to the network connection used by <application>libpq</application>. 5481 The functions described in this section allow applications to take 5482 advantage of this capability by supplying or consuming copied data. 5483 </para> 5484 5485 <para> 5486 The overall process is that the application first issues the SQL 5487 <command>COPY</command> command via <function>PQexec</function> or one 5488 of the equivalent functions. The response to this (if there is no 5489 error in the command) will be a <structname>PGresult</structname> object bearing 5490 a status code of <literal>PGRES_COPY_OUT</literal> or 5491 <literal>PGRES_COPY_IN</literal> (depending on the specified copy 5492 direction). The application should then use the functions of this 5493 section to receive or transmit data rows. When the data transfer is 5494 complete, another <structname>PGresult</structname> object is returned to indicate 5495 success or failure of the transfer. Its status will be 5496 <literal>PGRES_COMMAND_OK</literal> for success or 5497 <literal>PGRES_FATAL_ERROR</literal> if some problem was encountered. 5498 At this point further SQL commands can be issued via 5499 <function>PQexec</function>. (It is not possible to execute other SQL 5500 commands using the same connection while the <command>COPY</command> 5501 operation is in progress.) 5502 </para> 5503 5504 <para> 5505 If a <command>COPY</command> command is issued via 5506 <function>PQexec</function> in a string that could contain additional 5507 commands, the application must continue fetching results via 5508 <function>PQgetResult</function> after completing the <command>COPY</command> 5509 sequence. Only when <function>PQgetResult</function> returns 5510 <symbol>NULL</symbol> is it certain that the <function>PQexec</function> 5511 command string is done and it is safe to issue more commands. 5512 </para> 5513 5514 <para> 5515 The functions of this section should be executed only after obtaining 5516 a result status of <literal>PGRES_COPY_OUT</literal> or 5517 <literal>PGRES_COPY_IN</literal> from <function>PQexec</function> or 5518 <function>PQgetResult</function>. 5519 </para> 5520 5521 <para> 5522 A <structname>PGresult</structname> object bearing one of these status values 5523 carries some additional data about the <command>COPY</command> operation 5524 that is starting. This additional data is available using functions 5525 that are also used in connection with query results: 5526 5527 <variablelist> 5528 <varlistentry id="libpq-pqnfields-1"> 5529 <term> 5530 <function>PQnfields</function> 5531 <indexterm> 5532 <primary>PQnfields</primary> 5533 <secondary>with COPY</secondary> 5534 </indexterm> 5535 </term> 5536 5537 <listitem> 5538 <para> 5539 Returns the number of columns (fields) to be copied. 5540 </para> 5541 </listitem> 5542 </varlistentry> 5543 5544 <varlistentry id="libpq-pqbinarytuples-1"> 5545 <term> 5546 <function>PQbinaryTuples</function> 5547 <indexterm> 5548 <primary>PQbinaryTuples</primary> 5549 <secondary>with COPY</secondary> 5550 </indexterm> 5551 </term> 5552 5553 <listitem> 5554 <para> 5555 0 indicates the overall copy format is textual (rows separated by 5556 newlines, columns separated by separator characters, etc). 1 5557 indicates the overall copy format is binary. See <xref 5558 linkend="sql-copy"/> for more information. 5559 </para> 5560 </listitem> 5561 </varlistentry> 5562 5563 <varlistentry id="libpq-pqfformat-1"> 5564 <term> 5565 <function>PQfformat</function> 5566 <indexterm> 5567 <primary>PQfformat</primary> 5568 <secondary>with COPY</secondary> 5569 </indexterm> 5570 </term> 5571 5572 <listitem> 5573 <para> 5574 Returns the format code (0 for text, 1 for binary) associated with 5575 each column of the copy operation. The per-column format codes 5576 will always be zero when the overall copy format is textual, but 5577 the binary format can support both text and binary columns. 5578 (However, as of the current implementation of <command>COPY</command>, 5579 only binary columns appear in a binary copy; so the per-column 5580 formats always match the overall format at present.) 5581 </para> 5582 </listitem> 5583 </varlistentry> 5584 </variablelist> 5585 </para> 5586 5587 <note> 5588 <para> 5589 These additional data values are only available when using protocol 5590 3.0. When using protocol 2.0, all these functions will return 0. 5591 </para> 5592 </note> 5593 5594 <sect2 id="libpq-copy-send"> 5595 <title>Functions for Sending <command>COPY</command> Data</title> 5596 5597 <para> 5598 These functions are used to send data during <literal>COPY FROM 5599 STDIN</literal>. They will fail if called when the connection is not in 5600 <literal>COPY_IN</literal> state. 5601 </para> 5602 5603 <variablelist> 5604 <varlistentry id="libpq-pqputcopydata"> 5605 <term> 5606 <function>PQputCopyData</function> 5607 <indexterm> 5608 <primary>PQputCopyData</primary> 5609 </indexterm> 5610 </term> 5611 5612 <listitem> 5613 <para> 5614 Sends data to the server during <literal>COPY_IN</literal> state. 5615<synopsis> 5616int PQputCopyData(PGconn *conn, 5617 const char *buffer, 5618 int nbytes); 5619</synopsis> 5620 </para> 5621 5622 <para> 5623 Transmits the <command>COPY</command> data in the specified 5624 <parameter>buffer</parameter>, of length <parameter>nbytes</parameter>, to the server. 5625 The result is 1 if the data was queued, zero if it was not queued 5626 because of full buffers (this will only happen in nonblocking mode), 5627 or -1 if an error occurred. 5628 (Use <function>PQerrorMessage</function> to retrieve details if 5629 the return value is -1. If the value is zero, wait for write-ready 5630 and try again.) 5631 </para> 5632 5633 <para> 5634 The application can divide the <command>COPY</command> data stream 5635 into buffer loads of any convenient size. Buffer-load boundaries 5636 have no semantic significance when sending. The contents of the 5637 data stream must match the data format expected by the 5638 <command>COPY</command> command; see <xref linkend="sql-copy"/> for details. 5639 </para> 5640 </listitem> 5641 </varlistentry> 5642 5643 <varlistentry id="libpq-pqputcopyend"> 5644 <term> 5645 <function>PQputCopyEnd</function> 5646 <indexterm> 5647 <primary>PQputCopyEnd</primary> 5648 </indexterm> 5649 </term> 5650 5651 <listitem> 5652 <para> 5653 Sends end-of-data indication to the server during <literal>COPY_IN</literal> state. 5654<synopsis> 5655int PQputCopyEnd(PGconn *conn, 5656 const char *errormsg); 5657</synopsis> 5658 </para> 5659 5660 <para> 5661 Ends the <literal>COPY_IN</literal> operation successfully if 5662 <parameter>errormsg</parameter> is <symbol>NULL</symbol>. If 5663 <parameter>errormsg</parameter> is not <symbol>NULL</symbol> then the 5664 <command>COPY</command> is forced to fail, with the string pointed to by 5665 <parameter>errormsg</parameter> used as the error message. (One should not 5666 assume that this exact error message will come back from the server, 5667 however, as the server might have already failed the 5668 <command>COPY</command> for its own reasons. Also note that the option 5669 to force failure does not work when using pre-3.0-protocol 5670 connections.) 5671 </para> 5672 5673 <para> 5674 The result is 1 if the termination message was sent; or in 5675 nonblocking mode, this may only indicate that the termination 5676 message was successfully queued. (In nonblocking mode, to be 5677 certain that the data has been sent, you should next wait for 5678 write-ready and call <function>PQflush</function>, repeating until it 5679 returns zero.) Zero indicates that the function could not queue 5680 the termination message because of full buffers; this will only 5681 happen in nonblocking mode. (In this case, wait for 5682 write-ready and try the <function>PQputCopyEnd</function> call 5683 again.) If a hard error occurs, -1 is returned; you can use 5684 <function>PQerrorMessage</function> to retrieve details. 5685 </para> 5686 5687 <para> 5688 After successfully calling <function>PQputCopyEnd</function>, call 5689 <function>PQgetResult</function> to obtain the final result status of the 5690 <command>COPY</command> command. One can wait for this result to be 5691 available in the usual way. Then return to normal operation. 5692 </para> 5693 </listitem> 5694 </varlistentry> 5695 </variablelist> 5696 5697 </sect2> 5698 5699 <sect2 id="libpq-copy-receive"> 5700 <title>Functions for Receiving <command>COPY</command> Data</title> 5701 5702 <para> 5703 These functions are used to receive data during <literal>COPY TO 5704 STDOUT</literal>. They will fail if called when the connection is not in 5705 <literal>COPY_OUT</literal> state. 5706 </para> 5707 5708 <variablelist> 5709 <varlistentry id="libpq-pqgetcopydata"> 5710 <term> 5711 <function>PQgetCopyData</function> 5712 <indexterm> 5713 <primary>PQgetCopyData</primary> 5714 </indexterm> 5715 </term> 5716 5717 <listitem> 5718 <para> 5719 Receives data from the server during <literal>COPY_OUT</literal> state. 5720<synopsis> 5721int PQgetCopyData(PGconn *conn, 5722 char **buffer, 5723 int async); 5724</synopsis> 5725 </para> 5726 5727 <para> 5728 Attempts to obtain another row of data from the server during a 5729 <command>COPY</command>. Data is always returned one data row at 5730 a time; if only a partial row is available, it is not returned. 5731 Successful return of a data row involves allocating a chunk of 5732 memory to hold the data. The <parameter>buffer</parameter> parameter must 5733 be non-<symbol>NULL</symbol>. <parameter>*buffer</parameter> is set to 5734 point to the allocated memory, or to <symbol>NULL</symbol> in cases 5735 where no buffer is returned. A non-<symbol>NULL</symbol> result 5736 buffer should be freed using <function>PQfreemem</function> when no longer 5737 needed. 5738 </para> 5739 5740 <para> 5741 When a row is successfully returned, the return value is the number 5742 of data bytes in the row (this will always be greater than zero). 5743 The returned string is always null-terminated, though this is 5744 probably only useful for textual <command>COPY</command>. A result 5745 of zero indicates that the <command>COPY</command> is still in 5746 progress, but no row is yet available (this is only possible when 5747 <parameter>async</parameter> is true). A result of -1 indicates that the 5748 <command>COPY</command> is done. A result of -2 indicates that an 5749 error occurred (consult <function>PQerrorMessage</function> for the reason). 5750 </para> 5751 5752 <para> 5753 When <parameter>async</parameter> is true (not zero), 5754 <function>PQgetCopyData</function> will not block waiting for input; it 5755 will return zero if the <command>COPY</command> is still in progress 5756 but no complete row is available. (In this case wait for read-ready 5757 and then call <function>PQconsumeInput</function> before calling 5758 <function>PQgetCopyData</function> again.) When <parameter>async</parameter> is 5759 false (zero), <function>PQgetCopyData</function> will block until data is 5760 available or the operation completes. 5761 </para> 5762 5763 <para> 5764 After <function>PQgetCopyData</function> returns -1, call 5765 <function>PQgetResult</function> to obtain the final result status of the 5766 <command>COPY</command> command. One can wait for this result to be 5767 available in the usual way. Then return to normal operation. 5768 </para> 5769 </listitem> 5770 </varlistentry> 5771 </variablelist> 5772 5773 </sect2> 5774 5775 <sect2 id="libpq-copy-deprecated"> 5776 <title>Obsolete Functions for <command>COPY</command></title> 5777 5778 <para> 5779 These functions represent older methods of handling <command>COPY</command>. 5780 Although they still work, they are deprecated due to poor error handling, 5781 inconvenient methods of detecting end-of-data, and lack of support for binary 5782 or nonblocking transfers. 5783 </para> 5784 5785 <variablelist> 5786 <varlistentry id="libpq-pqgetline"> 5787 <term> 5788 <function>PQgetline</function> 5789 <indexterm> 5790 <primary>PQgetline</primary> 5791 </indexterm> 5792 </term> 5793 5794 <listitem> 5795 <para> 5796 Reads a newline-terminated line of characters (transmitted 5797 by the server) into a buffer string of size <parameter>length</parameter>. 5798<synopsis> 5799int PQgetline(PGconn *conn, 5800 char *buffer, 5801 int length); 5802</synopsis> 5803 </para> 5804 5805 <para> 5806 This function copies up to <parameter>length</parameter>-1 characters into 5807 the buffer and converts the terminating newline into a zero byte. 5808 <function>PQgetline</function> returns <symbol>EOF</symbol> at the 5809 end of input, 0 if the entire line has been read, and 1 if the 5810 buffer is full but the terminating newline has not yet been read. 5811 </para> 5812 <para> 5813 Note that the application must check to see if a new line consists 5814 of the two characters <literal>\.</literal>, which indicates 5815 that the server has finished sending the results of the 5816 <command>COPY</command> command. If the application might receive 5817 lines that are more than <parameter>length</parameter>-1 characters long, 5818 care is needed to be sure it recognizes the <literal>\.</literal> 5819 line correctly (and does not, for example, mistake the end of a 5820 long data line for a terminator line). 5821 </para> 5822 </listitem> 5823 </varlistentry> 5824 5825 <varlistentry id="libpq-pqgetlineasync"> 5826 <term> 5827 <function>PQgetlineAsync</function> 5828 <indexterm> 5829 <primary>PQgetlineAsync</primary> 5830 </indexterm> 5831 </term> 5832 5833 <listitem> 5834 <para> 5835 Reads a row of <command>COPY</command> data (transmitted by the 5836 server) into a buffer without blocking. 5837<synopsis> 5838int PQgetlineAsync(PGconn *conn, 5839 char *buffer, 5840 int bufsize); 5841</synopsis> 5842 </para> 5843 5844 <para> 5845 This function is similar to <function>PQgetline</function>, but it can be used 5846 by applications 5847 that must read <command>COPY</command> data asynchronously, that is, without blocking. 5848 Having issued the <command>COPY</command> command and gotten a <literal>PGRES_COPY_OUT</literal> 5849 response, the 5850 application should call <function>PQconsumeInput</function> and 5851 <function>PQgetlineAsync</function> until the 5852 end-of-data signal is detected. 5853 </para> 5854 <para> 5855 Unlike <function>PQgetline</function>, this function takes 5856 responsibility for detecting end-of-data. 5857 </para> 5858 5859 <para> 5860 On each call, <function>PQgetlineAsync</function> will return data if a 5861 complete data row is available in <application>libpq</application>'s input buffer. 5862 Otherwise, no data is returned until the rest of the row arrives. 5863 The function returns -1 if the end-of-copy-data marker has been recognized, 5864 or 0 if no data is available, or a positive number giving the number of 5865 bytes of data returned. If -1 is returned, the caller must next call 5866 <function>PQendcopy</function>, and then return to normal processing. 5867 </para> 5868 5869 <para> 5870 The data returned will not extend beyond a data-row boundary. If possible 5871 a whole row will be returned at one time. But if the buffer offered by 5872 the caller is too small to hold a row sent by the server, then a partial 5873 data row will be returned. With textual data this can be detected by testing 5874 whether the last returned byte is <literal>\n</literal> or not. (In a binary 5875 <command>COPY</command>, actual parsing of the <command>COPY</command> data format will be needed to make the 5876 equivalent determination.) 5877 The returned string is not null-terminated. (If you want to add a 5878 terminating null, be sure to pass a <parameter>bufsize</parameter> one smaller 5879 than the room actually available.) 5880 </para> 5881 </listitem> 5882 </varlistentry> 5883 5884 <varlistentry id="libpq-pqputline"> 5885 <term> 5886 <function>PQputline</function> 5887 <indexterm> 5888 <primary>PQputline</primary> 5889 </indexterm> 5890 </term> 5891 5892 <listitem> 5893 <para> 5894 Sends a null-terminated string to the server. Returns 0 if 5895 OK and <symbol>EOF</symbol> if unable to send the string. 5896<synopsis> 5897int PQputline(PGconn *conn, 5898 const char *string); 5899</synopsis> 5900 </para> 5901 5902 <para> 5903 The <command>COPY</command> data stream sent by a series of calls 5904 to <function>PQputline</function> has the same format as that 5905 returned by <function>PQgetlineAsync</function>, except that 5906 applications are not obliged to send exactly one data row per 5907 <function>PQputline</function> call; it is okay to send a partial 5908 line or multiple lines per call. 5909 </para> 5910 5911 <note> 5912 <para> 5913 Before <productname>PostgreSQL</productname> protocol 3.0, it was necessary 5914 for the application to explicitly send the two characters 5915 <literal>\.</literal> as a final line to indicate to the server that it had 5916 finished sending <command>COPY</command> data. While this still works, it is deprecated and the 5917 special meaning of <literal>\.</literal> can be expected to be removed in a 5918 future release. It is sufficient to call <function>PQendcopy</function> after 5919 having sent the actual data. 5920 </para> 5921 </note> 5922 </listitem> 5923 </varlistentry> 5924 5925 <varlistentry id="libpq-pqputnbytes"> 5926 <term> 5927 <function>PQputnbytes</function> 5928 <indexterm> 5929 <primary>PQputnbytes</primary> 5930 </indexterm> 5931 </term> 5932 5933 <listitem> 5934 <para> 5935 Sends a non-null-terminated string to the server. Returns 5936 0 if OK and <symbol>EOF</symbol> if unable to send the string. 5937<synopsis> 5938int PQputnbytes(PGconn *conn, 5939 const char *buffer, 5940 int nbytes); 5941</synopsis> 5942 </para> 5943 5944 <para> 5945 This is exactly like <function>PQputline</function>, except that the data 5946 buffer need not be null-terminated since the number of bytes to send is 5947 specified directly. Use this procedure when sending binary data. 5948 </para> 5949 </listitem> 5950 </varlistentry> 5951 5952 <varlistentry id="libpq-pqendcopy"> 5953 <term> 5954 <function>PQendcopy</function> 5955 <indexterm> 5956 <primary>PQendcopy</primary> 5957 </indexterm> 5958 </term> 5959 5960 <listitem> 5961 <para> 5962 Synchronizes with the server. 5963<synopsis> 5964int PQendcopy(PGconn *conn); 5965</synopsis> 5966 This function waits until the server has finished the copying. 5967 It should either be issued when the last string has been sent 5968 to the server using <function>PQputline</function> or when the 5969 last string has been received from the server using 5970 <function>PQgetline</function>. It must be issued or the server 5971 will get <quote>out of sync</quote> with the client. Upon return 5972 from this function, the server is ready to receive the next SQL 5973 command. The return value is 0 on successful completion, 5974 nonzero otherwise. (Use <function>PQerrorMessage</function> to 5975 retrieve details if the return value is nonzero.) 5976 </para> 5977 5978 <para> 5979 When using <function>PQgetResult</function>, the application should 5980 respond to a <literal>PGRES_COPY_OUT</literal> result by executing 5981 <function>PQgetline</function> repeatedly, followed by 5982 <function>PQendcopy</function> after the terminator line is seen. 5983 It should then return to the <function>PQgetResult</function> loop 5984 until <function>PQgetResult</function> returns a null pointer. 5985 Similarly a <literal>PGRES_COPY_IN</literal> result is processed 5986 by a series of <function>PQputline</function> calls followed by 5987 <function>PQendcopy</function>, then return to the 5988 <function>PQgetResult</function> loop. This arrangement will 5989 ensure that a <command>COPY</command> command embedded in a series 5990 of <acronym>SQL</acronym> commands will be executed correctly. 5991 </para> 5992 5993 <para> 5994 Older applications are likely to submit a <command>COPY</command> 5995 via <function>PQexec</function> and assume that the transaction 5996 is done after <function>PQendcopy</function>. This will work 5997 correctly only if the <command>COPY</command> is the only 5998 <acronym>SQL</acronym> command in the command string. 5999 </para> 6000 </listitem> 6001 </varlistentry> 6002 </variablelist> 6003 6004 </sect2> 6005 6006 </sect1> 6007 6008 <sect1 id="libpq-control"> 6009 <title>Control Functions</title> 6010 6011 <para> 6012 These functions control miscellaneous details of <application>libpq</application>'s 6013 behavior. 6014 </para> 6015 6016 <variablelist> 6017 <varlistentry id="libpq-pqclientencoding"> 6018 <term> 6019 <function>PQclientEncoding</function> 6020 <indexterm> 6021 <primary>PQclientEncoding</primary> 6022 </indexterm> 6023 </term> 6024 6025 <listitem> 6026 <para> 6027 Returns the client encoding. 6028<synopsis> 6029int PQclientEncoding(const PGconn *<replaceable>conn</replaceable>); 6030</synopsis> 6031 6032 Note that it returns the encoding ID, not a symbolic string 6033 such as <literal>EUC_JP</literal>. If unsuccessful, it returns -1. 6034 To convert an encoding ID to an encoding name, you 6035 can use: 6036 6037<synopsis> 6038char *pg_encoding_to_char(int <replaceable>encoding_id</replaceable>); 6039</synopsis> 6040 </para> 6041 </listitem> 6042 </varlistentry> 6043 6044 <varlistentry id="libpq-pqsetclientencoding"> 6045 <term> 6046 <function>PQsetClientEncoding</function> 6047 <indexterm> 6048 <primary>PQsetClientEncoding</primary> 6049 </indexterm> 6050 </term> 6051 6052 <listitem> 6053 <para> 6054 Sets the client encoding. 6055<synopsis> 6056int PQsetClientEncoding(PGconn *<replaceable>conn</replaceable>, const char *<replaceable>encoding</replaceable>); 6057</synopsis> 6058 6059 <replaceable>conn</replaceable> is a connection to the server, 6060 and <replaceable>encoding</replaceable> is the encoding you want to 6061 use. If the function successfully sets the encoding, it returns 0, 6062 otherwise -1. The current encoding for this connection can be 6063 determined by using <function>PQclientEncoding</function>. 6064 </para> 6065 </listitem> 6066 </varlistentry> 6067 6068 <varlistentry id="libpq-pqseterrorverbosity"> 6069 <term> 6070 <function>PQsetErrorVerbosity</function> 6071 <indexterm> 6072 <primary>PQsetErrorVerbosity</primary> 6073 </indexterm> 6074 </term> 6075 6076 <listitem> 6077 <para> 6078 Determines the verbosity of messages returned by 6079 <function>PQerrorMessage</function> and <function>PQresultErrorMessage</function>. 6080<synopsis> 6081typedef enum 6082{ 6083 PQERRORS_TERSE, 6084 PQERRORS_DEFAULT, 6085 PQERRORS_VERBOSE, 6086 PQERRORS_SQLSTATE 6087} PGVerbosity; 6088 6089PGVerbosity PQsetErrorVerbosity(PGconn *conn, PGVerbosity verbosity); 6090</synopsis> 6091 6092 <function>PQsetErrorVerbosity</function> sets the verbosity mode, 6093 returning the connection's previous setting. 6094 In <firstterm>TERSE</firstterm> mode, returned messages include 6095 severity, primary text, and position only; this will normally fit on a 6096 single line. The <firstterm>DEFAULT</firstterm> mode produces messages 6097 that include the above plus any detail, hint, or context fields (these 6098 might span multiple lines). The <firstterm>VERBOSE</firstterm> mode 6099 includes all available fields. The <firstterm>SQLSTATE</firstterm> 6100 mode includes only the error severity and the <symbol>SQLSTATE</symbol> 6101 error code, if one is available (if not, the output is like 6102 <firstterm>TERSE</firstterm> mode). 6103 </para> 6104 6105 <para> 6106 Changing the verbosity setting does not affect the messages available 6107 from already-existing <structname>PGresult</structname> objects, only 6108 subsequently-created ones. 6109 (But see <function>PQresultVerboseErrorMessage</function> if you 6110 want to print a previous error with a different verbosity.) 6111 </para> 6112 </listitem> 6113 </varlistentry> 6114 6115 <varlistentry id="libpq-pqseterrorcontextvisibility"> 6116 <term> 6117 <function>PQsetErrorContextVisibility</function> 6118 <indexterm> 6119 <primary>PQsetErrorContextVisibility</primary> 6120 </indexterm> 6121 </term> 6122 6123 <listitem> 6124 <para> 6125 Determines the handling of <literal>CONTEXT</literal> fields in messages 6126 returned by <function>PQerrorMessage</function> 6127 and <function>PQresultErrorMessage</function>. 6128<synopsis> 6129typedef enum 6130{ 6131 PQSHOW_CONTEXT_NEVER, 6132 PQSHOW_CONTEXT_ERRORS, 6133 PQSHOW_CONTEXT_ALWAYS 6134} PGContextVisibility; 6135 6136PGContextVisibility PQsetErrorContextVisibility(PGconn *conn, PGContextVisibility show_context); 6137</synopsis> 6138 6139 <function>PQsetErrorContextVisibility</function> sets the context display mode, 6140 returning the connection's previous setting. This mode controls 6141 whether the <literal>CONTEXT</literal> field is included in messages. 6142 The <firstterm>NEVER</firstterm> mode 6143 never includes <literal>CONTEXT</literal>, while <firstterm>ALWAYS</firstterm> always 6144 includes it if available. In <firstterm>ERRORS</firstterm> mode (the 6145 default), <literal>CONTEXT</literal> fields are included only in error 6146 messages, not in notices and warnings. 6147 (However, if the verbosity setting is <firstterm>TERSE</firstterm> 6148 or <firstterm>SQLSTATE</firstterm>, <literal>CONTEXT</literal> fields 6149 are omitted regardless of the context display mode.) 6150 </para> 6151 6152 <para> 6153 Changing this mode does not 6154 affect the messages available from 6155 already-existing <structname>PGresult</structname> objects, only 6156 subsequently-created ones. 6157 (But see <function>PQresultVerboseErrorMessage</function> if you 6158 want to print a previous error with a different display mode.) 6159 </para> 6160 </listitem> 6161 </varlistentry> 6162 6163 <varlistentry id="libpq-pqtrace"> 6164 <term> 6165 <function>PQtrace</function> 6166 <indexterm> 6167 <primary>PQtrace</primary> 6168 </indexterm> 6169 </term> 6170 6171 <listitem> 6172 <para> 6173 Enables tracing of the client/server communication to a debugging file stream. 6174<synopsis> 6175void PQtrace(PGconn *conn, FILE *stream); 6176</synopsis> 6177 </para> 6178 6179 <note> 6180 <para> 6181 On Windows, if the <application>libpq</application> library and an application are 6182 compiled with different flags, this function call will crash the 6183 application because the internal representation of the <literal>FILE</literal> 6184 pointers differ. Specifically, multithreaded/single-threaded, 6185 release/debug, and static/dynamic flags should be the same for the 6186 library and all applications using that library. 6187 </para> 6188 </note> 6189 6190 </listitem> 6191 </varlistentry> 6192 6193 <varlistentry id="libpq-pquntrace"> 6194 <term> 6195 <function>PQuntrace</function> 6196 <indexterm> 6197 <primary>PQuntrace</primary> 6198 </indexterm> 6199 </term> 6200 6201 <listitem> 6202 <para> 6203 Disables tracing started by <function>PQtrace</function>. 6204<synopsis> 6205void PQuntrace(PGconn *conn); 6206</synopsis> 6207 </para> 6208 </listitem> 6209 </varlistentry> 6210 </variablelist> 6211 6212 </sect1> 6213 6214 <sect1 id="libpq-misc"> 6215 <title>Miscellaneous Functions</title> 6216 6217 <para> 6218 As always, there are some functions that just don't fit anywhere. 6219 </para> 6220 6221 <variablelist> 6222 <varlistentry id="libpq-pqfreemem"> 6223 <term> 6224 <function>PQfreemem</function> 6225 <indexterm> 6226 <primary>PQfreemem</primary> 6227 </indexterm> 6228 </term> 6229 6230 <listitem> 6231 <para> 6232 Frees memory allocated by <application>libpq</application>. 6233<synopsis> 6234void PQfreemem(void *ptr); 6235</synopsis> 6236 </para> 6237 6238 <para> 6239 Frees memory allocated by <application>libpq</application>, particularly 6240 <function>PQescapeByteaConn</function>, 6241 <function>PQescapeBytea</function>, 6242 <function>PQunescapeBytea</function>, 6243 and <function>PQnotifies</function>. 6244 It is particularly important that this function, rather than 6245 <function>free()</function>, be used on Microsoft Windows. This is because 6246 allocating memory in a DLL and releasing it in the application works 6247 only if multithreaded/single-threaded, release/debug, and static/dynamic 6248 flags are the same for the DLL and the application. On non-Microsoft 6249 Windows platforms, this function is the same as the standard library 6250 function <function>free()</function>. 6251 </para> 6252 </listitem> 6253 </varlistentry> 6254 6255 <varlistentry id="libpq-pqconninfofree"> 6256 <term> 6257 <function>PQconninfoFree</function> 6258 <indexterm> 6259 <primary>PQconninfoFree</primary> 6260 </indexterm> 6261 </term> 6262 6263 <listitem> 6264 <para> 6265 Frees the data structures allocated by 6266 <function>PQconndefaults</function> or <function>PQconninfoParse</function>. 6267<synopsis> 6268void PQconninfoFree(PQconninfoOption *connOptions); 6269</synopsis> 6270 </para> 6271 6272 <para> 6273 A simple <function>PQfreemem</function> will not do for this, since 6274 the array contains references to subsidiary strings. 6275 </para> 6276 </listitem> 6277 </varlistentry> 6278 6279 <varlistentry id="libpq-pqencryptpasswordconn"> 6280 <term> 6281 <function>PQencryptPasswordConn</function> 6282 <indexterm> 6283 <primary>PQencryptPasswordConn</primary> 6284 </indexterm> 6285 </term> 6286 6287 <listitem> 6288 <para> 6289 Prepares the encrypted form of a <productname>PostgreSQL</productname> password. 6290<synopsis> 6291char *PQencryptPasswordConn(PGconn *conn, const char *passwd, const char *user, const char *algorithm); 6292</synopsis> 6293 This function is intended to be used by client applications that 6294 wish to send commands like <literal>ALTER USER joe PASSWORD 6295 'pwd'</literal>. It is good practice not to send the original cleartext 6296 password in such a command, because it might be exposed in command 6297 logs, activity displays, and so on. Instead, use this function to 6298 convert the password to encrypted form before it is sent. 6299 </para> 6300 6301 <para> 6302 The <parameter>passwd</parameter> and <parameter>user</parameter> arguments 6303 are the cleartext password, and the SQL name of the user it is for. 6304 <parameter>algorithm</parameter> specifies the encryption algorithm 6305 to use to encrypt the password. Currently supported algorithms are 6306 <literal>md5</literal> and <literal>scram-sha-256</literal> (<literal>on</literal> and 6307 <literal>off</literal> are also accepted as aliases for <literal>md5</literal>, for 6308 compatibility with older server versions). Note that support for 6309 <literal>scram-sha-256</literal> was introduced in <productname>PostgreSQL</productname> 6310 version 10, and will not work correctly with older server versions. If 6311 <parameter>algorithm</parameter> is <symbol>NULL</symbol>, this function will query 6312 the server for the current value of the 6313 <xref linkend="guc-password-encryption"/> setting. That can block, and 6314 will fail if the current transaction is aborted, or if the connection 6315 is busy executing another query. If you wish to use the default 6316 algorithm for the server but want to avoid blocking, query 6317 <varname>password_encryption</varname> yourself before calling 6318 <function>PQencryptPasswordConn</function>, and pass that value as the 6319 <parameter>algorithm</parameter>. 6320 </para> 6321 6322 <para> 6323 The return value is a string allocated by <function>malloc</function>. 6324 The caller can assume the string doesn't contain any special characters 6325 that would require escaping. Use <function>PQfreemem</function> to free the 6326 result when done with it. On error, returns <symbol>NULL</symbol>, and 6327 a suitable message is stored in the connection object. 6328 </para> 6329 6330 </listitem> 6331 </varlistentry> 6332 6333 <varlistentry id="libpq-pqencryptpassword"> 6334 <term> 6335 <function>PQencryptPassword</function> 6336 <indexterm> 6337 <primary>PQencryptPassword</primary> 6338 </indexterm> 6339 </term> 6340 6341 <listitem> 6342 <para> 6343 Prepares the md5-encrypted form of a <productname>PostgreSQL</productname> password. 6344<synopsis> 6345char *PQencryptPassword(const char *passwd, const char *user); 6346</synopsis> 6347 <function>PQencryptPassword</function> is an older, deprecated version of 6348 <function>PQencryptPasswordConn</function>. The difference is that 6349 <function>PQencryptPassword</function> does not 6350 require a connection object, and <literal>md5</literal> is always used as the 6351 encryption algorithm. 6352 </para> 6353 </listitem> 6354 </varlistentry> 6355 6356 <varlistentry id="libpq-pqmakeemptypgresult"> 6357 <term> 6358 <function>PQmakeEmptyPGresult</function> 6359 <indexterm> 6360 <primary>PQmakeEmptyPGresult</primary> 6361 </indexterm> 6362 </term> 6363 6364 <listitem> 6365 <para> 6366 Constructs an empty <structname>PGresult</structname> object with the given status. 6367<synopsis> 6368PGresult *PQmakeEmptyPGresult(PGconn *conn, ExecStatusType status); 6369</synopsis> 6370 </para> 6371 6372 <para> 6373 This is <application>libpq</application>'s internal function to allocate and 6374 initialize an empty <structname>PGresult</structname> object. This 6375 function returns <symbol>NULL</symbol> if memory could not be allocated. It is 6376 exported because some applications find it useful to generate result 6377 objects (particularly objects with error status) themselves. If 6378 <parameter>conn</parameter> is not null and <parameter>status</parameter> 6379 indicates an error, the current error message of the specified 6380 connection is copied into the <structname>PGresult</structname>. 6381 Also, if <parameter>conn</parameter> is not null, any event procedures 6382 registered in the connection are copied into the 6383 <structname>PGresult</structname>. (They do not get 6384 <literal>PGEVT_RESULTCREATE</literal> calls, but see 6385 <function>PQfireResultCreateEvents</function>.) 6386 Note that <function>PQclear</function> should eventually be called 6387 on the object, just as with a <structname>PGresult</structname> 6388 returned by <application>libpq</application> itself. 6389 </para> 6390 </listitem> 6391 </varlistentry> 6392 6393 <varlistentry id="libpq-pqfireresultcreateevents"> 6394 <term> 6395 <function>PQfireResultCreateEvents</function> 6396 <indexterm> 6397 <primary>PQfireResultCreateEvents</primary> 6398 </indexterm> 6399 </term> 6400 <listitem> 6401 <para> 6402 Fires a <literal>PGEVT_RESULTCREATE</literal> event (see <xref 6403 linkend="libpq-events"/>) for each event procedure registered in the 6404 <structname>PGresult</structname> object. Returns non-zero for success, 6405 zero if any event procedure fails. 6406 6407<synopsis> 6408int PQfireResultCreateEvents(PGconn *conn, PGresult *res); 6409</synopsis> 6410 </para> 6411 6412 <para> 6413 The <literal>conn</literal> argument is passed through to event procedures 6414 but not used directly. It can be <symbol>NULL</symbol> if the event 6415 procedures won't use it. 6416 </para> 6417 6418 <para> 6419 Event procedures that have already received a 6420 <literal>PGEVT_RESULTCREATE</literal> or <literal>PGEVT_RESULTCOPY</literal> event 6421 for this object are not fired again. 6422 </para> 6423 6424 <para> 6425 The main reason that this function is separate from 6426 <function>PQmakeEmptyPGresult</function> is that it is often appropriate 6427 to create a <structname>PGresult</structname> and fill it with data 6428 before invoking the event procedures. 6429 </para> 6430 </listitem> 6431 </varlistentry> 6432 6433 <varlistentry id="libpq-pqcopyresult"> 6434 <term> 6435 <function>PQcopyResult</function> 6436 <indexterm> 6437 <primary>PQcopyResult</primary> 6438 </indexterm> 6439 </term> 6440 6441 <listitem> 6442 <para> 6443 Makes a copy of a <structname>PGresult</structname> object. The copy is 6444 not linked to the source result in any way and 6445 <function>PQclear</function> must be called when the copy is no longer 6446 needed. If the function fails, <symbol>NULL</symbol> is returned. 6447 6448<synopsis> 6449PGresult *PQcopyResult(const PGresult *src, int flags); 6450</synopsis> 6451 </para> 6452 6453 <para> 6454 This is not intended to make an exact copy. The returned result is 6455 always put into <literal>PGRES_TUPLES_OK</literal> status, and does not 6456 copy any error message in the source. (It does copy the command status 6457 string, however.) The <parameter>flags</parameter> argument determines 6458 what else is copied. It is a bitwise OR of several flags. 6459 <literal>PG_COPYRES_ATTRS</literal> specifies copying the source 6460 result's attributes (column definitions). 6461 <literal>PG_COPYRES_TUPLES</literal> specifies copying the source 6462 result's tuples. (This implies copying the attributes, too.) 6463 <literal>PG_COPYRES_NOTICEHOOKS</literal> specifies 6464 copying the source result's notify hooks. 6465 <literal>PG_COPYRES_EVENTS</literal> specifies copying the source 6466 result's events. (But any instance data associated with the source 6467 is not copied.) 6468 </para> 6469 </listitem> 6470 </varlistentry> 6471 6472 <varlistentry id="libpq-pqsetresultattrs"> 6473 <term> 6474 <function>PQsetResultAttrs</function> 6475 <indexterm> 6476 <primary>PQsetResultAttrs</primary> 6477 </indexterm> 6478 </term> 6479 6480 <listitem> 6481 <para> 6482 Sets the attributes of a <structname>PGresult</structname> object. 6483<synopsis> 6484int PQsetResultAttrs(PGresult *res, int numAttributes, PGresAttDesc *attDescs); 6485</synopsis> 6486 </para> 6487 6488 <para> 6489 The provided <parameter>attDescs</parameter> are copied into the result. 6490 If the <parameter>attDescs</parameter> pointer is <symbol>NULL</symbol> or 6491 <parameter>numAttributes</parameter> is less than one, the request is 6492 ignored and the function succeeds. If <parameter>res</parameter> 6493 already contains attributes, the function will fail. If the function 6494 fails, the return value is zero. If the function succeeds, the return 6495 value is non-zero. 6496 </para> 6497 </listitem> 6498 </varlistentry> 6499 6500 <varlistentry id="libpq-pqsetvalue"> 6501 <term> 6502 <function>PQsetvalue</function> 6503 <indexterm> 6504 <primary>PQsetvalue</primary> 6505 </indexterm> 6506 </term> 6507 6508 <listitem> 6509 <para> 6510 Sets a tuple field value of a <structname>PGresult</structname> object. 6511<synopsis> 6512int PQsetvalue(PGresult *res, int tup_num, int field_num, char *value, int len); 6513</synopsis> 6514 </para> 6515 6516 <para> 6517 The function will automatically grow the result's internal tuples array 6518 as needed. However, the <parameter>tup_num</parameter> argument must be 6519 less than or equal to <function>PQntuples</function>, meaning this 6520 function can only grow the tuples array one tuple at a time. But any 6521 field of any existing tuple can be modified in any order. If a value at 6522 <parameter>field_num</parameter> already exists, it will be overwritten. 6523 If <parameter>len</parameter> is -1 or 6524 <parameter>value</parameter> is <symbol>NULL</symbol>, the field value 6525 will be set to an SQL null value. The 6526 <parameter>value</parameter> is copied into the result's private storage, 6527 thus is no longer needed after the function 6528 returns. If the function fails, the return value is zero. If the 6529 function succeeds, the return value is non-zero. 6530 </para> 6531 </listitem> 6532 </varlistentry> 6533 6534 <varlistentry id="libpq-pqresultalloc"> 6535 <term> 6536 <function>PQresultAlloc</function> 6537 <indexterm> 6538 <primary>PQresultAlloc</primary> 6539 </indexterm> 6540 </term> 6541 6542 <listitem> 6543 <para> 6544 Allocate subsidiary storage for a <structname>PGresult</structname> object. 6545<synopsis> 6546void *PQresultAlloc(PGresult *res, size_t nBytes); 6547</synopsis> 6548 </para> 6549 6550 <para> 6551 Any memory allocated with this function will be freed when 6552 <parameter>res</parameter> is cleared. If the function fails, 6553 the return value is <symbol>NULL</symbol>. The result is 6554 guaranteed to be adequately aligned for any type of data, 6555 just as for <function>malloc</function>. 6556 </para> 6557 </listitem> 6558 </varlistentry> 6559 6560 <varlistentry id="libpq-pqresultmemorysize"> 6561 <term> 6562 <function>PQresultMemorySize</function> 6563 <indexterm> 6564 <primary>PQresultMemorySize</primary> 6565 </indexterm> 6566 </term> 6567 6568 <listitem> 6569 <para> 6570 Retrieves the number of bytes allocated for 6571 a <structname>PGresult</structname> object. 6572<synopsis> 6573size_t PQresultMemorySize(const PGresult *res); 6574</synopsis> 6575 </para> 6576 6577 <para> 6578 This value is the sum of all <function>malloc</function> requests 6579 associated with the <structname>PGresult</structname> object, that is, 6580 all the space that will be freed by <function>PQclear</function>. 6581 This information can be useful for managing memory consumption. 6582 </para> 6583 </listitem> 6584 </varlistentry> 6585 6586 <varlistentry id="libpq-pqlibversion"> 6587 <term> 6588 <function>PQlibVersion</function> 6589 <indexterm> 6590 <primary>PQlibVersion</primary> 6591 <seealso>PQserverVersion</seealso> 6592 </indexterm> 6593 </term> 6594 6595 <listitem> 6596 <para> 6597 Return the version of <productname>libpq</productname> that is being used. 6598<synopsis> 6599int PQlibVersion(void); 6600</synopsis> 6601 </para> 6602 6603 <para> 6604 The result of this function can be used to determine, at 6605 run time, whether specific functionality is available in the currently 6606 loaded version of libpq. The function can be used, for example, 6607 to determine which connection options are available in 6608 <function>PQconnectdb</function>. 6609 </para> 6610 6611 <para> 6612 The result is formed by multiplying the library's major version 6613 number by 10000 and adding the minor version number. For example, 6614 version 10.1 will be returned as 100001, and version 11.0 will be 6615 returned as 110000. 6616 </para> 6617 6618 <para> 6619 Prior to major version 10, <productname>PostgreSQL</productname> used 6620 three-part version numbers in which the first two parts together 6621 represented the major version. For those 6622 versions, <function>PQlibVersion</function> uses two digits for each 6623 part; for example version 9.1.5 will be returned as 90105, and 6624 version 9.2.0 will be returned as 90200. 6625 </para> 6626 6627 <para> 6628 Therefore, for purposes of determining feature compatibility, 6629 applications should divide the result of <function>PQlibVersion</function> 6630 by 100 not 10000 to determine a logical major version number. 6631 In all release series, only the last two digits differ between 6632 minor releases (bug-fix releases). 6633 </para> 6634 6635 <note> 6636 <para> 6637 This function appeared in <productname>PostgreSQL</productname> version 9.1, so 6638 it cannot be used to detect required functionality in earlier 6639 versions, since calling it will create a link dependency 6640 on version 9.1 or later. 6641 </para> 6642 </note> 6643 </listitem> 6644 </varlistentry> 6645 6646 </variablelist> 6647 6648 </sect1> 6649 6650 <sect1 id="libpq-notice-processing"> 6651 <title>Notice Processing</title> 6652 6653 <indexterm zone="libpq-notice-processing"> 6654 <primary>notice processing</primary> 6655 <secondary>in libpq</secondary> 6656 </indexterm> 6657 6658 <para> 6659 Notice and warning messages generated by the server are not returned 6660 by the query execution functions, since they do not imply failure of 6661 the query. Instead they are passed to a notice handling function, and 6662 execution continues normally after the handler returns. The default 6663 notice handling function prints the message on 6664 <filename>stderr</filename>, but the application can override this 6665 behavior by supplying its own handling function. 6666 </para> 6667 6668 <para> 6669 For historical reasons, there are two levels of notice handling, called 6670 the notice receiver and notice processor. The default behavior is for 6671 the notice receiver to format the notice and pass a string to the notice 6672 processor for printing. However, an application that chooses to provide 6673 its own notice receiver will typically ignore the notice processor 6674 layer and just do all the work in the notice receiver. 6675 </para> 6676 6677 <para> 6678 The function <function>PQsetNoticeReceiver</function> 6679 <indexterm><primary>notice receiver</primary></indexterm> 6680 <indexterm><primary>PQsetNoticeReceiver</primary></indexterm> sets or 6681 examines the current notice receiver for a connection object. 6682 Similarly, <function>PQsetNoticeProcessor</function> 6683 <indexterm><primary>notice processor</primary></indexterm> 6684 <indexterm><primary>PQsetNoticeProcessor</primary></indexterm> sets or 6685 examines the current notice processor. 6686 6687<synopsis> 6688typedef void (*PQnoticeReceiver) (void *arg, const PGresult *res); 6689 6690PQnoticeReceiver 6691PQsetNoticeReceiver(PGconn *conn, 6692 PQnoticeReceiver proc, 6693 void *arg); 6694 6695typedef void (*PQnoticeProcessor) (void *arg, const char *message); 6696 6697PQnoticeProcessor 6698PQsetNoticeProcessor(PGconn *conn, 6699 PQnoticeProcessor proc, 6700 void *arg); 6701</synopsis> 6702 6703 Each of these functions returns the previous notice receiver or 6704 processor function pointer, and sets the new value. If you supply a 6705 null function pointer, no action is taken, but the current pointer is 6706 returned. 6707 </para> 6708 6709 <para> 6710 When a notice or warning message is received from the server, or 6711 generated internally by <application>libpq</application>, the notice 6712 receiver function is called. It is passed the message in the form of 6713 a <symbol>PGRES_NONFATAL_ERROR</symbol> 6714 <structname>PGresult</structname>. (This allows the receiver to extract 6715 individual fields using <function>PQresultErrorField</function>, or obtain a 6716 complete preformatted message using <function>PQresultErrorMessage</function> 6717 or <function>PQresultVerboseErrorMessage</function>.) The same 6718 void pointer passed to <function>PQsetNoticeReceiver</function> is also 6719 passed. (This pointer can be used to access application-specific state 6720 if needed.) 6721 </para> 6722 6723 <para> 6724 The default notice receiver simply extracts the message (using 6725 <function>PQresultErrorMessage</function>) and passes it to the notice 6726 processor. 6727 </para> 6728 6729 <para> 6730 The notice processor is responsible for handling a notice or warning 6731 message given in text form. It is passed the string text of the message 6732 (including a trailing newline), plus a void pointer that is the same 6733 one passed to <function>PQsetNoticeProcessor</function>. (This pointer 6734 can be used to access application-specific state if needed.) 6735 </para> 6736 6737 <para> 6738 The default notice processor is simply: 6739<programlisting> 6740static void 6741defaultNoticeProcessor(void *arg, const char *message) 6742{ 6743 fprintf(stderr, "%s", message); 6744} 6745</programlisting> 6746 </para> 6747 6748 <para> 6749 Once you have set a notice receiver or processor, you should expect 6750 that that function could be called as long as either the 6751 <structname>PGconn</structname> object or <structname>PGresult</structname> objects made 6752 from it exist. At creation of a <structname>PGresult</structname>, the 6753 <structname>PGconn</structname>'s current notice handling pointers are copied 6754 into the <structname>PGresult</structname> for possible use by functions like 6755 <function>PQgetvalue</function>. 6756 </para> 6757 6758 </sect1> 6759 6760 <sect1 id="libpq-events"> 6761 <title>Event System</title> 6762 6763 <para> 6764 <application>libpq</application>'s event system is designed to notify 6765 registered event handlers about interesting 6766 <application>libpq</application> events, such as the creation or 6767 destruction of <structname>PGconn</structname> and 6768 <structname>PGresult</structname> objects. A principal use case is that 6769 this allows applications to associate their own data with a 6770 <structname>PGconn</structname> or <structname>PGresult</structname> 6771 and ensure that that data is freed at an appropriate time. 6772 </para> 6773 6774 <para> 6775 Each registered event handler is associated with two pieces of data, 6776 known to <application>libpq</application> only as opaque <literal>void *</literal> 6777 pointers. There is a <firstterm>passthrough</firstterm> pointer that is provided 6778 by the application when the event handler is registered with a 6779 <structname>PGconn</structname>. The passthrough pointer never changes for the 6780 life of the <structname>PGconn</structname> and all <structname>PGresult</structname>s 6781 generated from it; so if used, it must point to long-lived data. 6782 In addition there is an <firstterm>instance data</firstterm> pointer, which starts 6783 out <symbol>NULL</symbol> in every <structname>PGconn</structname> and <structname>PGresult</structname>. 6784 This pointer can be manipulated using the 6785 <function>PQinstanceData</function>, 6786 <function>PQsetInstanceData</function>, 6787 <function>PQresultInstanceData</function> and 6788 <function>PQsetResultInstanceData</function> functions. Note that 6789 unlike the passthrough pointer, instance data of a <structname>PGconn</structname> 6790 is not automatically inherited by <structname>PGresult</structname>s created from 6791 it. <application>libpq</application> does not know what passthrough 6792 and instance data pointers point to (if anything) and will never attempt 6793 to free them — that is the responsibility of the event handler. 6794 </para> 6795 6796 <sect2 id="libpq-events-types"> 6797 <title>Event Types</title> 6798 6799 <para> 6800 The enum <literal>PGEventId</literal> names the types of events handled by 6801 the event system. All its values have names beginning with 6802 <literal>PGEVT</literal>. For each event type, there is a corresponding 6803 event info structure that carries the parameters passed to the event 6804 handlers. The event types are: 6805 </para> 6806 6807 <variablelist> 6808 <varlistentry id="libpq-pgevt-register"> 6809 <term><literal>PGEVT_REGISTER</literal></term> 6810 <listitem> 6811 <para> 6812 The register event occurs when <function>PQregisterEventProc</function> 6813 is called. It is the ideal time to initialize any 6814 <literal>instanceData</literal> an event procedure may need. Only one 6815 register event will be fired per event handler per connection. If the 6816 event procedure fails, the registration is aborted. 6817 6818<synopsis> 6819typedef struct 6820{ 6821 PGconn *conn; 6822} PGEventRegister; 6823</synopsis> 6824 6825 When a <literal>PGEVT_REGISTER</literal> event is received, the 6826 <parameter>evtInfo</parameter> pointer should be cast to a 6827 <structname>PGEventRegister *</structname>. This structure contains a 6828 <structname>PGconn</structname> that should be in the 6829 <literal>CONNECTION_OK</literal> status; guaranteed if one calls 6830 <function>PQregisterEventProc</function> right after obtaining a good 6831 <structname>PGconn</structname>. When returning a failure code, all 6832 cleanup must be performed as no <literal>PGEVT_CONNDESTROY</literal> 6833 event will be sent. 6834 </para> 6835 </listitem> 6836 </varlistentry> 6837 6838 <varlistentry id="libpq-pgevt-connreset"> 6839 <term><literal>PGEVT_CONNRESET</literal></term> 6840 <listitem> 6841 <para> 6842 The connection reset event is fired on completion of 6843 <function>PQreset</function> or <function>PQresetPoll</function>. In 6844 both cases, the event is only fired if the reset was successful. If 6845 the event procedure fails, the entire connection reset will fail; the 6846 <structname>PGconn</structname> is put into 6847 <literal>CONNECTION_BAD</literal> status and 6848 <function>PQresetPoll</function> will return 6849 <literal>PGRES_POLLING_FAILED</literal>. 6850 6851<synopsis> 6852typedef struct 6853{ 6854 PGconn *conn; 6855} PGEventConnReset; 6856</synopsis> 6857 6858 When a <literal>PGEVT_CONNRESET</literal> event is received, the 6859 <parameter>evtInfo</parameter> pointer should be cast to a 6860 <structname>PGEventConnReset *</structname>. Although the contained 6861 <structname>PGconn</structname> was just reset, all event data remains 6862 unchanged. This event should be used to reset/reload/requery any 6863 associated <literal>instanceData</literal>. Note that even if the 6864 event procedure fails to process <literal>PGEVT_CONNRESET</literal>, it will 6865 still receive a <literal>PGEVT_CONNDESTROY</literal> event when the connection 6866 is closed. 6867 </para> 6868 </listitem> 6869 </varlistentry> 6870 6871 <varlistentry id="libpq-pgevt-conndestroy"> 6872 <term><literal>PGEVT_CONNDESTROY</literal></term> 6873 <listitem> 6874 <para> 6875 The connection destroy event is fired in response to 6876 <function>PQfinish</function>. It is the event procedure's 6877 responsibility to properly clean up its event data as libpq has no 6878 ability to manage this memory. Failure to clean up will lead 6879 to memory leaks. 6880 6881<synopsis> 6882typedef struct 6883{ 6884 PGconn *conn; 6885} PGEventConnDestroy; 6886</synopsis> 6887 6888 When a <literal>PGEVT_CONNDESTROY</literal> event is received, the 6889 <parameter>evtInfo</parameter> pointer should be cast to a 6890 <structname>PGEventConnDestroy *</structname>. This event is fired 6891 prior to <function>PQfinish</function> performing any other cleanup. 6892 The return value of the event procedure is ignored since there is no 6893 way of indicating a failure from <function>PQfinish</function>. Also, 6894 an event procedure failure should not abort the process of cleaning up 6895 unwanted memory. 6896 </para> 6897 </listitem> 6898 </varlistentry> 6899 6900 <varlistentry id="libpq-pgevt-resultcreate"> 6901 <term><literal>PGEVT_RESULTCREATE</literal></term> 6902 <listitem> 6903 <para> 6904 The result creation event is fired in response to any query execution 6905 function that generates a result, including 6906 <function>PQgetResult</function>. This event will only be fired after 6907 the result has been created successfully. 6908 6909<synopsis> 6910typedef struct 6911{ 6912 PGconn *conn; 6913 PGresult *result; 6914} PGEventResultCreate; 6915</synopsis> 6916 6917 When a <literal>PGEVT_RESULTCREATE</literal> event is received, the 6918 <parameter>evtInfo</parameter> pointer should be cast to a 6919 <structname>PGEventResultCreate *</structname>. The 6920 <parameter>conn</parameter> is the connection used to generate the 6921 result. This is the ideal place to initialize any 6922 <literal>instanceData</literal> that needs to be associated with the 6923 result. If the event procedure fails, the result will be cleared and 6924 the failure will be propagated. The event procedure must not try to 6925 <function>PQclear</function> the result object for itself. When returning a 6926 failure code, all cleanup must be performed as no 6927 <literal>PGEVT_RESULTDESTROY</literal> event will be sent. 6928 </para> 6929 </listitem> 6930 </varlistentry> 6931 6932 <varlistentry id="libpq-pgevt-resultcopy"> 6933 <term><literal>PGEVT_RESULTCOPY</literal></term> 6934 <listitem> 6935 <para> 6936 The result copy event is fired in response to 6937 <function>PQcopyResult</function>. This event will only be fired after 6938 the copy is complete. Only event procedures that have 6939 successfully handled the <literal>PGEVT_RESULTCREATE</literal> 6940 or <literal>PGEVT_RESULTCOPY</literal> event for the source result 6941 will receive <literal>PGEVT_RESULTCOPY</literal> events. 6942 6943<synopsis> 6944typedef struct 6945{ 6946 const PGresult *src; 6947 PGresult *dest; 6948} PGEventResultCopy; 6949</synopsis> 6950 6951 When a <literal>PGEVT_RESULTCOPY</literal> event is received, the 6952 <parameter>evtInfo</parameter> pointer should be cast to a 6953 <structname>PGEventResultCopy *</structname>. The 6954 <parameter>src</parameter> result is what was copied while the 6955 <parameter>dest</parameter> result is the copy destination. This event 6956 can be used to provide a deep copy of <literal>instanceData</literal>, 6957 since <literal>PQcopyResult</literal> cannot do that. If the event 6958 procedure fails, the entire copy operation will fail and the 6959 <parameter>dest</parameter> result will be cleared. When returning a 6960 failure code, all cleanup must be performed as no 6961 <literal>PGEVT_RESULTDESTROY</literal> event will be sent for the 6962 destination result. 6963 </para> 6964 </listitem> 6965 </varlistentry> 6966 6967 <varlistentry id="libpq-pgevt-resultdestroy"> 6968 <term><literal>PGEVT_RESULTDESTROY</literal></term> 6969 <listitem> 6970 <para> 6971 The result destroy event is fired in response to a 6972 <function>PQclear</function>. It is the event procedure's 6973 responsibility to properly clean up its event data as libpq has no 6974 ability to manage this memory. Failure to clean up will lead 6975 to memory leaks. 6976 6977<synopsis> 6978typedef struct 6979{ 6980 PGresult *result; 6981} PGEventResultDestroy; 6982</synopsis> 6983 6984 When a <literal>PGEVT_RESULTDESTROY</literal> event is received, the 6985 <parameter>evtInfo</parameter> pointer should be cast to a 6986 <structname>PGEventResultDestroy *</structname>. This event is fired 6987 prior to <function>PQclear</function> performing any other cleanup. 6988 The return value of the event procedure is ignored since there is no 6989 way of indicating a failure from <function>PQclear</function>. Also, 6990 an event procedure failure should not abort the process of cleaning up 6991 unwanted memory. 6992 </para> 6993 </listitem> 6994 </varlistentry> 6995 </variablelist> 6996 </sect2> 6997 6998 <sect2 id="libpq-events-proc"> 6999 <title>Event Callback Procedure</title> 7000 7001 <variablelist> 7002 <varlistentry id="libpq-pgeventproc"> 7003 <term> 7004 <literal>PGEventProc</literal> 7005 <indexterm> 7006 <primary>PGEventProc</primary> 7007 </indexterm> 7008 </term> 7009 7010 <listitem> 7011 <para> 7012 <literal>PGEventProc</literal> is a typedef for a pointer to an 7013 event procedure, that is, the user callback function that receives 7014 events from libpq. The signature of an event procedure must be 7015 7016<synopsis> 7017int eventproc(PGEventId evtId, void *evtInfo, void *passThrough) 7018</synopsis> 7019 7020 The <parameter>evtId</parameter> parameter indicates which 7021 <literal>PGEVT</literal> event occurred. The 7022 <parameter>evtInfo</parameter> pointer must be cast to the appropriate 7023 structure type to obtain further information about the event. 7024 The <parameter>passThrough</parameter> parameter is the pointer 7025 provided to <function>PQregisterEventProc</function> when the event 7026 procedure was registered. The function should return a non-zero value 7027 if it succeeds and zero if it fails. 7028 </para> 7029 7030 <para> 7031 A particular event procedure can be registered only once in any 7032 <structname>PGconn</structname>. This is because the address of the procedure 7033 is used as a lookup key to identify the associated instance data. 7034 </para> 7035 7036 <caution> 7037 <para> 7038 On Windows, functions can have two different addresses: one visible 7039 from outside a DLL and another visible from inside the DLL. One 7040 should be careful that only one of these addresses is used with 7041 <application>libpq</application>'s event-procedure functions, else confusion will 7042 result. The simplest rule for writing code that will work is to 7043 ensure that event procedures are declared <literal>static</literal>. If the 7044 procedure's address must be available outside its own source file, 7045 expose a separate function to return the address. 7046 </para> 7047 </caution> 7048 </listitem> 7049 </varlistentry> 7050 </variablelist> 7051 </sect2> 7052 7053 <sect2 id="libpq-events-funcs"> 7054 <title>Event Support Functions</title> 7055 7056 <variablelist> 7057 <varlistentry id="libpq-pqregistereventproc"> 7058 <term> 7059 <function>PQregisterEventProc</function> 7060 <indexterm> 7061 <primary>PQregisterEventProc</primary> 7062 </indexterm> 7063 </term> 7064 7065 <listitem> 7066 <para> 7067 Registers an event callback procedure with libpq. 7068 7069<synopsis> 7070int PQregisterEventProc(PGconn *conn, PGEventProc proc, 7071 const char *name, void *passThrough); 7072</synopsis> 7073 </para> 7074 7075 <para> 7076 An event procedure must be registered once on each 7077 <structname>PGconn</structname> you want to receive events about. There is no 7078 limit, other than memory, on the number of event procedures that 7079 can be registered with a connection. The function returns a non-zero 7080 value if it succeeds and zero if it fails. 7081 </para> 7082 7083 <para> 7084 The <parameter>proc</parameter> argument will be called when a libpq 7085 event is fired. Its memory address is also used to lookup 7086 <literal>instanceData</literal>. The <parameter>name</parameter> 7087 argument is used to refer to the event procedure in error messages. 7088 This value cannot be <symbol>NULL</symbol> or a zero-length string. The name string is 7089 copied into the <structname>PGconn</structname>, so what is passed need not be 7090 long-lived. The <parameter>passThrough</parameter> pointer is passed 7091 to the <parameter>proc</parameter> whenever an event occurs. This 7092 argument can be <symbol>NULL</symbol>. 7093 </para> 7094 </listitem> 7095 </varlistentry> 7096 7097 <varlistentry id="libpq-pqsetinstancedata"> 7098 <term> 7099 <function>PQsetInstanceData</function> 7100 <indexterm> 7101 <primary>PQsetInstanceData</primary> 7102 </indexterm> 7103 </term> 7104 <listitem> 7105 <para> 7106 Sets the connection <parameter>conn</parameter>'s <literal>instanceData</literal> 7107 for procedure <parameter>proc</parameter> to <parameter>data</parameter>. This 7108 returns non-zero for success and zero for failure. (Failure is 7109 only possible if <parameter>proc</parameter> has not been properly 7110 registered in <parameter>conn</parameter>.) 7111 7112<synopsis> 7113int PQsetInstanceData(PGconn *conn, PGEventProc proc, void *data); 7114</synopsis> 7115 </para> 7116 </listitem> 7117 </varlistentry> 7118 7119 <varlistentry id="libpq-pqinstancedata"> 7120 <term> 7121 <function>PQinstanceData</function> 7122 <indexterm> 7123 <primary>PQinstanceData</primary> 7124 </indexterm> 7125 </term> 7126 <listitem> 7127 <para> 7128 Returns the 7129 connection <parameter>conn</parameter>'s <literal>instanceData</literal> 7130 associated with procedure <parameter>proc</parameter>, 7131 or <symbol>NULL</symbol> if there is none. 7132 7133<synopsis> 7134void *PQinstanceData(const PGconn *conn, PGEventProc proc); 7135</synopsis> 7136 </para> 7137 </listitem> 7138 </varlistentry> 7139 7140 <varlistentry id="libpq-pqresultsetinstancedata"> 7141 <term> 7142 <function>PQresultSetInstanceData</function> 7143 <indexterm> 7144 <primary>PQresultSetInstanceData</primary> 7145 </indexterm> 7146 </term> 7147 <listitem> 7148 <para> 7149 Sets the result's <literal>instanceData</literal> 7150 for <parameter>proc</parameter> to <parameter>data</parameter>. This returns 7151 non-zero for success and zero for failure. (Failure is only 7152 possible if <parameter>proc</parameter> has not been properly registered 7153 in the result.) 7154 7155<synopsis> 7156int PQresultSetInstanceData(PGresult *res, PGEventProc proc, void *data); 7157</synopsis> 7158 </para> 7159 7160 <para> 7161 Beware that any storage represented by <parameter>data</parameter> 7162 will not be accounted for by <function>PQresultMemorySize</function>, 7163 unless it is allocated using <function>PQresultAlloc</function>. 7164 (Doing so is recommendable because it eliminates the need to free 7165 such storage explicitly when the result is destroyed.) 7166 </para> 7167 </listitem> 7168 </varlistentry> 7169 7170 <varlistentry id="libpq-pqresultinstancedata"> 7171 <term> 7172 <function>PQresultInstanceData</function> 7173 <indexterm> 7174 <primary>PQresultInstanceData</primary> 7175 </indexterm> 7176 </term> 7177 <listitem> 7178 <para> 7179 Returns the result's <literal>instanceData</literal> associated with <parameter>proc</parameter>, or <symbol>NULL</symbol> 7180 if there is none. 7181 7182<synopsis> 7183void *PQresultInstanceData(const PGresult *res, PGEventProc proc); 7184</synopsis> 7185 </para> 7186 </listitem> 7187 </varlistentry> 7188 </variablelist> 7189 </sect2> 7190 7191 <sect2 id="libpq-events-example"> 7192 <title>Event Example</title> 7193 7194 <para> 7195 Here is a skeleton example of managing private data associated with 7196 libpq connections and results. 7197 </para> 7198 7199<programlisting> 7200<![CDATA[ 7201/* required header for libpq events (note: includes libpq-fe.h) */ 7202#include <libpq-events.h> 7203 7204/* The instanceData */ 7205typedef struct 7206{ 7207 int n; 7208 char *str; 7209} mydata; 7210 7211/* PGEventProc */ 7212static int myEventProc(PGEventId evtId, void *evtInfo, void *passThrough); 7213 7214int 7215main(void) 7216{ 7217 mydata *data; 7218 PGresult *res; 7219 PGconn *conn = 7220 PQconnectdb("dbname=postgres options=-csearch_path="); 7221 7222 if (PQstatus(conn) != CONNECTION_OK) 7223 { 7224 fprintf(stderr, "Connection to database failed: %s", 7225 PQerrorMessage(conn)); 7226 PQfinish(conn); 7227 return 1; 7228 } 7229 7230 /* called once on any connection that should receive events. 7231 * Sends a PGEVT_REGISTER to myEventProc. 7232 */ 7233 if (!PQregisterEventProc(conn, myEventProc, "mydata_proc", NULL)) 7234 { 7235 fprintf(stderr, "Cannot register PGEventProc\n"); 7236 PQfinish(conn); 7237 return 1; 7238 } 7239 7240 /* conn instanceData is available */ 7241 data = PQinstanceData(conn, myEventProc); 7242 7243 /* Sends a PGEVT_RESULTCREATE to myEventProc */ 7244 res = PQexec(conn, "SELECT 1 + 1"); 7245 7246 /* result instanceData is available */ 7247 data = PQresultInstanceData(res, myEventProc); 7248 7249 /* If PG_COPYRES_EVENTS is used, sends a PGEVT_RESULTCOPY to myEventProc */ 7250 res_copy = PQcopyResult(res, PG_COPYRES_TUPLES | PG_COPYRES_EVENTS); 7251 7252 /* result instanceData is available if PG_COPYRES_EVENTS was 7253 * used during the PQcopyResult call. 7254 */ 7255 data = PQresultInstanceData(res_copy, myEventProc); 7256 7257 /* Both clears send a PGEVT_RESULTDESTROY to myEventProc */ 7258 PQclear(res); 7259 PQclear(res_copy); 7260 7261 /* Sends a PGEVT_CONNDESTROY to myEventProc */ 7262 PQfinish(conn); 7263 7264 return 0; 7265} 7266 7267static int 7268myEventProc(PGEventId evtId, void *evtInfo, void *passThrough) 7269{ 7270 switch (evtId) 7271 { 7272 case PGEVT_REGISTER: 7273 { 7274 PGEventRegister *e = (PGEventRegister *)evtInfo; 7275 mydata *data = get_mydata(e->conn); 7276 7277 /* associate app specific data with connection */ 7278 PQsetInstanceData(e->conn, myEventProc, data); 7279 break; 7280 } 7281 7282 case PGEVT_CONNRESET: 7283 { 7284 PGEventConnReset *e = (PGEventConnReset *)evtInfo; 7285 mydata *data = PQinstanceData(e->conn, myEventProc); 7286 7287 if (data) 7288 memset(data, 0, sizeof(mydata)); 7289 break; 7290 } 7291 7292 case PGEVT_CONNDESTROY: 7293 { 7294 PGEventConnDestroy *e = (PGEventConnDestroy *)evtInfo; 7295 mydata *data = PQinstanceData(e->conn, myEventProc); 7296 7297 /* free instance data because the conn is being destroyed */ 7298 if (data) 7299 free_mydata(data); 7300 break; 7301 } 7302 7303 case PGEVT_RESULTCREATE: 7304 { 7305 PGEventResultCreate *e = (PGEventResultCreate *)evtInfo; 7306 mydata *conn_data = PQinstanceData(e->conn, myEventProc); 7307 mydata *res_data = dup_mydata(conn_data); 7308 7309 /* associate app specific data with result (copy it from conn) */ 7310 PQsetResultInstanceData(e->result, myEventProc, res_data); 7311 break; 7312 } 7313 7314 case PGEVT_RESULTCOPY: 7315 { 7316 PGEventResultCopy *e = (PGEventResultCopy *)evtInfo; 7317 mydata *src_data = PQresultInstanceData(e->src, myEventProc); 7318 mydata *dest_data = dup_mydata(src_data); 7319 7320 /* associate app specific data with result (copy it from a result) */ 7321 PQsetResultInstanceData(e->dest, myEventProc, dest_data); 7322 break; 7323 } 7324 7325 case PGEVT_RESULTDESTROY: 7326 { 7327 PGEventResultDestroy *e = (PGEventResultDestroy *)evtInfo; 7328 mydata *data = PQresultInstanceData(e->result, myEventProc); 7329 7330 /* free instance data because the result is being destroyed */ 7331 if (data) 7332 free_mydata(data); 7333 break; 7334 } 7335 7336 /* unknown event ID, just return true. */ 7337 default: 7338 break; 7339 } 7340 7341 return true; /* event processing succeeded */ 7342} 7343]]> 7344</programlisting> 7345 </sect2> 7346 </sect1> 7347 7348 <sect1 id="libpq-envars"> 7349 <title>Environment Variables</title> 7350 7351 <indexterm zone="libpq-envars"> 7352 <primary>environment variable</primary> 7353 </indexterm> 7354 7355 <para> 7356 The following environment variables can be used to select default 7357 connection parameter values, which will be used by 7358 <function>PQconnectdb</function>, <function>PQsetdbLogin</function> and 7359 <function>PQsetdb</function> if no value is directly specified by the calling 7360 code. These are useful to avoid hard-coding database connection 7361 information into simple client applications, for example. 7362 7363 <itemizedlist> 7364 <listitem> 7365 <para> 7366 <indexterm> 7367 <primary><envar>PGHOST</envar></primary> 7368 </indexterm> 7369 <envar>PGHOST</envar> behaves the same as the <xref 7370 linkend="libpq-connect-host"/> connection parameter. 7371 </para> 7372 </listitem> 7373 7374 <listitem> 7375 <para> 7376 <indexterm> 7377 <primary><envar>PGHOSTADDR</envar></primary> 7378 </indexterm> 7379 <envar>PGHOSTADDR</envar> behaves the same as the <xref 7380 linkend="libpq-connect-hostaddr"/> connection parameter. 7381 This can be set instead of or in addition to <envar>PGHOST</envar> 7382 to avoid DNS lookup overhead. 7383 </para> 7384 </listitem> 7385 7386 <listitem> 7387 <para> 7388 <indexterm> 7389 <primary><envar>PGPORT</envar></primary> 7390 </indexterm> 7391 <envar>PGPORT</envar> behaves the same as the <xref 7392 linkend="libpq-connect-port"/> connection parameter. 7393 </para> 7394 </listitem> 7395 7396 <listitem> 7397 <para> 7398 <indexterm> 7399 <primary><envar>PGDATABASE</envar></primary> 7400 </indexterm> 7401 <envar>PGDATABASE</envar> behaves the same as the <xref 7402 linkend="libpq-connect-dbname"/> connection parameter. 7403 </para> 7404 </listitem> 7405 7406 <listitem> 7407 <para> 7408 <indexterm> 7409 <primary><envar>PGUSER</envar></primary> 7410 </indexterm> 7411 <envar>PGUSER</envar> behaves the same as the <xref 7412 linkend="libpq-connect-user"/> connection parameter. 7413 </para> 7414 </listitem> 7415 7416 <listitem> 7417 <para> 7418 <indexterm> 7419 <primary><envar>PGPASSWORD</envar></primary> 7420 </indexterm> 7421 <envar>PGPASSWORD</envar> behaves the same as the <xref 7422 linkend="libpq-connect-password"/> connection parameter. 7423 Use of this environment variable 7424 is not recommended for security reasons, as some operating systems 7425 allow non-root users to see process environment variables via 7426 <application>ps</application>; instead consider using a password file 7427 (see <xref linkend="libpq-pgpass"/>). 7428 </para> 7429 </listitem> 7430 7431 <listitem> 7432 <para> 7433 <indexterm> 7434 <primary><envar>PGPASSFILE</envar></primary> 7435 </indexterm> 7436 <envar>PGPASSFILE</envar> behaves the same as the <xref 7437 linkend="libpq-connect-passfile"/> connection parameter. 7438 </para> 7439 </listitem> 7440 7441 <listitem> 7442 <para> 7443 <indexterm> 7444 <primary><envar>PGSERVICE</envar></primary> 7445 </indexterm> 7446 <envar>PGSERVICE</envar> behaves the same as the <xref 7447 linkend="libpq-connect-service"/> connection parameter. 7448 </para> 7449 </listitem> 7450 7451 <listitem> 7452 <para> 7453 <indexterm> 7454 <primary><envar>PGSERVICEFILE</envar></primary> 7455 </indexterm> 7456 <envar>PGSERVICEFILE</envar> specifies the name of the per-user 7457 connection service file. If not set, it defaults 7458 to <filename>~/.pg_service.conf</filename> 7459 (see <xref linkend="libpq-pgservice"/>). 7460 </para> 7461 </listitem> 7462 7463 <listitem> 7464 <para> 7465 <indexterm> 7466 <primary><envar>PGOPTIONS</envar></primary> 7467 </indexterm> 7468 <envar>PGOPTIONS</envar> behaves the same as the <xref 7469 linkend="libpq-connect-options"/> connection parameter. 7470 </para> 7471 </listitem> 7472 7473 <listitem> 7474 <para> 7475 <indexterm> 7476 <primary><envar>PGAPPNAME</envar></primary> 7477 </indexterm> 7478 <envar>PGAPPNAME</envar> behaves the same as the <xref 7479 linkend="libpq-connect-application-name"/> connection parameter. 7480 </para> 7481 </listitem> 7482 7483 <listitem> 7484 <para> 7485 <indexterm> 7486 <primary><envar>PGSSLMODE</envar></primary> 7487 </indexterm> 7488 <envar>PGSSLMODE</envar> behaves the same as the <xref 7489 linkend="libpq-connect-sslmode"/> connection parameter. 7490 </para> 7491 </listitem> 7492 7493 <listitem> 7494 <para> 7495 <indexterm> 7496 <primary><envar>PGREQUIRESSL</envar></primary> 7497 </indexterm> 7498 <envar>PGREQUIRESSL</envar> behaves the same as the <xref 7499 linkend="libpq-connect-requiressl"/> connection parameter. 7500 This environment variable is deprecated in favor of the 7501 <envar>PGSSLMODE</envar> variable; setting both variables suppresses the 7502 effect of this one. 7503 </para> 7504 </listitem> 7505 7506 <listitem> 7507 <para> 7508 <indexterm> 7509 <primary><envar>PGSSLCOMPRESSION</envar></primary> 7510 </indexterm> 7511 <envar>PGSSLCOMPRESSION</envar> behaves the same as the <xref 7512 linkend="libpq-connect-sslcompression"/> connection parameter. 7513 </para> 7514 </listitem> 7515 7516 <listitem> 7517 <para> 7518 <indexterm> 7519 <primary><envar>PGSSLCERT</envar></primary> 7520 </indexterm> 7521 <envar>PGSSLCERT</envar> behaves the same as the <xref 7522 linkend="libpq-connect-sslcert"/> connection parameter. 7523 </para> 7524 </listitem> 7525 7526 <listitem> 7527 <para> 7528 <indexterm> 7529 <primary><envar>PGSSLKEY</envar></primary> 7530 </indexterm> 7531 <envar>PGSSLKEY</envar> behaves the same as the <xref 7532 linkend="libpq-connect-sslkey"/> connection parameter. 7533 </para> 7534 </listitem> 7535 7536 <listitem> 7537 <para> 7538 <indexterm> 7539 <primary><envar>PGSSLROOTCERT</envar></primary> 7540 </indexterm> 7541 <envar>PGSSLROOTCERT</envar> behaves the same as the <xref 7542 linkend="libpq-connect-sslrootcert"/> connection parameter. 7543 </para> 7544 </listitem> 7545 7546 <listitem> 7547 <para> 7548 <indexterm> 7549 <primary><envar>PGSSLCRL</envar></primary> 7550 </indexterm> 7551 <envar>PGSSLCRL</envar> behaves the same as the <xref 7552 linkend="libpq-connect-sslcrl"/> connection parameter. 7553 </para> 7554 </listitem> 7555 7556 <listitem> 7557 <para> 7558 <indexterm> 7559 <primary><envar>PGREQUIREPEER</envar></primary> 7560 </indexterm> 7561 <envar>PGREQUIREPEER</envar> behaves the same as the <xref 7562 linkend="libpq-connect-requirepeer"/> connection parameter. 7563 </para> 7564 </listitem> 7565 7566 <listitem> 7567 <para> 7568 <indexterm> 7569 <primary><envar>PGGSSENCMODE</envar></primary> 7570 </indexterm> 7571 <envar>PGGSSENCMODE</envar> behaves the same as the <xref 7572 linkend="libpq-connect-gssencmode"/> connection parameter. 7573 </para> 7574 </listitem> 7575 7576 <listitem> 7577 <para> 7578 <indexterm> 7579 <primary><envar>PGKRBSRVNAME</envar></primary> 7580 </indexterm> 7581 <envar>PGKRBSRVNAME</envar> behaves the same as the <xref 7582 linkend="libpq-connect-krbsrvname"/> connection parameter. 7583 </para> 7584 </listitem> 7585 7586 <listitem> 7587 <para> 7588 <indexterm> 7589 <primary><envar>PGGSSLIB</envar></primary> 7590 </indexterm> 7591 <envar>PGGSSLIB</envar> behaves the same as the <xref 7592 linkend="libpq-connect-gsslib"/> connection parameter. 7593 </para> 7594 </listitem> 7595 7596 <listitem> 7597 <para> 7598 <indexterm> 7599 <primary><envar>PGCONNECT_TIMEOUT</envar></primary> 7600 </indexterm> 7601 <envar>PGCONNECT_TIMEOUT</envar> behaves the same as the <xref 7602 linkend="libpq-connect-connect-timeout"/> connection parameter. 7603 </para> 7604 </listitem> 7605 7606 <listitem> 7607 <para> 7608 <indexterm> 7609 <primary><envar>PGCLIENTENCODING</envar></primary> 7610 </indexterm> 7611 <envar>PGCLIENTENCODING</envar> behaves the same as the <xref 7612 linkend="libpq-connect-client-encoding"/> connection parameter. 7613 </para> 7614 </listitem> 7615 7616 <listitem> 7617 <para> 7618 <indexterm> 7619 <primary><envar>PGTARGETSESSIONATTRS</envar></primary> 7620 </indexterm> 7621 <envar>PGTARGETSESSIONATTRS</envar> behaves the same as the <xref 7622 linkend="libpq-connect-target-session-attrs"/> connection parameter. 7623 </para> 7624 </listitem> 7625 </itemizedlist> 7626 </para> 7627 7628 <para> 7629 The following environment variables can be used to specify default 7630 behavior for each <productname>PostgreSQL</productname> session. (See 7631 also the <xref linkend="sql-alterrole"/> 7632 and <xref linkend="sql-alterdatabase"/> 7633 commands for ways to set default behavior on a per-user or per-database 7634 basis.) 7635 7636 <itemizedlist> 7637 <listitem> 7638 <para> 7639 <indexterm> 7640 <primary><envar>PGDATESTYLE</envar></primary> 7641 </indexterm> 7642 <envar>PGDATESTYLE</envar> sets the default style of date/time 7643 representation. (Equivalent to <literal>SET datestyle TO 7644 ...</literal>.) 7645 </para> 7646 </listitem> 7647 7648 <listitem> 7649 <para> 7650 <indexterm> 7651 <primary><envar>PGTZ</envar></primary> 7652 </indexterm> 7653 <envar>PGTZ</envar> sets the default time zone. (Equivalent to 7654 <literal>SET timezone TO ...</literal>.) 7655 </para> 7656 </listitem> 7657 7658 <listitem> 7659 <para> 7660 <indexterm> 7661 <primary><envar>PGGEQO</envar></primary> 7662 </indexterm> 7663 <envar>PGGEQO</envar> sets the default mode for the genetic query 7664 optimizer. (Equivalent to <literal>SET geqo TO ...</literal>.) 7665 </para> 7666 </listitem> 7667 </itemizedlist> 7668 7669 Refer to the <acronym>SQL</acronym> command <xref linkend="sql-set"/> 7670 for information on correct values for these 7671 environment variables. 7672 </para> 7673 7674 <para> 7675 The following environment variables determine internal behavior of 7676 <application>libpq</application>; they override compiled-in defaults. 7677 7678 <itemizedlist> 7679 <listitem> 7680 <para> 7681 <indexterm> 7682 <primary><envar>PGSYSCONFDIR</envar></primary> 7683 </indexterm> 7684 <envar>PGSYSCONFDIR</envar> sets the directory containing the 7685 <filename>pg_service.conf</filename> file and in a future version 7686 possibly other system-wide configuration files. 7687 </para> 7688 </listitem> 7689 7690 <listitem> 7691 <para> 7692 <indexterm> 7693 <primary><envar>PGLOCALEDIR</envar></primary> 7694 </indexterm> 7695 <envar>PGLOCALEDIR</envar> sets the directory containing the 7696 <literal>locale</literal> files for message localization. 7697 </para> 7698 </listitem> 7699 </itemizedlist> 7700 </para> 7701 7702 </sect1> 7703 7704 7705 <sect1 id="libpq-pgpass"> 7706 <title>The Password File</title> 7707 7708 <indexterm zone="libpq-pgpass"> 7709 <primary>password file</primary> 7710 </indexterm> 7711 <indexterm zone="libpq-pgpass"> 7712 <primary>.pgpass</primary> 7713 </indexterm> 7714 7715 <para> 7716 The file <filename>.pgpass</filename> in a user's home directory can 7717 contain passwords to 7718 be used if the connection requires a password (and no password has been 7719 specified otherwise). On Microsoft Windows the file is named 7720 <filename>%APPDATA%\postgresql\pgpass.conf</filename> (where 7721 <filename>%APPDATA%</filename> refers to the Application Data subdirectory in 7722 the user's profile). 7723 Alternatively, a password file can be specified 7724 using the connection parameter <xref linkend="libpq-connect-passfile"/> 7725 or the environment variable <envar>PGPASSFILE</envar>. 7726 </para> 7727 7728 <para> 7729 This file should contain lines of the following format: 7730<synopsis> 7731<replaceable>hostname</replaceable>:<replaceable>port</replaceable>:<replaceable>database</replaceable>:<replaceable>username</replaceable>:<replaceable>password</replaceable> 7732</synopsis> 7733 (You can add a reminder comment to the file by copying the line above and 7734 preceding it with <literal>#</literal>.) 7735 Each of the first four fields can be a literal value, or 7736 <literal>*</literal>, which matches anything. The password field from 7737 the first line that matches the current connection parameters will be 7738 used. (Therefore, put more-specific entries first when you are using 7739 wildcards.) If an entry needs to contain <literal>:</literal> or 7740 <literal>\</literal>, escape this character with <literal>\</literal>. 7741 The host name field is matched to the <literal>host</literal> connection 7742 parameter if that is specified, otherwise to 7743 the <literal>hostaddr</literal> parameter if that is specified; if neither 7744 are given then the host name <literal>localhost</literal> is searched for. 7745 The host name <literal>localhost</literal> is also searched for when 7746 the connection is a Unix-domain socket connection and 7747 the <literal>host</literal> parameter 7748 matches <application>libpq</application>'s default socket directory path. 7749 In a standby server, a database field of <literal>replication</literal> 7750 matches streaming replication connections made to the master server. 7751 The database field is of limited usefulness otherwise, because users have 7752 the same password for all databases in the same cluster. 7753 </para> 7754 7755 <para> 7756 On Unix systems, the permissions on a password file must 7757 disallow any access to world or group; achieve this by a command such as 7758 <command>chmod 0600 ~/.pgpass</command>. If the permissions are less 7759 strict than this, the file will be ignored. On Microsoft Windows, it 7760 is assumed that the file is stored in a directory that is secure, so 7761 no special permissions check is made. 7762 </para> 7763 </sect1> 7764 7765 7766 <sect1 id="libpq-pgservice"> 7767 <title>The Connection Service File</title> 7768 7769 <indexterm zone="libpq-pgservice"> 7770 <primary>connection service file</primary> 7771 </indexterm> 7772 <indexterm zone="libpq-pgservice"> 7773 <primary>pg_service.conf</primary> 7774 </indexterm> 7775 <indexterm zone="libpq-pgservice"> 7776 <primary>.pg_service.conf</primary> 7777 </indexterm> 7778 7779 <para> 7780 The connection service file allows libpq connection parameters to be 7781 associated with a single service name. That service name can then be 7782 specified by a libpq connection, and the associated settings will be 7783 used. This allows connection parameters to be modified without requiring 7784 a recompile of the libpq application. The service name can also be 7785 specified using the <envar>PGSERVICE</envar> environment variable. 7786 </para> 7787 7788 <para> 7789 The connection service file can be a per-user service file 7790 at <filename>~/.pg_service.conf</filename> or the location 7791 specified by the environment variable <envar>PGSERVICEFILE</envar>, 7792 or it can be a system-wide file 7793 at <filename>`pg_config --sysconfdir`/pg_service.conf</filename> or in the directory 7794 specified by the environment variable 7795 <envar>PGSYSCONFDIR</envar>. If service definitions with the same 7796 name exist in the user and the system file, the user file takes 7797 precedence. 7798 </para> 7799 7800 <para> 7801 The file uses an <quote>INI file</quote> format where the section 7802 name is the service name and the parameters are connection 7803 parameters; see <xref linkend="libpq-paramkeywords"/> for a list. For 7804 example: 7805<programlisting> 7806# comment 7807[mydb] 7808host=somehost 7809port=5433 7810user=admin 7811</programlisting> 7812 An example file is provided at 7813 <filename>share/pg_service.conf.sample</filename>. 7814 </para> 7815 </sect1> 7816 7817 7818 <sect1 id="libpq-ldap"> 7819 <title>LDAP Lookup of Connection Parameters</title> 7820 7821 <indexterm zone="libpq-ldap"> 7822 <primary>LDAP connection parameter lookup</primary> 7823 </indexterm> 7824 7825 <para> 7826 If <application>libpq</application> has been compiled with LDAP support (option 7827 <literal><option>--with-ldap</option></literal> for <command>configure</command>) 7828 it is possible to retrieve connection options like <literal>host</literal> 7829 or <literal>dbname</literal> via LDAP from a central server. 7830 The advantage is that if the connection parameters for a database change, 7831 the connection information doesn't have to be updated on all client machines. 7832 </para> 7833 7834 <para> 7835 LDAP connection parameter lookup uses the connection service file 7836 <filename>pg_service.conf</filename> (see <xref 7837 linkend="libpq-pgservice"/>). A line in a 7838 <filename>pg_service.conf</filename> stanza that starts with 7839 <literal>ldap://</literal> will be recognized as an LDAP URL and an 7840 LDAP query will be performed. The result must be a list of 7841 <literal>keyword = value</literal> pairs which will be used to set 7842 connection options. The URL must conform to RFC 1959 and be of the 7843 form 7844<synopsis> 7845ldap://[<replaceable>hostname</replaceable>[:<replaceable>port</replaceable>]]/<replaceable>search_base</replaceable>?<replaceable>attribute</replaceable>?<replaceable>search_scope</replaceable>?<replaceable>filter</replaceable> 7846</synopsis> 7847 where <replaceable>hostname</replaceable> defaults to 7848 <literal>localhost</literal> and <replaceable>port</replaceable> 7849 defaults to 389. 7850 </para> 7851 7852 <para> 7853 Processing of <filename>pg_service.conf</filename> is terminated after 7854 a successful LDAP lookup, but is continued if the LDAP server cannot 7855 be contacted. This is to provide a fallback with further LDAP URL 7856 lines that point to different LDAP servers, classical <literal>keyword 7857 = value</literal> pairs, or default connection options. If you would 7858 rather get an error message in this case, add a syntactically incorrect 7859 line after the LDAP URL. 7860 </para> 7861 7862 <para> 7863 A sample LDAP entry that has been created with the LDIF file 7864<programlisting> 7865version:1 7866dn:cn=mydatabase,dc=mycompany,dc=com 7867changetype:add 7868objectclass:top 7869objectclass:device 7870cn:mydatabase 7871description:host=dbserver.mycompany.com 7872description:port=5439 7873description:dbname=mydb 7874description:user=mydb_user 7875description:sslmode=require 7876</programlisting> 7877 might be queried with the following LDAP URL: 7878<programlisting> 7879ldap://ldap.mycompany.com/dc=mycompany,dc=com?description?one?(cn=mydatabase) 7880</programlisting> 7881 </para> 7882 7883 <para> 7884 You can also mix regular service file entries with LDAP lookups. 7885 A complete example for a stanza in <filename>pg_service.conf</filename> 7886 would be: 7887<programlisting> 7888# only host and port are stored in LDAP, specify dbname and user explicitly 7889[customerdb] 7890dbname=customer 7891user=appuser 7892ldap://ldap.acme.com/cn=dbserver,cn=hosts?pgconnectinfo?base?(objectclass=*) 7893</programlisting> 7894 </para> 7895 7896 </sect1> 7897 7898 7899 <sect1 id="libpq-ssl"> 7900 <title>SSL Support</title> 7901 7902 <indexterm zone="libpq-ssl"> 7903 <primary>SSL</primary> 7904 </indexterm> 7905 7906 <para> 7907 <productname>PostgreSQL</productname> has native support for using <acronym>SSL</acronym> 7908 connections to encrypt client/server communications for increased 7909 security. See <xref linkend="ssl-tcp"/> for details about the server-side 7910 <acronym>SSL</acronym> functionality. 7911 </para> 7912 7913 <para> 7914 <application>libpq</application> reads the system-wide 7915 <productname>OpenSSL</productname> configuration file. By default, this 7916 file is named <filename>openssl.cnf</filename> and is located in the 7917 directory reported by <literal>openssl version -d</literal>. This default 7918 can be overridden by setting environment variable 7919 <envar>OPENSSL_CONF</envar> to the name of the desired configuration 7920 file. 7921 </para> 7922 7923 <sect2 id="libq-ssl-certificates"> 7924 <title>Client Verification of Server Certificates</title> 7925 7926 <para> 7927 By default, <productname>PostgreSQL</productname> will not perform any verification of 7928 the server certificate. This means that it is possible to spoof the server 7929 identity (for example by modifying a DNS record or by taking over the server 7930 IP address) without the client knowing. In order to prevent spoofing, 7931 the client must be able to verify the server's identity via a chain of 7932 trust. A chain of trust is established by placing a root (self-signed) 7933 certificate authority (<acronym>CA</acronym>) certificate on one 7934 computer and a leaf certificate <emphasis>signed</emphasis> by the 7935 root certificate on another computer. It is also possible to use an 7936 <quote>intermediate</quote> certificate which is signed by the root 7937 certificate and signs leaf certificates. 7938 </para> 7939 7940 <para> 7941 To allow the client to verify the identity of the server, place a root 7942 certificate on the client and a leaf certificate signed by the root 7943 certificate on the server. To allow the server to verify the identity 7944 of the client, place a root certificate on the server and a leaf 7945 certificate signed by the root certificate on the client. One or more 7946 intermediate certificates (usually stored with the leaf certificate) 7947 can also be used to link the leaf certificate to the root certificate. 7948 </para> 7949 7950 <para> 7951 Once a chain of trust has been established, there are two ways for 7952 the client to validate the leaf certificate sent by the server. 7953 If the parameter <literal>sslmode</literal> is set to <literal>verify-ca</literal>, 7954 libpq will verify that the server is trustworthy by checking the 7955 certificate chain up to the root certificate stored on the client. 7956 If <literal>sslmode</literal> is set to <literal>verify-full</literal>, 7957 libpq will <emphasis>also</emphasis> verify that the server host 7958 name matches the name stored in the server certificate. The 7959 SSL connection will fail if the server certificate cannot be 7960 verified. <literal>verify-full</literal> is recommended in most 7961 security-sensitive environments. 7962 </para> 7963 7964 <para> 7965 In <literal>verify-full</literal> mode, the host name is matched against the 7966 certificate's Subject Alternative Name attribute(s), or against the 7967 Common Name attribute if no Subject Alternative Name of type <literal>dNSName</literal> is 7968 present. If the certificate's name attribute starts with an asterisk 7969 (<literal>*</literal>), the asterisk will be treated as 7970 a wildcard, which will match all characters <emphasis>except</emphasis> a dot 7971 (<literal>.</literal>). This means the certificate will not match subdomains. 7972 If the connection is made using an IP address instead of a host name, the 7973 IP address will be matched (without doing any DNS lookups). 7974 </para> 7975 7976 <para> 7977 To allow server certificate verification, one or more root certificates 7978 must be placed in the file <filename>~/.postgresql/root.crt</filename> 7979 in the user's home directory. (On Microsoft Windows the file is named 7980 <filename>%APPDATA%\postgresql\root.crt</filename>.) Intermediate 7981 certificates should also be added to the file if they are needed to link 7982 the certificate chain sent by the server to the root certificates 7983 stored on the client. 7984 </para> 7985 7986 <para> 7987 Certificate Revocation List (CRL) entries are also checked 7988 if the file <filename>~/.postgresql/root.crl</filename> exists 7989 (<filename>%APPDATA%\postgresql\root.crl</filename> on Microsoft 7990 Windows). 7991 </para> 7992 7993 <para> 7994 The location of the root certificate file and the CRL can be changed by 7995 setting 7996 the connection parameters <literal>sslrootcert</literal> and <literal>sslcrl</literal> 7997 or the environment variables <envar>PGSSLROOTCERT</envar> and <envar>PGSSLCRL</envar>. 7998 </para> 7999 8000 <note> 8001 <para> 8002 For backwards compatibility with earlier versions of PostgreSQL, if a 8003 root CA file exists, the behavior of 8004 <literal>sslmode</literal>=<literal>require</literal> will be the same 8005 as that of <literal>verify-ca</literal>, meaning the server certificate 8006 is validated against the CA. Relying on this behavior is discouraged, 8007 and applications that need certificate validation should always use 8008 <literal>verify-ca</literal> or <literal>verify-full</literal>. 8009 </para> 8010 </note> 8011 </sect2> 8012 8013 <sect2 id="libpq-ssl-clientcert"> 8014 <title>Client Certificates</title> 8015 8016 <para> 8017 If the server attempts to verify the identity of the 8018 client by requesting the client's leaf certificate, 8019 <application>libpq</application> will send the certificates stored in 8020 file <filename>~/.postgresql/postgresql.crt</filename> in the user's home 8021 directory. The certificates must chain to the root certificate trusted 8022 by the server. A matching 8023 private key file <filename>~/.postgresql/postgresql.key</filename> must also 8024 be present. The private 8025 key file must not allow any access to world or group; achieve this by the 8026 command <command>chmod 0600 ~/.postgresql/postgresql.key</command>. 8027 On Microsoft Windows these files are named 8028 <filename>%APPDATA%\postgresql\postgresql.crt</filename> and 8029 <filename>%APPDATA%\postgresql\postgresql.key</filename>, and there 8030 is no special permissions check since the directory is presumed secure. 8031 The location of the certificate and key files can be overridden by the 8032 connection parameters <literal>sslcert</literal> and <literal>sslkey</literal> or the 8033 environment variables <envar>PGSSLCERT</envar> and <envar>PGSSLKEY</envar>. 8034 </para> 8035 8036 <para> 8037 The first certificate in <filename>postgresql.crt</filename> must be the 8038 client's certificate because it must match the client's private key. 8039 <quote>Intermediate</quote> certificates can be optionally appended 8040 to the file — doing so avoids requiring storage of intermediate 8041 certificates on the server (<xref linkend="guc-ssl-ca-file"/>). 8042 </para> 8043 8044 <para> 8045 For instructions on creating certificates, see <xref 8046 linkend="ssl-certificate-creation"/>. 8047 </para> 8048 </sect2> 8049 8050 <sect2 id="libpq-ssl-protection"> 8051 <title>Protection Provided in Different Modes</title> 8052 8053 <para> 8054 The different values for the <literal>sslmode</literal> parameter provide different 8055 levels of protection. SSL can provide 8056 protection against three types of attacks: 8057 8058 <variablelist> 8059 <varlistentry> 8060 <term>Eavesdropping</term> 8061 <listitem> 8062 <para>If a third party can examine the network traffic between the 8063 client and the server, it can read both connection information (including 8064 the user name and password) and the data that is passed. <acronym>SSL</acronym> 8065 uses encryption to prevent this. 8066 </para> 8067 </listitem> 8068 </varlistentry> 8069 8070 <varlistentry> 8071 <term>Man in the middle (<acronym>MITM</acronym>)</term> 8072 <listitem> 8073 <para>If a third party can modify the data while passing between the 8074 client and server, it can pretend to be the server and therefore see and 8075 modify data <emphasis>even if it is encrypted</emphasis>. The third party can then 8076 forward the connection information and data to the original server, 8077 making it impossible to detect this attack. Common vectors to do this 8078 include DNS poisoning and address hijacking, whereby the client is directed 8079 to a different server than intended. There are also several other 8080 attack methods that can accomplish this. <acronym>SSL</acronym> uses certificate 8081 verification to prevent this, by authenticating the server to the client. 8082 </para> 8083 </listitem> 8084 </varlistentry> 8085 8086 <varlistentry> 8087 <term>Impersonation</term> 8088 <listitem> 8089 <para>If a third party can pretend to be an authorized client, it can 8090 simply access data it should not have access to. Typically this can 8091 happen through insecure password management. <acronym>SSL</acronym> uses 8092 client certificates to prevent this, by making sure that only holders 8093 of valid certificates can access the server. 8094 </para> 8095 </listitem> 8096 </varlistentry> 8097 </variablelist> 8098 </para> 8099 8100 <para> 8101 For a connection to be known SSL-secured, SSL usage must be configured 8102 on <emphasis>both the client and the server</emphasis> before the connection 8103 is made. If it is only configured on the server, the client may end up 8104 sending sensitive information (e.g., passwords) before 8105 it knows that the server requires high security. In libpq, secure 8106 connections can be ensured 8107 by setting the <literal>sslmode</literal> parameter to <literal>verify-full</literal> or 8108 <literal>verify-ca</literal>, and providing the system with a root certificate to 8109 verify against. This is analogous to using an <literal>https</literal> 8110 <acronym>URL</acronym> for encrypted web browsing. 8111 </para> 8112 8113 <para> 8114 Once the server has been authenticated, the client can pass sensitive data. 8115 This means that up until this point, the client does not need to know if 8116 certificates will be used for authentication, making it safe to specify that 8117 only in the server configuration. 8118 </para> 8119 8120 <para> 8121 All <acronym>SSL</acronym> options carry overhead in the form of encryption and 8122 key-exchange, so there is a trade-off that has to be made between performance 8123 and security. <xref linkend="libpq-ssl-sslmode-statements"/> 8124 illustrates the risks the different <literal>sslmode</literal> values 8125 protect against, and what statement they make about security and overhead. 8126 </para> 8127 8128 <table id="libpq-ssl-sslmode-statements"> 8129 <title>SSL Mode Descriptions</title> 8130 <tgroup cols="4"> 8131 <thead> 8132 <row> 8133 <entry><literal>sslmode</literal></entry> 8134 <entry>Eavesdropping protection</entry> 8135 <entry><acronym>MITM</acronym> protection</entry> 8136 <entry>Statement</entry> 8137 </row> 8138 </thead> 8139 8140 <tbody> 8141 <row> 8142 <entry><literal>disable</literal></entry> 8143 <entry>No</entry> 8144 <entry>No</entry> 8145 <entry>I don't care about security, and I don't want to pay the overhead 8146 of encryption. 8147 </entry> 8148 </row> 8149 8150 <row> 8151 <entry><literal>allow</literal></entry> 8152 <entry>Maybe</entry> 8153 <entry>No</entry> 8154 <entry>I don't care about security, but I will pay the overhead of 8155 encryption if the server insists on it. 8156 </entry> 8157 </row> 8158 8159 <row> 8160 <entry><literal>prefer</literal></entry> 8161 <entry>Maybe</entry> 8162 <entry>No</entry> 8163 <entry>I don't care about encryption, but I wish to pay the overhead of 8164 encryption if the server supports it. 8165 </entry> 8166 </row> 8167 8168 <row> 8169 <entry><literal>require</literal></entry> 8170 <entry>Yes</entry> 8171 <entry>No</entry> 8172 <entry>I want my data to be encrypted, and I accept the overhead. I trust 8173 that the network will make sure I always connect to the server I want. 8174 </entry> 8175 </row> 8176 8177 <row> 8178 <entry><literal>verify-ca</literal></entry> 8179 <entry>Yes</entry> 8180 <entry>Depends on CA policy</entry> 8181 <entry>I want my data encrypted, and I accept the overhead. I want to be 8182 sure that I connect to a server that I trust. 8183 </entry> 8184 </row> 8185 8186 <row> 8187 <entry><literal>verify-full</literal></entry> 8188 <entry>Yes</entry> 8189 <entry>Yes</entry> 8190 <entry>I want my data encrypted, and I accept the overhead. I want to be 8191 sure that I connect to a server I trust, and that it's the one I 8192 specify. 8193 </entry> 8194 </row> 8195 8196 </tbody> 8197 </tgroup> 8198 </table> 8199 8200 <para> 8201 The difference between <literal>verify-ca</literal> and <literal>verify-full</literal> 8202 depends on the policy of the root <acronym>CA</acronym>. If a public 8203 <acronym>CA</acronym> is used, <literal>verify-ca</literal> allows connections to a server 8204 that <emphasis>somebody else</emphasis> may have registered with the <acronym>CA</acronym>. 8205 In this case, <literal>verify-full</literal> should always be used. If 8206 a local <acronym>CA</acronym> is used, or even a self-signed certificate, using 8207 <literal>verify-ca</literal> often provides enough protection. 8208 </para> 8209 8210 <para> 8211 The default value for <literal>sslmode</literal> is <literal>prefer</literal>. As is shown 8212 in the table, this makes no sense from a security point of view, and it only 8213 promises performance overhead if possible. It is only provided as the default 8214 for backward compatibility, and is not recommended in secure deployments. 8215 </para> 8216 8217 </sect2> 8218 8219 <sect2 id="libpq-ssl-fileusage"> 8220 <title>SSL Client File Usage</title> 8221 8222 <para> 8223 <xref linkend="libpq-ssl-file-usage"/> summarizes the files that are 8224 relevant to the SSL setup on the client. 8225 </para> 8226 8227 <table id="libpq-ssl-file-usage"> 8228 <title>Libpq/Client SSL File Usage</title> 8229 <tgroup cols="3"> 8230 <thead> 8231 <row> 8232 <entry>File</entry> 8233 <entry>Contents</entry> 8234 <entry>Effect</entry> 8235 </row> 8236 </thead> 8237 8238 <tbody> 8239 8240 <row> 8241 <entry><filename>~/.postgresql/postgresql.crt</filename></entry> 8242 <entry>client certificate</entry> 8243 <entry>sent to server</entry> 8244 </row> 8245 8246 <row> 8247 <entry><filename>~/.postgresql/postgresql.key</filename></entry> 8248 <entry>client private key</entry> 8249 <entry>proves client certificate sent by owner; does not indicate 8250 certificate owner is trustworthy</entry> 8251 </row> 8252 8253 <row> 8254 <entry><filename>~/.postgresql/root.crt</filename></entry> 8255 <entry>trusted certificate authorities</entry> 8256 <entry>checks that server certificate is signed by a trusted certificate 8257 authority</entry> 8258 </row> 8259 8260 <row> 8261 <entry><filename>~/.postgresql/root.crl</filename></entry> 8262 <entry>certificates revoked by certificate authorities</entry> 8263 <entry>server certificate must not be on this list</entry> 8264 </row> 8265 8266 </tbody> 8267 </tgroup> 8268 </table> 8269 </sect2> 8270 8271 <sect2 id="libpq-ssl-initialize"> 8272 <title>SSL Library Initialization</title> 8273 8274 <para> 8275 If your application initializes <literal>libssl</literal> and/or 8276 <literal>libcrypto</literal> libraries and <application>libpq</application> 8277 is built with <acronym>SSL</acronym> support, you should call 8278 <function>PQinitOpenSSL</function> to tell <application>libpq</application> 8279 that the <literal>libssl</literal> and/or <literal>libcrypto</literal> libraries 8280 have been initialized by your application, so that 8281 <application>libpq</application> will not also initialize those libraries. 8282 </para> 8283 8284 <para> 8285 <variablelist> 8286 <varlistentry id="libpq-pqinitopenssl"> 8287 <term> 8288 <function>PQinitOpenSSL</function> 8289 <indexterm> 8290 <primary>PQinitOpenSSL</primary> 8291 </indexterm> 8292 </term> 8293 8294 <listitem> 8295 <para> 8296 Allows applications to select which security libraries to initialize. 8297<synopsis> 8298void PQinitOpenSSL(int do_ssl, int do_crypto); 8299</synopsis> 8300 </para> 8301 8302 <para> 8303 When <parameter>do_ssl</parameter> is non-zero, <application>libpq</application> 8304 will initialize the <application>OpenSSL</application> library before first 8305 opening a database connection. When <parameter>do_crypto</parameter> is 8306 non-zero, the <literal>libcrypto</literal> library will be initialized. By 8307 default (if <function>PQinitOpenSSL</function> is not called), both libraries 8308 are initialized. When SSL support is not compiled in, this function is 8309 present but does nothing. 8310 </para> 8311 8312 <para> 8313 If your application uses and initializes either <application>OpenSSL</application> 8314 or its underlying <literal>libcrypto</literal> library, you <emphasis>must</emphasis> 8315 call this function with zeroes for the appropriate parameter(s) 8316 before first opening a database connection. Also be sure that you 8317 have done that initialization before opening a database connection. 8318 </para> 8319 </listitem> 8320 </varlistentry> 8321 8322 <varlistentry id="libpq-pqinitssl"> 8323 <term> 8324 <function>PQinitSSL</function> 8325 <indexterm> 8326 <primary>PQinitSSL</primary> 8327 </indexterm> 8328 </term> 8329 8330 <listitem> 8331 <para> 8332 Allows applications to select which security libraries to initialize. 8333<synopsis> 8334void PQinitSSL(int do_ssl); 8335</synopsis> 8336 </para> 8337 8338 <para> 8339 This function is equivalent to 8340 <literal>PQinitOpenSSL(do_ssl, do_ssl)</literal>. 8341 It is sufficient for applications that initialize both or neither 8342 of <application>OpenSSL</application> and <literal>libcrypto</literal>. 8343 </para> 8344 8345 <para> 8346 <function>PQinitSSL</function> has been present since 8347 <productname>PostgreSQL</productname> 8.0, while <function>PQinitOpenSSL</function> 8348 was added in <productname>PostgreSQL</productname> 8.4, so <function>PQinitSSL</function> 8349 might be preferable for applications that need to work with older 8350 versions of <application>libpq</application>. 8351 </para> 8352 </listitem> 8353 </varlistentry> 8354 </variablelist> 8355 </para> 8356 </sect2> 8357 8358 </sect1> 8359 8360 8361 <sect1 id="libpq-threading"> 8362 <title>Behavior in Threaded Programs</title> 8363 8364 <indexterm zone="libpq-threading"> 8365 <primary>threads</primary> 8366 <secondary>with libpq</secondary> 8367 </indexterm> 8368 8369 <para> 8370 <application>libpq</application> is reentrant and thread-safe by default. 8371 You might need to use special compiler command-line 8372 options when you compile your application code. Refer to your 8373 system's documentation for information about how to build 8374 thread-enabled applications, or look in 8375 <filename>src/Makefile.global</filename> for <literal>PTHREAD_CFLAGS</literal> 8376 and <literal>PTHREAD_LIBS</literal>. This function allows the querying of 8377 <application>libpq</application>'s thread-safe status: 8378 </para> 8379 8380 <variablelist> 8381 <varlistentry id="libpq-pqisthreadsafe"> 8382 <term> 8383 <function>PQisthreadsafe</function> 8384 <indexterm> 8385 <primary>PQisthreadsafe</primary> 8386 </indexterm> 8387 </term> 8388 8389 <listitem> 8390 <para> 8391 Returns the thread safety status of the 8392 <application>libpq</application> library. 8393<synopsis> 8394int PQisthreadsafe(); 8395</synopsis> 8396 </para> 8397 8398 <para> 8399 Returns 1 if the <application>libpq</application> is thread-safe 8400 and 0 if it is not. 8401 </para> 8402 </listitem> 8403 </varlistentry> 8404 </variablelist> 8405 8406 <para> 8407 One thread restriction is that no two threads attempt to manipulate 8408 the same <structname>PGconn</structname> object at the same time. In particular, 8409 you cannot issue concurrent commands from different threads through 8410 the same connection object. (If you need to run concurrent commands, 8411 use multiple connections.) 8412 </para> 8413 8414 <para> 8415 <structname>PGresult</structname> objects are normally read-only after creation, 8416 and so can be passed around freely between threads. However, if you use 8417 any of the <structname>PGresult</structname>-modifying functions described in 8418 <xref linkend="libpq-misc"/> or <xref linkend="libpq-events"/>, it's up 8419 to you to avoid concurrent operations on the same <structname>PGresult</structname>, 8420 too. 8421 </para> 8422 8423 <para> 8424 The deprecated functions <function>PQrequestCancel</function> and 8425 <function>PQoidStatus</function> are not thread-safe and should not be 8426 used in multithread programs. <function>PQrequestCancel</function> 8427 can be replaced by <function>PQcancel</function>. 8428 <function>PQoidStatus</function> can be replaced by 8429 <function>PQoidValue</function>. 8430 </para> 8431 8432 <para> 8433 If you are using Kerberos inside your application (in addition to inside 8434 <application>libpq</application>), you will need to do locking around 8435 Kerberos calls because Kerberos functions are not thread-safe. See 8436 function <function>PQregisterThreadLock</function> in the 8437 <application>libpq</application> source code for a way to do cooperative 8438 locking between <application>libpq</application> and your application. 8439 </para> 8440 </sect1> 8441 8442 8443 <sect1 id="libpq-build"> 8444 <title>Building <application>libpq</application> Programs</title> 8445 8446 <indexterm zone="libpq-build"> 8447 <primary>compiling</primary> 8448 <secondary>libpq applications</secondary> 8449 </indexterm> 8450 8451 <para> 8452 To build (i.e., compile and link) a program using 8453 <application>libpq</application> you need to do all of the following 8454 things: 8455 8456 <itemizedlist> 8457 <listitem> 8458 <para> 8459 Include the <filename>libpq-fe.h</filename> header file: 8460<programlisting> 8461#include <libpq-fe.h> 8462</programlisting> 8463 If you failed to do that then you will normally get error messages 8464 from your compiler similar to: 8465<screen> 8466foo.c: In function `main': 8467foo.c:34: `PGconn' undeclared (first use in this function) 8468foo.c:35: `PGresult' undeclared (first use in this function) 8469foo.c:54: `CONNECTION_BAD' undeclared (first use in this function) 8470foo.c:68: `PGRES_COMMAND_OK' undeclared (first use in this function) 8471foo.c:95: `PGRES_TUPLES_OK' undeclared (first use in this function) 8472</screen> 8473 </para> 8474 </listitem> 8475 8476 <listitem> 8477 <para> 8478 Point your compiler to the directory where the <productname>PostgreSQL</productname> header 8479 files were installed, by supplying the 8480 <literal>-I<replaceable>directory</replaceable></literal> option 8481 to your compiler. (In some cases the compiler will look into 8482 the directory in question by default, so you can omit this 8483 option.) For instance, your compile command line could look 8484 like: 8485<programlisting> 8486cc -c -I/usr/local/pgsql/include testprog.c 8487</programlisting> 8488 If you are using makefiles then add the option to the 8489 <varname>CPPFLAGS</varname> variable: 8490<programlisting> 8491CPPFLAGS += -I/usr/local/pgsql/include 8492</programlisting> 8493 </para> 8494 8495 <para> 8496 If there is any chance that your program might be compiled by 8497 other users then you should not hardcode the directory location 8498 like that. Instead, you can run the utility 8499 <command>pg_config</command><indexterm><primary>pg_config</primary><secondary 8500 sortas="libpq">with libpq</secondary></indexterm> to find out where the header 8501 files are on the local system: 8502<screen> 8503<prompt>$</prompt> pg_config --includedir 8504<computeroutput>/usr/local/include</computeroutput> 8505</screen> 8506 </para> 8507 8508 <para> 8509 If you 8510 have <command>pkg-config</command><indexterm><primary>pkg-config</primary><secondary sortas="libpq">with 8511 libpq</secondary></indexterm> installed, you can run instead: 8512<screen> 8513<prompt>$</prompt> pkg-config --cflags libpq 8514<computeroutput>-I/usr/local/include</computeroutput> 8515</screen> 8516 Note that this will already include the <option>-I</option> in front of 8517 the path. 8518 </para> 8519 8520 <para> 8521 Failure to specify the correct option to the compiler will 8522 result in an error message such as: 8523<screen> 8524testlibpq.c:8:22: libpq-fe.h: No such file or directory 8525</screen> 8526 </para> 8527 </listitem> 8528 8529 <listitem> 8530 <para> 8531 When linking the final program, specify the option 8532 <literal>-lpq</literal> so that the <application>libpq</application> 8533 library gets pulled in, as well as the option 8534 <literal>-L<replaceable>directory</replaceable></literal> to point 8535 the compiler to the directory where the 8536 <application>libpq</application> library resides. (Again, the 8537 compiler will search some directories by default.) For maximum 8538 portability, put the <option>-L</option> option before the 8539 <option>-lpq</option> option. For example: 8540<programlisting> 8541cc -o testprog testprog1.o testprog2.o -L/usr/local/pgsql/lib -lpq 8542</programlisting> 8543 </para> 8544 8545 <para> 8546 You can find out the library directory using 8547 <command>pg_config</command> as well: 8548<screen> 8549<prompt>$</prompt> pg_config --libdir 8550<computeroutput>/usr/local/pgsql/lib</computeroutput> 8551</screen> 8552 </para> 8553 8554 <para> 8555 Or again use <command>pkg-config</command>: 8556<screen> 8557<prompt>$</prompt> pkg-config --libs libpq 8558<computeroutput>-L/usr/local/pgsql/lib -lpq</computeroutput> 8559</screen> 8560 Note again that this prints the full options, not only the path. 8561 </para> 8562 8563 <para> 8564 Error messages that point to problems in this area could look like 8565 the following: 8566<screen> 8567testlibpq.o: In function `main': 8568testlibpq.o(.text+0x60): undefined reference to `PQsetdbLogin' 8569testlibpq.o(.text+0x71): undefined reference to `PQstatus' 8570testlibpq.o(.text+0xa4): undefined reference to `PQerrorMessage' 8571</screen> 8572 This means you forgot <option>-lpq</option>. 8573<screen> 8574/usr/bin/ld: cannot find -lpq 8575</screen> 8576 This means you forgot the <option>-L</option> option or did not 8577 specify the right directory. 8578 </para> 8579 </listitem> 8580 </itemizedlist> 8581 </para> 8582 8583 </sect1> 8584 8585 8586 <sect1 id="libpq-example"> 8587 <title>Example Programs</title> 8588 8589 <para> 8590 These examples and others can be found in the 8591 directory <filename>src/test/examples</filename> in the source code 8592 distribution. 8593 </para> 8594 8595 <example id="libpq-example-1"> 8596 <title><application>libpq</application> Example Program 1</title> 8597 8598<programlisting> 8599<![CDATA[ 8600/* 8601 * src/test/examples/testlibpq.c 8602 * 8603 * 8604 * testlibpq.c 8605 * 8606 * Test the C version of libpq, the PostgreSQL frontend library. 8607 */ 8608#include <stdio.h> 8609#include <stdlib.h> 8610#include "libpq-fe.h" 8611 8612static void 8613exit_nicely(PGconn *conn) 8614{ 8615 PQfinish(conn); 8616 exit(1); 8617} 8618 8619int 8620main(int argc, char **argv) 8621{ 8622 const char *conninfo; 8623 PGconn *conn; 8624 PGresult *res; 8625 int nFields; 8626 int i, 8627 j; 8628 8629 /* 8630 * If the user supplies a parameter on the command line, use it as the 8631 * conninfo string; otherwise default to setting dbname=postgres and using 8632 * environment variables or defaults for all other connection parameters. 8633 */ 8634 if (argc > 1) 8635 conninfo = argv[1]; 8636 else 8637 conninfo = "dbname = postgres"; 8638 8639 /* Make a connection to the database */ 8640 conn = PQconnectdb(conninfo); 8641 8642 /* Check to see that the backend connection was successfully made */ 8643 if (PQstatus(conn) != CONNECTION_OK) 8644 { 8645 fprintf(stderr, "Connection to database failed: %s", 8646 PQerrorMessage(conn)); 8647 exit_nicely(conn); 8648 } 8649 8650 /* Set always-secure search path, so malicious users can't take control. */ 8651 res = PQexec(conn, 8652 "SELECT pg_catalog.set_config('search_path', '', false)"); 8653 if (PQresultStatus(res) != PGRES_TUPLES_OK) 8654 { 8655 fprintf(stderr, "SET failed: %s", PQerrorMessage(conn)); 8656 PQclear(res); 8657 exit_nicely(conn); 8658 } 8659 8660 /* 8661 * Should PQclear PGresult whenever it is no longer needed to avoid memory 8662 * leaks 8663 */ 8664 PQclear(res); 8665 8666 /* 8667 * Our test case here involves using a cursor, for which we must be inside 8668 * a transaction block. We could do the whole thing with a single 8669 * PQexec() of "select * from pg_database", but that's too trivial to make 8670 * a good example. 8671 */ 8672 8673 /* Start a transaction block */ 8674 res = PQexec(conn, "BEGIN"); 8675 if (PQresultStatus(res) != PGRES_COMMAND_OK) 8676 { 8677 fprintf(stderr, "BEGIN command failed: %s", PQerrorMessage(conn)); 8678 PQclear(res); 8679 exit_nicely(conn); 8680 } 8681 PQclear(res); 8682 8683 /* 8684 * Fetch rows from pg_database, the system catalog of databases 8685 */ 8686 res = PQexec(conn, "DECLARE myportal CURSOR FOR select * from pg_database"); 8687 if (PQresultStatus(res) != PGRES_COMMAND_OK) 8688 { 8689 fprintf(stderr, "DECLARE CURSOR failed: %s", PQerrorMessage(conn)); 8690 PQclear(res); 8691 exit_nicely(conn); 8692 } 8693 PQclear(res); 8694 8695 res = PQexec(conn, "FETCH ALL in myportal"); 8696 if (PQresultStatus(res) != PGRES_TUPLES_OK) 8697 { 8698 fprintf(stderr, "FETCH ALL failed: %s", PQerrorMessage(conn)); 8699 PQclear(res); 8700 exit_nicely(conn); 8701 } 8702 8703 /* first, print out the attribute names */ 8704 nFields = PQnfields(res); 8705 for (i = 0; i < nFields; i++) 8706 printf("%-15s", PQfname(res, i)); 8707 printf("\n\n"); 8708 8709 /* next, print out the rows */ 8710 for (i = 0; i < PQntuples(res); i++) 8711 { 8712 for (j = 0; j < nFields; j++) 8713 printf("%-15s", PQgetvalue(res, i, j)); 8714 printf("\n"); 8715 } 8716 8717 PQclear(res); 8718 8719 /* close the portal ... we don't bother to check for errors ... */ 8720 res = PQexec(conn, "CLOSE myportal"); 8721 PQclear(res); 8722 8723 /* end the transaction */ 8724 res = PQexec(conn, "END"); 8725 PQclear(res); 8726 8727 /* close the connection to the database and cleanup */ 8728 PQfinish(conn); 8729 8730 return 0; 8731} 8732]]> 8733</programlisting> 8734 </example> 8735 8736 <example id="libpq-example-2"> 8737 <title><application>libpq</application> Example Program 2</title> 8738 8739<programlisting> 8740<![CDATA[ 8741/* 8742 * src/test/examples/testlibpq2.c 8743 * 8744 * 8745 * testlibpq2.c 8746 * Test of the asynchronous notification interface 8747 * 8748 * Start this program, then from psql in another window do 8749 * NOTIFY TBL2; 8750 * Repeat four times to get this program to exit. 8751 * 8752 * Or, if you want to get fancy, try this: 8753 * populate a database with the following commands 8754 * (provided in src/test/examples/testlibpq2.sql): 8755 * 8756 * CREATE SCHEMA TESTLIBPQ2; 8757 * SET search_path = TESTLIBPQ2; 8758 * CREATE TABLE TBL1 (i int4); 8759 * CREATE TABLE TBL2 (i int4); 8760 * CREATE RULE r1 AS ON INSERT TO TBL1 DO 8761 * (INSERT INTO TBL2 VALUES (new.i); NOTIFY TBL2); 8762 * 8763 * Start this program, then from psql do this four times: 8764 * 8765 * INSERT INTO TESTLIBPQ2.TBL1 VALUES (10); 8766 */ 8767 8768#ifdef WIN32 8769#include <windows.h> 8770#endif 8771#include <stdio.h> 8772#include <stdlib.h> 8773#include <string.h> 8774#include <errno.h> 8775#include <sys/time.h> 8776#include <sys/types.h> 8777#ifdef HAVE_SYS_SELECT_H 8778#include <sys/select.h> 8779#endif 8780 8781#include "libpq-fe.h" 8782 8783static void 8784exit_nicely(PGconn *conn) 8785{ 8786 PQfinish(conn); 8787 exit(1); 8788} 8789 8790int 8791main(int argc, char **argv) 8792{ 8793 const char *conninfo; 8794 PGconn *conn; 8795 PGresult *res; 8796 PGnotify *notify; 8797 int nnotifies; 8798 8799 /* 8800 * If the user supplies a parameter on the command line, use it as the 8801 * conninfo string; otherwise default to setting dbname=postgres and using 8802 * environment variables or defaults for all other connection parameters. 8803 */ 8804 if (argc > 1) 8805 conninfo = argv[1]; 8806 else 8807 conninfo = "dbname = postgres"; 8808 8809 /* Make a connection to the database */ 8810 conn = PQconnectdb(conninfo); 8811 8812 /* Check to see that the backend connection was successfully made */ 8813 if (PQstatus(conn) != CONNECTION_OK) 8814 { 8815 fprintf(stderr, "Connection to database failed: %s", 8816 PQerrorMessage(conn)); 8817 exit_nicely(conn); 8818 } 8819 8820 /* Set always-secure search path, so malicious users can't take control. */ 8821 res = PQexec(conn, 8822 "SELECT pg_catalog.set_config('search_path', '', false)"); 8823 if (PQresultStatus(res) != PGRES_TUPLES_OK) 8824 { 8825 fprintf(stderr, "SET failed: %s", PQerrorMessage(conn)); 8826 PQclear(res); 8827 exit_nicely(conn); 8828 } 8829 8830 /* 8831 * Should PQclear PGresult whenever it is no longer needed to avoid memory 8832 * leaks 8833 */ 8834 PQclear(res); 8835 8836 /* 8837 * Issue LISTEN command to enable notifications from the rule's NOTIFY. 8838 */ 8839 res = PQexec(conn, "LISTEN TBL2"); 8840 if (PQresultStatus(res) != PGRES_COMMAND_OK) 8841 { 8842 fprintf(stderr, "LISTEN command failed: %s", PQerrorMessage(conn)); 8843 PQclear(res); 8844 exit_nicely(conn); 8845 } 8846 PQclear(res); 8847 8848 /* Quit after four notifies are received. */ 8849 nnotifies = 0; 8850 while (nnotifies < 4) 8851 { 8852 /* 8853 * Sleep until something happens on the connection. We use select(2) 8854 * to wait for input, but you could also use poll() or similar 8855 * facilities. 8856 */ 8857 int sock; 8858 fd_set input_mask; 8859 8860 sock = PQsocket(conn); 8861 8862 if (sock < 0) 8863 break; /* shouldn't happen */ 8864 8865 FD_ZERO(&input_mask); 8866 FD_SET(sock, &input_mask); 8867 8868 if (select(sock + 1, &input_mask, NULL, NULL, NULL) < 0) 8869 { 8870 fprintf(stderr, "select() failed: %s\n", strerror(errno)); 8871 exit_nicely(conn); 8872 } 8873 8874 /* Now check for input */ 8875 PQconsumeInput(conn); 8876 while ((notify = PQnotifies(conn)) != NULL) 8877 { 8878 fprintf(stderr, 8879 "ASYNC NOTIFY of '%s' received from backend PID %d\n", 8880 notify->relname, notify->be_pid); 8881 PQfreemem(notify); 8882 nnotifies++; 8883 PQconsumeInput(conn); 8884 } 8885 } 8886 8887 fprintf(stderr, "Done.\n"); 8888 8889 /* close the connection to the database and cleanup */ 8890 PQfinish(conn); 8891 8892 return 0; 8893} 8894]]> 8895</programlisting> 8896 </example> 8897 8898 <example id="libpq-example-3"> 8899 <title><application>libpq</application> Example Program 3</title> 8900 8901<programlisting> 8902<![CDATA[ 8903/* 8904 * src/test/examples/testlibpq3.c 8905 * 8906 * 8907 * testlibpq3.c 8908 * Test out-of-line parameters and binary I/O. 8909 * 8910 * Before running this, populate a database with the following commands 8911 * (provided in src/test/examples/testlibpq3.sql): 8912 * 8913 * CREATE SCHEMA testlibpq3; 8914 * SET search_path = testlibpq3; 8915 * CREATE TABLE test1 (i int4, t text, b bytea); 8916 * INSERT INTO test1 values (1, 'joe''s place', '\\000\\001\\002\\003\\004'); 8917 * INSERT INTO test1 values (2, 'ho there', '\\004\\003\\002\\001\\000'); 8918 * 8919 * The expected output is: 8920 * 8921 * tuple 0: got 8922 * i = (4 bytes) 1 8923 * t = (11 bytes) 'joe's place' 8924 * b = (5 bytes) \000\001\002\003\004 8925 * 8926 * tuple 0: got 8927 * i = (4 bytes) 2 8928 * t = (8 bytes) 'ho there' 8929 * b = (5 bytes) \004\003\002\001\000 8930 */ 8931 8932#ifdef WIN32 8933#include <windows.h> 8934#endif 8935 8936#include <stdio.h> 8937#include <stdlib.h> 8938#include <stdint.h> 8939#include <string.h> 8940#include <sys/types.h> 8941#include "libpq-fe.h" 8942 8943/* for ntohl/htonl */ 8944#include <netinet/in.h> 8945#include <arpa/inet.h> 8946 8947 8948static void 8949exit_nicely(PGconn *conn) 8950{ 8951 PQfinish(conn); 8952 exit(1); 8953} 8954 8955/* 8956 * This function prints a query result that is a binary-format fetch from 8957 * a table defined as in the comment above. We split it out because the 8958 * main() function uses it twice. 8959 */ 8960static void 8961show_binary_results(PGresult *res) 8962{ 8963 int i, 8964 j; 8965 int i_fnum, 8966 t_fnum, 8967 b_fnum; 8968 8969 /* Use PQfnumber to avoid assumptions about field order in result */ 8970 i_fnum = PQfnumber(res, "i"); 8971 t_fnum = PQfnumber(res, "t"); 8972 b_fnum = PQfnumber(res, "b"); 8973 8974 for (i = 0; i < PQntuples(res); i++) 8975 { 8976 char *iptr; 8977 char *tptr; 8978 char *bptr; 8979 int blen; 8980 int ival; 8981 8982 /* Get the field values (we ignore possibility they are null!) */ 8983 iptr = PQgetvalue(res, i, i_fnum); 8984 tptr = PQgetvalue(res, i, t_fnum); 8985 bptr = PQgetvalue(res, i, b_fnum); 8986 8987 /* 8988 * The binary representation of INT4 is in network byte order, which 8989 * we'd better coerce to the local byte order. 8990 */ 8991 ival = ntohl(*((uint32_t *) iptr)); 8992 8993 /* 8994 * The binary representation of TEXT is, well, text, and since libpq 8995 * was nice enough to append a zero byte to it, it'll work just fine 8996 * as a C string. 8997 * 8998 * The binary representation of BYTEA is a bunch of bytes, which could 8999 * include embedded nulls so we have to pay attention to field length. 9000 */ 9001 blen = PQgetlength(res, i, b_fnum); 9002 9003 printf("tuple %d: got\n", i); 9004 printf(" i = (%d bytes) %d\n", 9005 PQgetlength(res, i, i_fnum), ival); 9006 printf(" t = (%d bytes) '%s'\n", 9007 PQgetlength(res, i, t_fnum), tptr); 9008 printf(" b = (%d bytes) ", blen); 9009 for (j = 0; j < blen; j++) 9010 printf("\\%03o", bptr[j]); 9011 printf("\n\n"); 9012 } 9013} 9014 9015int 9016main(int argc, char **argv) 9017{ 9018 const char *conninfo; 9019 PGconn *conn; 9020 PGresult *res; 9021 const char *paramValues[1]; 9022 int paramLengths[1]; 9023 int paramFormats[1]; 9024 uint32_t binaryIntVal; 9025 9026 /* 9027 * If the user supplies a parameter on the command line, use it as the 9028 * conninfo string; otherwise default to setting dbname=postgres and using 9029 * environment variables or defaults for all other connection parameters. 9030 */ 9031 if (argc > 1) 9032 conninfo = argv[1]; 9033 else 9034 conninfo = "dbname = postgres"; 9035 9036 /* Make a connection to the database */ 9037 conn = PQconnectdb(conninfo); 9038 9039 /* Check to see that the backend connection was successfully made */ 9040 if (PQstatus(conn) != CONNECTION_OK) 9041 { 9042 fprintf(stderr, "Connection to database failed: %s", 9043 PQerrorMessage(conn)); 9044 exit_nicely(conn); 9045 } 9046 9047 /* Set always-secure search path, so malicious users can't take control. */ 9048 res = PQexec(conn, "SET search_path = testlibpq3"); 9049 if (PQresultStatus(res) != PGRES_COMMAND_OK) 9050 { 9051 fprintf(stderr, "SET failed: %s", PQerrorMessage(conn)); 9052 PQclear(res); 9053 exit_nicely(conn); 9054 } 9055 PQclear(res); 9056 9057 /* 9058 * The point of this program is to illustrate use of PQexecParams() with 9059 * out-of-line parameters, as well as binary transmission of data. 9060 * 9061 * This first example transmits the parameters as text, but receives the 9062 * results in binary format. By using out-of-line parameters we can avoid 9063 * a lot of tedious mucking about with quoting and escaping, even though 9064 * the data is text. Notice how we don't have to do anything special with 9065 * the quote mark in the parameter value. 9066 */ 9067 9068 /* Here is our out-of-line parameter value */ 9069 paramValues[0] = "joe's place"; 9070 9071 res = PQexecParams(conn, 9072 "SELECT * FROM test1 WHERE t = $1", 9073 1, /* one param */ 9074 NULL, /* let the backend deduce param type */ 9075 paramValues, 9076 NULL, /* don't need param lengths since text */ 9077 NULL, /* default to all text params */ 9078 1); /* ask for binary results */ 9079 9080 if (PQresultStatus(res) != PGRES_TUPLES_OK) 9081 { 9082 fprintf(stderr, "SELECT failed: %s", PQerrorMessage(conn)); 9083 PQclear(res); 9084 exit_nicely(conn); 9085 } 9086 9087 show_binary_results(res); 9088 9089 PQclear(res); 9090 9091 /* 9092 * In this second example we transmit an integer parameter in binary form, 9093 * and again retrieve the results in binary form. 9094 * 9095 * Although we tell PQexecParams we are letting the backend deduce 9096 * parameter type, we really force the decision by casting the parameter 9097 * symbol in the query text. This is a good safety measure when sending 9098 * binary parameters. 9099 */ 9100 9101 /* Convert integer value "2" to network byte order */ 9102 binaryIntVal = htonl((uint32_t) 2); 9103 9104 /* Set up parameter arrays for PQexecParams */ 9105 paramValues[0] = (char *) &binaryIntVal; 9106 paramLengths[0] = sizeof(binaryIntVal); 9107 paramFormats[0] = 1; /* binary */ 9108 9109 res = PQexecParams(conn, 9110 "SELECT * FROM test1 WHERE i = $1::int4", 9111 1, /* one param */ 9112 NULL, /* let the backend deduce param type */ 9113 paramValues, 9114 paramLengths, 9115 paramFormats, 9116 1); /* ask for binary results */ 9117 9118 if (PQresultStatus(res) != PGRES_TUPLES_OK) 9119 { 9120 fprintf(stderr, "SELECT failed: %s", PQerrorMessage(conn)); 9121 PQclear(res); 9122 exit_nicely(conn); 9123 } 9124 9125 show_binary_results(res); 9126 9127 PQclear(res); 9128 9129 /* close the connection to the database and cleanup */ 9130 PQfinish(conn); 9131 9132 return 0; 9133} 9134]]> 9135</programlisting> 9136 </example> 9137 9138 </sect1> 9139</chapter> 9140