1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888
|
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>28.3.Command Execution Functions</title>
<link rel="stylesheet" href="stylesheet.css" type="text/css">
<link rev="made" href="pgsql-docs@postgresql.org">
<meta name="generator" content="DocBook XSL Stylesheets V1.70.0">
<link rel="start" href="index.html" title="PostgreSQL 8.1.4 Documentation">
<link rel="up" href="libpq.html" title="Chapter28.libpq - C Library">
<link rel="prev" href="libpq-status.html" title="28.2.Connection Status Functions">
<link rel="next" href="libpq-async.html" title="28.4.Asynchronous Command Processing">
<link rel="copyright" href="ln-legalnotice.html" title="Legal Notice">
</head>
<body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF"><div class="sect1" lang="en">
<div class="titlepage"><div><div><h2 class="title" style="clear: both">
<a name="libpq-exec"></a>28.3.Command Execution Functions</h2></div></div></div>
<p>Once a connection to a database server has been successfully
established, the functions described here are used to perform
SQL queries and commands.</p>
<div class="sect2" lang="en">
<div class="titlepage"><div><div><h3 class="title">
<a name="libpq-exec-main"></a>28.3.1.Main Functions</h3></div></div></div>
<div class="variablelist"><dl>
<dt><span class="term"><code class="function">PQexec</code><a name="id678539"></a></span></dt>
<dd>
<p> Submits a command to the server
and waits for the result.
</p>
<pre class="synopsis">PGresult *PQexec(PGconn *conn, const char *command);</pre>
<p> Returns a <code class="structname">PGresult</code> pointer or possibly a null pointer.
A non-null pointer will generally be returned except in
out-of-memory conditions or serious errors such as inability
to send the command to the server.
If a null pointer is returned, it
should be treated like a <code class="symbol">PGRES_FATAL_ERROR</code> result.
Use <code class="function">PQerrorMessage</code> to get more information
about such errors.</p>
</dd>
</dl></div>
<p>
It is allowed to include multiple SQL commands (separated by semicolons) in
the command string. Multiple queries sent in a single <code class="function">PQexec</code>
call are processed in a single transaction, unless there are explicit
<code class="command">BEGIN</code>/<code class="command">COMMIT</code> commands included in the query string to divide it into multiple
transactions. Note however that the returned <code class="structname">PGresult</code>
structure describes only the result of the last command executed from the
string. Should one of the commands fail, processing of the string stops with
it and the returned <code class="structname">PGresult</code> describes the error
condition.</p>
<div class="variablelist"><dl>
<dt><span class="term"><code class="function">PQexecParams</code><a name="id678628"></a></span></dt>
<dd>
<p> Submits a command to the server and waits for the result,
with the ability to pass parameters separately from the SQL
command text.
</p>
<pre class="synopsis">PGresult *PQexecParams(PGconn *conn,
const char *command,
int nParams,
const Oid *paramTypes,
const char * const *paramValues,
const int *paramLengths,
const int *paramFormats,
int resultFormat);</pre>
<p><code class="function">PQexecParams</code> is like <code class="function">PQexec</code>, but offers additional
functionality: parameter values can be specified separately from the command
string proper, and query results can be requested in either text or binary
format. <code class="function">PQexecParams</code> is supported only in protocol 3.0 and later
connections; it will fail when using protocol 2.0.</p>
<p>If parameters are used, they are referred to in the command string
as <code class="literal">$1</code>, <code class="literal">$2</code>, etc.
<em class="parameter"><code>nParams</code></em> is the number of parameters supplied; it is the length
of the arrays <em class="parameter"><code>paramTypes[]</code></em>, <em class="parameter"><code>paramValues[]</code></em>,
<em class="parameter"><code>paramLengths[]</code></em>, and <em class="parameter"><code>paramFormats[]</code></em>. (The
array pointers may be <code class="symbol">NULL</code> when <em class="parameter"><code>nParams</code></em> is zero.)
<em class="parameter"><code>paramTypes[]</code></em> specifies, by OID, the data types to be assigned to
the parameter symbols. If <em class="parameter"><code>paramTypes</code></em> is <code class="symbol">NULL</code>, or any particular
element in the array is zero, the server assigns a data type to the parameter
symbol in the same way it would do for an untyped literal string.
<em class="parameter"><code>paramValues[]</code></em> specifies the actual values of the parameters.
A null pointer in this array means the corresponding parameter is null;
otherwise the pointer points to a zero-terminated text string (for text
format) or binary data in the format expected by the server (for binary
format).
<em class="parameter"><code>paramLengths[]</code></em> specifies the actual data lengths of
binary-format parameters. It is ignored for null parameters and text-format
parameters. The array pointer may be null when there are no binary
parameters.
<em class="parameter"><code>paramFormats[]</code></em> specifies whether parameters are text (put a zero
in the array) or binary (put a one in the array). If the array pointer is
null then all parameters are presumed to be text.
<em class="parameter"><code>resultFormat</code></em> is zero to obtain results in text format, or one to
obtain results in binary format. (There is not currently a provision to
obtain different result columns in different formats, although that is
possible in the underlying protocol.)</p>
</dd>
</dl></div>
<p>
The primary advantage of <code class="function">PQexecParams</code> over <code class="function">PQexec</code>
is that parameter values may be separated from the command string, thus
avoiding the need for tedious and error-prone quoting and escaping.
Unlike <code class="function">PQexec</code>, <code class="function">PQexecParams</code> allows at most one SQL
command in the given string. (There can be semicolons in it, but not more
than one nonempty command.) This is a limitation of the underlying protocol,
but has some usefulness as an extra defense against SQL-injection attacks.</p>
<div class="tip" style="margin-left: 0.5in; margin-right: 0.5in;">
<h3 class="title">Tip</h3>
<p>Specifying parameter types via OIDs is tedious, particularly if you prefer
not to hard-wire particular OID values into your program. However, you can
avoid doing so even in cases where the server by itself cannot determine the
type of the parameter, or chooses a different type than you want. In the
SQL command text, attach an explicit cast to the parameter symbol to show what
data type you will send. For example,
</p>
<pre class="programlisting">select * from mytable where x = $1::bigint;</pre>
<p>
This forces parameter <code class="literal">$1</code> to be treated as <code class="type">bigint</code>, whereas
by default it would be assigned the same type as <code class="literal">x</code>. Forcing the
parameter type decision, either this way or by specifying a numeric type OID,
is strongly recommended when sending parameter values in binary format, because
binary format has less redundancy than text format and so there is less chance
that the server will detect a type mismatch mistake for you.</p>
</div>
<div class="variablelist"><dl>
<dt><span class="term"><code class="function">PQprepare</code><a name="id678887"></a></span></dt>
<dd>
<p> Submits a request to create a prepared statement with the
given parameters, and waits for completion.
</p>
<pre class="synopsis">PGresult *PQprepare(PGconn *conn,
const char *stmtName,
const char *query,
int nParams,
const Oid *paramTypes);</pre>
<p><code class="function">PQprepare</code> creates a prepared statement for later execution with
<code class="function">PQexecPrepared</code>.
This feature allows commands
that will be used repeatedly to be parsed and planned just once, rather
than each time they are executed.
<code class="function">PQprepare</code> is supported only in protocol 3.0 and later
connections; it will fail when using protocol 2.0.</p>
<p>The function creates a prepared statement named <em class="parameter"><code>stmtName</code></em>
from the <em class="parameter"><code>query</code></em> string, which must contain a single SQL command.
<em class="parameter"><code>stmtName</code></em> may be <code class="literal">""</code> to create an unnamed statement,
in which case any pre-existing unnamed statement is automatically replaced;
otherwise it is an error if the statement name is already defined in the
current session.
If any parameters are used, they are referred
to in the query as <code class="literal">$1</code>, <code class="literal">$2</code>, etc.
<em class="parameter"><code>nParams</code></em> is the number of parameters for which types are
pre-specified in the array <em class="parameter"><code>paramTypes[]</code></em>. (The array pointer
may be <code class="symbol">NULL</code> when <em class="parameter"><code>nParams</code></em> is zero.)
<em class="parameter"><code>paramTypes[]</code></em> specifies, by OID, the data types to be assigned to
the parameter symbols. If <em class="parameter"><code>paramTypes</code></em> is <code class="symbol">NULL</code>,
or any particular element in the array is zero, the server assigns a data type
to the parameter symbol in the same way it would do for an untyped literal
string. Also, the query may use parameter symbols with numbers higher than
<em class="parameter"><code>nParams</code></em>; data types will be inferred for these symbols as
well.</p>
<p>As with <code class="function">PQexec</code>, the result is normally a
<code class="structname">PGresult</code> object whose contents indicate server-side
success or failure. A null result indicates out-of-memory or inability to
send the command at all.
Use <code class="function">PQerrorMessage</code> to get more information
about such errors.</p>
<p>At present, there is no way to determine the actual data type inferred for
any parameters whose types are not specified in <em class="parameter"><code>paramTypes[]</code></em>.
This is a <span class="application">libpq</span> omission that will probably be rectified
in a future release.</p>
</dd>
</dl></div>
<p>
Prepared statements for use with <code class="function">PQexecPrepared</code> can also
be created by executing SQL <a href="sql-prepare.html">PREPARE</a> statements. (But <code class="function">PQprepare</code>
is more flexible since it does not require parameter types to be
pre-specified.) Also, although there is no <span class="application">libpq</span>
function for deleting a prepared statement, the SQL <a href="sql-deallocate.html">DEALLOCATE</a> statement can
be used for that purpose.</p>
<div class="variablelist"><dl>
<dt><span class="term"><code class="function">PQexecPrepared</code><a name="id679140"></a></span></dt>
<dd>
<p> Sends a request to execute a prepared statement with given
parameters, and waits for the result.
</p>
<pre class="synopsis">PGresult *PQexecPrepared(PGconn *conn,
const char *stmtName,
int nParams,
const char * const *paramValues,
const int *paramLengths,
const int *paramFormats,
int resultFormat);</pre>
<p><code class="function">PQexecPrepared</code> is like <code class="function">PQexecParams</code>, but the
command to be executed is specified by naming a previously-prepared
statement, instead of giving a query string.
This feature allows commands
that will be used repeatedly to be parsed and planned just once, rather
than each time they are executed.
The statement must have been prepared previously in the current session.
<code class="function">PQexecPrepared</code> is supported only in protocol 3.0 and later
connections; it will fail when using protocol 2.0.</p>
<p>The parameters are identical to <code class="function">PQexecParams</code>, except that the
name of a prepared statement is given instead of a query string, and the
<em class="parameter"><code>paramTypes[]</code></em> parameter is not present (it is not needed since
the prepared statement's parameter types were determined when it was created).</p>
</dd>
</dl></div>
<p>The
<code class="structname">PGresult</code><a name="id679216"></a>
structure encapsulates the result returned by the server.
<span class="application">libpq</span> application programmers should be
careful to maintain the <code class="structname">PGresult</code> abstraction.
Use the accessor functions below to get at the contents of
<code class="structname">PGresult</code>. Avoid directly referencing the
fields of the <code class="structname">PGresult</code> structure because they
are subject to change in the future.
</p>
<div class="variablelist"><dl>
<dt><span class="term"><code class="function">PQresultStatus</code><a name="id679256"></a></span></dt>
<dd>
<p> Returns the result status of the command.
</p>
<pre class="synopsis">ExecStatusType PQresultStatus(const PGresult *res);</pre>
<p><code class="function">PQresultStatus</code> can return one of the following values:
</p>
<div class="variablelist"><dl>
<dt><span class="term"><code class="literal">PGRES_EMPTY_QUERY</code></span></dt>
<dd><p>The string sent to the server was empty.</p></dd>
<dt><span class="term"><code class="literal">PGRES_COMMAND_OK</code></span></dt>
<dd><p>Successful completion of a command returning no data.</p></dd>
<dt><span class="term"><code class="literal">PGRES_TUPLES_OK</code></span></dt>
<dd><p>Successful completion of a command returning data (such as
a <code class="command">SELECT</code> or <code class="command">SHOW</code>).</p></dd>
<dt><span class="term"><code class="literal">PGRES_COPY_OUT</code></span></dt>
<dd><p>Copy Out (from server) data transfer started.</p></dd>
<dt><span class="term"><code class="literal">PGRES_COPY_IN</code></span></dt>
<dd><p>Copy In (to server) data transfer started.</p></dd>
<dt><span class="term"><code class="literal">PGRES_BAD_RESPONSE</code></span></dt>
<dd><p>The server's response was not understood.</p></dd>
<dt><span class="term"><code class="literal">PGRES_NONFATAL_ERROR</code></span></dt>
<dd><p>A nonfatal error (a notice or warning) occurred.</p></dd>
<dt><span class="term"><code class="literal">PGRES_FATAL_ERROR</code></span></dt>
<dd><p>A fatal error occurred.</p></dd>
</dl></div>
<p>
If the result status is <code class="literal">PGRES_TUPLES_OK</code>, then the
functions described below can be used to retrieve the rows returned by
the query. Note that a <code class="command">SELECT</code> command that happens
to retrieve zero rows still shows <code class="literal">PGRES_TUPLES_OK</code>.
<code class="literal">PGRES_COMMAND_OK</code> is for commands that can never
return rows (<code class="command">INSERT</code>, <code class="command">UPDATE</code>,
etc.). A response of <code class="literal">PGRES_EMPTY_QUERY</code> may indicate
a bug in the client software.</p>
<p>A result of status <code class="symbol">PGRES_NONFATAL_ERROR</code> will never be
returned directly by <code class="function">PQexec</code> or other query
execution functions; results of this kind are instead passed to the notice
processor (see <a href="libpq-notice-processing.html" title="28.10.Notice Processing">Section28.10, “Notice Processing”</a>).</p>
</dd>
<dt><span class="term"><code class="function">PQresStatus</code><a name="id679479"></a></span></dt>
<dd>
<p> Converts the enumerated type returned by <code class="function">PQresultStatus</code> into
a string constant describing the status code. The caller should not
free the result.
</p>
<pre class="synopsis">char *PQresStatus(ExecStatusType status);</pre>
</dd>
<dt><span class="term"><code class="function">PQresultErrorMessage</code><a name="id679511"></a></span></dt>
<dd>
<p>Returns the error message associated with the command, or an empty string
if there was no error.
</p>
<pre class="synopsis">char *PQresultErrorMessage(const PGresult *res);</pre>
<p>
If there was an error, the returned string will include a trailing newline.
The caller should not free the result directly. It will be freed when the
associated <code class="structname">PGresult</code> handle is passed to
<code class="function">PQclear</code>.</p>
<p>Immediately following a <code class="function">PQexec</code> or <code class="function">PQgetResult</code>
call, <code class="function">PQerrorMessage</code> (on the connection) will return the same
string as <code class="function">PQresultErrorMessage</code> (on the result). However, a
<code class="structname">PGresult</code> will retain its error message
until destroyed, whereas the connection's error message will change when
subsequent operations are done. Use <code class="function">PQresultErrorMessage</code> when you want to
know the status associated with a particular <code class="structname">PGresult</code>; use <code class="function">PQerrorMessage</code>
when you want to know the status from the latest operation on the connection.</p>
</dd>
<dt><span class="term"><code class="function">PQresultErrorField</code><a name="id679609"></a></span></dt>
<dd>
<p>Returns an individual field of an error report.
</p>
<pre class="synopsis">char *PQresultErrorField(const PGresult *res, int fieldcode);</pre>
<p>
<em class="parameter"><code>fieldcode</code></em> is an error field identifier; see the symbols
listed below. <code class="symbol">NULL</code> is returned if the
<code class="structname">PGresult</code> is not an error or warning result,
or does not include the specified field. Field values will normally
not include a trailing newline. The caller should not free the
result directly. It will be freed when the
associated <code class="structname">PGresult</code> handle is passed to
<code class="function">PQclear</code>.</p>
<p>The following field codes are available:
</p>
<div class="variablelist"><dl>
<dt><span class="term"><code class="symbol">PG_DIAG_SEVERITY</code></span></dt>
<dd><p>The severity; the field contents are <code class="literal">ERROR</code>,
<code class="literal">FATAL</code>, or <code class="literal">PANIC</code> (in an error message), or
<code class="literal">WARNING</code>, <code class="literal">NOTICE</code>, <code class="literal">DEBUG</code>,
<code class="literal">INFO</code>, or <code class="literal">LOG</code> (in a notice message), or a
localized translation of one of these. Always present.</p></dd>
<dt><span class="term"><code class="symbol">PG_DIAG_SQLSTATE</code></span></dt>
<dd><p>The SQLSTATE code for the error. The SQLSTATE code identifies the type
of error that has occurred; it can be used by front-end applications
to perform specific operations (such as error handling) in response to
a particular database error. For a list of the possible SQLSTATE
codes, see <a href="errcodes-appendix.html" title="AppendixA.PostgreSQL Error Codes">AppendixA, <i><span class="productname">PostgreSQL</span> Error Codes</i></a>. This field is not
localizable, and is always present.</p></dd>
<dt><span class="term"><code class="symbol">PG_DIAG_MESSAGE_PRIMARY</code></span></dt>
<dd><p>The primary human-readable error message (typically one line). Always
present.</p></dd>
<dt><span class="term"><code class="symbol">PG_DIAG_MESSAGE_DETAIL</code></span></dt>
<dd><p>Detail: an optional secondary error message carrying more detail about
the problem. May run to multiple lines.</p></dd>
<dt><span class="term"><code class="symbol">PG_DIAG_MESSAGE_HINT</code></span></dt>
<dd><p>Hint: an optional suggestion what to do about the problem. This is
intended to differ from detail in that it offers advice (potentially
inappropriate) rather than hard facts. May run to multiple lines.</p></dd>
<dt><span class="term"><code class="symbol">PG_DIAG_STATEMENT_POSITION</code></span></dt>
<dd><p>A string containing a decimal integer indicating an error cursor
position as an index into the original statement string. The first
character has index 1, and positions are measured in characters not
bytes.</p></dd>
<dt><span class="term"><code class="symbol">PG_DIAG_INTERNAL_POSITION</code></span></dt>
<dd><p>This is defined the same as the <code class="symbol">PG_DIAG_STATEMENT_POSITION</code>
field, but it is used when the cursor position refers to an internally
generated command rather than the one submitted by the client.
The <code class="symbol">PG_DIAG_INTERNAL_QUERY</code> field will always appear when this field
appears.</p></dd>
<dt><span class="term"><code class="symbol">PG_DIAG_INTERNAL_QUERY</code></span></dt>
<dd><p>The text of a failed internally-generated command.
This could be, for example, a SQL query issued by a PL/pgSQL function.</p></dd>
<dt><span class="term"><code class="symbol">PG_DIAG_CONTEXT</code></span></dt>
<dd><p>An indication of the context in which the error occurred.
Presently this includes a call stack traceback of active
procedural language functions and internally-generated queries.
The trace is one entry per line, most recent first.</p></dd>
<dt><span class="term"><code class="symbol">PG_DIAG_SOURCE_FILE</code></span></dt>
<dd><p>The file name of the source-code location where the error was
reported.</p></dd>
<dt><span class="term"><code class="symbol">PG_DIAG_SOURCE_LINE</code></span></dt>
<dd><p>The line number of the source-code location where the error was
reported.</p></dd>
<dt><span class="term"><code class="symbol">PG_DIAG_SOURCE_FUNCTION</code></span></dt>
<dd><p>The name of the source-code function reporting the error.</p></dd>
</dl></div>
<p>The client is responsible for formatting displayed information to meet
its needs; in particular it should break long lines as needed.
Newline characters appearing in the error message fields should be
treated as paragraph breaks, not line breaks.</p>
<p>Errors generated internally by <span class="application">libpq</span> will
have severity and primary message, but typically no other fields.
Errors returned by a pre-3.0-protocol server will include severity and
primary message, and sometimes a detail message, but no other fields.</p>
<p>Note that error fields are only available from
<code class="structname">PGresult</code> objects, not
<code class="structname">PGconn</code> objects; there is no
<code class="function">PQerrorField</code> function.</p>
</dd>
<dt><span class="term"><code class="function">PQclear</code><a name="id679921"></a></span></dt>
<dd>
<p> Frees the storage associated with a <code class="structname">PGresult</code>.
Every command result should be freed via <code class="function">PQclear</code> when
it is no longer needed.
</p>
<pre class="synopsis">void PQclear(PGresult *res);</pre>
<p> You can keep a <code class="structname">PGresult</code> object around for as long as you
need it; it does not go away when you issue a new command,
nor even if you close the connection. To get rid of it,
you must call <code class="function">PQclear</code>. Failure to do this will
result in memory leaks in your application.</p>
</dd>
<dt><span class="term"><code class="function">PQmakeEmptyPGresult</code><a name="id679976"></a></span></dt>
<dd>
<p> Constructs an empty <code class="structname">PGresult</code> object with the given status.
</p>
<pre class="synopsis">PGresult *PQmakeEmptyPGresult(PGconn *conn, ExecStatusType status);</pre>
<p>This is <span class="application">libpq</span>'s internal function to allocate and
initialize an empty <code class="structname">PGresult</code> object. This
function returns NULL if memory could not be allocated. It is exported
because some applications find it useful to generate result objects
(particularly objects with error status) themselves. If
<em class="parameter"><code>conn</code></em> is not null and <em class="parameter"><code>status</code></em>
indicates an error, the current error message of the specified
connection is copied into the <code class="structname">PGresult</code>. Note
that <code class="function">PQclear</code> should eventually be called on the
object, just as with a <code class="structname">PGresult</code> returned by
<span class="application">libpq</span> itself.</p>
</dd>
</dl></div>
</div>
<div class="sect2" lang="en">
<div class="titlepage"><div><div><h3 class="title">
<a name="libpq-exec-select-info"></a>28.3.2.Retrieving Query Result Information</h3></div></div></div>
<p>These functions are used to extract information from a
<code class="structname">PGresult</code> object that represents a successful
query result (that is, one that has status
<code class="literal">PGRES_TUPLES_OK</code>). For objects with other status
values they will act as though the result has zero rows and zero columns.</p>
<div class="variablelist"><dl>
<dt><span class="term"><code class="function">PQntuples</code><a name="id680090"></a></span></dt>
<dd>
<p> Returns the number of rows (tuples)
in the query result.
</p>
<pre class="synopsis">int PQntuples(const PGresult *res);</pre>
</dd>
<dt><span class="term"><code class="function">PQnfields</code><a name="id680114"></a></span></dt>
<dd>
<p> Returns the number of columns (fields)
in each row of the query result.
</p>
<pre class="synopsis">int PQnfields(const PGresult *res);</pre>
</dd>
<dt><span class="term"><code class="function">PQfname</code><a name="id680139"></a></span></dt>
<dd>
<p>Returns the column name associated with the given column number.
Column numbers start at 0. The caller should not free the result
directly. It will be freed when the associated <code class="structname">PGresult</code>
handle is passed to <code class="function">PQclear</code>.
</p>
<pre class="synopsis">char *PQfname(const PGresult *res,
int column_number);</pre>
<p><code class="symbol">NULL</code> is returned if the column number is out of range.</p>
</dd>
<dt><span class="term"><code class="function">PQfnumber</code><a name="id680183"></a></span></dt>
<dd>
<p> Returns the column number associated with the given column name.
</p>
<pre class="synopsis">int PQfnumber(const PGresult *res,
const char *column_name);</pre>
<p> -1 is returned if the given name does not match any column.</p>
<p> The given name is treated like an identifier in an SQL command,
that is, it is downcased unless double-quoted. For example,
given a query result generated from the SQL command
</p>
<pre class="programlisting">select 1 as FOO, 2 as "BAR";</pre>
<p>
we would have the results:
</p>
<pre class="programlisting">PQfname(res, 0) <em class="lineannotation"><span class="lineannotation">foo</span></em>
PQfname(res, 1) <em class="lineannotation"><span class="lineannotation">BAR</span></em>
PQfnumber(res, "FOO") <em class="lineannotation"><span class="lineannotation">0</span></em>
PQfnumber(res, "foo") <em class="lineannotation"><span class="lineannotation">0</span></em>
PQfnumber(res, "BAR") <em class="lineannotation"><span class="lineannotation">-1</span></em>
PQfnumber(res, "\"BAR\"") <em class="lineannotation"><span class="lineannotation">1</span></em></pre>
</dd>
<dt><span class="term"><code class="function">PQftable</code><a name="id680255"></a></span></dt>
<dd>
<p> Returns the OID of the table from which the given column was fetched.
Column numbers start at 0.
</p>
<pre class="synopsis">Oid PQftable(const PGresult *res,
int column_number);</pre>
<p><code class="literal">InvalidOid</code> is returned if the column number is out of range,
or if the specified column is not a simple reference to a table column,
or when using pre-3.0 protocol.
You can query the system table <code class="literal">pg_class</code> to determine
exactly which table is referenced.</p>
<p> The type <code class="type">Oid</code> and the constant
<code class="literal">InvalidOid</code> will be defined when you include
the <span class="application">libpq</span> header file. They will
both be some integer type.</p>
</dd>
<dt><span class="term"><code class="function">PQftablecol</code><a name="id680321"></a></span></dt>
<dd>
<p> Returns the column number (within its table) of the column making up
the specified query result column.
Query-result column numbers start at 0, but table columns have nonzero
numbers.
</p>
<pre class="synopsis">int PQftablecol(const PGresult *res,
int column_number);</pre>
<p>Zero is returned if the column number is out of range,
or if the specified column is not a simple reference to a table column,
or when using pre-3.0 protocol.</p>
</dd>
<dt><span class="term"><code class="function">PQfformat</code><a name="id680354"></a></span></dt>
<dd>
<p> Returns the format code indicating the format of the given column.
Column numbers start at 0.
</p>
<pre class="synopsis">int PQfformat(const PGresult *res,
int column_number);</pre>
<p>Format code zero indicates textual data representation, while format
code one indicates binary representation. (Other codes are reserved
for future definition.)</p>
</dd>
<dt><span class="term"><code class="function">PQftype</code><a name="id680385"></a></span></dt>
<dd>
<p> Returns the data type associated with the
given column number. The integer returned is the
internal OID number of the type. Column numbers start
at 0.
</p>
<pre class="synopsis">Oid PQftype(const PGresult *res,
int column_number);</pre>
<p>You can query the system table <code class="literal">pg_type</code> to obtain
the names and properties of the various data types. The <acronym class="acronym">OID</acronym>s
of the built-in data types are defined in the file <code class="filename">src/include/catalog/pg_type.h</code>
in the source tree.</p>
</dd>
<dt><span class="term"><code class="function">PQfmod</code><a name="id680434"></a></span></dt>
<dd>
<p> Returns the type modifier of the column
associated with the given column number.
Column numbers start at 0.
</p>
<pre class="synopsis">int PQfmod(const PGresult *res,
int column_number);</pre>
<p>The interpretation of modifier values is type-specific; they typically
indicate precision or size limits. The value -1 is used to indicate
“<span class="quote">no information available</span>”. Most data types do not use modifiers,
in which case the value is always -1.</p>
</dd>
<dt><span class="term"><code class="function">PQfsize</code><a name="id680471"></a></span></dt>
<dd>
<p> Returns the size in bytes of the column
associated with the given column number.
Column numbers start at 0.
</p>
<pre class="synopsis">int PQfsize(const PGresult *res,
int column_number);</pre>
<p><code class="function">PQfsize</code> returns the space allocated for this column in a database
row, in other words the size of the server's internal representation
of the data type. (Accordingly, it is not really very useful to clients.)
A negative value indicates the data type is variable-length.</p>
</dd>
<dt><span class="term"><code class="function">PQbinaryTuples</code><a name="id680509"></a></span></dt>
<dd>
<p>Returns 1 if the <code class="structname">PGresult</code> contains binary data
and 0 if it contains text data.
</p>
<pre class="synopsis">int PQbinaryTuples(const PGresult *res);</pre>
<p>This function is deprecated (except for its use in connection with
<code class="command">COPY</code>), because it is possible for a single
<code class="structname">PGresult</code>
to contain text data in some columns and binary data in others.
<code class="function">PQfformat</code> is preferred. <code class="function">PQbinaryTuples</code>
returns 1 only if all columns of the result are binary (format 1).</p>
</dd>
<dt><span class="term"><code class="function">PQgetvalue</code><a name="id680569"></a></span></dt>
<dd>
<p> Returns a single field value of one row of a
<code class="structname">PGresult</code>. Row and column numbers
start at 0. The caller should not free the result
directly. It will be freed when the associated
<code class="structname">PGresult</code> handle is passed to
<code class="function">PQclear</code>.
</p>
<pre class="synopsis">char *PQgetvalue(const PGresult *res,
int row_number,
int column_number);</pre>
<p>For data in text format, the value returned by <code class="function">PQgetvalue</code>
is a null-terminated character string representation
of the field value. For data in binary format, the value is in the binary
representation determined by the data type's <code class="function">typsend</code> and
<code class="function">typreceive</code> functions. (The value is actually followed by
a zero byte in this case too, but that is not ordinarily useful, since
the value is likely to contain embedded nulls.)</p>
<p>An empty string is returned if the field value is null. See
<code class="function">PQgetisnull</code> to distinguish null values from empty-string values.</p>
<p>The pointer
returned by <code class="function">PQgetvalue</code> points to storage that is
part of the <code class="structname">PGresult</code> structure. One should not modify the data it points to,
and one must explicitly
copy the data into other storage if it is to
be used past the lifetime of the <code class="structname">PGresult</code> structure itself.</p>
</dd>
<dt><span class="term"><code class="function">PQgetisnull</code><a name="id680674"></a></span></dt>
<dd>
<p> Tests a field for a null value.
Row and column numbers start at 0.
</p>
<pre class="synopsis">int PQgetisnull(const PGresult *res,
int row_number,
int column_number);</pre>
<p>This function returns 1 if the field is null and 0 if
it contains a non-null value. (Note that <code class="function">PQgetvalue</code>
will return an empty string, not a null pointer, for a null field.)</p>
</dd>
<dt><span class="term"><code class="function">PQgetlength</code><a name="id680724"></a></span></dt>
<dd>
<p> Returns the actual length of a field value in bytes.
Row and column numbers start at 0.
</p>
<pre class="synopsis">int PQgetlength(const PGresult *res,
int row_number,
int column_number);</pre>
<p>This is the actual data length for the particular data value, that is, the
size of the object pointed to by <code class="function">PQgetvalue</code>. For text
data format this is the same as <code class="function">strlen()</code>. For binary format
this is essential information. Note that one should <span class="emphasis"><em>not</em></span> rely
on <code class="function">PQfsize</code> to obtain the actual data length.</p>
</dd>
<dt><span class="term"><code class="function">PQprint</code><a name="id680781"></a></span></dt>
<dd>
<p> Prints out all the rows and, optionally, the
column names to the specified output stream.
</p>
<pre class="synopsis">void PQprint(FILE *fout, /* output stream */
const PGresult *res,
const PQprintOpt *po);
typedef struct {
pqbool header; /* print output field headings and row count */
pqbool align; /* fill align the fields */
pqbool standard; /* old brain dead format */
pqbool html3; /* output HTML tables */
pqbool expanded; /* expand tables */
pqbool pager; /* use pager for output if needed */
char *fieldSep; /* field separator */
char *tableOpt; /* attributes for HTML table element */
char *caption; /* HTML table caption */
char **fieldName; /* null-terminated array of replacement field names */
} PQprintOpt;</pre>
<p>This function was formerly used by <span class="application">psql</span>
to print query results, but this is no longer the case. Note that it
assumes all the data is in text format.</p>
</dd>
</dl></div>
</div>
<div class="sect2" lang="en">
<div class="titlepage"><div><div><h3 class="title">
<a name="libpq-exec-nonselect"></a>28.3.3.Retrieving Result Information for Other Commands</h3></div></div></div>
<p>These functions are used to extract information from
<code class="structname">PGresult</code> objects that are not <code class="command">SELECT</code>
results.</p>
<div class="variablelist"><dl>
<dt><span class="term"><code class="function">PQcmdStatus</code><a name="id680855"></a></span></dt>
<dd>
<p> Returns the command status tag from the SQL command that
generated the <code class="structname">PGresult</code>.
</p>
<pre class="synopsis">char *PQcmdStatus(PGresult *res);</pre>
<p>Commonly this is just the name of the command, but it may include additional
data such as the number of rows processed. The caller should
not free the result directly. It will be freed when the
associated <code class="structname">PGresult</code> handle is passed to
<code class="function">PQclear</code>.</p>
</dd>
<dt><span class="term"><code class="function">PQcmdTuples</code><a name="id680901"></a></span></dt>
<dd>
<p> Returns the number of rows affected by the SQL command.
</p>
<pre class="synopsis">char *PQcmdTuples(PGresult *res);</pre>
<p> This function returns a string containing the number of rows
affected by the <acronym class="acronym">SQL</acronym> statement that generated the
<code class="structname">PGresult</code>. This function can only be used
following the execution of an <code class="command">INSERT</code>,
<code class="command">UPDATE</code>, <code class="command">DELETE</code>, <code class="command">MOVE</code>, or
<code class="command">FETCH</code> statement, or an <code class="command">EXECUTE</code> of a
prepared query that contains a <code class="command">INSERT</code>,
<code class="command">UPDATE</code>, or <code class="command">DELETE</code> statement. If the
command that generated the <code class="structname">PGresult</code> was
anything else, <code class="function">PQcmdTuples</code> returns the empty
string. The caller should not free the return value
directly. It will be freed when the associated
<code class="structname">PGresult</code> handle is passed to
<code class="function">PQclear</code>.</p>
</dd>
<dt><span class="term"><code class="function">PQoidValue</code><a name="id681025"></a></span></dt>
<dd>
<p> Returns the OID<a name="id681036"></a> of the inserted row, if the <acronym class="acronym">SQL</acronym>
command was an <code class="command">INSERT</code> that inserted exactly one
row into a table that has OIDs, or a <code class="command">EXECUTE</code> of
a prepared query containing a suitable <code class="command">INSERT</code>
statement. Otherwise, this function returns
<code class="literal">InvalidOid</code>. This function will also
return <code class="literal">InvalidOid</code> if the table affected
by the <code class="command">INSERT</code> statement does not contain OIDs.
</p>
<pre class="synopsis">Oid PQoidValue(const PGresult *res);</pre>
</dd>
<dt><span class="term"><code class="function">PQoidStatus</code><a name="id681108"></a></span></dt>
<dd>
<p> Returns a string with the OID of the inserted row, if the
<acronym class="acronym">SQL</acronym> command was an
<code class="command">INSERT</code> that inserted exactly one row, or
a <code class="command">EXECUTE</code> of a prepared statement
consisting of a suitable <code class="command">INSERT</code>. (The string will be
<code class="literal">0</code> if the <code class="command">INSERT</code> did not
insert exactly one row, or if the target table does not have
OIDs.) If the command was not an <code class="command">INSERT</code>,
returns an empty string.
</p>
<pre class="synopsis">char *PQoidStatus(const PGresult *res);</pre>
<p>This function is deprecated in favor of <code class="function">PQoidValue</code>.
It is not thread-safe.</p>
</dd>
</dl></div>
</div>
<div class="sect2" lang="en">
<div class="titlepage"><div><div><h3 class="title">
<a name="libpq-exec-escape-string"></a>28.3.4.Escaping Strings for Inclusion in SQL Commands</h3></div></div></div>
<a name="id681194"></a><a name="id681206"></a><a name="id681217"></a><p><code class="function">PQescapeStringConn</code> escapes a string for use within an SQL
command. This is useful when inserting data values as literal constants
in SQL commands. Certain characters (such as quotes and backslashes) must
be escaped to prevent them from being interpreted specially by the SQL parser.
<code class="function">PQescapeStringConn</code> performs this operation.</p>
<div class="tip" style="margin-left: 0.5in; margin-right: 0.5in;">
<h3 class="title">Tip</h3>
<p>It is especially important to do proper escaping when handling strings that
were received from an untrustworthy source. Otherwise there is a security
risk: you are vulnerable to “<span class="quote">SQL injection</span>” attacks wherein unwanted
SQL commands are fed to your database.</p>
</div>
<p>Note that it is not necessary nor correct to do escaping when a data
value is passed as a separate parameter in <code class="function">PQexecParams</code> or
its sibling routines.
</p>
<pre class="synopsis">size_t PQescapeStringConn (PGconn *conn,
char *to, const char *from, size_t length,
int *error);</pre>
<p><code class="function">PQescapeStringConn</code> writes an escaped
version of the <em class="parameter"><code>from</code></em> string to the <em class="parameter"><code>to</code></em>
buffer, escaping special characters so that they cannot cause any
harm, and adding a terminating zero byte. The single quotes that
must surround <span class="productname">PostgreSQL</span> string literals are not
included in the result string; they should be provided in the SQL
command that the result is inserted into.
The parameter <em class="parameter"><code>from</code></em> points to the first character of the string
that is to be escaped, and the <em class="parameter"><code>length</code></em> parameter gives the
number of bytes in this string. A terminating zero byte is not
required, and should not be counted in <em class="parameter"><code>length</code></em>. (If
a terminating zero byte is found before <em class="parameter"><code>length</code></em> bytes are
processed, <code class="function">PQescapeStringConn</code> stops at the zero; the behavior
is thus rather like <code class="function">strncpy</code>.)
<em class="parameter"><code>to</code></em> shall point to a
buffer that is able to hold at least one more byte than twice
the value of <em class="parameter"><code>length</code></em>, otherwise the behavior is
undefined.
Behavior is likewise undefined if the <em class="parameter"><code>to</code></em> and <em class="parameter"><code>from</code></em>
strings overlap.</p>
<p>If the <em class="parameter"><code>error</code></em> parameter is not NULL, then <code class="literal">*error</code>
is set to zero on success, nonzero on error. Presently the only possible
error conditions involve invalid multibyte encoding in the source string.
The output string is still generated on error, but it can be expected that
the server will reject it as malformed. On error, a suitable message is
stored in the <em class="parameter"><code>conn</code></em> object, whether or not <em class="parameter"><code>error</code></em>
is NULL.</p>
<p><code class="function">PQescapeStringConn</code> returns the number of bytes written
to <em class="parameter"><code>to</code></em>, not including the terminating zero byte.</p>
<pre class="synopsis">size_t PQescapeString (char *to, const char *from, size_t length);</pre>
<p><code class="function">PQescapeString</code> is an older, deprecated version of
<code class="function">PQescapeStringConn</code>; the difference is that it does not
take <em class="parameter"><code>conn</code></em> or <em class="parameter"><code>error</code></em> parameters. Because of this,
it cannot adjust its behavior depending on the connection properties (such as
character encoding) and therefore <span class="emphasis"><em>it may give the wrong results</em></span>.
Also, it has no way to report error conditions.</p>
<p><code class="function">PQescapeString</code> can be used safely in single-threaded client
programs that work with only one <span class="productname">PostgreSQL</span> connection at
a time (in this case it can find out what it needs to know “<span class="quote">behind the
scenes</span>”). In other contexts it is a security hazard and should be avoided
in favor of <code class="function">PQescapeStringConn</code>.</p>
</div>
<div class="sect2" lang="en">
<div class="titlepage"><div><div><h3 class="title">
<a name="libpq-exec-escape-bytea"></a>28.3.5.Escaping Binary Strings for Inclusion in SQL Commands</h3></div></div></div>
<a name="id681518"></a><div class="variablelist"><dl>
<dt><span class="term"><code class="function">PQescapeByteaConn</code><a name="id681543"></a></span></dt>
<dd>
<p> Escapes binary data for use within an SQL command with the type
<code class="type">bytea</code>. As with <code class="function">PQescapeStringConn</code>,
this is only used when inserting data directly into an SQL command string.
</p>
<pre class="synopsis">unsigned char *PQescapeByteaConn(PGconn *conn,
const unsigned char *from,
size_t from_length,
size_t *to_length);</pre>
<p> Certain byte values <span class="emphasis"><em>must</em></span> be escaped (but all
byte values <span class="emphasis"><em>can</em></span> be escaped) when used as part
of a <code class="type">bytea</code> literal in an <acronym class="acronym">SQL</acronym>
statement. In general, to escape a byte, it is converted into the
three digit octal number equal to the octet value, and preceded by
one or two backslashes. The single quote (<code class="literal">'</code>) and backslash
(<code class="literal">\</code>) characters have special alternative escape
sequences. See <a href="datatype-binary.html" title="8.4.Binary Data Types">Section8.4, “Binary Data Types”</a> for more
information. <code class="function">PQescapeByteaConn</code> performs this
operation, escaping only the minimally required bytes.
</p>
<p> The <em class="parameter"><code>from</code></em> parameter points to the first
byte of the string that is to be escaped, and the
<em class="parameter"><code>from_length</code></em> parameter gives the number of
bytes in this binary string. (A terminating zero byte is
neither necessary nor counted.) The <em class="parameter"><code>to_length</code></em>
parameter points to a variable that will hold the resultant
escaped string length. This result string length includes the terminating
zero byte of the result.
</p>
<p> <code class="function">PQescapeByteaConn</code> returns an escaped version of the
<em class="parameter"><code>from</code></em> parameter binary string in memory
allocated with <code class="function">malloc()</code>. This memory must be freed using
<code class="function">PQfreemem()</code> when the result is no longer needed. The
return string has all special characters replaced so that they can
be properly processed by the <span class="productname">PostgreSQL</span>
string literal parser, and the <code class="type">bytea</code> input function. A
terminating zero byte is also added. The single quotes that must
surround <span class="productname">PostgreSQL</span> string literals are
not part of the result string.
</p>
<p> On error, a NULL pointer is returned, and a suitable error message
is stored in the <em class="parameter"><code>conn</code></em> object. Currently, the only
possible error is insufficient memory for the result string.
</p>
</dd>
<dt><span class="term"><code class="function">PQescapeBytea</code><a name="id681730"></a></span></dt>
<dd>
<p> <code class="function">PQescapeBytea</code> is an older, deprecated version of
<code class="function">PQescapeByteaConn</code>.
</p>
<pre class="synopsis">unsigned char *PQescapeBytea(const unsigned char *from,
size_t from_length,
size_t *to_length);</pre>
<p> The only difference from <code class="function">PQescapeByteaConn</code> is that
<code class="function">PQescapeBytea</code> does not
take a <code class="structname">PGconn</code> parameter. Because of this, it cannot adjust
its behavior depending on the connection properties (in particular,
whether standard-conforming strings are enabled)
and therefore <span class="emphasis"><em>it may give the wrong results</em></span>. Also, it
has no way to return an error message on failure.
</p>
<p> <code class="function">PQescapeBytea</code> can be used safely in single-threaded client
programs that work with only one <span class="productname">PostgreSQL</span> connection at
a time (in this case it can find out what it needs to know “<span class="quote">behind the
scenes</span>”). In other contexts it is a security hazard and should be
avoided in favor of <code class="function">PQescapeByteaConn</code>.
</p>
</dd>
<dt><span class="term"><code class="function">PQunescapeBytea</code><a name="id681830"></a></span></dt>
<dd>
<p> Converts a string representation of binary data into binary
data [mdash ] the reverse of <code class="function">PQescapeBytea</code>.
This is needed when retrieving <code class="type">bytea</code> data in text format,
but not when retrieving it in binary format.
</p>
<pre class="synopsis">unsigned char *PQunescapeBytea(const unsigned char *from, size_t *to_length);</pre>
<p> The <em class="parameter"><code>from</code></em> parameter points to a string
such as might be returned by <code class="function">PQgetvalue</code> when applied
to a <code class="type">bytea</code> column. <code class="function">PQunescapeBytea</code>
converts this string representation into its binary representation.
It returns a pointer to a buffer allocated with
<code class="function">malloc()</code>, or null on error, and puts the size of
the buffer in <em class="parameter"><code>to_length</code></em>. The result must be
freed using <code class="function">PQfreemem</code> when it is no longer needed.
</p>
<p> This conversion is not exactly the inverse of
<code class="function">PQescapeBytea</code>, because the string is not expected
to be “<span class="quote">escaped</span>” when received from <code class="function">PQgetvalue</code>.
In particular this means there is no need for string quoting considerations,
and so no need for a <code class="structname">PGconn</code> parameter.
</p>
</dd>
<dt><span class="term"><code class="function">PQfreemem</code><a name="id681948"></a></span></dt>
<dd>
<p> Frees memory allocated by <span class="application">libpq</span>.
</p>
<pre class="synopsis">void PQfreemem(void *ptr);</pre>
<p> Frees memory allocated by <span class="application">libpq</span>, particularly
<code class="function">PQescapeByteaConn</code>,
<code class="function">PQescapeBytea</code>,
<code class="function">PQunescapeBytea</code>,
and <code class="function">PQnotifies</code>.
It is needed by Microsoft Windows, which cannot free memory across
DLLs, unless multithreaded DLLs (<code class="option">/MD</code> in VC6) are used.
On other platforms, this function is the same as the standard library function <code class="function">free()</code>.
</p>
</dd>
</dl></div>
</div>
</div></body>
</html>
|