1<!-- doc/src/sgml/ecpg.sgml --> 2 3<chapter id="ecpg"> 4 <title><application>ECPG</application> - Embedded <acronym>SQL</acronym> in C</title> 5 6 <indexterm zone="ecpg"><primary>embedded SQL</primary><secondary>in C</secondary></indexterm> 7 <indexterm zone="ecpg"><primary>C</primary></indexterm> 8 <indexterm zone="ecpg"><primary>ECPG</primary></indexterm> 9 10 <para> 11 This chapter describes the embedded <acronym>SQL</acronym> package 12 for <productname>PostgreSQL</productname>. It was written by 13 Linus Tolke (<email>linus@epact.se</email>) and Michael Meskes 14 (<email>meskes@postgresql.org</email>). Originally it was written to work with 15 <acronym>C</acronym>. It also works with <acronym>C++</acronym>, but 16 it does not recognize all <acronym>C++</acronym> constructs yet. 17 </para> 18 19 <para> 20 This documentation is quite incomplete. But since this 21 interface is standardized, additional information can be found in 22 many resources about SQL. 23 </para> 24 25 <sect1 id="ecpg-concept"> 26 <title>The Concept</title> 27 28 <para> 29 An embedded SQL program consists of code written in an ordinary 30 programming language, in this case C, mixed with SQL commands in 31 specially marked sections. To build the program, the source code (<filename>*.pgc</filename>) 32 is first passed through the embedded SQL preprocessor, which converts it 33 to an ordinary C program (<filename>*.c</filename>), and afterwards it can be processed by a C 34 compiler. (For details about the compiling and linking see <xref linkend="ecpg-process"/>). 35 Converted ECPG applications call functions in the libpq library 36 through the embedded SQL library (ecpglib), and communicate with 37 the PostgreSQL server using the normal frontend-backend protocol. 38 </para> 39 40 <para> 41 Embedded <acronym>SQL</acronym> has advantages over other methods 42 for handling <acronym>SQL</acronym> commands from C code. First, it 43 takes care of the tedious passing of information to and from 44 variables in your <acronym>C</acronym> program. Second, the SQL 45 code in the program is checked at build time for syntactical 46 correctness. Third, embedded <acronym>SQL</acronym> in C is 47 specified in the <acronym>SQL</acronym> standard and supported by 48 many other <acronym>SQL</acronym> database systems. The 49 <productname>PostgreSQL</productname> implementation is designed to match this 50 standard as much as possible, and it is usually possible to port 51 embedded <acronym>SQL</acronym> programs written for other SQL 52 databases to <productname>PostgreSQL</productname> with relative 53 ease. 54 </para> 55 56 <para> 57 As already stated, programs written for the embedded 58 <acronym>SQL</acronym> interface are normal C programs with special 59 code inserted to perform database-related actions. This special 60 code always has the form: 61<programlisting> 62EXEC SQL ...; 63</programlisting> 64 These statements syntactically take the place of a C statement. 65 Depending on the particular statement, they can appear at the 66 global level or within a function. Embedded 67 <acronym>SQL</acronym> statements follow the case-sensitivity rules of 68 normal <acronym>SQL</acronym> code, and not those of C. Also they allow nested 69 C-style comments that are part of the SQL standard. The C part of the 70 program, however, follows the C standard of not accepting nested comments. 71 </para> 72 73 <para> 74 The following sections explain all the embedded SQL statements. 75 </para> 76 </sect1> 77 78 <sect1 id="ecpg-connect"> 79 <title>Managing Database Connections</title> 80 81 <para> 82 This section describes how to open, close, and switch database 83 connections. 84 </para> 85 86 <sect2 id="ecpg-connecting"> 87 <title>Connecting to the Database Server</title> 88 89 <para> 90 One connects to a database using the following statement: 91<programlisting> 92EXEC SQL CONNECT TO <replaceable>target</replaceable> <optional>AS <replaceable>connection-name</replaceable></optional> <optional>USER <replaceable>user-name</replaceable></optional>; 93</programlisting> 94 The <replaceable>target</replaceable> can be specified in the 95 following ways: 96 97 <itemizedlist> 98 <listitem> 99 <simpara> 100 <literal><replaceable>dbname</replaceable><optional>@<replaceable>hostname</replaceable></optional><optional>:<replaceable>port</replaceable></optional></literal> 101 </simpara> 102 </listitem> 103 104 <listitem> 105 <simpara> 106 <literal>tcp:postgresql://<replaceable>hostname</replaceable><optional>:<replaceable>port</replaceable></optional><optional>/<replaceable>dbname</replaceable></optional><optional>?<replaceable>options</replaceable></optional></literal> 107 </simpara> 108 </listitem> 109 110 <listitem> 111 <simpara> 112 <literal>unix:postgresql://<replaceable>hostname</replaceable><optional>:<replaceable>port</replaceable></optional><optional>/<replaceable>dbname</replaceable></optional><optional>?<replaceable>options</replaceable></optional></literal> 113 </simpara> 114 </listitem> 115 116 <listitem> 117 <simpara> 118 an SQL string literal containing one of the above forms 119 </simpara> 120 </listitem> 121 122 <listitem> 123 <simpara> 124 a reference to a character variable containing one of the above forms (see examples) 125 </simpara> 126 </listitem> 127 128 <listitem> 129 <simpara> 130 <literal>DEFAULT</literal> 131 </simpara> 132 </listitem> 133 </itemizedlist> 134 135 If you specify the connection target literally (that is, not 136 through a variable reference) and you don't quote the value, then 137 the case-insensitivity rules of normal SQL are applied. In that 138 case you can also double-quote the individual parameters separately 139 as needed. In practice, it is probably less error-prone to use a 140 (single-quoted) string literal or a variable reference. The 141 connection target <literal>DEFAULT</literal> initiates a connection 142 to the default database under the default user name. No separate 143 user name or connection name can be specified in that case. 144 </para> 145 146 <para> 147 There are also different ways to specify the user name: 148 149 <itemizedlist> 150 <listitem> 151 <simpara> 152 <literal><replaceable>username</replaceable></literal> 153 </simpara> 154 </listitem> 155 156 <listitem> 157 <simpara> 158 <literal><replaceable>username</replaceable>/<replaceable>password</replaceable></literal> 159 </simpara> 160 </listitem> 161 162 <listitem> 163 <simpara> 164 <literal><replaceable>username</replaceable> IDENTIFIED BY <replaceable>password</replaceable></literal> 165 </simpara> 166 </listitem> 167 168 <listitem> 169 <simpara> 170 <literal><replaceable>username</replaceable> USING <replaceable>password</replaceable></literal> 171 </simpara> 172 </listitem> 173 </itemizedlist> 174 175 As above, the parameters <replaceable>username</replaceable> and 176 <replaceable>password</replaceable> can be an SQL identifier, an 177 SQL string literal, or a reference to a character variable. 178 </para> 179 180 <para> 181 If the connection target includes any <replaceable>options</replaceable>, 182 those consist of 183 <literal><replaceable>keyword</replaceable>=<replaceable>value</replaceable></literal> 184 specifications separated by ampersands (<literal>&</literal>). 185 The allowed key words are the same ones recognized 186 by <application>libpq</application> (see 187 <xref linkend="libpq-paramkeywords"/>). Spaces are ignored before 188 any <replaceable>keyword</replaceable> or <replaceable>value</replaceable>, 189 though not within or after one. Note that there is no way to 190 write <literal>&</literal> within a <replaceable>value</replaceable>. 191 </para> 192 193 <para> 194 The <replaceable>connection-name</replaceable> is used to handle 195 multiple connections in one program. It can be omitted if a 196 program uses only one connection. The most recently opened 197 connection becomes the current connection, which is used by default 198 when an SQL statement is to be executed (see later in this 199 chapter). 200 </para> 201 202 <para> 203 If untrusted users have access to a database that has not adopted a 204 <link linkend="ddl-schemas-patterns">secure schema usage pattern</link>, 205 begin each session by removing publicly-writable schemas 206 from <varname>search_path</varname>. For example, 207 add <literal>options=-c search_path=</literal> 208 to <literal><replaceable>options</replaceable></literal>, or 209 issue <literal>EXEC SQL SELECT pg_catalog.set_config('search_path', '', 210 false);</literal> after connecting. This consideration is not specific to 211 ECPG; it applies to every interface for executing arbitrary SQL commands. 212 </para> 213 214 <para> 215 Here are some examples of <command>CONNECT</command> statements: 216<programlisting> 217EXEC SQL CONNECT TO mydb@sql.mydomain.com; 218 219EXEC SQL CONNECT TO unix:postgresql://sql.mydomain.com/mydb AS myconnection USER john; 220 221EXEC SQL BEGIN DECLARE SECTION; 222const char *target = "mydb@sql.mydomain.com"; 223const char *user = "john"; 224const char *passwd = "secret"; 225EXEC SQL END DECLARE SECTION; 226 ... 227EXEC SQL CONNECT TO :target USER :user USING :passwd; 228/* or EXEC SQL CONNECT TO :target USER :user/:passwd; */ 229</programlisting> 230 The last form makes use of the variant referred to above as 231 character variable reference. You will see in later sections how C 232 variables can be used in SQL statements when you prefix them with a 233 colon. 234 </para> 235 236 <para> 237 Be advised that the format of the connection target is not 238 specified in the SQL standard. So if you want to develop portable 239 applications, you might want to use something based on the last 240 example above to encapsulate the connection target string 241 somewhere. 242 </para> 243 </sect2> 244 245 <sect2 id="ecpg-set-connection"> 246 <title>Choosing a Connection</title> 247 248 <para> 249 SQL statements in embedded SQL programs are by default executed on 250 the current connection, that is, the most recently opened one. If 251 an application needs to manage multiple connections, then there are 252 two ways to handle this. 253 </para> 254 255 <para> 256 The first option is to explicitly choose a connection for each SQL 257 statement, for example: 258<programlisting> 259EXEC SQL AT <replaceable>connection-name</replaceable> SELECT ...; 260</programlisting> 261 This option is particularly suitable if the application needs to 262 use several connections in mixed order. 263 </para> 264 265 <para> 266 If your application uses multiple threads of execution, they cannot share a 267 connection concurrently. You must either explicitly control access to the connection 268 (using mutexes) or use a connection for each thread. 269 </para> 270 271 <para> 272 The second option is to execute a statement to switch the current 273 connection. That statement is: 274<programlisting> 275EXEC SQL SET CONNECTION <replaceable>connection-name</replaceable>; 276</programlisting> 277 This option is particularly convenient if many statements are to be 278 executed on the same connection. 279 </para> 280 281 <para> 282 Here is an example program managing multiple database connections: 283<programlisting><![CDATA[ 284#include <stdio.h> 285 286EXEC SQL BEGIN DECLARE SECTION; 287 char dbname[1024]; 288EXEC SQL END DECLARE SECTION; 289 290int 291main() 292{ 293 EXEC SQL CONNECT TO testdb1 AS con1 USER testuser; 294 EXEC SQL SELECT pg_catalog.set_config('search_path', '', false); EXEC SQL COMMIT; 295 EXEC SQL CONNECT TO testdb2 AS con2 USER testuser; 296 EXEC SQL SELECT pg_catalog.set_config('search_path', '', false); EXEC SQL COMMIT; 297 EXEC SQL CONNECT TO testdb3 AS con3 USER testuser; 298 EXEC SQL SELECT pg_catalog.set_config('search_path', '', false); EXEC SQL COMMIT; 299 300 /* This query would be executed in the last opened database "testdb3". */ 301 EXEC SQL SELECT current_database() INTO :dbname; 302 printf("current=%s (should be testdb3)\n", dbname); 303 304 /* Using "AT" to run a query in "testdb2" */ 305 EXEC SQL AT con2 SELECT current_database() INTO :dbname; 306 printf("current=%s (should be testdb2)\n", dbname); 307 308 /* Switch the current connection to "testdb1". */ 309 EXEC SQL SET CONNECTION con1; 310 311 EXEC SQL SELECT current_database() INTO :dbname; 312 printf("current=%s (should be testdb1)\n", dbname); 313 314 EXEC SQL DISCONNECT ALL; 315 return 0; 316} 317]]></programlisting> 318 319 This example would produce this output: 320<screen> 321current=testdb3 (should be testdb3) 322current=testdb2 (should be testdb2) 323current=testdb1 (should be testdb1) 324</screen> 325 </para> 326 </sect2> 327 328 <sect2 id="ecpg-disconnect"> 329 <title>Closing a Connection</title> 330 331 <para> 332 To close a connection, use the following statement: 333<programlisting> 334EXEC SQL DISCONNECT <optional><replaceable>connection</replaceable></optional>; 335</programlisting> 336 The <replaceable>connection</replaceable> can be specified 337 in the following ways: 338 339 <itemizedlist> 340 <listitem> 341 <simpara> 342 <literal><replaceable>connection-name</replaceable></literal> 343 </simpara> 344 </listitem> 345 346 <listitem> 347 <simpara> 348 <literal>DEFAULT</literal> 349 </simpara> 350 </listitem> 351 352 <listitem> 353 <simpara> 354 <literal>CURRENT</literal> 355 </simpara> 356 </listitem> 357 358 <listitem> 359 <simpara> 360 <literal>ALL</literal> 361 </simpara> 362 </listitem> 363 </itemizedlist> 364 365 If no connection name is specified, the current connection is 366 closed. 367 </para> 368 369 <para> 370 It is good style that an application always explicitly disconnect 371 from every connection it opened. 372 </para> 373 </sect2> 374 375 </sect1> 376 377 <sect1 id="ecpg-commands"> 378 <title>Running SQL Commands</title> 379 380 <para> 381 Any SQL command can be run from within an embedded SQL application. 382 Below are some examples of how to do that. 383 </para> 384 385 <sect2 id="ecpg-executing"> 386 <title>Executing SQL Statements</title> 387 388 <para> 389 Creating a table: 390<programlisting> 391EXEC SQL CREATE TABLE foo (number integer, ascii char(16)); 392EXEC SQL CREATE UNIQUE INDEX num1 ON foo(number); 393EXEC SQL COMMIT; 394</programlisting> 395 </para> 396 397 <para> 398 Inserting rows: 399<programlisting> 400EXEC SQL INSERT INTO foo (number, ascii) VALUES (9999, 'doodad'); 401EXEC SQL COMMIT; 402</programlisting> 403 </para> 404 405 <para> 406 Deleting rows: 407<programlisting> 408EXEC SQL DELETE FROM foo WHERE number = 9999; 409EXEC SQL COMMIT; 410</programlisting> 411 </para> 412 413 <para> 414 Updates: 415<programlisting> 416EXEC SQL UPDATE foo 417 SET ascii = 'foobar' 418 WHERE number = 9999; 419EXEC SQL COMMIT; 420</programlisting> 421 </para> 422 423 <para> 424 <literal>SELECT</literal> statements that return a single result 425 row can also be executed using 426 <literal>EXEC SQL</literal> directly. To handle result sets with 427 multiple rows, an application has to use a cursor; 428 see <xref linkend="ecpg-cursors"/> below. (As a special case, an 429 application can fetch multiple rows at once into an array host 430 variable; see <xref linkend="ecpg-variables-arrays"/>.) 431 </para> 432 433 <para> 434 Single-row select: 435<programlisting> 436EXEC SQL SELECT foo INTO :FooBar FROM table1 WHERE ascii = 'doodad'; 437</programlisting> 438 </para> 439 440 <para> 441 Also, a configuration parameter can be retrieved with the 442 <literal>SHOW</literal> command: 443<programlisting> 444EXEC SQL SHOW search_path INTO :var; 445</programlisting> 446 </para> 447 448 <para> 449 The tokens of the form 450 <literal>:<replaceable>something</replaceable></literal> are 451 <firstterm>host variables</firstterm>, that is, they refer to 452 variables in the C program. They are explained in <xref 453 linkend="ecpg-variables"/>. 454 </para> 455 </sect2> 456 457 <sect2 id="ecpg-cursors"> 458 <title>Using Cursors</title> 459 460 <para> 461 To retrieve a result set holding multiple rows, an application has 462 to declare a cursor and fetch each row from the cursor. The steps 463 to use a cursor are the following: declare a cursor, open it, fetch 464 a row from the cursor, repeat, and finally close it. 465 </para> 466 467 <para> 468 Select using cursors: 469<programlisting> 470EXEC SQL DECLARE foo_bar CURSOR FOR 471 SELECT number, ascii FROM foo 472 ORDER BY ascii; 473EXEC SQL OPEN foo_bar; 474EXEC SQL FETCH foo_bar INTO :FooBar, DooDad; 475... 476EXEC SQL CLOSE foo_bar; 477EXEC SQL COMMIT; 478</programlisting> 479 </para> 480 481 <para> 482 For more details about declaration of the cursor, 483 see <xref linkend="ecpg-sql-declare"/>, and 484 see <xref linkend="sql-fetch"/> for <literal>FETCH</literal> command 485 details. 486 </para> 487 488 <note> 489 <para> 490 The ECPG <command>DECLARE</command> command does not actually 491 cause a statement to be sent to the PostgreSQL backend. The 492 cursor is opened in the backend (using the 493 backend's <command>DECLARE</command> command) at the point when 494 the <command>OPEN</command> command is executed. 495 </para> 496 </note> 497 </sect2> 498 499 <sect2 id="ecpg-transactions"> 500 <title>Managing Transactions</title> 501 502 <para> 503 In the default mode, statements are committed only when 504 <command>EXEC SQL COMMIT</command> is issued. The embedded SQL 505 interface also supports autocommit of transactions (similar to 506 <application>psql</application>'s default behavior) via the <option>-t</option> 507 command-line option to <command>ecpg</command> (see <xref 508 linkend="app-ecpg"/>) or via the <literal>EXEC SQL SET AUTOCOMMIT TO 509 ON</literal> statement. In autocommit mode, each command is 510 automatically committed unless it is inside an explicit transaction 511 block. This mode can be explicitly turned off using <literal>EXEC 512 SQL SET AUTOCOMMIT TO OFF</literal>. 513 </para> 514 515 <para> 516 The following transaction management commands are available: 517 518 <variablelist> 519 <varlistentry> 520 <term><literal>EXEC SQL COMMIT</literal></term> 521 <listitem> 522 <para> 523 Commit an in-progress transaction. 524 </para> 525 </listitem> 526 </varlistentry> 527 528 <varlistentry> 529 <term><literal>EXEC SQL ROLLBACK</literal></term> 530 <listitem> 531 <para> 532 Roll back an in-progress transaction. 533 </para> 534 </listitem> 535 </varlistentry> 536 537 <varlistentry> 538 <term><literal>EXEC SQL PREPARE TRANSACTION </literal><replaceable class="parameter">transaction_id</replaceable></term> 539 <listitem> 540 <para> 541 Prepare the current transaction for two-phase commit. 542 </para> 543 </listitem> 544 </varlistentry> 545 546 <varlistentry> 547 <term><literal>EXEC SQL COMMIT PREPARED </literal><replaceable class="parameter">transaction_id</replaceable></term> 548 <listitem> 549 <para> 550 Commit a transaction that is in prepared state. 551 </para> 552 </listitem> 553 </varlistentry> 554 555 <varlistentry> 556 <term><literal>EXEC SQL ROLLBACK PREPARED </literal><replaceable class="parameter">transaction_id</replaceable></term> 557 <listitem> 558 <para> 559 Roll back a transaction that is in prepared state. 560 </para> 561 </listitem> 562 </varlistentry> 563 564 <varlistentry> 565 <term><literal>EXEC SQL SET AUTOCOMMIT TO ON</literal></term> 566 <listitem> 567 <para> 568 Enable autocommit mode. 569 </para> 570 </listitem> 571 </varlistentry> 572 573 <varlistentry> 574 <term><literal>EXEC SQL SET AUTOCOMMIT TO OFF</literal></term> 575 <listitem> 576 <para> 577 Disable autocommit mode. This is the default. 578 </para> 579 </listitem> 580 </varlistentry> 581 </variablelist> 582 </para> 583 </sect2> 584 585 <sect2 id="ecpg-prepared"> 586 <title>Prepared Statements</title> 587 588 <para> 589 When the values to be passed to an SQL statement are not known at 590 compile time, or the same statement is going to be used many 591 times, then prepared statements can be useful. 592 </para> 593 594 <para> 595 The statement is prepared using the 596 command <literal>PREPARE</literal>. For the values that are not 597 known yet, use the 598 placeholder <quote><literal>?</literal></quote>: 599<programlisting> 600EXEC SQL PREPARE stmt1 FROM "SELECT oid, datname FROM pg_database WHERE oid = ?"; 601</programlisting> 602 </para> 603 604 <para> 605 If a statement returns a single row, the application can 606 call <literal>EXECUTE</literal> after 607 <literal>PREPARE</literal> to execute the statement, supplying the 608 actual values for the placeholders with a <literal>USING</literal> 609 clause: 610<programlisting> 611EXEC SQL EXECUTE stmt1 INTO :dboid, :dbname USING 1; 612</programlisting> 613 </para> 614 615 <para> 616 If a statement returns multiple rows, the application can use a 617 cursor declared based on the prepared statement. To bind input 618 parameters, the cursor must be opened with 619 a <literal>USING</literal> clause: 620<programlisting> 621EXEC SQL PREPARE stmt1 FROM "SELECT oid,datname FROM pg_database WHERE oid > ?"; 622EXEC SQL DECLARE foo_bar CURSOR FOR stmt1; 623 624/* when end of result set reached, break out of while loop */ 625EXEC SQL WHENEVER NOT FOUND DO BREAK; 626 627EXEC SQL OPEN foo_bar USING 100; 628... 629while (1) 630{ 631 EXEC SQL FETCH NEXT FROM foo_bar INTO :dboid, :dbname; 632 ... 633} 634EXEC SQL CLOSE foo_bar; 635</programlisting> 636 </para> 637 638 <para> 639 When you don't need the prepared statement anymore, you should 640 deallocate it: 641<programlisting> 642EXEC SQL DEALLOCATE PREPARE <replaceable>name</replaceable>; 643</programlisting> 644 </para> 645 646 <para> 647 For more details about <literal>PREPARE</literal>, 648 see <xref linkend="ecpg-sql-prepare"/>. Also 649 see <xref linkend="ecpg-dynamic"/> for more details about using 650 placeholders and input parameters. 651 </para> 652 </sect2> 653 </sect1> 654 655 <sect1 id="ecpg-variables"> 656 <title>Using Host Variables</title> 657 658 <para> 659 In <xref linkend="ecpg-commands"/> you saw how you can execute SQL 660 statements from an embedded SQL program. Some of those statements 661 only used fixed values and did not provide a way to insert 662 user-supplied values into statements or have the program process 663 the values returned by the query. Those kinds of statements are 664 not really useful in real applications. This section explains in 665 detail how you can pass data between your C program and the 666 embedded SQL statements using a simple mechanism called 667 <firstterm>host variables</firstterm>. In an embedded SQL program we 668 consider the SQL statements to be <firstterm>guests</firstterm> in the C 669 program code which is the <firstterm>host language</firstterm>. Therefore 670 the variables of the C program are called <firstterm>host 671 variables</firstterm>. 672 </para> 673 674 <para> 675 Another way to exchange values between PostgreSQL backends and ECPG 676 applications is the use of SQL descriptors, described 677 in <xref linkend="ecpg-descriptors"/>. 678 </para> 679 680 <sect2 id="ecpg-variables-overview"> 681 <title>Overview</title> 682 683 <para> 684 Passing data between the C program and the SQL statements is 685 particularly simple in embedded SQL. Instead of having the 686 program paste the data into the statement, which entails various 687 complications, such as properly quoting the value, you can simply 688 write the name of a C variable into the SQL statement, prefixed by 689 a colon. For example: 690<programlisting> 691EXEC SQL INSERT INTO sometable VALUES (:v1, 'foo', :v2); 692</programlisting> 693 This statement refers to two C variables named 694 <varname>v1</varname> and <varname>v2</varname> and also uses a 695 regular SQL string literal, to illustrate that you are not 696 restricted to use one kind of data or the other. 697 </para> 698 699 <para> 700 This style of inserting C variables in SQL statements works 701 anywhere a value expression is expected in an SQL statement. 702 </para> 703 </sect2> 704 705 <sect2 id="ecpg-declare-sections"> 706 <title>Declare Sections</title> 707 708 <para> 709 To pass data from the program to the database, for example as 710 parameters in a query, or to pass data from the database back to 711 the program, the C variables that are intended to contain this 712 data need to be declared in specially marked sections, so the 713 embedded SQL preprocessor is made aware of them. 714 </para> 715 716 <para> 717 This section starts with: 718<programlisting> 719EXEC SQL BEGIN DECLARE SECTION; 720</programlisting> 721 and ends with: 722<programlisting> 723EXEC SQL END DECLARE SECTION; 724</programlisting> 725 Between those lines, there must be normal C variable declarations, 726 such as: 727<programlisting> 728int x = 4; 729char foo[16], bar[16]; 730</programlisting> 731 As you can see, you can optionally assign an initial value to the variable. 732 The variable's scope is determined by the location of its declaring 733 section within the program. 734 You can also declare variables with the following syntax which implicitly 735 creates a declare section: 736<programlisting> 737EXEC SQL int i = 4; 738</programlisting> 739 You can have as many declare sections in a program as you like. 740 </para> 741 742 <para> 743 The declarations are also echoed to the output file as normal C 744 variables, so there's no need to declare them again. Variables 745 that are not intended to be used in SQL commands can be declared 746 normally outside these special sections. 747 </para> 748 749 <para> 750 The definition of a structure or union also must be listed inside 751 a <literal>DECLARE</literal> section. Otherwise the preprocessor cannot 752 handle these types since it does not know the definition. 753 </para> 754 </sect2> 755 756 <sect2 id="ecpg-retrieving"> 757 <title>Retrieving Query Results</title> 758 759 <para> 760 Now you should be able to pass data generated by your program into 761 an SQL command. But how do you retrieve the results of a query? 762 For that purpose, embedded SQL provides special variants of the 763 usual commands <command>SELECT</command> and 764 <command>FETCH</command>. These commands have a special 765 <literal>INTO</literal> clause that specifies which host variables 766 the retrieved values are to be stored in. 767 <command>SELECT</command> is used for a query that returns only 768 single row, and <command>FETCH</command> is used for a query that 769 returns multiple rows, using a cursor. 770 </para> 771 772 <para> 773 Here is an example: 774<programlisting> 775/* 776 * assume this table: 777 * CREATE TABLE test1 (a int, b varchar(50)); 778 */ 779 780EXEC SQL BEGIN DECLARE SECTION; 781int v1; 782VARCHAR v2; 783EXEC SQL END DECLARE SECTION; 784 785 ... 786 787EXEC SQL SELECT a, b INTO :v1, :v2 FROM test; 788</programlisting> 789 So the <literal>INTO</literal> clause appears between the select 790 list and the <literal>FROM</literal> clause. The number of 791 elements in the select list and the list after 792 <literal>INTO</literal> (also called the target list) must be 793 equal. 794 </para> 795 796 <para> 797 Here is an example using the command <command>FETCH</command>: 798<programlisting> 799EXEC SQL BEGIN DECLARE SECTION; 800int v1; 801VARCHAR v2; 802EXEC SQL END DECLARE SECTION; 803 804 ... 805 806EXEC SQL DECLARE foo CURSOR FOR SELECT a, b FROM test; 807 808 ... 809 810do 811{ 812 ... 813 EXEC SQL FETCH NEXT FROM foo INTO :v1, :v2; 814 ... 815} while (...); 816</programlisting> 817 Here the <literal>INTO</literal> clause appears after all the 818 normal clauses. 819 </para> 820 821 </sect2> 822 823 <sect2 id="ecpg-variables-type-mapping"> 824 <title>Type Mapping</title> 825 826 <para> 827 When ECPG applications exchange values between the PostgreSQL 828 server and the C application, such as when retrieving query 829 results from the server or executing SQL statements with input 830 parameters, the values need to be converted between PostgreSQL 831 data types and host language variable types (C language data 832 types, concretely). One of the main points of ECPG is that it 833 takes care of this automatically in most cases. 834 </para> 835 836 <para> 837 In this respect, there are two kinds of data types: Some simple 838 PostgreSQL data types, such as <type>integer</type> 839 and <type>text</type>, can be read and written by the application 840 directly. Other PostgreSQL data types, such 841 as <type>timestamp</type> and <type>numeric</type> can only be 842 accessed through special library functions; see 843 <xref linkend="ecpg-special-types"/>. 844 </para> 845 846 <para> 847 <xref linkend="ecpg-datatype-hostvars-table"/> shows which PostgreSQL 848 data types correspond to which C data types. When you wish to 849 send or receive a value of a given PostgreSQL data type, you 850 should declare a C variable of the corresponding C data type in 851 the declare section. 852 </para> 853 854 <table id="ecpg-datatype-hostvars-table"> 855 <title>Mapping Between PostgreSQL Data Types and C Variable Types</title> 856 <tgroup cols="2"> 857 <thead> 858 <row> 859 <entry>PostgreSQL data type</entry> 860 <entry>Host variable type</entry> 861 </row> 862 </thead> 863 864 <tbody> 865 <row> 866 <entry><type>smallint</type></entry> 867 <entry><type>short</type></entry> 868 </row> 869 870 <row> 871 <entry><type>integer</type></entry> 872 <entry><type>int</type></entry> 873 </row> 874 875 <row> 876 <entry><type>bigint</type></entry> 877 <entry><type>long long int</type></entry> 878 </row> 879 880 <row> 881 <entry><type>decimal</type></entry> 882 <entry><type>decimal</type><footnote id="ecpg-datatype-table-fn"><para>This type can only be accessed through special library functions; see <xref linkend="ecpg-special-types"/>.</para></footnote></entry> 883 </row> 884 885 <row> 886 <entry><type>numeric</type></entry> 887 <entry><type>numeric</type><footnoteref linkend="ecpg-datatype-table-fn"/></entry> 888 </row> 889 890 <row> 891 <entry><type>real</type></entry> 892 <entry><type>float</type></entry> 893 </row> 894 895 <row> 896 <entry><type>double precision</type></entry> 897 <entry><type>double</type></entry> 898 </row> 899 900 <row> 901 <entry><type>smallserial</type></entry> 902 <entry><type>short</type></entry> 903 </row> 904 905 <row> 906 <entry><type>serial</type></entry> 907 <entry><type>int</type></entry> 908 </row> 909 910 <row> 911 <entry><type>bigserial</type></entry> 912 <entry><type>long long int</type></entry> 913 </row> 914 915 <row> 916 <entry><type>oid</type></entry> 917 <entry><type>unsigned int</type></entry> 918 </row> 919 920 <row> 921 <entry><type>character(<replaceable>n</replaceable>)</type>, <type>varchar(<replaceable>n</replaceable>)</type>, <type>text</type></entry> 922 <entry><type>char[<replaceable>n</replaceable>+1]</type>, <type>VARCHAR[<replaceable>n</replaceable>+1]</type></entry> 923 </row> 924 925 <row> 926 <entry><type>name</type></entry> 927 <entry><type>char[NAMEDATALEN]</type></entry> 928 </row> 929 930 <row> 931 <entry><type>timestamp</type></entry> 932 <entry><type>timestamp</type><footnoteref linkend="ecpg-datatype-table-fn"/></entry> 933 </row> 934 935 <row> 936 <entry><type>interval</type></entry> 937 <entry><type>interval</type><footnoteref linkend="ecpg-datatype-table-fn"/></entry> 938 </row> 939 940 <row> 941 <entry><type>date</type></entry> 942 <entry><type>date</type><footnoteref linkend="ecpg-datatype-table-fn"/></entry> 943 </row> 944 945 <row> 946 <entry><type>boolean</type></entry> 947 <entry><type>bool</type><footnote><para>declared in <filename>ecpglib.h</filename> if not native</para></footnote></entry> 948 </row> 949 950 <row> 951 <entry><type>bytea</type></entry> 952 <entry><type>char *</type>, <type>bytea[<replaceable>n</replaceable>]</type></entry> 953 </row> 954 </tbody> 955 </tgroup> 956 </table> 957 958 <sect3 id="ecpg-char"> 959 <title>Handling Character Strings</title> 960 961 <para> 962 To handle SQL character string data types, such 963 as <type>varchar</type> and <type>text</type>, there are two 964 possible ways to declare the host variables. 965 </para> 966 967 <para> 968 One way is using <type>char[]</type>, an array 969 of <type>char</type>, which is the most common way to handle 970 character data in C. 971<programlisting> 972EXEC SQL BEGIN DECLARE SECTION; 973 char str[50]; 974EXEC SQL END DECLARE SECTION; 975</programlisting> 976 Note that you have to take care of the length yourself. If you 977 use this host variable as the target variable of a query which 978 returns a string with more than 49 characters, a buffer overflow 979 occurs. 980 </para> 981 982 <para> 983 The other way is using the <type>VARCHAR</type> type, which is a 984 special type provided by ECPG. The definition on an array of 985 type <type>VARCHAR</type> is converted into a 986 named <type>struct</type> for every variable. A declaration like: 987<programlisting> 988VARCHAR var[180]; 989</programlisting> 990 is converted into: 991<programlisting> 992struct varchar_var { int len; char arr[180]; } var; 993</programlisting> 994 The member <structfield>arr</structfield> hosts the string 995 including a terminating zero byte. Thus, to store a string in 996 a <type>VARCHAR</type> host variable, the host variable has to be 997 declared with the length including the zero byte terminator. The 998 member <structfield>len</structfield> holds the length of the 999 string stored in the <structfield>arr</structfield> without the 1000 terminating zero byte. When a host variable is used as input for 1001 a query, if <literal>strlen(arr)</literal> 1002 and <structfield>len</structfield> are different, the shorter one 1003 is used. 1004 </para> 1005 1006 <para> 1007 <type>VARCHAR</type> can be written in upper or lower case, but 1008 not in mixed case. 1009 </para> 1010 1011 <para> 1012 <type>char</type> and <type>VARCHAR</type> host variables can 1013 also hold values of other SQL types, which will be stored in 1014 their string forms. 1015 </para> 1016 </sect3> 1017 1018 <sect3 id="ecpg-special-types"> 1019 <title>Accessing Special Data Types</title> 1020 1021 <para> 1022 ECPG contains some special types that help you to interact easily 1023 with some special data types from the PostgreSQL server. In 1024 particular, it has implemented support for the 1025 <type>numeric</type>, <type>decimal</type>, <type>date</type>, <type>timestamp</type>, 1026 and <type>interval</type> types. These data types cannot usefully be 1027 mapped to primitive host variable types (such 1028 as <type>int</type>, <type>long long int</type>, 1029 or <type>char[]</type>), because they have a complex internal 1030 structure. Applications deal with these types by declaring host 1031 variables in special types and accessing them using functions in 1032 the pgtypes library. The pgtypes library, described in detail 1033 in <xref linkend="ecpg-pgtypes"/> contains basic functions to deal 1034 with those types, such that you do not need to send a query to 1035 the SQL server just for adding an interval to a time stamp for 1036 example. 1037 </para> 1038 1039 <para> 1040 The follow subsections describe these special data types. For 1041 more details about pgtypes library functions, 1042 see <xref linkend="ecpg-pgtypes"/>. 1043 </para> 1044 1045 <sect4> 1046 <title id="ecpg-type-timestamp-date">timestamp, date</title> 1047 1048 <para> 1049 Here is a pattern for handling <type>timestamp</type> variables 1050 in the ECPG host application. 1051 </para> 1052 1053 <para> 1054 First, the program has to include the header file for the 1055 <type>timestamp</type> type: 1056<programlisting> 1057#include <pgtypes_timestamp.h> 1058</programlisting> 1059 </para> 1060 1061 <para> 1062 Next, declare a host variable as type <type>timestamp</type> in 1063 the declare section: 1064<programlisting> 1065EXEC SQL BEGIN DECLARE SECTION; 1066timestamp ts; 1067EXEC SQL END DECLARE SECTION; 1068</programlisting> 1069 </para> 1070 1071 <para> 1072 And after reading a value into the host variable, process it 1073 using pgtypes library functions. In following example, the 1074 <type>timestamp</type> value is converted into text (ASCII) form 1075 with the <function>PGTYPEStimestamp_to_asc()</function> 1076 function: 1077<programlisting> 1078EXEC SQL SELECT now()::timestamp INTO :ts; 1079 1080printf("ts = %s\n", PGTYPEStimestamp_to_asc(ts)); 1081</programlisting> 1082 This example will show some result like following: 1083<screen> 1084ts = 2010-06-27 18:03:56.949343 1085</screen> 1086 </para> 1087 1088 <para> 1089 In addition, the DATE type can be handled in the same way. The 1090 program has to include <filename>pgtypes_date.h</filename>, declare a host variable 1091 as the date type and convert a DATE value into a text form using 1092 <function>PGTYPESdate_to_asc()</function> function. For more details about the 1093 pgtypes library functions, see <xref linkend="ecpg-pgtypes"/>. 1094 </para> 1095 </sect4> 1096 1097 <sect4 id="ecpg-type-interval"> 1098 <title>interval</title> 1099 1100 <para> 1101 The handling of the <type>interval</type> type is also similar 1102 to the <type>timestamp</type> and <type>date</type> types. It 1103 is required, however, to allocate memory for 1104 an <type>interval</type> type value explicitly. In other words, 1105 the memory space for the variable has to be allocated in the 1106 heap memory, not in the stack memory. 1107 </para> 1108 1109 <para> 1110 Here is an example program: 1111<programlisting> 1112#include <stdio.h> 1113#include <stdlib.h> 1114#include <pgtypes_interval.h> 1115 1116int 1117main(void) 1118{ 1119EXEC SQL BEGIN DECLARE SECTION; 1120 interval *in; 1121EXEC SQL END DECLARE SECTION; 1122 1123 EXEC SQL CONNECT TO testdb; 1124 EXEC SQL SELECT pg_catalog.set_config('search_path', '', false); EXEC SQL COMMIT; 1125 1126 in = PGTYPESinterval_new(); 1127 EXEC SQL SELECT '1 min'::interval INTO :in; 1128 printf("interval = %s\n", PGTYPESinterval_to_asc(in)); 1129 PGTYPESinterval_free(in); 1130 1131 EXEC SQL COMMIT; 1132 EXEC SQL DISCONNECT ALL; 1133 return 0; 1134} 1135</programlisting> 1136 </para> 1137 </sect4> 1138 1139 <sect4 id="ecpg-type-numeric-decimal"> 1140 <title>numeric, decimal</title> 1141 1142 <para> 1143 The handling of the <type>numeric</type> 1144 and <type>decimal</type> types is similar to the 1145 <type>interval</type> type: It requires defining a pointer, 1146 allocating some memory space on the heap, and accessing the 1147 variable using the pgtypes library functions. For more details 1148 about the pgtypes library functions, 1149 see <xref linkend="ecpg-pgtypes"/>. 1150 </para> 1151 1152 <para> 1153 No functions are provided specifically for 1154 the <type>decimal</type> type. An application has to convert it 1155 to a <type>numeric</type> variable using a pgtypes library 1156 function to do further processing. 1157 </para> 1158 1159 <para> 1160 Here is an example program handling <type>numeric</type> 1161 and <type>decimal</type> type variables. 1162<programlisting> 1163#include <stdio.h> 1164#include <stdlib.h> 1165#include <pgtypes_numeric.h> 1166 1167EXEC SQL WHENEVER SQLERROR STOP; 1168 1169int 1170main(void) 1171{ 1172EXEC SQL BEGIN DECLARE SECTION; 1173 numeric *num; 1174 numeric *num2; 1175 decimal *dec; 1176EXEC SQL END DECLARE SECTION; 1177 1178 EXEC SQL CONNECT TO testdb; 1179 EXEC SQL SELECT pg_catalog.set_config('search_path', '', false); EXEC SQL COMMIT; 1180 1181 num = PGTYPESnumeric_new(); 1182 dec = PGTYPESdecimal_new(); 1183 1184 EXEC SQL SELECT 12.345::numeric(4,2), 23.456::decimal(4,2) INTO :num, :dec; 1185 1186 printf("numeric = %s\n", PGTYPESnumeric_to_asc(num, 0)); 1187 printf("numeric = %s\n", PGTYPESnumeric_to_asc(num, 1)); 1188 printf("numeric = %s\n", PGTYPESnumeric_to_asc(num, 2)); 1189 1190 /* Convert decimal to numeric to show a decimal value. */ 1191 num2 = PGTYPESnumeric_new(); 1192 PGTYPESnumeric_from_decimal(dec, num2); 1193 1194 printf("decimal = %s\n", PGTYPESnumeric_to_asc(num2, 0)); 1195 printf("decimal = %s\n", PGTYPESnumeric_to_asc(num2, 1)); 1196 printf("decimal = %s\n", PGTYPESnumeric_to_asc(num2, 2)); 1197 1198 PGTYPESnumeric_free(num2); 1199 PGTYPESdecimal_free(dec); 1200 PGTYPESnumeric_free(num); 1201 1202 EXEC SQL COMMIT; 1203 EXEC SQL DISCONNECT ALL; 1204 return 0; 1205} 1206</programlisting> 1207 </para> 1208 </sect4> 1209 1210 <sect4> 1211 <title id="ecpg-type-bytea">bytea</title> 1212 1213 <para> 1214 The handling of the <type>bytea</type> type is similar to 1215 that of <type>VARCHAR</type>. The definition on an array of type 1216 <type>bytea</type> is converted into a named struct for every 1217 variable. A declaration like: 1218<programlisting> 1219bytea var[180]; 1220</programlisting> 1221 is converted into: 1222<programlisting> 1223struct bytea_var { int len; char arr[180]; } var; 1224</programlisting> 1225 The member <structfield>arr</structfield> hosts binary format 1226 data. It can also handle <literal>'\0'</literal> as part of 1227 data, unlike <type>VARCHAR</type>. 1228 The data is converted from/to hex format and sent/received by 1229 ecpglib. 1230 </para> 1231 1232 <note> 1233 <para> 1234 <type>bytea</type> variable can be used only when 1235 <xref linkend="guc-bytea-output"/> is set to <literal>hex</literal>. 1236 </para> 1237 </note> 1238 </sect4> 1239 </sect3> 1240 1241 <sect3 id="ecpg-variables-nonprimitive-c"> 1242 <title>Host Variables with Nonprimitive Types</title> 1243 1244 <para> 1245 As a host variable you can also use arrays, typedefs, structs, and 1246 pointers. 1247 </para> 1248 1249 <sect4 id="ecpg-variables-arrays"> 1250 <title>Arrays</title> 1251 1252 <para> 1253 There are two use cases for arrays as host variables. The first 1254 is a way to store some text string in <type>char[]</type> 1255 or <type>VARCHAR[]</type>, as 1256 explained in <xref linkend="ecpg-char"/>. The second use case is to 1257 retrieve multiple rows from a query result without using a 1258 cursor. Without an array, to process a query result consisting 1259 of multiple rows, it is required to use a cursor and 1260 the <command>FETCH</command> command. But with array host 1261 variables, multiple rows can be received at once. The length of 1262 the array has to be defined to be able to accommodate all rows, 1263 otherwise a buffer overflow will likely occur. 1264 </para> 1265 1266 <para> 1267 Following example scans the <literal>pg_database</literal> 1268 system table and shows all OIDs and names of the available 1269 databases: 1270<programlisting> 1271int 1272main(void) 1273{ 1274EXEC SQL BEGIN DECLARE SECTION; 1275 int dbid[8]; 1276 char dbname[8][16]; 1277 int i; 1278EXEC SQL END DECLARE SECTION; 1279 1280 memset(dbname, 0, sizeof(char)* 16 * 8); 1281 memset(dbid, 0, sizeof(int) * 8); 1282 1283 EXEC SQL CONNECT TO testdb; 1284 EXEC SQL SELECT pg_catalog.set_config('search_path', '', false); EXEC SQL COMMIT; 1285 1286 /* Retrieve multiple rows into arrays at once. */ 1287 EXEC SQL SELECT oid,datname INTO :dbid, :dbname FROM pg_database; 1288 1289 for (i = 0; i < 8; i++) 1290 printf("oid=%d, dbname=%s\n", dbid[i], dbname[i]); 1291 1292 EXEC SQL COMMIT; 1293 EXEC SQL DISCONNECT ALL; 1294 return 0; 1295} 1296</programlisting> 1297 1298 This example shows following result. (The exact values depend on 1299 local circumstances.) 1300<screen> 1301oid=1, dbname=template1 1302oid=11510, dbname=template0 1303oid=11511, dbname=postgres 1304oid=313780, dbname=testdb 1305oid=0, dbname= 1306oid=0, dbname= 1307oid=0, dbname= 1308</screen> 1309 </para> 1310 </sect4> 1311 1312 <sect4 id="ecpg-variables-struct"> 1313 <title>Structures</title> 1314 1315 <para> 1316 A structure whose member names match the column names of a query 1317 result, can be used to retrieve multiple columns at once. The 1318 structure enables handling multiple column values in a single 1319 host variable. 1320 </para> 1321 1322 <para> 1323 The following example retrieves OIDs, names, and sizes of the 1324 available databases from the <literal>pg_database</literal> 1325 system table and using 1326 the <function>pg_database_size()</function> function. In this 1327 example, a structure variable <varname>dbinfo_t</varname> with 1328 members whose names match each column in 1329 the <literal>SELECT</literal> result is used to retrieve one 1330 result row without putting multiple host variables in 1331 the <literal>FETCH</literal> statement. 1332<programlisting> 1333EXEC SQL BEGIN DECLARE SECTION; 1334 typedef struct 1335 { 1336 int oid; 1337 char datname[65]; 1338 long long int size; 1339 } dbinfo_t; 1340 1341 dbinfo_t dbval; 1342EXEC SQL END DECLARE SECTION; 1343 1344 memset(&dbval, 0, sizeof(dbinfo_t)); 1345 1346 EXEC SQL DECLARE cur1 CURSOR FOR SELECT oid, datname, pg_database_size(oid) AS size FROM pg_database; 1347 EXEC SQL OPEN cur1; 1348 1349 /* when end of result set reached, break out of while loop */ 1350 EXEC SQL WHENEVER NOT FOUND DO BREAK; 1351 1352 while (1) 1353 { 1354 /* Fetch multiple columns into one structure. */ 1355 EXEC SQL FETCH FROM cur1 INTO :dbval; 1356 1357 /* Print members of the structure. */ 1358 printf("oid=%d, datname=%s, size=%lld\n", dbval.oid, dbval.datname, dbval.size); 1359 } 1360 1361 EXEC SQL CLOSE cur1; 1362</programlisting> 1363 </para> 1364 1365 <para> 1366 This example shows following result. (The exact values depend on 1367 local circumstances.) 1368<screen> 1369oid=1, datname=template1, size=4324580 1370oid=11510, datname=template0, size=4243460 1371oid=11511, datname=postgres, size=4324580 1372oid=313780, datname=testdb, size=8183012 1373</screen> 1374 </para> 1375 1376 <para> 1377 Structure host variables <quote>absorb</quote> as many columns 1378 as the structure as fields. Additional columns can be assigned 1379 to other host variables. For example, the above program could 1380 also be restructured like this, with the <varname>size</varname> 1381 variable outside the structure: 1382<programlisting> 1383EXEC SQL BEGIN DECLARE SECTION; 1384 typedef struct 1385 { 1386 int oid; 1387 char datname[65]; 1388 } dbinfo_t; 1389 1390 dbinfo_t dbval; 1391 long long int size; 1392EXEC SQL END DECLARE SECTION; 1393 1394 memset(&dbval, 0, sizeof(dbinfo_t)); 1395 1396 EXEC SQL DECLARE cur1 CURSOR FOR SELECT oid, datname, pg_database_size(oid) AS size FROM pg_database; 1397 EXEC SQL OPEN cur1; 1398 1399 /* when end of result set reached, break out of while loop */ 1400 EXEC SQL WHENEVER NOT FOUND DO BREAK; 1401 1402 while (1) 1403 { 1404 /* Fetch multiple columns into one structure. */ 1405 EXEC SQL FETCH FROM cur1 INTO :dbval, :size; 1406 1407 /* Print members of the structure. */ 1408 printf("oid=%d, datname=%s, size=%lld\n", dbval.oid, dbval.datname, size); 1409 } 1410 1411 EXEC SQL CLOSE cur1; 1412</programlisting> 1413 </para> 1414 </sect4> 1415 1416 <sect4> 1417 <title>Typedefs</title> 1418 1419 <para> 1420 Use the <literal>typedef</literal> keyword to map new types to already 1421 existing types. 1422<programlisting> 1423EXEC SQL BEGIN DECLARE SECTION; 1424 typedef char mychartype[40]; 1425 typedef long serial_t; 1426EXEC SQL END DECLARE SECTION; 1427</programlisting> 1428 Note that you could also use: 1429<programlisting> 1430EXEC SQL TYPE serial_t IS long; 1431</programlisting> 1432 This declaration does not need to be part of a declare section. 1433 </para> 1434 </sect4> 1435 1436 <sect4> 1437 <title>Pointers</title> 1438 1439 <para> 1440 You can declare pointers to the most common types. Note however 1441 that you cannot use pointers as target variables of queries 1442 without auto-allocation. See <xref linkend="ecpg-descriptors"/> 1443 for more information on auto-allocation. 1444 </para> 1445 1446 <para> 1447<programlisting> 1448EXEC SQL BEGIN DECLARE SECTION; 1449 int *intp; 1450 char **charp; 1451EXEC SQL END DECLARE SECTION; 1452</programlisting> 1453 </para> 1454 </sect4> 1455 </sect3> 1456 </sect2> 1457 1458 <sect2 id="ecpg-variables-nonprimitive-sql"> 1459 <title>Handling Nonprimitive SQL Data Types</title> 1460 1461 <para> 1462 This section contains information on how to handle nonscalar and 1463 user-defined SQL-level data types in ECPG applications. Note that 1464 this is distinct from the handling of host variables of 1465 nonprimitive types, described in the previous section. 1466 </para> 1467 1468 <sect3> 1469 <title>Arrays</title> 1470 1471 <para> 1472 Multi-dimensional SQL-level arrays are not directly supported in ECPG. 1473 One-dimensional SQL-level arrays can be mapped into C array host 1474 variables and vice-versa. However, when creating a statement ecpg does 1475 not know the types of the columns, so that it cannot check if a C array 1476 is input into a corresponding SQL-level array. When processing the 1477 output of a SQL statement, ecpg has the necessary information and thus 1478 checks if both are arrays. 1479 </para> 1480 1481 <para> 1482 If a query accesses <emphasis>elements</emphasis> of an array 1483 separately, then this avoids the use of arrays in ECPG. Then, a 1484 host variable with a type that can be mapped to the element type 1485 should be used. For example, if a column type is array of 1486 <type>integer</type>, a host variable of type <type>int</type> 1487 can be used. Also if the element type is <type>varchar</type> 1488 or <type>text</type>, a host variable of type <type>char[]</type> 1489 or <type>VARCHAR[]</type> can be used. 1490 </para> 1491 1492 <para> 1493 Here is an example. Assume the following table: 1494<programlisting> 1495CREATE TABLE t3 ( 1496 ii integer[] 1497); 1498 1499testdb=> SELECT * FROM t3; 1500 ii 1501------------- 1502 {1,2,3,4,5} 1503(1 row) 1504</programlisting> 1505 1506 The following example program retrieves the 4th element of the 1507 array and stores it into a host variable of 1508 type <type>int</type>: 1509<programlisting> 1510EXEC SQL BEGIN DECLARE SECTION; 1511int ii; 1512EXEC SQL END DECLARE SECTION; 1513 1514EXEC SQL DECLARE cur1 CURSOR FOR SELECT ii[4] FROM t3; 1515EXEC SQL OPEN cur1; 1516 1517EXEC SQL WHENEVER NOT FOUND DO BREAK; 1518 1519while (1) 1520{ 1521 EXEC SQL FETCH FROM cur1 INTO :ii ; 1522 printf("ii=%d\n", ii); 1523} 1524 1525EXEC SQL CLOSE cur1; 1526</programlisting> 1527 1528 This example shows the following result: 1529<screen> 1530ii=4 1531</screen> 1532 </para> 1533 1534 <para> 1535 To map multiple array elements to the multiple elements in an 1536 array type host variables each element of array column and each 1537 element of the host variable array have to be managed separately, 1538 for example: 1539<programlisting> 1540EXEC SQL BEGIN DECLARE SECTION; 1541int ii_a[8]; 1542EXEC SQL END DECLARE SECTION; 1543 1544EXEC SQL DECLARE cur1 CURSOR FOR SELECT ii[1], ii[2], ii[3], ii[4] FROM t3; 1545EXEC SQL OPEN cur1; 1546 1547EXEC SQL WHENEVER NOT FOUND DO BREAK; 1548 1549while (1) 1550{ 1551 EXEC SQL FETCH FROM cur1 INTO :ii_a[0], :ii_a[1], :ii_a[2], :ii_a[3]; 1552 ... 1553} 1554</programlisting> 1555 </para> 1556 1557 <para> 1558 Note again that 1559<programlisting> 1560EXEC SQL BEGIN DECLARE SECTION; 1561int ii_a[8]; 1562EXEC SQL END DECLARE SECTION; 1563 1564EXEC SQL DECLARE cur1 CURSOR FOR SELECT ii FROM t3; 1565EXEC SQL OPEN cur1; 1566 1567EXEC SQL WHENEVER NOT FOUND DO BREAK; 1568 1569while (1) 1570{ 1571 /* WRONG */ 1572 EXEC SQL FETCH FROM cur1 INTO :ii_a; 1573 ... 1574} 1575</programlisting> 1576 would not work correctly in this case, because you cannot map an 1577 array type column to an array host variable directly. 1578 </para> 1579 1580 <para> 1581 Another workaround is to store arrays in their external string 1582 representation in host variables of type <type>char[]</type> 1583 or <type>VARCHAR[]</type>. For more details about this 1584 representation, see <xref linkend="arrays-input"/>. Note that 1585 this means that the array cannot be accessed naturally as an 1586 array in the host program (without further processing that parses 1587 the text representation). 1588 </para> 1589 </sect3> 1590 1591 <sect3> 1592 <title>Composite Types</title> 1593 1594 <para> 1595 Composite types are not directly supported in ECPG, but an easy workaround is possible. 1596 The 1597 available workarounds are similar to the ones described for 1598 arrays above: Either access each attribute separately or use the 1599 external string representation. 1600 </para> 1601 1602 <para> 1603 For the following examples, assume the following type and table: 1604<programlisting> 1605CREATE TYPE comp_t AS (intval integer, textval varchar(32)); 1606CREATE TABLE t4 (compval comp_t); 1607INSERT INTO t4 VALUES ( (256, 'PostgreSQL') ); 1608</programlisting> 1609 1610 The most obvious solution is to access each attribute separately. 1611 The following program retrieves data from the example table by 1612 selecting each attribute of the type <type>comp_t</type> 1613 separately: 1614<programlisting> 1615EXEC SQL BEGIN DECLARE SECTION; 1616int intval; 1617varchar textval[33]; 1618EXEC SQL END DECLARE SECTION; 1619 1620/* Put each element of the composite type column in the SELECT list. */ 1621EXEC SQL DECLARE cur1 CURSOR FOR SELECT (compval).intval, (compval).textval FROM t4; 1622EXEC SQL OPEN cur1; 1623 1624EXEC SQL WHENEVER NOT FOUND DO BREAK; 1625 1626while (1) 1627{ 1628 /* Fetch each element of the composite type column into host variables. */ 1629 EXEC SQL FETCH FROM cur1 INTO :intval, :textval; 1630 1631 printf("intval=%d, textval=%s\n", intval, textval.arr); 1632} 1633 1634EXEC SQL CLOSE cur1; 1635</programlisting> 1636 </para> 1637 1638 <para> 1639 To enhance this example, the host variables to store values in 1640 the <command>FETCH</command> command can be gathered into one 1641 structure. For more details about the host variable in the 1642 structure form, see <xref linkend="ecpg-variables-struct"/>. 1643 To switch to the structure, the example can be modified as below. 1644 The two host variables, <varname>intval</varname> 1645 and <varname>textval</varname>, become members of 1646 the <structname>comp_t</structname> structure, and the structure 1647 is specified on the <command>FETCH</command> command. 1648<programlisting> 1649EXEC SQL BEGIN DECLARE SECTION; 1650typedef struct 1651{ 1652 int intval; 1653 varchar textval[33]; 1654} comp_t; 1655 1656comp_t compval; 1657EXEC SQL END DECLARE SECTION; 1658 1659/* Put each element of the composite type column in the SELECT list. */ 1660EXEC SQL DECLARE cur1 CURSOR FOR SELECT (compval).intval, (compval).textval FROM t4; 1661EXEC SQL OPEN cur1; 1662 1663EXEC SQL WHENEVER NOT FOUND DO BREAK; 1664 1665while (1) 1666{ 1667 /* Put all values in the SELECT list into one structure. */ 1668 EXEC SQL FETCH FROM cur1 INTO :compval; 1669 1670 printf("intval=%d, textval=%s\n", compval.intval, compval.textval.arr); 1671} 1672 1673EXEC SQL CLOSE cur1; 1674</programlisting> 1675 1676 Although a structure is used in the <command>FETCH</command> 1677 command, the attribute names in the <command>SELECT</command> 1678 clause are specified one by one. This can be enhanced by using 1679 a <literal>*</literal> to ask for all attributes of the composite 1680 type value. 1681<programlisting> 1682... 1683EXEC SQL DECLARE cur1 CURSOR FOR SELECT (compval).* FROM t4; 1684EXEC SQL OPEN cur1; 1685 1686EXEC SQL WHENEVER NOT FOUND DO BREAK; 1687 1688while (1) 1689{ 1690 /* Put all values in the SELECT list into one structure. */ 1691 EXEC SQL FETCH FROM cur1 INTO :compval; 1692 1693 printf("intval=%d, textval=%s\n", compval.intval, compval.textval.arr); 1694} 1695... 1696</programlisting> 1697 This way, composite types can be mapped into structures almost 1698 seamlessly, even though ECPG does not understand the composite 1699 type itself. 1700 </para> 1701 1702 <para> 1703 Finally, it is also possible to store composite type values in 1704 their external string representation in host variables of 1705 type <type>char[]</type> or <type>VARCHAR[]</type>. But that 1706 way, it is not easily possible to access the fields of the value 1707 from the host program. 1708 </para> 1709 </sect3> 1710 1711 <sect3> 1712 <title>User-Defined Base Types</title> 1713 1714 <para> 1715 New user-defined base types are not directly supported by ECPG. 1716 You can use the external string representation and host variables 1717 of type <type>char[]</type> or <type>VARCHAR[]</type>, and this 1718 solution is indeed appropriate and sufficient for many types. 1719 </para> 1720 1721 <para> 1722 Here is an example using the data type <type>complex</type> from 1723 the example in <xref linkend="xtypes"/>. The external string 1724 representation of that type is <literal>(%f,%f)</literal>, 1725 which is defined in the 1726 functions <function>complex_in()</function> 1727 and <function>complex_out()</function> functions 1728 in <xref linkend="xtypes"/>. The following example inserts the 1729 complex type values <literal>(1,1)</literal> 1730 and <literal>(3,3)</literal> into the 1731 columns <literal>a</literal> and <literal>b</literal>, and select 1732 them from the table after that. 1733 1734<programlisting> 1735EXEC SQL BEGIN DECLARE SECTION; 1736 varchar a[64]; 1737 varchar b[64]; 1738EXEC SQL END DECLARE SECTION; 1739 1740 EXEC SQL INSERT INTO test_complex VALUES ('(1,1)', '(3,3)'); 1741 1742 EXEC SQL DECLARE cur1 CURSOR FOR SELECT a, b FROM test_complex; 1743 EXEC SQL OPEN cur1; 1744 1745 EXEC SQL WHENEVER NOT FOUND DO BREAK; 1746 1747 while (1) 1748 { 1749 EXEC SQL FETCH FROM cur1 INTO :a, :b; 1750 printf("a=%s, b=%s\n", a.arr, b.arr); 1751 } 1752 1753 EXEC SQL CLOSE cur1; 1754</programlisting> 1755 1756 This example shows following result: 1757<screen> 1758a=(1,1), b=(3,3) 1759</screen> 1760 </para> 1761 1762 <para> 1763 Another workaround is avoiding the direct use of the user-defined 1764 types in ECPG and instead create a function or cast that converts 1765 between the user-defined type and a primitive type that ECPG can 1766 handle. Note, however, that type casts, especially implicit 1767 ones, should be introduced into the type system very carefully. 1768 </para> 1769 1770 <para> 1771 For example, 1772<programlisting> 1773CREATE FUNCTION create_complex(r double, i double) RETURNS complex 1774LANGUAGE SQL 1775IMMUTABLE 1776AS $$ SELECT $1 * complex '(1,0')' + $2 * complex '(0,1)' $$; 1777</programlisting> 1778 After this definition, the following 1779<programlisting> 1780EXEC SQL BEGIN DECLARE SECTION; 1781double a, b, c, d; 1782EXEC SQL END DECLARE SECTION; 1783 1784a = 1; 1785b = 2; 1786c = 3; 1787d = 4; 1788 1789EXEC SQL INSERT INTO test_complex VALUES (create_complex(:a, :b), create_complex(:c, :d)); 1790</programlisting> 1791 has the same effect as 1792<programlisting> 1793EXEC SQL INSERT INTO test_complex VALUES ('(1,2)', '(3,4)'); 1794</programlisting> 1795 </para> 1796 </sect3> 1797 </sect2> 1798 1799 <sect2 id="ecpg-indicators"> 1800 <title>Indicators</title> 1801 1802 <para> 1803 The examples above do not handle null values. In fact, the 1804 retrieval examples will raise an error if they fetch a null value 1805 from the database. To be able to pass null values to the database 1806 or retrieve null values from the database, you need to append a 1807 second host variable specification to each host variable that 1808 contains data. This second host variable is called the 1809 <firstterm>indicator</firstterm> and contains a flag that tells 1810 whether the datum is null, in which case the value of the real 1811 host variable is ignored. Here is an example that handles the 1812 retrieval of null values correctly: 1813<programlisting> 1814EXEC SQL BEGIN DECLARE SECTION; 1815VARCHAR val; 1816int val_ind; 1817EXEC SQL END DECLARE SECTION: 1818 1819 ... 1820 1821EXEC SQL SELECT b INTO :val :val_ind FROM test1; 1822</programlisting> 1823 The indicator variable <varname>val_ind</varname> will be zero if 1824 the value was not null, and it will be negative if the value was 1825 null. 1826 </para> 1827 1828 <para> 1829 The indicator has another function: if the indicator value is 1830 positive, it means that the value is not null, but it was 1831 truncated when it was stored in the host variable. 1832 </para> 1833 1834 <para> 1835 If the argument <literal>-r no_indicator</literal> is passed to 1836 the preprocessor <command>ecpg</command>, it works in 1837 <quote>no-indicator</quote> mode. In no-indicator mode, if no 1838 indicator variable is specified, null values are signaled (on 1839 input and output) for character string types as empty string and 1840 for integer types as the lowest possible value for type (for 1841 example, <symbol>INT_MIN</symbol> for <type>int</type>). 1842 </para> 1843 </sect2> 1844 </sect1> 1845 1846 <sect1 id="ecpg-dynamic"> 1847 <title>Dynamic SQL</title> 1848 1849 <para> 1850 In many cases, the particular SQL statements that an application 1851 has to execute are known at the time the application is written. 1852 In some cases, however, the SQL statements are composed at run time 1853 or provided by an external source. In these cases you cannot embed 1854 the SQL statements directly into the C source code, but there is a 1855 facility that allows you to call arbitrary SQL statements that you 1856 provide in a string variable. 1857 </para> 1858 1859 <sect2 id="ecpg-dynamic-without-result"> 1860 <title>Executing Statements without a Result Set</title> 1861 1862 <para> 1863 The simplest way to execute an arbitrary SQL statement is to use 1864 the command <command>EXECUTE IMMEDIATE</command>. For example: 1865<programlisting> 1866EXEC SQL BEGIN DECLARE SECTION; 1867const char *stmt = "CREATE TABLE test1 (...);"; 1868EXEC SQL END DECLARE SECTION; 1869 1870EXEC SQL EXECUTE IMMEDIATE :stmt; 1871</programlisting> 1872 <command>EXECUTE IMMEDIATE</command> can be used for SQL 1873 statements that do not return a result set (e.g., 1874 DDL, <command>INSERT</command>, <command>UPDATE</command>, 1875 <command>DELETE</command>). You cannot execute statements that 1876 retrieve data (e.g., <command>SELECT</command>) this way. The 1877 next section describes how to do that. 1878 </para> 1879 </sect2> 1880 1881 <sect2 id="ecpg-dynamic-input"> 1882 <title>Executing a Statement with Input Parameters</title> 1883 1884 <para> 1885 A more powerful way to execute arbitrary SQL statements is to 1886 prepare them once and execute the prepared statement as often as 1887 you like. It is also possible to prepare a generalized version of 1888 a statement and then execute specific versions of it by 1889 substituting parameters. When preparing the statement, write 1890 question marks where you want to substitute parameters later. For 1891 example: 1892<programlisting> 1893EXEC SQL BEGIN DECLARE SECTION; 1894const char *stmt = "INSERT INTO test1 VALUES(?, ?);"; 1895EXEC SQL END DECLARE SECTION; 1896 1897EXEC SQL PREPARE mystmt FROM :stmt; 1898 ... 1899EXEC SQL EXECUTE mystmt USING 42, 'foobar'; 1900</programlisting> 1901 </para> 1902 1903 <para> 1904 When you don't need the prepared statement anymore, you should 1905 deallocate it: 1906<programlisting> 1907EXEC SQL DEALLOCATE PREPARE <replaceable>name</replaceable>; 1908</programlisting> 1909 </para> 1910 </sect2> 1911 1912 <sect2 id="ecpg-dynamic-with-result"> 1913 <title>Executing a Statement with a Result Set</title> 1914 1915 <para> 1916 To execute an SQL statement with a single result row, 1917 <command>EXECUTE</command> can be used. To save the result, add 1918 an <literal>INTO</literal> clause. 1919<programlisting><![CDATA[ 1920EXEC SQL BEGIN DECLARE SECTION; 1921const char *stmt = "SELECT a, b, c FROM test1 WHERE a > ?"; 1922int v1, v2; 1923VARCHAR v3[50]; 1924EXEC SQL END DECLARE SECTION; 1925 1926EXEC SQL PREPARE mystmt FROM :stmt; 1927 ... 1928EXEC SQL EXECUTE mystmt INTO :v1, :v2, :v3 USING 37; 1929]]> 1930</programlisting> 1931 An <command>EXECUTE</command> command can have an 1932 <literal>INTO</literal> clause, a <literal>USING</literal> clause, 1933 both, or neither. 1934 </para> 1935 1936 <para> 1937 If a query is expected to return more than one result row, a 1938 cursor should be used, as in the following example. 1939 (See <xref linkend="ecpg-cursors"/> for more details about the 1940 cursor.) 1941<programlisting> 1942EXEC SQL BEGIN DECLARE SECTION; 1943char dbaname[128]; 1944char datname[128]; 1945char *stmt = "SELECT u.usename as dbaname, d.datname " 1946 " FROM pg_database d, pg_user u " 1947 " WHERE d.datdba = u.usesysid"; 1948EXEC SQL END DECLARE SECTION; 1949 1950EXEC SQL CONNECT TO testdb AS con1 USER testuser; 1951EXEC SQL SELECT pg_catalog.set_config('search_path', '', false); EXEC SQL COMMIT; 1952 1953EXEC SQL PREPARE stmt1 FROM :stmt; 1954 1955EXEC SQL DECLARE cursor1 CURSOR FOR stmt1; 1956EXEC SQL OPEN cursor1; 1957 1958EXEC SQL WHENEVER NOT FOUND DO BREAK; 1959 1960while (1) 1961{ 1962 EXEC SQL FETCH cursor1 INTO :dbaname,:datname; 1963 printf("dbaname=%s, datname=%s\n", dbaname, datname); 1964} 1965 1966EXEC SQL CLOSE cursor1; 1967 1968EXEC SQL COMMIT; 1969EXEC SQL DISCONNECT ALL; 1970</programlisting> 1971 </para> 1972 </sect2> 1973 </sect1> 1974 1975 <sect1 id="ecpg-pgtypes"> 1976 <title>pgtypes Library</title> 1977 1978 <para> 1979 The pgtypes library maps <productname>PostgreSQL</productname> database 1980 types to C equivalents that can be used in C programs. It also offers 1981 functions to do basic calculations with those types within C, i.e., without 1982 the help of the <productname>PostgreSQL</productname> server. See the 1983 following example: 1984<programlisting><![CDATA[ 1985EXEC SQL BEGIN DECLARE SECTION; 1986 date date1; 1987 timestamp ts1, tsout; 1988 interval iv1; 1989 char *out; 1990EXEC SQL END DECLARE SECTION; 1991 1992PGTYPESdate_today(&date1); 1993EXEC SQL SELECT started, duration INTO :ts1, :iv1 FROM datetbl WHERE d=:date1; 1994PGTYPEStimestamp_add_interval(&ts1, &iv1, &tsout); 1995out = PGTYPEStimestamp_to_asc(&tsout); 1996printf("Started + duration: %s\n", out); 1997PGTYPESchar_free(out); 1998]]> 1999</programlisting> 2000 </para> 2001 2002 <sect2 id="ecpg-pgtypes-cstrings"> 2003 <title>Character Strings</title> 2004 <para> 2005 Some functions such as <function>PGTYPESnumeric_to_asc</function> return 2006 a pointer to a freshly allocated character string. These results should be 2007 freed with <function>PGTYPESchar_free</function> instead of 2008 <function>free</function>. (This is important only on Windows, where 2009 memory allocation and release sometimes need to be done by the same 2010 library.) 2011 </para> 2012 </sect2> 2013 2014 <sect2 id="ecpg-pgtypes-numeric"> 2015 <title>The numeric Type</title> 2016 <para> 2017 The numeric type offers to do calculations with arbitrary precision. See 2018 <xref linkend="datatype-numeric"/> for the equivalent type in the 2019 <productname>PostgreSQL</productname> server. Because of the arbitrary precision this 2020 variable needs to be able to expand and shrink dynamically. That's why you 2021 can only create numeric variables on the heap, by means of the 2022 <function>PGTYPESnumeric_new</function> and <function>PGTYPESnumeric_free</function> 2023 functions. The decimal type, which is similar but limited in precision, 2024 can be created on the stack as well as on the heap. 2025 </para> 2026 <para> 2027 The following functions can be used to work with the numeric type: 2028 <variablelist> 2029 <varlistentry> 2030 <term><function>PGTYPESnumeric_new</function></term> 2031 <listitem> 2032 <para> 2033 Request a pointer to a newly allocated numeric variable. 2034<synopsis> 2035numeric *PGTYPESnumeric_new(void); 2036</synopsis> 2037 </para> 2038 </listitem> 2039 </varlistentry> 2040 2041 <varlistentry> 2042 <term><function>PGTYPESnumeric_free</function></term> 2043 <listitem> 2044 <para> 2045 Free a numeric type, release all of its memory. 2046<synopsis> 2047void PGTYPESnumeric_free(numeric *var); 2048</synopsis> 2049 </para> 2050 </listitem> 2051 </varlistentry> 2052 2053 <varlistentry> 2054 <term><function>PGTYPESnumeric_from_asc</function></term> 2055 <listitem> 2056 <para> 2057 Parse a numeric type from its string notation. 2058<synopsis> 2059numeric *PGTYPESnumeric_from_asc(char *str, char **endptr); 2060</synopsis> 2061 Valid formats are for example: 2062 <literal>-2</literal>, 2063 <literal>.794</literal>, 2064 <literal>+3.44</literal>, 2065 <literal>592.49E07</literal> or 2066 <literal>-32.84e-4</literal>. 2067 If the value could be parsed successfully, a valid pointer is returned, 2068 else the NULL pointer. At the moment ECPG always parses the complete 2069 string and so it currently does not support to store the address of the 2070 first invalid character in <literal>*endptr</literal>. You can safely 2071 set <literal>endptr</literal> to NULL. 2072 </para> 2073 </listitem> 2074 </varlistentry> 2075 2076 <varlistentry> 2077 <term><function>PGTYPESnumeric_to_asc</function></term> 2078 <listitem> 2079 <para> 2080 Returns a pointer to a string allocated by <function>malloc</function> that contains the string 2081 representation of the numeric type <literal>num</literal>. 2082<synopsis> 2083char *PGTYPESnumeric_to_asc(numeric *num, int dscale); 2084</synopsis> 2085 The numeric value will be printed with <literal>dscale</literal> decimal 2086 digits, with rounding applied if necessary. 2087 The result must be freed with <function>PGTYPESchar_free()</function>. 2088 </para> 2089 </listitem> 2090 </varlistentry> 2091 2092 <varlistentry> 2093 <term><function>PGTYPESnumeric_add</function></term> 2094 <listitem> 2095 <para> 2096 Add two numeric variables into a third one. 2097<synopsis> 2098int PGTYPESnumeric_add(numeric *var1, numeric *var2, numeric *result); 2099</synopsis> 2100 The function adds the variables <literal>var1</literal> and 2101 <literal>var2</literal> into the result variable 2102 <literal>result</literal>. 2103 The function returns 0 on success and -1 in case of error. 2104 </para> 2105 </listitem> 2106 </varlistentry> 2107 2108 <varlistentry> 2109 <term><function>PGTYPESnumeric_sub</function></term> 2110 <listitem> 2111 <para> 2112 Subtract two numeric variables and return the result in a third one. 2113<synopsis> 2114int PGTYPESnumeric_sub(numeric *var1, numeric *var2, numeric *result); 2115</synopsis> 2116 The function subtracts the variable <literal>var2</literal> from 2117 the variable <literal>var1</literal>. The result of the operation is 2118 stored in the variable <literal>result</literal>. 2119 The function returns 0 on success and -1 in case of error. 2120 </para> 2121 </listitem> 2122 </varlistentry> 2123 2124 <varlistentry> 2125 <term><function>PGTYPESnumeric_mul</function></term> 2126 <listitem> 2127 <para> 2128 Multiply two numeric variables and return the result in a third one. 2129<synopsis> 2130int PGTYPESnumeric_mul(numeric *var1, numeric *var2, numeric *result); 2131</synopsis> 2132 The function multiplies the variables <literal>var1</literal> and 2133 <literal>var2</literal>. The result of the operation is stored in the 2134 variable <literal>result</literal>. 2135 The function returns 0 on success and -1 in case of error. 2136 </para> 2137 </listitem> 2138 </varlistentry> 2139 2140 <varlistentry> 2141 <term><function>PGTYPESnumeric_div</function></term> 2142 <listitem> 2143 <para> 2144 Divide two numeric variables and return the result in a third one. 2145<synopsis> 2146int PGTYPESnumeric_div(numeric *var1, numeric *var2, numeric *result); 2147</synopsis> 2148 The function divides the variables <literal>var1</literal> by 2149 <literal>var2</literal>. The result of the operation is stored in the 2150 variable <literal>result</literal>. 2151 The function returns 0 on success and -1 in case of error. 2152 </para> 2153 </listitem> 2154 </varlistentry> 2155 2156 <varlistentry> 2157 <term><function>PGTYPESnumeric_cmp</function></term> 2158 <listitem> 2159 <para> 2160 Compare two numeric variables. 2161<synopsis> 2162int PGTYPESnumeric_cmp(numeric *var1, numeric *var2) 2163</synopsis> 2164 This function compares two numeric variables. In case of error, 2165 <literal>INT_MAX</literal> is returned. On success, the function 2166 returns one of three possible results: 2167 <itemizedlist> 2168 <listitem> 2169 <para> 2170 1, if <literal>var1</literal> is bigger than <literal>var2</literal> 2171 </para> 2172 </listitem> 2173 <listitem> 2174 <para> 2175 -1, if <literal>var1</literal> is smaller than <literal>var2</literal> 2176 </para> 2177 </listitem> 2178 <listitem> 2179 <para> 2180 0, if <literal>var1</literal> and <literal>var2</literal> are equal 2181 </para> 2182 </listitem> 2183 </itemizedlist> 2184 </para> 2185 </listitem> 2186 </varlistentry> 2187 2188 <varlistentry> 2189 <term><function>PGTYPESnumeric_from_int</function></term> 2190 <listitem> 2191 <para> 2192 Convert an int variable to a numeric variable. 2193<synopsis> 2194int PGTYPESnumeric_from_int(signed int int_val, numeric *var); 2195</synopsis> 2196 This function accepts a variable of type signed int and stores it 2197 in the numeric variable <literal>var</literal>. Upon success, 0 is returned and 2198 -1 in case of a failure. 2199 </para> 2200 </listitem> 2201 </varlistentry> 2202 2203 <varlistentry> 2204 <term><function>PGTYPESnumeric_from_long</function></term> 2205 <listitem> 2206 <para> 2207 Convert a long int variable to a numeric variable. 2208<synopsis> 2209int PGTYPESnumeric_from_long(signed long int long_val, numeric *var); 2210</synopsis> 2211 This function accepts a variable of type signed long int and stores it 2212 in the numeric variable <literal>var</literal>. Upon success, 0 is returned and 2213 -1 in case of a failure. 2214 </para> 2215 </listitem> 2216 </varlistentry> 2217 2218 <varlistentry> 2219 <term><function>PGTYPESnumeric_copy</function></term> 2220 <listitem> 2221 <para> 2222 Copy over one numeric variable into another one. 2223<synopsis> 2224int PGTYPESnumeric_copy(numeric *src, numeric *dst); 2225</synopsis> 2226 This function copies over the value of the variable that 2227 <literal>src</literal> points to into the variable that <literal>dst</literal> 2228 points to. It returns 0 on success and -1 if an error occurs. 2229 </para> 2230 </listitem> 2231 </varlistentry> 2232 2233 <varlistentry> 2234 <term><function>PGTYPESnumeric_from_double</function></term> 2235 <listitem> 2236 <para> 2237 Convert a variable of type double to a numeric. 2238<synopsis> 2239int PGTYPESnumeric_from_double(double d, numeric *dst); 2240</synopsis> 2241 This function accepts a variable of type double and stores the result 2242 in the variable that <literal>dst</literal> points to. It returns 0 on success 2243 and -1 if an error occurs. 2244 </para> 2245 </listitem> 2246 </varlistentry> 2247 2248 <varlistentry> 2249 <term><function>PGTYPESnumeric_to_double</function></term> 2250 <listitem> 2251 <para> 2252 Convert a variable of type numeric to double. 2253<synopsis> 2254int PGTYPESnumeric_to_double(numeric *nv, double *dp) 2255</synopsis> 2256 The function converts the numeric value from the variable that 2257 <literal>nv</literal> points to into the double variable that <literal>dp</literal> points 2258 to. It returns 0 on success and -1 if an error occurs, including 2259 overflow. On overflow, the global variable <literal>errno</literal> will be set 2260 to <literal>PGTYPES_NUM_OVERFLOW</literal> additionally. 2261 </para> 2262 </listitem> 2263 </varlistentry> 2264 2265 <varlistentry> 2266 <term><function>PGTYPESnumeric_to_int</function></term> 2267 <listitem> 2268 <para> 2269 Convert a variable of type numeric to int. 2270<synopsis> 2271int PGTYPESnumeric_to_int(numeric *nv, int *ip); 2272</synopsis> 2273 The function converts the numeric value from the variable that 2274 <literal>nv</literal> points to into the integer variable that <literal>ip</literal> 2275 points to. It returns 0 on success and -1 if an error occurs, including 2276 overflow. On overflow, the global variable <literal>errno</literal> will be set 2277 to <literal>PGTYPES_NUM_OVERFLOW</literal> additionally. 2278 </para> 2279 </listitem> 2280 </varlistentry> 2281 2282 <varlistentry> 2283 <term><function>PGTYPESnumeric_to_long</function></term> 2284 <listitem> 2285 <para> 2286 Convert a variable of type numeric to long. 2287<synopsis> 2288int PGTYPESnumeric_to_long(numeric *nv, long *lp); 2289</synopsis> 2290 The function converts the numeric value from the variable that 2291 <literal>nv</literal> points to into the long integer variable that 2292 <literal>lp</literal> points to. It returns 0 on success and -1 if an error 2293 occurs, including overflow. On overflow, the global variable 2294 <literal>errno</literal> will be set to <literal>PGTYPES_NUM_OVERFLOW</literal> 2295 additionally. 2296 </para> 2297 </listitem> 2298 </varlistentry> 2299 2300 <varlistentry> 2301 <term><function>PGTYPESnumeric_to_decimal</function></term> 2302 <listitem> 2303 <para> 2304 Convert a variable of type numeric to decimal. 2305<synopsis> 2306int PGTYPESnumeric_to_decimal(numeric *src, decimal *dst); 2307</synopsis> 2308 The function converts the numeric value from the variable that 2309 <literal>src</literal> points to into the decimal variable that 2310 <literal>dst</literal> points to. It returns 0 on success and -1 if an error 2311 occurs, including overflow. On overflow, the global variable 2312 <literal>errno</literal> will be set to <literal>PGTYPES_NUM_OVERFLOW</literal> 2313 additionally. 2314 </para> 2315 </listitem> 2316 </varlistentry> 2317 2318 <varlistentry> 2319 <term><function>PGTYPESnumeric_from_decimal</function></term> 2320 <listitem> 2321 <para> 2322 Convert a variable of type decimal to numeric. 2323<synopsis> 2324int PGTYPESnumeric_from_decimal(decimal *src, numeric *dst); 2325</synopsis> 2326 The function converts the decimal value from the variable that 2327 <literal>src</literal> points to into the numeric variable that 2328 <literal>dst</literal> points to. It returns 0 on success and -1 if an error 2329 occurs. Since the decimal type is implemented as a limited version of 2330 the numeric type, overflow cannot occur with this conversion. 2331 </para> 2332 </listitem> 2333 </varlistentry> 2334 </variablelist> 2335 </para> 2336 </sect2> 2337 2338 <sect2 id="ecpg-pgtypes-date"> 2339 <title>The date Type</title> 2340 <para> 2341 The date type in C enables your programs to deal with data of the SQL type 2342 date. See <xref linkend="datatype-datetime"/> for the equivalent type in the 2343 <productname>PostgreSQL</productname> server. 2344 </para> 2345 <para> 2346 The following functions can be used to work with the date type: 2347 <variablelist> 2348 <varlistentry id="pgtypesdatefromtimestamp"> 2349 <term><function>PGTYPESdate_from_timestamp</function></term> 2350 <listitem> 2351 <para> 2352 Extract the date part from a timestamp. 2353<synopsis> 2354date PGTYPESdate_from_timestamp(timestamp dt); 2355</synopsis> 2356 The function receives a timestamp as its only argument and returns the 2357 extracted date part from this timestamp. 2358 </para> 2359 </listitem> 2360 </varlistentry> 2361 2362 <varlistentry id="pgtypesdatefromasc"> 2363 <term><function>PGTYPESdate_from_asc</function></term> 2364 <listitem> 2365 <para> 2366 Parse a date from its textual representation. 2367<synopsis> 2368date PGTYPESdate_from_asc(char *str, char **endptr); 2369</synopsis> 2370 The function receives a C char* string <literal>str</literal> and a pointer to 2371 a C char* string <literal>endptr</literal>. At the moment ECPG always parses 2372 the complete string and so it currently does not support to store the 2373 address of the first invalid character in <literal>*endptr</literal>. 2374 You can safely set <literal>endptr</literal> to NULL. 2375 </para> 2376 <para> 2377 Note that the function always assumes MDY-formatted dates and there is 2378 currently no variable to change that within ECPG. 2379 </para> 2380 <para> 2381 <xref linkend="ecpg-pgtypesdate-from-asc-table"/> shows the allowed input formats. 2382 </para> 2383 <table id="ecpg-pgtypesdate-from-asc-table"> 2384 <title>Valid Input Formats for <function>PGTYPESdate_from_asc</function></title> 2385 <tgroup cols="2"> 2386 <thead> 2387 <row> 2388 <entry>Input</entry> 2389 <entry>Result</entry> 2390 </row> 2391 </thead> 2392 <tbody> 2393 <row> 2394 <entry><literal>January 8, 1999</literal></entry> 2395 <entry><literal>January 8, 1999</literal></entry> 2396 </row> 2397 <row> 2398 <entry><literal>1999-01-08</literal></entry> 2399 <entry><literal>January 8, 1999</literal></entry> 2400 </row> 2401 <row> 2402 <entry><literal>1/8/1999</literal></entry> 2403 <entry><literal>January 8, 1999</literal></entry> 2404 </row> 2405 <row> 2406 <entry><literal>1/18/1999</literal></entry> 2407 <entry><literal>January 18, 1999</literal></entry> 2408 </row> 2409 <row> 2410 <entry><literal>01/02/03</literal></entry> 2411 <entry><literal>February 1, 2003</literal></entry> 2412 </row> 2413 <row> 2414 <entry><literal>1999-Jan-08</literal></entry> 2415 <entry><literal>January 8, 1999</literal></entry> 2416 </row> 2417 <row> 2418 <entry><literal>Jan-08-1999</literal></entry> 2419 <entry><literal>January 8, 1999</literal></entry> 2420 </row> 2421 <row> 2422 <entry><literal>08-Jan-1999</literal></entry> 2423 <entry><literal>January 8, 1999</literal></entry> 2424 </row> 2425 <row> 2426 <entry><literal>99-Jan-08</literal></entry> 2427 <entry><literal>January 8, 1999</literal></entry> 2428 </row> 2429 <row> 2430 <entry><literal>08-Jan-99</literal></entry> 2431 <entry><literal>January 8, 1999</literal></entry> 2432 </row> 2433 <row> 2434 <entry><literal>08-Jan-06</literal></entry> 2435 <entry><literal>January 8, 2006</literal></entry> 2436 </row> 2437 <row> 2438 <entry><literal>Jan-08-99</literal></entry> 2439 <entry><literal>January 8, 1999</literal></entry> 2440 </row> 2441 <row> 2442 <entry><literal>19990108</literal></entry> 2443 <entry><literal>ISO 8601; January 8, 1999</literal></entry> 2444 </row> 2445 <row> 2446 <entry><literal>990108</literal></entry> 2447 <entry><literal>ISO 8601; January 8, 1999</literal></entry> 2448 </row> 2449 <row> 2450 <entry><literal>1999.008</literal></entry> 2451 <entry><literal>year and day of year</literal></entry> 2452 </row> 2453 <row> 2454 <entry><literal>J2451187</literal></entry> 2455 <entry><literal>Julian day</literal></entry> 2456 </row> 2457 <row> 2458 <entry><literal>January 8, 99 BC</literal></entry> 2459 <entry><literal>year 99 before the Common Era</literal></entry> 2460 </row> 2461 </tbody> 2462 </tgroup> 2463 </table> 2464 </listitem> 2465 </varlistentry> 2466 2467 <varlistentry id="pgtypesdatetoasc"> 2468 <term><function>PGTYPESdate_to_asc</function></term> 2469 <listitem> 2470 <para> 2471 Return the textual representation of a date variable. 2472<synopsis> 2473char *PGTYPESdate_to_asc(date dDate); 2474</synopsis> 2475 The function receives the date <literal>dDate</literal> as its only parameter. 2476 It will output the date in the form <literal>1999-01-18</literal>, i.e., in the 2477 <literal>YYYY-MM-DD</literal> format. 2478 The result must be freed with <function>PGTYPESchar_free()</function>. 2479 </para> 2480 </listitem> 2481 </varlistentry> 2482 2483 <varlistentry id="pgtypesdatejulmdy"> 2484 <term><function>PGTYPESdate_julmdy</function></term> 2485 <listitem> 2486 <para> 2487 Extract the values for the day, the month and the year from a variable 2488 of type date. 2489<synopsis> 2490void PGTYPESdate_julmdy(date d, int *mdy); 2491</synopsis> 2492 <!-- almost same description as for rjulmdy() --> 2493 The function receives the date <literal>d</literal> and a pointer to an array 2494 of 3 integer values <literal>mdy</literal>. The variable name indicates 2495 the sequential order: <literal>mdy[0]</literal> will be set to contain the 2496 number of the month, <literal>mdy[1]</literal> will be set to the value of the 2497 day and <literal>mdy[2]</literal> will contain the year. 2498 </para> 2499 </listitem> 2500 </varlistentry> 2501 2502 <varlistentry id="pgtypesdatemdyjul"> 2503 <term><function>PGTYPESdate_mdyjul</function></term> 2504 <listitem> 2505 <para> 2506 Create a date value from an array of 3 integers that specify the 2507 day, the month and the year of the date. 2508<synopsis> 2509void PGTYPESdate_mdyjul(int *mdy, date *jdate); 2510</synopsis> 2511 The function receives the array of the 3 integers (<literal>mdy</literal>) as 2512 its first argument and as its second argument a pointer to a variable 2513 of type date that should hold the result of the operation. 2514 </para> 2515 </listitem> 2516 </varlistentry> 2517 2518 <varlistentry id="pgtypesdatedayofweek"> 2519 <term><function>PGTYPESdate_dayofweek</function></term> 2520 <listitem> 2521 <para> 2522 Return a number representing the day of the week for a date value. 2523<synopsis> 2524int PGTYPESdate_dayofweek(date d); 2525</synopsis> 2526 The function receives the date variable <literal>d</literal> as its only 2527 argument and returns an integer that indicates the day of the week for 2528 this date. 2529 <itemizedlist> 2530 <listitem> 2531 <para> 2532 0 - Sunday 2533 </para> 2534 </listitem> 2535 <listitem> 2536 <para> 2537 1 - Monday 2538 </para> 2539 </listitem> 2540 <listitem> 2541 <para> 2542 2 - Tuesday 2543 </para> 2544 </listitem> 2545 <listitem> 2546 <para> 2547 3 - Wednesday 2548 </para> 2549 </listitem> 2550 <listitem> 2551 <para> 2552 4 - Thursday 2553 </para> 2554 </listitem> 2555 <listitem> 2556 <para> 2557 5 - Friday 2558 </para> 2559 </listitem> 2560 <listitem> 2561 <para> 2562 6 - Saturday 2563 </para> 2564 </listitem> 2565 </itemizedlist> 2566 </para> 2567 </listitem> 2568 </varlistentry> 2569 2570 <varlistentry id="pgtypesdatetoday"> 2571 <term><function>PGTYPESdate_today</function></term> 2572 <listitem> 2573 <para> 2574 Get the current date. 2575<synopsis> 2576void PGTYPESdate_today(date *d); 2577</synopsis> 2578 The function receives a pointer to a date variable (<literal>d</literal>) 2579 that it sets to the current date. 2580 </para> 2581 </listitem> 2582 </varlistentry> 2583 2584 <varlistentry id="pgtypesdatefmtasc"> 2585 <term><function>PGTYPESdate_fmt_asc</function></term> 2586 <listitem> 2587 <para> 2588 Convert a variable of type date to its textual representation using a 2589 format mask. 2590<synopsis> 2591int PGTYPESdate_fmt_asc(date dDate, char *fmtstring, char *outbuf); 2592</synopsis> 2593 The function receives the date to convert (<literal>dDate</literal>), the 2594 format mask (<literal>fmtstring</literal>) and the string that will hold the 2595 textual representation of the date (<literal>outbuf</literal>). 2596 </para> 2597 <para> 2598 On success, 0 is returned and a negative value if an error occurred. 2599 </para> 2600 <para> 2601 The following literals are the field specifiers you can use: 2602 <itemizedlist> 2603 <listitem> 2604 <para> 2605 <literal>dd</literal> - The number of the day of the month. 2606 </para> 2607 </listitem> 2608 <listitem> 2609 <para> 2610 <literal>mm</literal> - The number of the month of the year. 2611 </para> 2612 </listitem> 2613 <listitem> 2614 <para> 2615 <literal>yy</literal> - The number of the year as a two digit number. 2616 </para> 2617 </listitem> 2618 <listitem> 2619 <para> 2620 <literal>yyyy</literal> - The number of the year as a four digit number. 2621 </para> 2622 </listitem> 2623 <listitem> 2624 <para> 2625 <literal>ddd</literal> - The name of the day (abbreviated). 2626 </para> 2627 </listitem> 2628 <listitem> 2629 <para> 2630 <literal>mmm</literal> - The name of the month (abbreviated). 2631 </para> 2632 </listitem> 2633 </itemizedlist> 2634 All other characters are copied 1:1 to the output string. 2635 </para> 2636 <para> 2637 <xref linkend="ecpg-pgtypesdate-fmt-asc-example-table"/> indicates a few possible formats. This will give 2638 you an idea of how to use this function. All output lines are based on 2639 the same date: November 23, 1959. 2640 </para> 2641 <table id="ecpg-pgtypesdate-fmt-asc-example-table"> 2642 <title>Valid Input Formats for <function>PGTYPESdate_fmt_asc</function></title> 2643 <tgroup cols="2"> 2644 <thead> 2645 <row> 2646 <entry>Format</entry> 2647 <entry>Result</entry> 2648 </row> 2649 </thead> 2650 <tbody> 2651 <row> 2652 <entry><literal>mmddyy</literal></entry> 2653 <entry><literal>112359</literal></entry> 2654 </row> 2655 <row> 2656 <entry><literal>ddmmyy</literal></entry> 2657 <entry><literal>231159</literal></entry> 2658 </row> 2659 <row> 2660 <entry><literal>yymmdd</literal></entry> 2661 <entry><literal>591123</literal></entry> 2662 </row> 2663 <row> 2664 <entry><literal>yy/mm/dd</literal></entry> 2665 <entry><literal>59/11/23</literal></entry> 2666 </row> 2667 <row> 2668 <entry><literal>yy mm dd</literal></entry> 2669 <entry><literal>59 11 23</literal></entry> 2670 </row> 2671 <row> 2672 <entry><literal>yy.mm.dd</literal></entry> 2673 <entry><literal>59.11.23</literal></entry> 2674 </row> 2675 <row> 2676 <entry><literal>.mm.yyyy.dd.</literal></entry> 2677 <entry><literal>.11.1959.23.</literal></entry> 2678 </row> 2679 <row> 2680 <entry><literal>mmm. dd, yyyy</literal></entry> 2681 <entry><literal>Nov. 23, 1959</literal></entry> 2682 </row> 2683 <row> 2684 <entry><literal>mmm dd yyyy</literal></entry> 2685 <entry><literal>Nov 23 1959</literal></entry> 2686 </row> 2687 <row> 2688 <entry><literal>yyyy dd mm</literal></entry> 2689 <entry><literal>1959 23 11</literal></entry> 2690 </row> 2691 <row> 2692 <entry><literal>ddd, mmm. dd, yyyy</literal></entry> 2693 <entry><literal>Mon, Nov. 23, 1959</literal></entry> 2694 </row> 2695 <row> 2696 <entry><literal>(ddd) mmm. dd, yyyy</literal></entry> 2697 <entry><literal>(Mon) Nov. 23, 1959</literal></entry> 2698 </row> 2699 </tbody> 2700 </tgroup> 2701 </table> 2702 </listitem> 2703 </varlistentry> 2704 2705 <varlistentry id="pgtypesdatedefmtasc"> 2706 <term><function>PGTYPESdate_defmt_asc</function></term> 2707 <listitem> 2708 <para> 2709 Use a format mask to convert a C <type>char*</type> string to a value of type 2710 date. 2711<synopsis> 2712int PGTYPESdate_defmt_asc(date *d, char *fmt, char *str); 2713</synopsis> 2714 <!-- same description as rdefmtdate --> 2715 The function receives a pointer to the date value that should hold the 2716 result of the operation (<literal>d</literal>), the format mask to use for 2717 parsing the date (<literal>fmt</literal>) and the C char* string containing 2718 the textual representation of the date (<literal>str</literal>). The textual 2719 representation is expected to match the format mask. However you do not 2720 need to have a 1:1 mapping of the string to the format mask. The 2721 function only analyzes the sequential order and looks for the literals 2722 <literal>yy</literal> or <literal>yyyy</literal> that indicate the 2723 position of the year, <literal>mm</literal> to indicate the position of 2724 the month and <literal>dd</literal> to indicate the position of the 2725 day. 2726 </para> 2727 <para> 2728 <xref linkend="ecpg-rdefmtdate-example-table"/> indicates a few possible formats. This will give 2729 you an idea of how to use this function. 2730 </para> 2731 <table id="ecpg-rdefmtdate-example-table"> 2732 <title>Valid Input Formats for <function>rdefmtdate</function></title> 2733 <tgroup cols="3"> 2734 <thead> 2735 <row> 2736 <entry>Format</entry> 2737 <entry>String</entry> 2738 <entry>Result</entry> 2739 </row> 2740 </thead> 2741 <tbody> 2742 <row> 2743 <entry><literal>ddmmyy</literal></entry> 2744 <entry><literal>21-2-54</literal></entry> 2745 <entry><literal>1954-02-21</literal></entry> 2746 </row> 2747 <row> 2748 <entry><literal>ddmmyy</literal></entry> 2749 <entry><literal>2-12-54</literal></entry> 2750 <entry><literal>1954-12-02</literal></entry> 2751 </row> 2752 <row> 2753 <entry><literal>ddmmyy</literal></entry> 2754 <entry><literal>20111954</literal></entry> 2755 <entry><literal>1954-11-20</literal></entry> 2756 </row> 2757 <row> 2758 <entry><literal>ddmmyy</literal></entry> 2759 <entry><literal>130464</literal></entry> 2760 <entry><literal>1964-04-13</literal></entry> 2761 </row> 2762 <row> 2763 <entry><literal>mmm.dd.yyyy</literal></entry> 2764 <entry><literal>MAR-12-1967</literal></entry> 2765 <entry><literal>1967-03-12</literal></entry> 2766 </row> 2767 <row> 2768 <entry><literal>yy/mm/dd</literal></entry> 2769 <entry><literal>1954, February 3rd</literal></entry> 2770 <entry><literal>1954-02-03</literal></entry> 2771 </row> 2772 <row> 2773 <entry><literal>mmm.dd.yyyy</literal></entry> 2774 <entry><literal>041269</literal></entry> 2775 <entry><literal>1969-04-12</literal></entry> 2776 </row> 2777 <row> 2778 <entry><literal>yy/mm/dd</literal></entry> 2779 <entry><literal>In the year 2525, in the month of July, mankind will be alive on the 28th day</literal></entry> 2780 <entry><literal>2525-07-28</literal></entry> 2781 </row> 2782 <row> 2783 <entry><literal>dd-mm-yy</literal></entry> 2784 <entry><literal>I said on the 28th of July in the year 2525</literal></entry> 2785 <entry><literal>2525-07-28</literal></entry> 2786 </row> 2787 <row> 2788 <entry><literal>mmm.dd.yyyy</literal></entry> 2789 <entry><literal>9/14/58</literal></entry> 2790 <entry><literal>1958-09-14</literal></entry> 2791 </row> 2792 <row> 2793 <entry><literal>yy/mm/dd</literal></entry> 2794 <entry><literal>47/03/29</literal></entry> 2795 <entry><literal>1947-03-29</literal></entry> 2796 </row> 2797 <row> 2798 <entry><literal>mmm.dd.yyyy</literal></entry> 2799 <entry><literal>oct 28 1975</literal></entry> 2800 <entry><literal>1975-10-28</literal></entry> 2801 </row> 2802 <row> 2803 <entry><literal>mmddyy</literal></entry> 2804 <entry><literal>Nov 14th, 1985</literal></entry> 2805 <entry><literal>1985-11-14</literal></entry> 2806 </row> 2807 </tbody> 2808 </tgroup> 2809 </table> 2810 </listitem> 2811 </varlistentry> 2812 </variablelist> 2813 </para> 2814 </sect2> 2815 2816 <sect2 id="ecpg-pgtypes-timestamp"> 2817 <title>The timestamp Type</title> 2818 <para> 2819 The timestamp type in C enables your programs to deal with data of the SQL 2820 type timestamp. See <xref linkend="datatype-datetime"/> for the equivalent 2821 type in the <productname>PostgreSQL</productname> server. 2822 </para> 2823 <para> 2824 The following functions can be used to work with the timestamp type: 2825 <variablelist> 2826 <varlistentry id="pgtypestimestampfromasc"> 2827 <term><function>PGTYPEStimestamp_from_asc</function></term> 2828 <listitem> 2829 <para> 2830 Parse a timestamp from its textual representation into a timestamp 2831 variable. 2832<synopsis> 2833timestamp PGTYPEStimestamp_from_asc(char *str, char **endptr); 2834</synopsis> 2835 The function receives the string to parse (<literal>str</literal>) and a 2836 pointer to a C char* (<literal>endptr</literal>). 2837 At the moment ECPG always parses 2838 the complete string and so it currently does not support to store the 2839 address of the first invalid character in <literal>*endptr</literal>. 2840 You can safely set <literal>endptr</literal> to NULL. 2841 </para> 2842 <para> 2843 The function returns the parsed timestamp on success. On error, 2844 <literal>PGTYPESInvalidTimestamp</literal> is returned and <varname>errno</varname> is 2845 set to <literal>PGTYPES_TS_BAD_TIMESTAMP</literal>. See <xref linkend="pgtypesinvalidtimestamp"/> for important notes on this value. 2846 </para> 2847 <para> 2848 In general, the input string can contain any combination of an allowed 2849 date specification, a whitespace character and an allowed time 2850 specification. Note that time zones are not supported by ECPG. It can 2851 parse them but does not apply any calculation as the 2852 <productname>PostgreSQL</productname> server does for example. Timezone 2853 specifiers are silently discarded. 2854 </para> 2855 <para> 2856 <xref linkend="ecpg-pgtypestimestamp-from-asc-example-table"/> contains a few examples for input strings. 2857 </para> 2858 <table id="ecpg-pgtypestimestamp-from-asc-example-table"> 2859 <title>Valid Input Formats for <function>PGTYPEStimestamp_from_asc</function></title> 2860 <tgroup cols="2"> 2861 <thead> 2862 <row> 2863 <entry>Input</entry> 2864 <entry>Result</entry> 2865 </row> 2866 </thead> 2867 <tbody> 2868 <row> 2869 <entry><literal>1999-01-08 04:05:06</literal></entry> 2870 <entry><literal>1999-01-08 04:05:06</literal></entry> 2871 </row> 2872 <row> 2873 <entry><literal>January 8 04:05:06 1999 PST</literal></entry> 2874 <entry><literal>1999-01-08 04:05:06</literal></entry> 2875 </row> 2876 <row> 2877 <entry><literal>1999-Jan-08 04:05:06.789-8</literal></entry> 2878 <entry><literal>1999-01-08 04:05:06.789 (time zone specifier ignored)</literal></entry> 2879 </row> 2880 <row> 2881 <entry><literal>J2451187 04:05-08:00</literal></entry> 2882 <entry><literal>1999-01-08 04:05:00 (time zone specifier ignored)</literal></entry> 2883 </row> 2884 </tbody> 2885 </tgroup> 2886 </table> 2887 </listitem> 2888 </varlistentry> 2889 2890 <varlistentry id="pgtypestimestamptoasc"> 2891 <term><function>PGTYPEStimestamp_to_asc</function></term> 2892 <listitem> 2893 <para> 2894 Converts a date to a C char* string. 2895<synopsis> 2896char *PGTYPEStimestamp_to_asc(timestamp tstamp); 2897</synopsis> 2898 The function receives the timestamp <literal>tstamp</literal> as 2899 its only argument and returns an allocated string that contains the 2900 textual representation of the timestamp. 2901 The result must be freed with <function>PGTYPESchar_free()</function>. 2902 </para> 2903 </listitem> 2904 </varlistentry> 2905 2906 <varlistentry id="pgtypestimestampcurrent"> 2907 <term><function>PGTYPEStimestamp_current</function></term> 2908 <listitem> 2909 <para> 2910 Retrieve the current timestamp. 2911<synopsis> 2912void PGTYPEStimestamp_current(timestamp *ts); 2913</synopsis> 2914 The function retrieves the current timestamp and saves it into the 2915 timestamp variable that <literal>ts</literal> points to. 2916 </para> 2917 </listitem> 2918 </varlistentry> 2919 2920 <varlistentry id="pgtypestimestampfmtasc"> 2921 <term><function>PGTYPEStimestamp_fmt_asc</function></term> 2922 <listitem> 2923 <para> 2924 Convert a timestamp variable to a C char* using a format mask. 2925<synopsis> 2926int PGTYPEStimestamp_fmt_asc(timestamp *ts, char *output, int str_len, char *fmtstr); 2927</synopsis> 2928 The function receives a pointer to the timestamp to convert as its 2929 first argument (<literal>ts</literal>), a pointer to the output buffer 2930 (<literal>output</literal>), the maximal length that has been allocated for 2931 the output buffer (<literal>str_len</literal>) and the format mask to 2932 use for the conversion (<literal>fmtstr</literal>). 2933 </para> 2934 <para> 2935 Upon success, the function returns 0 and a negative value if an 2936 error occurred. 2937 </para> 2938 <para> 2939 You can use the following format specifiers for the format mask. The 2940 format specifiers are the same ones that are used in the 2941 <function>strftime</function> function in <productname>libc</productname>. Any 2942 non-format specifier will be copied into the output buffer. 2943 <!-- This is from the FreeBSD man page: 2944 http://www.freebsd.org/cgi/man.cgi?query=strftime&apropos=0&sektion=3&manpath=FreeBSD+7.0-current&format=html 2945 --> 2946 <itemizedlist> 2947 <listitem> 2948 <para> 2949 <literal>%A</literal> - is replaced by national representation of 2950 the full weekday name. 2951 </para> 2952 </listitem> 2953 <listitem> 2954 <para> 2955 <literal>%a</literal> - is replaced by national representation of 2956 the abbreviated weekday name. 2957 </para> 2958 </listitem> 2959 <listitem> 2960 <para> 2961 <literal>%B</literal> - is replaced by national representation of 2962 the full month name. 2963 </para> 2964 </listitem> 2965 <listitem> 2966 <para> 2967 <literal>%b</literal> - is replaced by national representation of 2968 the abbreviated month name. 2969 </para> 2970 </listitem> 2971 <listitem> 2972 <para> 2973 <literal>%C</literal> - is replaced by (year / 100) as decimal 2974 number; single digits are preceded by a zero. 2975 </para> 2976 </listitem> 2977 <listitem> 2978 <para> 2979 <literal>%c</literal> - is replaced by national representation of 2980 time and date. 2981 </para> 2982 </listitem> 2983 <listitem> 2984 <para> 2985 <literal>%D</literal> - is equivalent to 2986 <literal>%m/%d/%y</literal>. 2987 </para> 2988 </listitem> 2989 <listitem> 2990 <para> 2991 <literal>%d</literal> - is replaced by the day of the month as a 2992 decimal number (01-31). 2993 </para> 2994 </listitem> 2995 <listitem> 2996 <para> 2997 <literal>%E*</literal> <literal>%O*</literal> - POSIX locale 2998 extensions. The sequences 2999 <literal>%Ec</literal> 3000 <literal>%EC</literal> 3001 <literal>%Ex</literal> 3002 <literal>%EX</literal> 3003 <literal>%Ey</literal> 3004 <literal>%EY</literal> 3005 <literal>%Od</literal> 3006 <literal>%Oe</literal> 3007 <literal>%OH</literal> 3008 <literal>%OI</literal> 3009 <literal>%Om</literal> 3010 <literal>%OM</literal> 3011 <literal>%OS</literal> 3012 <literal>%Ou</literal> 3013 <literal>%OU</literal> 3014 <literal>%OV</literal> 3015 <literal>%Ow</literal> 3016 <literal>%OW</literal> 3017 <literal>%Oy</literal> 3018 are supposed to provide alternative representations. 3019 </para> 3020 <para> 3021 Additionally <literal>%OB</literal> implemented to represent 3022 alternative months names (used standalone, without day mentioned). 3023 </para> 3024 </listitem> 3025 <listitem> 3026 <para> 3027 <literal>%e</literal> - is replaced by the day of month as a decimal 3028 number (1-31); single digits are preceded by a blank. 3029 </para> 3030 </listitem> 3031 <listitem> 3032 <para> 3033 <literal>%F</literal> - is equivalent to <literal>%Y-%m-%d</literal>. 3034 </para> 3035 </listitem> 3036 <listitem> 3037 <para> 3038 <literal>%G</literal> - is replaced by a year as a decimal number 3039 with century. This year is the one that contains the greater part of 3040 the week (Monday as the first day of the week). 3041 </para> 3042 </listitem> 3043 <listitem> 3044 <para> 3045 <literal>%g</literal> - is replaced by the same year as in 3046 <literal>%G</literal>, but as a decimal number without century 3047 (00-99). 3048 </para> 3049 </listitem> 3050 <listitem> 3051 <para> 3052 <literal>%H</literal> - is replaced by the hour (24-hour clock) as a 3053 decimal number (00-23). 3054 </para> 3055 </listitem> 3056 <listitem> 3057 <para> 3058 <literal>%h</literal> - the same as <literal>%b</literal>. 3059 </para> 3060 </listitem> 3061 <listitem> 3062 <para> 3063 <literal>%I</literal> - is replaced by the hour (12-hour clock) as a 3064 decimal number (01-12). 3065 </para> 3066 </listitem> 3067 <listitem> 3068 <para> 3069 <literal>%j</literal> - is replaced by the day of the year as a 3070 decimal number (001-366). 3071 </para> 3072 </listitem> 3073 <listitem> 3074 <para> 3075 <literal>%k</literal> - is replaced by the hour (24-hour clock) as a 3076 decimal number (0-23); single digits are preceded by a blank. 3077 </para> 3078 </listitem> 3079 <listitem> 3080 <para> 3081 <literal>%l</literal> - is replaced by the hour (12-hour clock) as a 3082 decimal number (1-12); single digits are preceded by a blank. 3083 </para> 3084 </listitem> 3085 <listitem> 3086 <para> 3087 <literal>%M</literal> - is replaced by the minute as a decimal 3088 number (00-59). 3089 </para> 3090 </listitem> 3091 <listitem> 3092 <para> 3093 <literal>%m</literal> - is replaced by the month as a decimal number 3094 (01-12). 3095 </para> 3096 </listitem> 3097 <listitem> 3098 <para> 3099 <literal>%n</literal> - is replaced by a newline. 3100 </para> 3101 </listitem> 3102 <listitem> 3103 <para> 3104 <literal>%O*</literal> - the same as <literal>%E*</literal>. 3105 </para> 3106 </listitem> 3107 <listitem> 3108 <para> 3109 <literal>%p</literal> - is replaced by national representation of 3110 either <quote>ante meridiem</quote> or <quote>post meridiem</quote> as appropriate. 3111 </para> 3112 </listitem> 3113 <listitem> 3114 <para> 3115 <literal>%R</literal> - is equivalent to <literal>%H:%M</literal>. 3116 </para> 3117 </listitem> 3118 <listitem> 3119 <para> 3120 <literal>%r</literal> - is equivalent to <literal>%I:%M:%S 3121 %p</literal>. 3122 </para> 3123 </listitem> 3124 <listitem> 3125 <para> 3126 <literal>%S</literal> - is replaced by the second as a decimal 3127 number (00-60). 3128 </para> 3129 </listitem> 3130 <listitem> 3131 <para> 3132 <literal>%s</literal> - is replaced by the number of seconds since 3133 the Epoch, UTC. 3134 </para> 3135 </listitem> 3136 <listitem> 3137 <para> 3138 <literal>%T</literal> - is equivalent to <literal>%H:%M:%S</literal> 3139 </para> 3140 </listitem> 3141 <listitem> 3142 <para> 3143 <literal>%t</literal> - is replaced by a tab. 3144 </para> 3145 </listitem> 3146 <listitem> 3147 <para> 3148 <literal>%U</literal> - is replaced by the week number of the year 3149 (Sunday as the first day of the week) as a decimal number (00-53). 3150 </para> 3151 </listitem> 3152 <listitem> 3153 <para> 3154 <literal>%u</literal> - is replaced by the weekday (Monday as the 3155 first day of the week) as a decimal number (1-7). 3156 </para> 3157 </listitem> 3158 <listitem> 3159 <para> 3160 <literal>%V</literal> - is replaced by the week number of the year 3161 (Monday as the first day of the week) as a decimal number (01-53). 3162 If the week containing January 1 has four or more days in the new 3163 year, then it is week 1; otherwise it is the last week of the 3164 previous year, and the next week is week 1. 3165 </para> 3166 </listitem> 3167 <listitem> 3168 <para> 3169 <literal>%v</literal> - is equivalent to 3170 <literal>%e-%b-%Y</literal>. 3171 </para> 3172 </listitem> 3173 <listitem> 3174 <para> 3175 <literal>%W</literal> - is replaced by the week number of the year 3176 (Monday as the first day of the week) as a decimal number (00-53). 3177 </para> 3178 </listitem> 3179 <listitem> 3180 <para> 3181 <literal>%w</literal> - is replaced by the weekday (Sunday as the 3182 first day of the week) as a decimal number (0-6). 3183 </para> 3184 </listitem> 3185 <listitem> 3186 <para> 3187 <literal>%X</literal> - is replaced by national representation of 3188 the time. 3189 </para> 3190 </listitem> 3191 <listitem> 3192 <para> 3193 <literal>%x</literal> - is replaced by national representation of 3194 the date. 3195 </para> 3196 </listitem> 3197 <listitem> 3198 <para> 3199 <literal>%Y</literal> - is replaced by the year with century as a 3200 decimal number. 3201 </para> 3202 </listitem> 3203 <listitem> 3204 <para> 3205 <literal>%y</literal> - is replaced by the year without century as a 3206 decimal number (00-99). 3207 </para> 3208 </listitem> 3209 <listitem> 3210 <para> 3211 <literal>%Z</literal> - is replaced by the time zone name. 3212 </para> 3213 </listitem> 3214 <listitem> 3215 <para> 3216 <literal>%z</literal> - is replaced by the time zone offset from 3217 UTC; a leading plus sign stands for east of UTC, a minus sign for 3218 west of UTC, hours and minutes follow with two digits each and no 3219 delimiter between them (common form for RFC 822 date headers). 3220 </para> 3221 </listitem> 3222 <listitem> 3223 <para> 3224 <literal>%+</literal> - is replaced by national representation of 3225 the date and time. 3226 </para> 3227 </listitem> 3228 <listitem> 3229 <para> 3230 <literal>%-*</literal> - GNU libc extension. Do not do any padding 3231 when performing numerical outputs. 3232 </para> 3233 </listitem> 3234 <listitem> 3235 <para> 3236 $_* - GNU libc extension. Explicitly specify space for padding. 3237 </para> 3238 </listitem> 3239 <listitem> 3240 <para> 3241 <literal>%0*</literal> - GNU libc extension. Explicitly specify zero 3242 for padding. 3243 </para> 3244 </listitem> 3245 <listitem> 3246 <para> 3247 <literal>%%</literal> - is replaced by <literal>%</literal>. 3248 </para> 3249 </listitem> 3250 </itemizedlist> 3251 </para> 3252 </listitem> 3253 </varlistentry> 3254 3255 <varlistentry id="pgtypestimestampsub"> 3256 <term><function>PGTYPEStimestamp_sub</function></term> 3257 <listitem> 3258 <para> 3259 Subtract one timestamp from another one and save the result in a 3260 variable of type interval. 3261<synopsis> 3262int PGTYPEStimestamp_sub(timestamp *ts1, timestamp *ts2, interval *iv); 3263</synopsis> 3264 The function will subtract the timestamp variable that <literal>ts2</literal> 3265 points to from the timestamp variable that <literal>ts1</literal> points to 3266 and will store the result in the interval variable that <literal>iv</literal> 3267 points to. 3268 </para> 3269 <para> 3270 Upon success, the function returns 0 and a negative value if an 3271 error occurred. 3272 </para> 3273 </listitem> 3274 </varlistentry> 3275 3276 <varlistentry id="pgtypestimestampdefmtasc"> 3277 <term><function>PGTYPEStimestamp_defmt_asc</function></term> 3278 <listitem> 3279 <para> 3280 Parse a timestamp value from its textual representation using a 3281 formatting mask. 3282<synopsis> 3283int PGTYPEStimestamp_defmt_asc(char *str, char *fmt, timestamp *d); 3284</synopsis> 3285 The function receives the textual representation of a timestamp in the 3286 variable <literal>str</literal> as well as the formatting mask to use in the 3287 variable <literal>fmt</literal>. The result will be stored in the variable 3288 that <literal>d</literal> points to. 3289 </para> 3290 <para> 3291 If the formatting mask <literal>fmt</literal> is NULL, the function will fall 3292 back to the default formatting mask which is <literal>%Y-%m-%d 3293 %H:%M:%S</literal>. 3294 </para> 3295 <para> 3296 This is the reverse function to <xref 3297 linkend="pgtypestimestampfmtasc"/>. See the documentation there in 3298 order to find out about the possible formatting mask entries. 3299 </para> 3300 </listitem> 3301 </varlistentry> 3302 3303 <varlistentry id="pgtypestimestampaddinterval"> 3304 <term><function>PGTYPEStimestamp_add_interval</function></term> 3305 <listitem> 3306 <para> 3307 Add an interval variable to a timestamp variable. 3308<synopsis> 3309int PGTYPEStimestamp_add_interval(timestamp *tin, interval *span, timestamp *tout); 3310</synopsis> 3311 The function receives a pointer to a timestamp variable <literal>tin</literal> 3312 and a pointer to an interval variable <literal>span</literal>. It adds the 3313 interval to the timestamp and saves the resulting timestamp in the 3314 variable that <literal>tout</literal> points to. 3315 </para> 3316 <para> 3317 Upon success, the function returns 0 and a negative value if an 3318 error occurred. 3319 </para> 3320 </listitem> 3321 </varlistentry> 3322 3323 <varlistentry id="pgtypestimestampsubinterval"> 3324 <term><function>PGTYPEStimestamp_sub_interval</function></term> 3325 <listitem> 3326 <para> 3327 Subtract an interval variable from a timestamp variable. 3328<synopsis> 3329int PGTYPEStimestamp_sub_interval(timestamp *tin, interval *span, timestamp *tout); 3330</synopsis> 3331 The function subtracts the interval variable that <literal>span</literal> 3332 points to from the timestamp variable that <literal>tin</literal> points to 3333 and saves the result into the variable that <literal>tout</literal> points 3334 to. 3335 </para> 3336 <para> 3337 Upon success, the function returns 0 and a negative value if an 3338 error occurred. 3339 </para> 3340 </listitem> 3341 </varlistentry> 3342 </variablelist> 3343 </para> 3344 </sect2> 3345 3346 <sect2 id="ecpg-pgtypes-interval"> 3347 <title>The interval Type</title> 3348 <para> 3349 The interval type in C enables your programs to deal with data of the SQL 3350 type interval. See <xref linkend="datatype-datetime"/> for the equivalent 3351 type in the <productname>PostgreSQL</productname> server. 3352 </para> 3353 <para> 3354 The following functions can be used to work with the interval type: 3355 <variablelist> 3356 3357 <varlistentry id="pgtypesintervalnew"> 3358 <term><function>PGTYPESinterval_new</function></term> 3359 <listitem> 3360 <para> 3361 Return a pointer to a newly allocated interval variable. 3362<synopsis> 3363interval *PGTYPESinterval_new(void); 3364</synopsis> 3365 </para> 3366 </listitem> 3367 </varlistentry> 3368 3369 <varlistentry id="pgtypesintervalfree"> 3370 <term><function>PGTYPESinterval_free</function></term> 3371 <listitem> 3372 <para> 3373 Release the memory of a previously allocated interval variable. 3374<synopsis> 3375void PGTYPESinterval_free(interval *intvl); 3376</synopsis> 3377 </para> 3378 </listitem> 3379 </varlistentry> 3380 3381 <varlistentry id="pgtypesintervalfromasc"> 3382 <term><function>PGTYPESinterval_from_asc</function></term> 3383 <listitem> 3384 <para> 3385 Parse an interval from its textual representation. 3386<synopsis> 3387interval *PGTYPESinterval_from_asc(char *str, char **endptr); 3388</synopsis> 3389 The function parses the input string <literal>str</literal> and returns a 3390 pointer to an allocated interval variable. 3391 At the moment ECPG always parses 3392 the complete string and so it currently does not support to store the 3393 address of the first invalid character in <literal>*endptr</literal>. 3394 You can safely set <literal>endptr</literal> to NULL. 3395 </para> 3396 </listitem> 3397 </varlistentry> 3398 3399 <varlistentry id="pgtypesintervaltoasc"> 3400 <term><function>PGTYPESinterval_to_asc</function></term> 3401 <listitem> 3402 <para> 3403 Convert a variable of type interval to its textual representation. 3404<synopsis> 3405char *PGTYPESinterval_to_asc(interval *span); 3406</synopsis> 3407 The function converts the interval variable that <literal>span</literal> 3408 points to into a C char*. The output looks like this example: 3409 <literal>@ 1 day 12 hours 59 mins 10 secs</literal>. 3410 The result must be freed with <function>PGTYPESchar_free()</function>. 3411 </para> 3412 </listitem> 3413 </varlistentry> 3414 3415 <varlistentry id="pgtypesintervalcopy"> 3416 <term><function>PGTYPESinterval_copy</function></term> 3417 <listitem> 3418 <para> 3419 Copy a variable of type interval. 3420<synopsis> 3421int PGTYPESinterval_copy(interval *intvlsrc, interval *intvldest); 3422</synopsis> 3423 The function copies the interval variable that <literal>intvlsrc</literal> 3424 points to into the variable that <literal>intvldest</literal> points to. Note 3425 that you need to allocate the memory for the destination variable 3426 before. 3427 </para> 3428 </listitem> 3429 </varlistentry> 3430 </variablelist> 3431 </para> 3432 </sect2> 3433 3434 <sect2 id="ecpg-pgtypes-decimal"> 3435 <title>The decimal Type</title> 3436 <para> 3437 The decimal type is similar to the numeric type. However it is limited to 3438 a maximum precision of 30 significant digits. In contrast to the numeric 3439 type which can be created on the heap only, the decimal type can be 3440 created either on the stack or on the heap (by means of the functions 3441 <function>PGTYPESdecimal_new</function> and 3442 <function>PGTYPESdecimal_free</function>). 3443 There are a lot of other functions that deal with the decimal type in the 3444 <productname>Informix</productname> compatibility mode described in <xref 3445 linkend="ecpg-informix-compat"/>. 3446 </para> 3447 <para> 3448 The following functions can be used to work with the decimal type and are 3449 not only contained in the <literal>libcompat</literal> library. 3450 <variablelist> 3451 <varlistentry> 3452 <term><function>PGTYPESdecimal_new</function></term> 3453 <listitem> 3454 <para> 3455 Request a pointer to a newly allocated decimal variable. 3456<synopsis> 3457decimal *PGTYPESdecimal_new(void); 3458</synopsis> 3459 </para> 3460 </listitem> 3461 </varlistentry> 3462 3463 <varlistentry> 3464 <term><function>PGTYPESdecimal_free</function></term> 3465 <listitem> 3466 <para> 3467 Free a decimal type, release all of its memory. 3468<synopsis> 3469void PGTYPESdecimal_free(decimal *var); 3470</synopsis> 3471 </para> 3472 </listitem> 3473 </varlistentry> 3474 </variablelist> 3475 </para> 3476 </sect2> 3477 3478 <sect2 id="ecpg-pgtypes-errno"> 3479 <title>errno Values of pgtypeslib</title> 3480 <para> 3481 <variablelist> 3482 <varlistentry> 3483 <term><literal>PGTYPES_NUM_BAD_NUMERIC</literal></term> 3484 <listitem> 3485 <para> 3486 An argument should contain a numeric variable (or point to a numeric 3487 variable) but in fact its in-memory representation was invalid. 3488 </para> 3489 </listitem> 3490 </varlistentry> 3491 3492 <varlistentry> 3493 <term><literal>PGTYPES_NUM_OVERFLOW</literal></term> 3494 <listitem> 3495 <para> 3496 An overflow occurred. Since the numeric type can deal with almost 3497 arbitrary precision, converting a numeric variable into other types 3498 might cause overflow. 3499 </para> 3500 </listitem> 3501 </varlistentry> 3502 3503 <varlistentry> 3504 <term><literal>PGTYPES_NUM_UNDERFLOW</literal></term> 3505 <listitem> 3506 <para> 3507 An underflow occurred. Since the numeric type can deal with almost 3508 arbitrary precision, converting a numeric variable into other types 3509 might cause underflow. 3510 </para> 3511 </listitem> 3512 </varlistentry> 3513 3514 <varlistentry> 3515 <term><literal>PGTYPES_NUM_DIVIDE_ZERO</literal></term> 3516 <listitem> 3517 <para> 3518 A division by zero has been attempted. 3519 </para> 3520 </listitem> 3521 </varlistentry> 3522 3523 <varlistentry> 3524 <term><literal>PGTYPES_DATE_BAD_DATE</literal></term> 3525 <listitem> 3526 <para> 3527 An invalid date string was passed to 3528 the <function>PGTYPESdate_from_asc</function> function. 3529 </para> 3530 </listitem> 3531 </varlistentry> 3532 3533 <varlistentry> 3534 <term><literal>PGTYPES_DATE_ERR_EARGS</literal></term> 3535 <listitem> 3536 <para> 3537 Invalid arguments were passed to the 3538 <function>PGTYPESdate_defmt_asc</function> function. 3539 </para> 3540 </listitem> 3541 </varlistentry> 3542 3543 <varlistentry> 3544 <term><literal>PGTYPES_DATE_ERR_ENOSHORTDATE</literal></term> 3545 <listitem> 3546 <para> 3547 An invalid token in the input string was found by the 3548 <function>PGTYPESdate_defmt_asc</function> function. 3549 </para> 3550 </listitem> 3551 </varlistentry> 3552 3553 <varlistentry> 3554 <term><literal>PGTYPES_INTVL_BAD_INTERVAL</literal></term> 3555 <listitem> 3556 <para> 3557 An invalid interval string was passed to the 3558 <function>PGTYPESinterval_from_asc</function> function, or an 3559 invalid interval value was passed to the 3560 <function>PGTYPESinterval_to_asc</function> function. 3561 </para> 3562 </listitem> 3563 </varlistentry> 3564 3565 <varlistentry> 3566 <term><literal>PGTYPES_DATE_ERR_ENOTDMY</literal></term> 3567 <listitem> 3568 <para> 3569 There was a mismatch in the day/month/year assignment in the 3570 <function>PGTYPESdate_defmt_asc</function> function. 3571 </para> 3572 </listitem> 3573 </varlistentry> 3574 3575 <varlistentry> 3576 <term><literal>PGTYPES_DATE_BAD_DAY</literal></term> 3577 <listitem> 3578 <para> 3579 An invalid day of the month value was found by 3580 the <function>PGTYPESdate_defmt_asc</function> function. 3581 </para> 3582 </listitem> 3583 </varlistentry> 3584 3585 <varlistentry> 3586 <term><literal>PGTYPES_DATE_BAD_MONTH</literal></term> 3587 <listitem> 3588 <para> 3589 An invalid month value was found by 3590 the <function>PGTYPESdate_defmt_asc</function> function. 3591 </para> 3592 </listitem> 3593 </varlistentry> 3594 3595 <varlistentry> 3596 <term><literal>PGTYPES_TS_BAD_TIMESTAMP</literal></term> 3597 <listitem> 3598 <para> 3599 An invalid timestamp string pass passed to 3600 the <function>PGTYPEStimestamp_from_asc</function> function, 3601 or an invalid timestamp value was passed to 3602 the <function>PGTYPEStimestamp_to_asc</function> function. 3603 </para> 3604 </listitem> 3605 </varlistentry> 3606 3607 <varlistentry> 3608 <term><literal>PGTYPES_TS_ERR_EINFTIME</literal></term> 3609 <listitem> 3610 <para> 3611 An infinite timestamp value was encountered in a context that 3612 cannot handle it. 3613 </para> 3614 </listitem> 3615 </varlistentry> 3616 </variablelist> 3617 </para> 3618 </sect2> 3619 3620 <sect2 id="ecpg-pgtypes-constants"> 3621 <title>Special Constants of pgtypeslib</title> 3622 <para> 3623 <variablelist> 3624 <varlistentry id="pgtypesinvalidtimestamp"> 3625 <term><literal>PGTYPESInvalidTimestamp</literal></term> 3626 <listitem> 3627 <para> 3628 A value of type timestamp representing an invalid time stamp. This is 3629 returned by the function <function>PGTYPEStimestamp_from_asc</function> on 3630 parse error. 3631 Note that due to the internal representation of the <type>timestamp</type> data type, 3632 <literal>PGTYPESInvalidTimestamp</literal> is also a valid timestamp at 3633 the same time. It is set to <literal>1899-12-31 23:59:59</literal>. In order 3634 to detect errors, make sure that your application does not only test 3635 for <literal>PGTYPESInvalidTimestamp</literal> but also for 3636 <literal>errno != 0</literal> after each call to 3637 <function>PGTYPEStimestamp_from_asc</function>. 3638 </para> 3639 </listitem> 3640 </varlistentry> 3641 </variablelist> 3642 </para> 3643 </sect2> 3644 </sect1> 3645 3646 <sect1 id="ecpg-descriptors"> 3647 <title>Using Descriptor Areas</title> 3648 3649 <para> 3650 An SQL descriptor area is a more sophisticated method for processing 3651 the result of a <command>SELECT</command>, <command>FETCH</command> or 3652 a <command>DESCRIBE</command> statement. An SQL descriptor area groups 3653 the data of one row of data together with metadata items into one 3654 data structure. The metadata is particularly useful when executing 3655 dynamic SQL statements, where the nature of the result columns might 3656 not be known ahead of time. PostgreSQL provides two ways to use 3657 Descriptor Areas: the named SQL Descriptor Areas and the C-structure 3658 SQLDAs. 3659 </para> 3660 3661 <sect2 id="ecpg-named-descriptors"> 3662 <title>Named SQL Descriptor Areas</title> 3663 3664 <para> 3665 A named SQL descriptor area consists of a header, which contains 3666 information concerning the entire descriptor, and one or more item 3667 descriptor areas, which basically each describe one column in the 3668 result row. 3669 </para> 3670 3671 <para> 3672 Before you can use an SQL descriptor area, you need to allocate one: 3673<programlisting> 3674EXEC SQL ALLOCATE DESCRIPTOR <replaceable>identifier</replaceable>; 3675</programlisting> 3676 The identifier serves as the <quote>variable name</quote> of the 3677 descriptor area. <!-- The scope of the allocated descriptor is WHAT?. --> 3678 When you don't need the descriptor anymore, you should deallocate 3679 it: 3680<programlisting> 3681EXEC SQL DEALLOCATE DESCRIPTOR <replaceable>identifier</replaceable>; 3682</programlisting> 3683 </para> 3684 3685 <para> 3686 To use a descriptor area, specify it as the storage target in an 3687 <literal>INTO</literal> clause, instead of listing host variables: 3688<programlisting> 3689EXEC SQL FETCH NEXT FROM mycursor INTO SQL DESCRIPTOR mydesc; 3690</programlisting> 3691 If the result set is empty, the Descriptor Area will still contain 3692 the metadata from the query, i.e., the field names. 3693 </para> 3694 3695 <para> 3696 For not yet executed prepared queries, the <command>DESCRIBE</command> 3697 statement can be used to get the metadata of the result set: 3698<programlisting> 3699EXEC SQL BEGIN DECLARE SECTION; 3700char *sql_stmt = "SELECT * FROM table1"; 3701EXEC SQL END DECLARE SECTION; 3702 3703EXEC SQL PREPARE stmt1 FROM :sql_stmt; 3704EXEC SQL DESCRIBE stmt1 INTO SQL DESCRIPTOR mydesc; 3705</programlisting> 3706 </para> 3707 3708 <para> 3709 Before PostgreSQL 9.0, the <literal>SQL</literal> keyword was optional, 3710 so using <literal>DESCRIPTOR</literal> and <literal>SQL DESCRIPTOR</literal> 3711 produced named SQL Descriptor Areas. Now it is mandatory, omitting 3712 the <literal>SQL</literal> keyword produces SQLDA Descriptor Areas, 3713 see <xref linkend="ecpg-sqlda-descriptors"/>. 3714 </para> 3715 3716 <para> 3717 In <command>DESCRIBE</command> and <command>FETCH</command> statements, 3718 the <literal>INTO</literal> and <literal>USING</literal> keywords can be 3719 used to similarly: they produce the result set and the metadata in a 3720 Descriptor Area. 3721 </para> 3722 3723 <para> 3724 Now how do you get the data out of the descriptor area? You can 3725 think of the descriptor area as a structure with named fields. To 3726 retrieve the value of a field from the header and store it into a 3727 host variable, use the following command: 3728<programlisting> 3729EXEC SQL GET DESCRIPTOR <replaceable>name</replaceable> :<replaceable>hostvar</replaceable> = <replaceable>field</replaceable>; 3730</programlisting> 3731 Currently, there is only one header field defined: 3732 <replaceable>COUNT</replaceable>, which tells how many item 3733 descriptor areas exist (that is, how many columns are contained in 3734 the result). The host variable needs to be of an integer type. To 3735 get a field from the item descriptor area, use the following 3736 command: 3737<programlisting> 3738EXEC SQL GET DESCRIPTOR <replaceable>name</replaceable> VALUE <replaceable>num</replaceable> :<replaceable>hostvar</replaceable> = <replaceable>field</replaceable>; 3739</programlisting> 3740 <replaceable>num</replaceable> can be a literal integer or a host 3741 variable containing an integer. Possible fields are: 3742 3743 <variablelist> 3744 <varlistentry> 3745 <term><literal>CARDINALITY</literal> (integer)</term> 3746 <listitem> 3747 <para> 3748 number of rows in the result set 3749 </para> 3750 </listitem> 3751 </varlistentry> 3752 3753 <varlistentry> 3754 <term><literal>DATA</literal></term> 3755 <listitem> 3756 <para> 3757 actual data item (therefore, the data type of this field 3758 depends on the query) 3759 </para> 3760 </listitem> 3761 </varlistentry> 3762 3763 <varlistentry> 3764 <term><literal>DATETIME_INTERVAL_CODE</literal> (integer)</term> 3765 <listitem> 3766 <para> 3767 When <literal>TYPE</literal> is <literal>9</literal>, 3768 <literal>DATETIME_INTERVAL_CODE</literal> will have a value of 3769 <literal>1</literal> for <literal>DATE</literal>, 3770 <literal>2</literal> for <literal>TIME</literal>, 3771 <literal>3</literal> for <literal>TIMESTAMP</literal>, 3772 <literal>4</literal> for <literal>TIME WITH TIME ZONE</literal>, or 3773 <literal>5</literal> for <literal>TIMESTAMP WITH TIME ZONE</literal>. 3774 </para> 3775 </listitem> 3776 </varlistentry> 3777 3778 <varlistentry> 3779 <term><literal>DATETIME_INTERVAL_PRECISION</literal> (integer)</term> 3780 <listitem> 3781 <para> 3782 not implemented 3783 </para> 3784 </listitem> 3785 </varlistentry> 3786 3787 <varlistentry> 3788 <term><literal>INDICATOR</literal> (integer)</term> 3789 <listitem> 3790 <para> 3791 the indicator (indicating a null value or a value truncation) 3792 </para> 3793 </listitem> 3794 </varlistentry> 3795 3796 <varlistentry> 3797 <term><literal>KEY_MEMBER</literal> (integer)</term> 3798 <listitem> 3799 <para> 3800 not implemented 3801 </para> 3802 </listitem> 3803 </varlistentry> 3804 3805 <varlistentry> 3806 <term><literal>LENGTH</literal> (integer)</term> 3807 <listitem> 3808 <para> 3809 length of the datum in characters 3810 </para> 3811 </listitem> 3812 </varlistentry> 3813 3814 <varlistentry> 3815 <term><literal>NAME</literal> (string)</term> 3816 <listitem> 3817 <para> 3818 name of the column 3819 </para> 3820 </listitem> 3821 </varlistentry> 3822 3823 <varlistentry> 3824 <term><literal>NULLABLE</literal> (integer)</term> 3825 <listitem> 3826 <para> 3827 not implemented 3828 </para> 3829 </listitem> 3830 </varlistentry> 3831 3832 <varlistentry> 3833 <term><literal>OCTET_LENGTH</literal> (integer)</term> 3834 <listitem> 3835 <para> 3836 length of the character representation of the datum in bytes 3837 </para> 3838 </listitem> 3839 </varlistentry> 3840 3841 <varlistentry> 3842 <term><literal>PRECISION</literal> (integer)</term> 3843 <listitem> 3844 <para> 3845 precision (for type <type>numeric</type>) 3846 </para> 3847 </listitem> 3848 </varlistentry> 3849 3850 <varlistentry> 3851 <term><literal>RETURNED_LENGTH</literal> (integer)</term> 3852 <listitem> 3853 <para> 3854 length of the datum in characters 3855 </para> 3856 </listitem> 3857 </varlistentry> 3858 3859 <varlistentry> 3860 <term><literal>RETURNED_OCTET_LENGTH</literal> (integer)</term> 3861 <listitem> 3862 <para> 3863 length of the character representation of the datum in bytes 3864 </para> 3865 </listitem> 3866 </varlistentry> 3867 3868 <varlistentry> 3869 <term><literal>SCALE</literal> (integer)</term> 3870 <listitem> 3871 <para> 3872 scale (for type <type>numeric</type>) 3873 </para> 3874 </listitem> 3875 </varlistentry> 3876 3877 <varlistentry> 3878 <term><literal>TYPE</literal> (integer)</term> 3879 <listitem> 3880 <para> 3881 numeric code of the data type of the column 3882 </para> 3883 </listitem> 3884 </varlistentry> 3885 </variablelist> 3886 </para> 3887 3888 <para> 3889 In <command>EXECUTE</command>, <command>DECLARE</command> and <command>OPEN</command> 3890 statements, the effect of the <literal>INTO</literal> and <literal>USING</literal> 3891 keywords are different. A Descriptor Area can also be manually built to 3892 provide the input parameters for a query or a cursor and 3893 <literal>USING SQL DESCRIPTOR <replaceable>name</replaceable></literal> 3894 is the way to pass the input parameters into a parameterized query. The statement 3895 to build a named SQL Descriptor Area is below: 3896<programlisting> 3897EXEC SQL SET DESCRIPTOR <replaceable>name</replaceable> VALUE <replaceable>num</replaceable> <replaceable>field</replaceable> = :<replaceable>hostvar</replaceable>; 3898</programlisting> 3899 </para> 3900 3901 <para> 3902 PostgreSQL supports retrieving more that one record in one <command>FETCH</command> 3903 statement and storing the data in host variables in this case assumes that the 3904 variable is an array. E.g.: 3905<programlisting> 3906EXEC SQL BEGIN DECLARE SECTION; 3907int id[5]; 3908EXEC SQL END DECLARE SECTION; 3909 3910EXEC SQL FETCH 5 FROM mycursor INTO SQL DESCRIPTOR mydesc; 3911 3912EXEC SQL GET DESCRIPTOR mydesc VALUE 1 :id = DATA; 3913</programlisting> 3914 3915 </para> 3916 3917 </sect2> 3918 3919 <sect2 id="ecpg-sqlda-descriptors"> 3920 <title>SQLDA Descriptor Areas</title> 3921 3922 <para> 3923 An SQLDA Descriptor Area is a C language structure which can be also used 3924 to get the result set and the metadata of a query. One structure stores one 3925 record from the result set. 3926<programlisting> 3927EXEC SQL include sqlda.h; 3928sqlda_t *mysqlda; 3929 3930EXEC SQL FETCH 3 FROM mycursor INTO DESCRIPTOR mysqlda; 3931</programlisting> 3932 Note that the <literal>SQL</literal> keyword is omitted. The paragraphs about 3933 the use cases of the <literal>INTO</literal> and <literal>USING</literal> 3934 keywords in <xref linkend="ecpg-named-descriptors"/> also apply here with an addition. 3935 In a <command>DESCRIBE</command> statement the <literal>DESCRIPTOR</literal> 3936 keyword can be completely omitted if the <literal>INTO</literal> keyword is used: 3937<programlisting> 3938EXEC SQL DESCRIBE prepared_statement INTO mysqlda; 3939</programlisting> 3940 </para> 3941 3942 <procedure> 3943 <para> 3944 The general flow of a program that uses SQLDA is: 3945 </para> 3946 <step><simpara>Prepare a query, and declare a cursor for it.</simpara></step> 3947 <step><simpara>Declare an SQLDA for the result rows.</simpara></step> 3948 <step><simpara>Declare an SQLDA for the input parameters, and initialize them (memory allocation, parameter settings).</simpara></step> 3949 <step><simpara>Open a cursor with the input SQLDA.</simpara></step> 3950 <step><simpara>Fetch rows from the cursor, and store them into an output SQLDA.</simpara></step> 3951 <step><simpara>Read values from the output SQLDA into the host variables (with conversion if necessary).</simpara></step> 3952 <step><simpara>Close the cursor.</simpara></step> 3953 <step><simpara>Free the memory area allocated for the input SQLDA.</simpara></step> 3954 </procedure> 3955 3956 <sect3> 3957 <title>SQLDA Data Structure</title> 3958 3959 <para> 3960 SQLDA uses three data structure 3961 types: <type>sqlda_t</type>, <type>sqlvar_t</type>, 3962 and <type>struct sqlname</type>. 3963 </para> 3964 3965 <tip> 3966 <para> 3967 PostgreSQL's SQLDA has a similar data structure to the one in 3968 IBM DB2 Universal Database, so some technical information on 3969 DB2's SQLDA could help understanding PostgreSQL's one better. 3970 </para> 3971 </tip> 3972 3973 <sect4 id="ecpg-sqlda-sqlda"> 3974 <title>sqlda_t Structure</title> 3975 3976 <para> 3977 The structure type <type>sqlda_t</type> is the type of the 3978 actual SQLDA. It holds one record. And two or 3979 more <type>sqlda_t</type> structures can be connected in a 3980 linked list with the pointer in 3981 the <structfield>desc_next</structfield> field, thus 3982 representing an ordered collection of rows. So, when two or 3983 more rows are fetched, the application can read them by 3984 following the <structfield>desc_next</structfield> pointer in 3985 each <type>sqlda_t</type> node. 3986 </para> 3987 3988 <para> 3989 The definition of <type>sqlda_t</type> is: 3990<programlisting> 3991struct sqlda_struct 3992{ 3993 char sqldaid[8]; 3994 long sqldabc; 3995 short sqln; 3996 short sqld; 3997 struct sqlda_struct *desc_next; 3998 struct sqlvar_struct sqlvar[1]; 3999}; 4000 4001typedef struct sqlda_struct sqlda_t; 4002</programlisting> 4003 4004 The meaning of the fields is: 4005 4006 <variablelist> 4007 <varlistentry> 4008 <term><literal>sqldaid</literal></term> 4009 <listitem> 4010 <para> 4011 It contains the literal string <literal>"SQLDA "</literal>. 4012 </para> 4013 </listitem> 4014 </varlistentry> 4015 4016 <varlistentry> 4017 <term><literal>sqldabc</literal></term> 4018 <listitem> 4019 <para> 4020 It contains the size of the allocated space in bytes. 4021 </para> 4022 </listitem> 4023 </varlistentry> 4024 4025 <varlistentry> 4026 <term><literal>sqln</literal></term> 4027 <listitem> 4028 <para> 4029 It contains the number of input parameters for a parameterized query in 4030 case it's passed into <command>OPEN</command>, <command>DECLARE</command> or 4031 <command>EXECUTE</command> statements using the <literal>USING</literal> 4032 keyword. In case it's used as output of <command>SELECT</command>, 4033 <command>EXECUTE</command> or <command>FETCH</command> statements, 4034 its value is the same as <literal>sqld</literal> 4035 statement 4036 </para> 4037 </listitem> 4038 </varlistentry> 4039 4040 <varlistentry> 4041 <term><literal>sqld</literal></term> 4042 <listitem> 4043 <para> 4044 It contains the number of fields in a result set. 4045 </para> 4046 </listitem> 4047 </varlistentry> 4048 4049 <varlistentry> 4050 <term><literal>desc_next</literal></term> 4051 <listitem> 4052 <para> 4053 If the query returns more than one record, multiple linked 4054 SQLDA structures are returned, and <literal>desc_next</literal> holds 4055 a pointer to the next entry in the list. 4056 </para> 4057 </listitem> 4058 </varlistentry> 4059 <varlistentry> 4060 <term><literal>sqlvar</literal></term> 4061 <listitem> 4062 <para> 4063 This is the array of the columns in the result set. 4064 </para> 4065 </listitem> 4066 </varlistentry> 4067 </variablelist> 4068 </para> 4069 </sect4> 4070 4071 <sect4 id="ecpg-sqlda-sqlvar"> 4072 <title>sqlvar_t Structure</title> 4073 4074 <para> 4075 The structure type <type>sqlvar_t</type> holds a column value 4076 and metadata such as type and length. The definition of the type 4077 is: 4078 4079<programlisting> 4080struct sqlvar_struct 4081{ 4082 short sqltype; 4083 short sqllen; 4084 char *sqldata; 4085 short *sqlind; 4086 struct sqlname sqlname; 4087}; 4088 4089typedef struct sqlvar_struct sqlvar_t; 4090</programlisting> 4091 4092 The meaning of the fields is: 4093 4094 <variablelist> 4095 <varlistentry> 4096 <term><literal>sqltype</literal></term> 4097 <listitem> 4098 <para> 4099 Contains the type identifier of the field. For values, 4100 see <literal>enum ECPGttype</literal> in <literal>ecpgtype.h</literal>. 4101 </para> 4102 </listitem> 4103 </varlistentry> 4104 4105 <varlistentry> 4106 <term><literal>sqllen</literal></term> 4107 <listitem> 4108 <para> 4109 Contains the binary length of the field. e.g., 4 bytes for <type>ECPGt_int</type>. 4110 </para> 4111 </listitem> 4112 </varlistentry> 4113 4114 <varlistentry> 4115 <term><literal>sqldata</literal></term> 4116 <listitem> 4117 <para> 4118 Points to the data. The format of the data is described 4119 in <xref linkend="ecpg-variables-type-mapping"/>. 4120 </para> 4121 </listitem> 4122 </varlistentry> 4123 4124 <varlistentry> 4125 <term><literal>sqlind</literal></term> 4126 <listitem> 4127 <para> 4128 Points to the null indicator. 0 means not null, -1 means 4129 null. 4130 </para> 4131 </listitem> 4132 </varlistentry> 4133 4134 <varlistentry> 4135 <term><literal>sqlname</literal></term> 4136 <listitem> 4137 <para> 4138 The name of the field. 4139 </para> 4140 </listitem> 4141 </varlistentry> 4142 </variablelist> 4143 </para> 4144 </sect4> 4145 4146 <sect4 id="ecpg-sqlda-sqlname"> 4147 <title>struct sqlname Structure</title> 4148 4149 <para> 4150 A <type>struct sqlname</type> structure holds a column name. It 4151 is used as a member of the <type>sqlvar_t</type> structure. The 4152 definition of the structure is: 4153<programlisting> 4154#define NAMEDATALEN 64 4155 4156struct sqlname 4157{ 4158 short length; 4159 char data[NAMEDATALEN]; 4160}; 4161</programlisting> 4162 The meaning of the fields is: 4163 <variablelist> 4164 <varlistentry> 4165 <term><literal>length</literal></term> 4166 <listitem> 4167 <para> 4168 Contains the length of the field name. 4169 </para> 4170 </listitem> 4171 </varlistentry> 4172 <varlistentry> 4173 <term><literal>data</literal></term> 4174 <listitem> 4175 <para> 4176 Contains the actual field name. 4177 </para> 4178 </listitem> 4179 </varlistentry> 4180 </variablelist> 4181 </para> 4182 </sect4> 4183 </sect3> 4184 4185 <sect3 id="ecpg-sqlda-output"> 4186 <title>Retrieving a Result Set Using an SQLDA</title> 4187 4188 <procedure> 4189 <para> 4190 The general steps to retrieve a query result set through an 4191 SQLDA are: 4192 </para> 4193 <step><simpara>Declare an <type>sqlda_t</type> structure to receive the result set.</simpara></step> 4194 <step><simpara>Execute <command>FETCH</command>/<command>EXECUTE</command>/<command>DESCRIBE</command> commands to process a query specifying the declared SQLDA.</simpara></step> 4195 <step><simpara>Check the number of records in the result set by looking at <structfield>sqln</structfield>, a member of the <type>sqlda_t</type> structure.</simpara></step> 4196 <step><simpara>Get the values of each column from <literal>sqlvar[0]</literal>, <literal>sqlvar[1]</literal>, etc., members of the <type>sqlda_t</type> structure.</simpara></step> 4197 <step><simpara>Go to next row (<type>sqlda_t</type> structure) by following the <structfield>desc_next</structfield> pointer, a member of the <type>sqlda_t</type> structure.</simpara></step> 4198 <step><simpara>Repeat above as you need.</simpara></step> 4199 </procedure> 4200 4201 <para> 4202 Here is an example retrieving a result set through an SQLDA. 4203 </para> 4204 4205 <para> 4206 First, declare a <type>sqlda_t</type> structure to receive the result set. 4207<programlisting> 4208sqlda_t *sqlda1; 4209</programlisting> 4210 </para> 4211 4212 <para> 4213 Next, specify the SQLDA in a command. This is 4214 a <command>FETCH</command> command example. 4215<programlisting> 4216EXEC SQL FETCH NEXT FROM cur1 INTO DESCRIPTOR sqlda1; 4217</programlisting> 4218 </para> 4219 4220 <para> 4221 Run a loop following the linked list to retrieve the rows. 4222<programlisting> 4223sqlda_t *cur_sqlda; 4224 4225for (cur_sqlda = sqlda1; 4226 cur_sqlda != NULL; 4227 cur_sqlda = cur_sqlda->desc_next) 4228{ 4229 ... 4230} 4231</programlisting> 4232 </para> 4233 4234 <para> 4235 Inside the loop, run another loop to retrieve each column data 4236 (<type>sqlvar_t</type> structure) of the row. 4237<programlisting> 4238for (i = 0; i < cur_sqlda->sqld; i++) 4239{ 4240 sqlvar_t v = cur_sqlda->sqlvar[i]; 4241 char *sqldata = v.sqldata; 4242 short sqllen = v.sqllen; 4243 ... 4244} 4245</programlisting> 4246 </para> 4247 4248 <para> 4249 To get a column value, check the <structfield>sqltype</structfield> value, 4250 a member of the <type>sqlvar_t</type> structure. Then, switch 4251 to an appropriate way, depending on the column type, to copy 4252 data from the <structfield>sqlvar</structfield> field to a host variable. 4253<programlisting> 4254char var_buf[1024]; 4255 4256switch (v.sqltype) 4257{ 4258 case ECPGt_char: 4259 memset(&var_buf, 0, sizeof(var_buf)); 4260 memcpy(&var_buf, sqldata, (sizeof(var_buf) <= sqllen ? sizeof(var_buf) - 1 : sqllen)); 4261 break; 4262 4263 case ECPGt_int: /* integer */ 4264 memcpy(&intval, sqldata, sqllen); 4265 snprintf(var_buf, sizeof(var_buf), "%d", intval); 4266 break; 4267 4268 ... 4269} 4270</programlisting> 4271 </para> 4272 </sect3> 4273 4274 <sect3 id="ecpg-sqlda-input"> 4275 <title>Passing Query Parameters Using an SQLDA</title> 4276 4277 <procedure> 4278 <para> 4279 The general steps to use an SQLDA to pass input 4280 parameters to a prepared query are: 4281 </para> 4282 <step><simpara>Create a prepared query (prepared statement)</simpara></step> 4283 <step><simpara>Declare a sqlda_t structure as an input SQLDA.</simpara></step> 4284 <step><simpara>Allocate memory area (as sqlda_t structure) for the input SQLDA.</simpara></step> 4285 <step><simpara>Set (copy) input values in the allocated memory.</simpara></step> 4286 <step><simpara>Open a cursor with specifying the input SQLDA.</simpara></step> 4287 </procedure> 4288 4289 <para> 4290 Here is an example. 4291 </para> 4292 4293 <para> 4294 First, create a prepared statement. 4295<programlisting> 4296EXEC SQL BEGIN DECLARE SECTION; 4297char query[1024] = "SELECT d.oid, * FROM pg_database d, pg_stat_database s WHERE d.oid = s.datid AND (d.datname = ? OR d.oid = ?)"; 4298EXEC SQL END DECLARE SECTION; 4299 4300EXEC SQL PREPARE stmt1 FROM :query; 4301</programlisting> 4302 </para> 4303 4304 <para> 4305 Next, allocate memory for an SQLDA, and set the number of input 4306 parameters in <structfield>sqln</structfield>, a member variable of 4307 the <type>sqlda_t</type> structure. When two or more input 4308 parameters are required for the prepared query, the application 4309 has to allocate additional memory space which is calculated by 4310 (nr. of params - 1) * sizeof(sqlvar_t). The example shown here 4311 allocates memory space for two input parameters. 4312<programlisting> 4313sqlda_t *sqlda2; 4314 4315sqlda2 = (sqlda_t *) malloc(sizeof(sqlda_t) + sizeof(sqlvar_t)); 4316memset(sqlda2, 0, sizeof(sqlda_t) + sizeof(sqlvar_t)); 4317 4318sqlda2->sqln = 2; /* number of input variables */ 4319</programlisting> 4320 </para> 4321 4322 <para> 4323 After memory allocation, store the parameter values into the 4324 <literal>sqlvar[]</literal> array. (This is same array used for 4325 retrieving column values when the SQLDA is receiving a result 4326 set.) In this example, the input parameters 4327 are <literal>"postgres"</literal>, having a string type, 4328 and <literal>1</literal>, having an integer type. 4329<programlisting> 4330sqlda2->sqlvar[0].sqltype = ECPGt_char; 4331sqlda2->sqlvar[0].sqldata = "postgres"; 4332sqlda2->sqlvar[0].sqllen = 8; 4333 4334int intval = 1; 4335sqlda2->sqlvar[1].sqltype = ECPGt_int; 4336sqlda2->sqlvar[1].sqldata = (char *) &intval; 4337sqlda2->sqlvar[1].sqllen = sizeof(intval); 4338</programlisting> 4339 </para> 4340 4341 <para> 4342 By opening a cursor and specifying the SQLDA that was set up 4343 beforehand, the input parameters are passed to the prepared 4344 statement. 4345<programlisting> 4346EXEC SQL OPEN cur1 USING DESCRIPTOR sqlda2; 4347</programlisting> 4348 </para> 4349 4350 <para> 4351 Finally, after using input SQLDAs, the allocated memory space 4352 must be freed explicitly, unlike SQLDAs used for receiving query 4353 results. 4354<programlisting> 4355free(sqlda2); 4356</programlisting> 4357 </para> 4358 </sect3> 4359 4360 <sect3 id="ecpg-sqlda-example"> 4361 <title>A Sample Application Using SQLDA</title> 4362 4363 <para> 4364 Here is an example program, which describes how to fetch access 4365 statistics of the databases, specified by the input parameters, 4366 from the system catalogs. 4367 </para> 4368 4369 <para> 4370 This application joins two system tables, pg_database and 4371 pg_stat_database on the database OID, and also fetches and shows 4372 the database statistics which are retrieved by two input 4373 parameters (a database <literal>postgres</literal>, and OID <literal>1</literal>). 4374 </para> 4375 4376 <para> 4377 First, declare an SQLDA for input and an SQLDA for output. 4378<programlisting> 4379EXEC SQL include sqlda.h; 4380 4381sqlda_t *sqlda1; /* an output descriptor */ 4382sqlda_t *sqlda2; /* an input descriptor */ 4383</programlisting> 4384 </para> 4385 4386 <para> 4387 Next, connect to the database, prepare a statement, and declare a 4388 cursor for the prepared statement. 4389<programlisting> 4390int 4391main(void) 4392{ 4393 EXEC SQL BEGIN DECLARE SECTION; 4394 char query[1024] = "SELECT d.oid,* FROM pg_database d, pg_stat_database s WHERE d.oid=s.datid AND ( d.datname=? OR d.oid=? )"; 4395 EXEC SQL END DECLARE SECTION; 4396 4397 EXEC SQL CONNECT TO testdb AS con1 USER testuser; 4398 EXEC SQL SELECT pg_catalog.set_config('search_path', '', false); EXEC SQL COMMIT; 4399 4400 EXEC SQL PREPARE stmt1 FROM :query; 4401 EXEC SQL DECLARE cur1 CURSOR FOR stmt1; 4402</programlisting> 4403 </para> 4404 4405 <para> 4406 Next, put some values in the input SQLDA for the input 4407 parameters. Allocate memory for the input SQLDA, and set the 4408 number of input parameters to <literal>sqln</literal>. Store 4409 type, value, and value length into <literal>sqltype</literal>, 4410 <literal>sqldata</literal>, and <literal>sqllen</literal> in the 4411 <literal>sqlvar</literal> structure. 4412 4413<programlisting> 4414 /* Create SQLDA structure for input parameters. */ 4415 sqlda2 = (sqlda_t *) malloc(sizeof(sqlda_t) + sizeof(sqlvar_t)); 4416 memset(sqlda2, 0, sizeof(sqlda_t) + sizeof(sqlvar_t)); 4417 sqlda2->sqln = 2; /* number of input variables */ 4418 4419 sqlda2->sqlvar[0].sqltype = ECPGt_char; 4420 sqlda2->sqlvar[0].sqldata = "postgres"; 4421 sqlda2->sqlvar[0].sqllen = 8; 4422 4423 intval = 1; 4424 sqlda2->sqlvar[1].sqltype = ECPGt_int; 4425 sqlda2->sqlvar[1].sqldata = (char *)&intval; 4426 sqlda2->sqlvar[1].sqllen = sizeof(intval); 4427</programlisting> 4428 </para> 4429 4430 <para> 4431 After setting up the input SQLDA, open a cursor with the input 4432 SQLDA. 4433 4434<programlisting> 4435 /* Open a cursor with input parameters. */ 4436 EXEC SQL OPEN cur1 USING DESCRIPTOR sqlda2; 4437</programlisting> 4438 </para> 4439 4440 <para> 4441 Fetch rows into the output SQLDA from the opened cursor. 4442 (Generally, you have to call <command>FETCH</command> repeatedly 4443 in the loop, to fetch all rows in the result set.) 4444<programlisting> 4445 while (1) 4446 { 4447 sqlda_t *cur_sqlda; 4448 4449 /* Assign descriptor to the cursor */ 4450 EXEC SQL FETCH NEXT FROM cur1 INTO DESCRIPTOR sqlda1; 4451</programlisting> 4452 </para> 4453 4454 <para> 4455 Next, retrieve the fetched records from the SQLDA, by following 4456 the linked list of the <type>sqlda_t</type> structure. 4457<programlisting> 4458 for (cur_sqlda = sqlda1 ; 4459 cur_sqlda != NULL ; 4460 cur_sqlda = cur_sqlda->desc_next) 4461 { 4462 ... 4463</programlisting> 4464 </para> 4465 4466 <para> 4467 Read each columns in the first record. The number of columns is 4468 stored in <structfield>sqld</structfield>, the actual data of the first 4469 column is stored in <literal>sqlvar[0]</literal>, both members of 4470 the <type>sqlda_t</type> structure. 4471 4472<programlisting> 4473 /* Print every column in a row. */ 4474 for (i = 0; i < sqlda1->sqld; i++) 4475 { 4476 sqlvar_t v = sqlda1->sqlvar[i]; 4477 char *sqldata = v.sqldata; 4478 short sqllen = v.sqllen; 4479 4480 strncpy(name_buf, v.sqlname.data, v.sqlname.length); 4481 name_buf[v.sqlname.length] = '\0'; 4482</programlisting> 4483 </para> 4484 4485 <para> 4486 Now, the column data is stored in the variable <varname>v</varname>. 4487 Copy every datum into host variables, looking 4488 at <literal>v.sqltype</literal> for the type of the column. 4489<programlisting> 4490 switch (v.sqltype) { 4491 int intval; 4492 double doubleval; 4493 unsigned long long int longlongval; 4494 4495 case ECPGt_char: 4496 memset(&var_buf, 0, sizeof(var_buf)); 4497 memcpy(&var_buf, sqldata, (sizeof(var_buf) <= sqllen ? sizeof(var_buf)-1 : sqllen)); 4498 break; 4499 4500 case ECPGt_int: /* integer */ 4501 memcpy(&intval, sqldata, sqllen); 4502 snprintf(var_buf, sizeof(var_buf), "%d", intval); 4503 break; 4504 4505 ... 4506 4507 default: 4508 ... 4509 } 4510 4511 printf("%s = %s (type: %d)\n", name_buf, var_buf, v.sqltype); 4512 } 4513</programlisting> 4514 </para> 4515 4516 <para> 4517 Close the cursor after processing all of records, and disconnect 4518 from the database. 4519<programlisting> 4520 EXEC SQL CLOSE cur1; 4521 EXEC SQL COMMIT; 4522 4523 EXEC SQL DISCONNECT ALL; 4524</programlisting> 4525 </para> 4526 4527 <para> 4528 The whole program is shown 4529 in <xref linkend="ecpg-sqlda-example-example"/>. 4530 </para> 4531 4532 <example id="ecpg-sqlda-example-example"> 4533 <title>Example SQLDA Program</title> 4534<programlisting> 4535#include <stdlib.h> 4536#include <string.h> 4537#include <stdlib.h> 4538#include <stdio.h> 4539#include <unistd.h> 4540 4541EXEC SQL include sqlda.h; 4542 4543sqlda_t *sqlda1; /* descriptor for output */ 4544sqlda_t *sqlda2; /* descriptor for input */ 4545 4546EXEC SQL WHENEVER NOT FOUND DO BREAK; 4547EXEC SQL WHENEVER SQLERROR STOP; 4548 4549int 4550main(void) 4551{ 4552 EXEC SQL BEGIN DECLARE SECTION; 4553 char query[1024] = "SELECT d.oid,* FROM pg_database d, pg_stat_database s WHERE d.oid=s.datid AND ( d.datname=? OR d.oid=? )"; 4554 4555 int intval; 4556 unsigned long long int longlongval; 4557 EXEC SQL END DECLARE SECTION; 4558 4559 EXEC SQL CONNECT TO uptimedb AS con1 USER uptime; 4560 EXEC SQL SELECT pg_catalog.set_config('search_path', '', false); EXEC SQL COMMIT; 4561 4562 EXEC SQL PREPARE stmt1 FROM :query; 4563 EXEC SQL DECLARE cur1 CURSOR FOR stmt1; 4564 4565 /* Create a SQLDA structure for an input parameter */ 4566 sqlda2 = (sqlda_t *)malloc(sizeof(sqlda_t) + sizeof(sqlvar_t)); 4567 memset(sqlda2, 0, sizeof(sqlda_t) + sizeof(sqlvar_t)); 4568 sqlda2->sqln = 2; /* a number of input variables */ 4569 4570 sqlda2->sqlvar[0].sqltype = ECPGt_char; 4571 sqlda2->sqlvar[0].sqldata = "postgres"; 4572 sqlda2->sqlvar[0].sqllen = 8; 4573 4574 intval = 1; 4575 sqlda2->sqlvar[1].sqltype = ECPGt_int; 4576 sqlda2->sqlvar[1].sqldata = (char *) &intval; 4577 sqlda2->sqlvar[1].sqllen = sizeof(intval); 4578 4579 /* Open a cursor with input parameters. */ 4580 EXEC SQL OPEN cur1 USING DESCRIPTOR sqlda2; 4581 4582 while (1) 4583 { 4584 sqlda_t *cur_sqlda; 4585 4586 /* Assign descriptor to the cursor */ 4587 EXEC SQL FETCH NEXT FROM cur1 INTO DESCRIPTOR sqlda1; 4588 4589 for (cur_sqlda = sqlda1 ; 4590 cur_sqlda != NULL ; 4591 cur_sqlda = cur_sqlda->desc_next) 4592 { 4593 int i; 4594 char name_buf[1024]; 4595 char var_buf[1024]; 4596 4597 /* Print every column in a row. */ 4598 for (i=0 ; i<cur_sqlda->sqld ; i++) 4599 { 4600 sqlvar_t v = cur_sqlda->sqlvar[i]; 4601 char *sqldata = v.sqldata; 4602 short sqllen = v.sqllen; 4603 4604 strncpy(name_buf, v.sqlname.data, v.sqlname.length); 4605 name_buf[v.sqlname.length] = '\0'; 4606 4607 switch (v.sqltype) 4608 { 4609 case ECPGt_char: 4610 memset(&var_buf, 0, sizeof(var_buf)); 4611 memcpy(&var_buf, sqldata, (sizeof(var_buf)<=sqllen ? sizeof(var_buf)-1 : sqllen) ); 4612 break; 4613 4614 case ECPGt_int: /* integer */ 4615 memcpy(&intval, sqldata, sqllen); 4616 snprintf(var_buf, sizeof(var_buf), "%d", intval); 4617 break; 4618 4619 case ECPGt_long_long: /* bigint */ 4620 memcpy(&longlongval, sqldata, sqllen); 4621 snprintf(var_buf, sizeof(var_buf), "%lld", longlongval); 4622 break; 4623 4624 default: 4625 { 4626 int i; 4627 memset(var_buf, 0, sizeof(var_buf)); 4628 for (i = 0; i < sqllen; i++) 4629 { 4630 char tmpbuf[16]; 4631 snprintf(tmpbuf, sizeof(tmpbuf), "%02x ", (unsigned char) sqldata[i]); 4632 strncat(var_buf, tmpbuf, sizeof(var_buf)); 4633 } 4634 } 4635 break; 4636 } 4637 4638 printf("%s = %s (type: %d)\n", name_buf, var_buf, v.sqltype); 4639 } 4640 4641 printf("\n"); 4642 } 4643 } 4644 4645 EXEC SQL CLOSE cur1; 4646 EXEC SQL COMMIT; 4647 4648 EXEC SQL DISCONNECT ALL; 4649 4650 return 0; 4651} 4652</programlisting> 4653 4654 <para> 4655 The output of this example should look something like the 4656 following (some numbers will vary). 4657 </para> 4658 4659<screen> 4660oid = 1 (type: 1) 4661datname = template1 (type: 1) 4662datdba = 10 (type: 1) 4663encoding = 0 (type: 5) 4664datistemplate = t (type: 1) 4665datallowconn = t (type: 1) 4666datconnlimit = -1 (type: 5) 4667datlastsysoid = 11510 (type: 1) 4668datfrozenxid = 379 (type: 1) 4669dattablespace = 1663 (type: 1) 4670datconfig = (type: 1) 4671datacl = {=c/uptime,uptime=CTc/uptime} (type: 1) 4672datid = 1 (type: 1) 4673datname = template1 (type: 1) 4674numbackends = 0 (type: 5) 4675xact_commit = 113606 (type: 9) 4676xact_rollback = 0 (type: 9) 4677blks_read = 130 (type: 9) 4678blks_hit = 7341714 (type: 9) 4679tup_returned = 38262679 (type: 9) 4680tup_fetched = 1836281 (type: 9) 4681tup_inserted = 0 (type: 9) 4682tup_updated = 0 (type: 9) 4683tup_deleted = 0 (type: 9) 4684 4685oid = 11511 (type: 1) 4686datname = postgres (type: 1) 4687datdba = 10 (type: 1) 4688encoding = 0 (type: 5) 4689datistemplate = f (type: 1) 4690datallowconn = t (type: 1) 4691datconnlimit = -1 (type: 5) 4692datlastsysoid = 11510 (type: 1) 4693datfrozenxid = 379 (type: 1) 4694dattablespace = 1663 (type: 1) 4695datconfig = (type: 1) 4696datacl = (type: 1) 4697datid = 11511 (type: 1) 4698datname = postgres (type: 1) 4699numbackends = 0 (type: 5) 4700xact_commit = 221069 (type: 9) 4701xact_rollback = 18 (type: 9) 4702blks_read = 1176 (type: 9) 4703blks_hit = 13943750 (type: 9) 4704tup_returned = 77410091 (type: 9) 4705tup_fetched = 3253694 (type: 9) 4706tup_inserted = 0 (type: 9) 4707tup_updated = 0 (type: 9) 4708tup_deleted = 0 (type: 9) 4709</screen> 4710 </example> 4711 </sect3> 4712 </sect2> 4713 </sect1> 4714 4715 <sect1 id="ecpg-errors"> 4716 <title>Error Handling</title> 4717 4718 <para> 4719 This section describes how you can handle exceptional conditions 4720 and warnings in an embedded SQL program. There are two 4721 nonexclusive facilities for this. 4722 4723 <itemizedlist> 4724 <listitem> 4725 <simpara> 4726 Callbacks can be configured to handle warning and error 4727 conditions using the <literal>WHENEVER</literal> command. 4728 </simpara> 4729 </listitem> 4730 4731 <listitem> 4732 <simpara> 4733 Detailed information about the error or warning can be obtained 4734 from the <varname>sqlca</varname> variable. 4735 </simpara> 4736 </listitem> 4737 </itemizedlist> 4738 </para> 4739 4740 <sect2 id="ecpg-whenever"> 4741 <title>Setting Callbacks</title> 4742 4743 <para> 4744 One simple method to catch errors and warnings is to set a 4745 specific action to be executed whenever a particular condition 4746 occurs. In general: 4747<programlisting> 4748EXEC SQL WHENEVER <replaceable>condition</replaceable> <replaceable>action</replaceable>; 4749</programlisting> 4750 </para> 4751 4752 <para> 4753 <replaceable>condition</replaceable> can be one of the following: 4754 4755 <variablelist> 4756 <varlistentry> 4757 <term><literal>SQLERROR</literal></term> 4758 <listitem> 4759 <para> 4760 The specified action is called whenever an error occurs during 4761 the execution of an SQL statement. 4762 </para> 4763 </listitem> 4764 </varlistentry> 4765 4766 <varlistentry> 4767 <term><literal>SQLWARNING</literal></term> 4768 <listitem> 4769 <para> 4770 The specified action is called whenever a warning occurs 4771 during the execution of an SQL statement. 4772 </para> 4773 </listitem> 4774 </varlistentry> 4775 4776 <varlistentry> 4777 <term><literal>NOT FOUND</literal></term> 4778 <listitem> 4779 <para> 4780 The specified action is called whenever an SQL statement 4781 retrieves or affects zero rows. (This condition is not an 4782 error, but you might be interested in handling it specially.) 4783 </para> 4784 </listitem> 4785 </varlistentry> 4786 </variablelist> 4787 </para> 4788 4789 <para> 4790 <replaceable>action</replaceable> can be one of the following: 4791 4792 <variablelist> 4793 <varlistentry> 4794 <term><literal>CONTINUE</literal></term> 4795 <listitem> 4796 <para> 4797 This effectively means that the condition is ignored. This is 4798 the default. 4799 </para> 4800 </listitem> 4801 </varlistentry> 4802 4803 <varlistentry> 4804 <term><literal>GOTO <replaceable>label</replaceable></literal></term> 4805 <term><literal>GO TO <replaceable>label</replaceable></literal></term> 4806 <listitem> 4807 <para> 4808 Jump to the specified label (using a C <literal>goto</literal> 4809 statement). 4810 </para> 4811 </listitem> 4812 </varlistentry> 4813 4814 <varlistentry> 4815 <term><literal>SQLPRINT</literal></term> 4816 <listitem> 4817 <para> 4818 Print a message to standard error. This is useful for simple 4819 programs or during prototyping. The details of the message 4820 cannot be configured. 4821 </para> 4822 </listitem> 4823 </varlistentry> 4824 4825 <varlistentry> 4826 <term><literal>STOP</literal></term> 4827 <listitem> 4828 <para> 4829 Call <literal>exit(1)</literal>, which will terminate the 4830 program. 4831 </para> 4832 </listitem> 4833 </varlistentry> 4834 4835 <varlistentry> 4836 <term><literal>DO BREAK</literal></term> 4837 <listitem> 4838 <para> 4839 Execute the C statement <literal>break</literal>. This should 4840 only be used in loops or <literal>switch</literal> statements. 4841 </para> 4842 </listitem> 4843 </varlistentry> 4844 4845 <varlistentry> 4846 <term><literal>DO CONTINUE</literal></term> 4847 <listitem> 4848 <para> 4849 Execute the C statement <literal>continue</literal>. This should 4850 only be used in loops statements. if executed, will cause the flow 4851 of control to return to the top of the loop. 4852 </para> 4853 </listitem> 4854 </varlistentry> 4855 4856 <varlistentry> 4857 <term><literal>CALL <replaceable>name</replaceable> (<replaceable>args</replaceable>)</literal></term> 4858 <term><literal>DO <replaceable>name</replaceable> (<replaceable>args</replaceable>)</literal></term> 4859 <listitem> 4860 <para> 4861 Call the specified C functions with the specified arguments. (This 4862 use is different from the meaning of <literal>CALL</literal> 4863 and <literal>DO</literal> in the normal PostgreSQL grammar.) 4864 </para> 4865 </listitem> 4866 </varlistentry> 4867 </variablelist> 4868 4869 The SQL standard only provides for the actions 4870 <literal>CONTINUE</literal> and <literal>GOTO</literal> (and 4871 <literal>GO TO</literal>). 4872 </para> 4873 4874 <para> 4875 Here is an example that you might want to use in a simple program. 4876 It prints a simple message when a warning occurs and aborts the 4877 program when an error happens: 4878<programlisting> 4879EXEC SQL WHENEVER SQLWARNING SQLPRINT; 4880EXEC SQL WHENEVER SQLERROR STOP; 4881</programlisting> 4882 </para> 4883 4884 <para> 4885 The statement <literal>EXEC SQL WHENEVER</literal> is a directive 4886 of the SQL preprocessor, not a C statement. The error or warning 4887 actions that it sets apply to all embedded SQL statements that 4888 appear below the point where the handler is set, unless a 4889 different action was set for the same condition between the first 4890 <literal>EXEC SQL WHENEVER</literal> and the SQL statement causing 4891 the condition, regardless of the flow of control in the C program. 4892 So neither of the two following C program excerpts will have the 4893 desired effect: 4894<programlisting> 4895/* 4896 * WRONG 4897 */ 4898int main(int argc, char *argv[]) 4899{ 4900 ... 4901 if (verbose) { 4902 EXEC SQL WHENEVER SQLWARNING SQLPRINT; 4903 } 4904 ... 4905 EXEC SQL SELECT ...; 4906 ... 4907} 4908</programlisting> 4909 4910<programlisting> 4911/* 4912 * WRONG 4913 */ 4914int main(int argc, char *argv[]) 4915{ 4916 ... 4917 set_error_handler(); 4918 ... 4919 EXEC SQL SELECT ...; 4920 ... 4921} 4922 4923static void set_error_handler(void) 4924{ 4925 EXEC SQL WHENEVER SQLERROR STOP; 4926} 4927</programlisting> 4928 </para> 4929 </sect2> 4930 4931 <sect2 id="ecpg-sqlca"> 4932 <title>sqlca</title> 4933 4934 <para> 4935 For more powerful error handling, the embedded SQL interface 4936 provides a global variable with the name <varname>sqlca</varname> 4937 (SQL communication area) 4938 that has the following structure: 4939<programlisting> 4940struct 4941{ 4942 char sqlcaid[8]; 4943 long sqlabc; 4944 long sqlcode; 4945 struct 4946 { 4947 int sqlerrml; 4948 char sqlerrmc[SQLERRMC_LEN]; 4949 } sqlerrm; 4950 char sqlerrp[8]; 4951 long sqlerrd[6]; 4952 char sqlwarn[8]; 4953 char sqlstate[5]; 4954} sqlca; 4955</programlisting> 4956 (In a multithreaded program, every thread automatically gets its 4957 own copy of <varname>sqlca</varname>. This works similarly to the 4958 handling of the standard C global variable 4959 <varname>errno</varname>.) 4960 </para> 4961 4962 <para> 4963 <varname>sqlca</varname> covers both warnings and errors. If 4964 multiple warnings or errors occur during the execution of a 4965 statement, then <varname>sqlca</varname> will only contain 4966 information about the last one. 4967 </para> 4968 4969 <para> 4970 If no error occurred in the last <acronym>SQL</acronym> statement, 4971 <literal>sqlca.sqlcode</literal> will be 0 and 4972 <literal>sqlca.sqlstate</literal> will be 4973 <literal>"00000"</literal>. If a warning or error occurred, then 4974 <literal>sqlca.sqlcode</literal> will be negative and 4975 <literal>sqlca.sqlstate</literal> will be different from 4976 <literal>"00000"</literal>. A positive 4977 <literal>sqlca.sqlcode</literal> indicates a harmless condition, 4978 such as that the last query returned zero rows. 4979 <literal>sqlcode</literal> and <literal>sqlstate</literal> are two 4980 different error code schemes; details appear below. 4981 </para> 4982 4983 <para> 4984 If the last SQL statement was successful, then 4985 <literal>sqlca.sqlerrd[1]</literal> contains the OID of the 4986 processed row, if applicable, and 4987 <literal>sqlca.sqlerrd[2]</literal> contains the number of 4988 processed or returned rows, if applicable to the command. 4989 </para> 4990 4991 <para> 4992 In case of an error or warning, 4993 <literal>sqlca.sqlerrm.sqlerrmc</literal> will contain a string 4994 that describes the error. The field 4995 <literal>sqlca.sqlerrm.sqlerrml</literal> contains the length of 4996 the error message that is stored in 4997 <literal>sqlca.sqlerrm.sqlerrmc</literal> (the result of 4998 <function>strlen()</function>, not really interesting for a C 4999 programmer). Note that some messages are too long to fit in the 5000 fixed-size <literal>sqlerrmc</literal> array; they will be truncated. 5001 </para> 5002 5003 <para> 5004 In case of a warning, <literal>sqlca.sqlwarn[2]</literal> is set 5005 to <literal>W</literal>. (In all other cases, it is set to 5006 something different from <literal>W</literal>.) If 5007 <literal>sqlca.sqlwarn[1]</literal> is set to 5008 <literal>W</literal>, then a value was truncated when it was 5009 stored in a host variable. <literal>sqlca.sqlwarn[0]</literal> is 5010 set to <literal>W</literal> if any of the other elements are set 5011 to indicate a warning. 5012 </para> 5013 5014 <para> 5015 The fields <structfield>sqlcaid</structfield>, 5016 <structfield>sqlabc</structfield>, 5017 <structfield>sqlerrp</structfield>, and the remaining elements of 5018 <structfield>sqlerrd</structfield> and 5019 <structfield>sqlwarn</structfield> currently contain no useful 5020 information. 5021 </para> 5022 5023 <para> 5024 The structure <varname>sqlca</varname> is not defined in the SQL 5025 standard, but is implemented in several other SQL database 5026 systems. The definitions are similar at the core, but if you want 5027 to write portable applications, then you should investigate the 5028 different implementations carefully. 5029 </para> 5030 5031 <para> 5032 Here is one example that combines the use of <literal>WHENEVER</literal> 5033 and <varname>sqlca</varname>, printing out the contents 5034 of <varname>sqlca</varname> when an error occurs. This is perhaps 5035 useful for debugging or prototyping applications, before 5036 installing a more <quote>user-friendly</quote> error handler. 5037 5038<programlisting> 5039EXEC SQL WHENEVER SQLERROR CALL print_sqlca(); 5040 5041void 5042print_sqlca() 5043{ 5044 fprintf(stderr, "==== sqlca ====\n"); 5045 fprintf(stderr, "sqlcode: %ld\n", sqlca.sqlcode); 5046 fprintf(stderr, "sqlerrm.sqlerrml: %d\n", sqlca.sqlerrm.sqlerrml); 5047 fprintf(stderr, "sqlerrm.sqlerrmc: %s\n", sqlca.sqlerrm.sqlerrmc); 5048 fprintf(stderr, "sqlerrd: %ld %ld %ld %ld %ld %ld\n", sqlca.sqlerrd[0],sqlca.sqlerrd[1],sqlca.sqlerrd[2], 5049 sqlca.sqlerrd[3],sqlca.sqlerrd[4],sqlca.sqlerrd[5]); 5050 fprintf(stderr, "sqlwarn: %d %d %d %d %d %d %d %d\n", sqlca.sqlwarn[0], sqlca.sqlwarn[1], sqlca.sqlwarn[2], 5051 sqlca.sqlwarn[3], sqlca.sqlwarn[4], sqlca.sqlwarn[5], 5052 sqlca.sqlwarn[6], sqlca.sqlwarn[7]); 5053 fprintf(stderr, "sqlstate: %5s\n", sqlca.sqlstate); 5054 fprintf(stderr, "===============\n"); 5055} 5056</programlisting> 5057 5058 The result could look as follows (here an error due to a 5059 misspelled table name): 5060 5061<screen> 5062==== sqlca ==== 5063sqlcode: -400 5064sqlerrm.sqlerrml: 49 5065sqlerrm.sqlerrmc: relation "pg_databasep" does not exist on line 38 5066sqlerrd: 0 0 0 0 0 0 5067sqlwarn: 0 0 0 0 0 0 0 0 5068sqlstate: 42P01 5069=============== 5070</screen> 5071 </para> 5072 </sect2> 5073 5074 <sect2 id="ecpg-sqlstate-sqlcode"> 5075 <title><literal>SQLSTATE</literal> vs. <literal>SQLCODE</literal></title> 5076 5077 <para> 5078 The fields <literal>sqlca.sqlstate</literal> and 5079 <literal>sqlca.sqlcode</literal> are two different schemes that 5080 provide error codes. Both are derived from the SQL standard, but 5081 <literal>SQLCODE</literal> has been marked deprecated in the SQL-92 5082 edition of the standard and has been dropped in later editions. 5083 Therefore, new applications are strongly encouraged to use 5084 <literal>SQLSTATE</literal>. 5085 </para> 5086 5087 <para> 5088 <literal>SQLSTATE</literal> is a five-character array. The five 5089 characters contain digits or upper-case letters that represent 5090 codes of various error and warning conditions. 5091 <literal>SQLSTATE</literal> has a hierarchical scheme: the first 5092 two characters indicate the general class of the condition, the 5093 last three characters indicate a subclass of the general 5094 condition. A successful state is indicated by the code 5095 <literal>00000</literal>. The <literal>SQLSTATE</literal> codes are for 5096 the most part defined in the SQL standard. The 5097 <productname>PostgreSQL</productname> server natively supports 5098 <literal>SQLSTATE</literal> error codes; therefore a high degree 5099 of consistency can be achieved by using this error code scheme 5100 throughout all applications. For further information see 5101 <xref linkend="errcodes-appendix"/>. 5102 </para> 5103 5104 <para> 5105 <literal>SQLCODE</literal>, the deprecated error code scheme, is a 5106 simple integer. A value of 0 indicates success, a positive value 5107 indicates success with additional information, a negative value 5108 indicates an error. The SQL standard only defines the positive 5109 value +100, which indicates that the last command returned or 5110 affected zero rows, and no specific negative values. Therefore, 5111 this scheme can only achieve poor portability and does not have a 5112 hierarchical code assignment. Historically, the embedded SQL 5113 processor for <productname>PostgreSQL</productname> has assigned 5114 some specific <literal>SQLCODE</literal> values for its use, which 5115 are listed below with their numeric value and their symbolic name. 5116 Remember that these are not portable to other SQL implementations. 5117 To simplify the porting of applications to the 5118 <literal>SQLSTATE</literal> scheme, the corresponding 5119 <literal>SQLSTATE</literal> is also listed. There is, however, no 5120 one-to-one or one-to-many mapping between the two schemes (indeed 5121 it is many-to-many), so you should consult the global 5122 <literal>SQLSTATE</literal> listing in <xref linkend="errcodes-appendix"/> 5123 in each case. 5124 </para> 5125 5126 <para> 5127 These are the assigned <literal>SQLCODE</literal> values: 5128 5129 <variablelist> 5130 <varlistentry> 5131 <term>0 (<symbol>ECPG_NO_ERROR</symbol>)</term> 5132 <listitem> 5133 <para> 5134 Indicates no error. (SQLSTATE 00000) 5135 </para> 5136 </listitem> 5137 </varlistentry> 5138 5139 <varlistentry> 5140 <term>100 (<symbol>ECPG_NOT_FOUND</symbol>)</term> 5141 <listitem> 5142 <para> 5143 This is a harmless condition indicating that the last command 5144 retrieved or processed zero rows, or that you are at the end of 5145 the cursor. (SQLSTATE 02000) 5146 </para> 5147 5148 <para> 5149 When processing a cursor in a loop, you could use this code as 5150 a way to detect when to abort the loop, like this: 5151<programlisting> 5152while (1) 5153{ 5154 EXEC SQL FETCH ... ; 5155 if (sqlca.sqlcode == ECPG_NOT_FOUND) 5156 break; 5157} 5158</programlisting> 5159 But <literal>WHENEVER NOT FOUND DO BREAK</literal> effectively 5160 does this internally, so there is usually no advantage in 5161 writing this out explicitly. 5162 </para> 5163 </listitem> 5164 </varlistentry> 5165 5166 <varlistentry> 5167 <term>-12 (<symbol>ECPG_OUT_OF_MEMORY</symbol>)</term> 5168 <listitem> 5169 <para> 5170 Indicates that your virtual memory is exhausted. The numeric 5171 value is defined as <literal>-ENOMEM</literal>. (SQLSTATE 5172 YE001) 5173 </para> 5174 </listitem> 5175 </varlistentry> 5176 5177 <varlistentry> 5178 <term>-200 (<symbol>ECPG_UNSUPPORTED</symbol>)</term> 5179 <listitem> 5180 <para> 5181 Indicates the preprocessor has generated something that the 5182 library does not know about. Perhaps you are running 5183 incompatible versions of the preprocessor and the 5184 library. (SQLSTATE YE002) 5185 </para> 5186 </listitem> 5187 </varlistentry> 5188 5189 <varlistentry> 5190 <term>-201 (<symbol>ECPG_TOO_MANY_ARGUMENTS</symbol>)</term> 5191 <listitem> 5192 <para> 5193 This means that the command specified more host variables than 5194 the command expected. (SQLSTATE 07001 or 07002) 5195 </para> 5196 </listitem> 5197 </varlistentry> 5198 5199 <varlistentry> 5200 <term>-202 (<symbol>ECPG_TOO_FEW_ARGUMENTS</symbol>)</term> 5201 <listitem> 5202 <para> 5203 This means that the command specified fewer host variables than 5204 the command expected. (SQLSTATE 07001 or 07002) 5205 </para> 5206 </listitem> 5207 </varlistentry> 5208 5209 <varlistentry> 5210 <term>-203 (<symbol>ECPG_TOO_MANY_MATCHES</symbol>)</term> 5211 <listitem> 5212 <para> 5213 This means a query has returned multiple rows but the statement 5214 was only prepared to store one result row (for example, because 5215 the specified variables are not arrays). (SQLSTATE 21000) 5216 </para> 5217 </listitem> 5218 </varlistentry> 5219 5220 <varlistentry> 5221 <term>-204 (<symbol>ECPG_INT_FORMAT</symbol>)</term> 5222 <listitem> 5223 <para> 5224 The host variable is of type <type>int</type> and the datum in 5225 the database is of a different type and contains a value that 5226 cannot be interpreted as an <type>int</type>. The library uses 5227 <function>strtol()</function> for this conversion. (SQLSTATE 5228 42804) 5229 </para> 5230 </listitem> 5231 </varlistentry> 5232 5233 <varlistentry> 5234 <term>-205 (<symbol>ECPG_UINT_FORMAT</symbol>)</term> 5235 <listitem> 5236 <para> 5237 The host variable is of type <type>unsigned int</type> and the 5238 datum in the database is of a different type and contains a 5239 value that cannot be interpreted as an <type>unsigned 5240 int</type>. The library uses <function>strtoul()</function> 5241 for this conversion. (SQLSTATE 42804) 5242 </para> 5243 </listitem> 5244 </varlistentry> 5245 5246 <varlistentry> 5247 <term>-206 (<symbol>ECPG_FLOAT_FORMAT</symbol>)</term> 5248 <listitem> 5249 <para> 5250 The host variable is of type <type>float</type> and the datum 5251 in the database is of another type and contains a value that 5252 cannot be interpreted as a <type>float</type>. The library 5253 uses <function>strtod()</function> for this conversion. 5254 (SQLSTATE 42804) 5255 </para> 5256 </listitem> 5257 </varlistentry> 5258 5259 <varlistentry> 5260 <term>-207 (<symbol>ECPG_NUMERIC_FORMAT</symbol>)</term> 5261 <listitem> 5262 <para> 5263 The host variable is of type <type>numeric</type> and the datum 5264 in the database is of another type and contains a value that 5265 cannot be interpreted as a <type>numeric</type> value. 5266 (SQLSTATE 42804) 5267 </para> 5268 </listitem> 5269 </varlistentry> 5270 5271 <varlistentry> 5272 <term>-208 (<symbol>ECPG_INTERVAL_FORMAT</symbol>)</term> 5273 <listitem> 5274 <para> 5275 The host variable is of type <type>interval</type> and the datum 5276 in the database is of another type and contains a value that 5277 cannot be interpreted as an <type>interval</type> value. 5278 (SQLSTATE 42804) 5279 </para> 5280 </listitem> 5281 </varlistentry> 5282 5283 <varlistentry> 5284 <term>-209 (<symbol>ECPG_DATE_FORMAT</symbol>)</term> 5285 <listitem> 5286 <para> 5287 The host variable is of type <type>date</type> and the datum in 5288 the database is of another type and contains a value that 5289 cannot be interpreted as a <type>date</type> value. 5290 (SQLSTATE 42804) 5291 </para> 5292 </listitem> 5293 </varlistentry> 5294 5295 <varlistentry> 5296 <term>-210 (<symbol>ECPG_TIMESTAMP_FORMAT</symbol>)</term> 5297 <listitem> 5298 <para> 5299 The host variable is of type <type>timestamp</type> and the 5300 datum in the database is of another type and contains a value 5301 that cannot be interpreted as a <type>timestamp</type> value. 5302 (SQLSTATE 42804) 5303 </para> 5304 </listitem> 5305 </varlistentry> 5306 5307 <varlistentry> 5308 <term>-211 (<symbol>ECPG_CONVERT_BOOL</symbol>)</term> 5309 <listitem> 5310 <para> 5311 This means the host variable is of type <type>bool</type> and 5312 the datum in the database is neither <literal>'t'</literal> nor 5313 <literal>'f'</literal>. (SQLSTATE 42804) 5314 </para> 5315 </listitem> 5316 </varlistentry> 5317 5318 <varlistentry> 5319 <term>-212 (<symbol>ECPG_EMPTY</symbol>)</term> 5320 <listitem> 5321 <para> 5322 The statement sent to the <productname>PostgreSQL</productname> 5323 server was empty. (This cannot normally happen in an embedded 5324 SQL program, so it might point to an internal error.) (SQLSTATE 5325 YE002) 5326 </para> 5327 </listitem> 5328 </varlistentry> 5329 5330 <varlistentry> 5331 <term>-213 (<symbol>ECPG_MISSING_INDICATOR</symbol>)</term> 5332 <listitem> 5333 <para> 5334 A null value was returned and no null indicator variable was 5335 supplied. (SQLSTATE 22002) 5336 </para> 5337 </listitem> 5338 </varlistentry> 5339 5340 <varlistentry> 5341 <term>-214 (<symbol>ECPG_NO_ARRAY</symbol>)</term> 5342 <listitem> 5343 <para> 5344 An ordinary variable was used in a place that requires an 5345 array. (SQLSTATE 42804) 5346 </para> 5347 </listitem> 5348 </varlistentry> 5349 5350 <varlistentry> 5351 <term>-215 (<symbol>ECPG_DATA_NOT_ARRAY</symbol>)</term> 5352 <listitem> 5353 <para> 5354 The database returned an ordinary variable in a place that 5355 requires array value. (SQLSTATE 42804) 5356 </para> 5357 </listitem> 5358 </varlistentry> 5359 5360 <varlistentry> 5361 <term>-216 (<symbol>ECPG_ARRAY_INSERT</symbol>)</term> 5362 <listitem> 5363 <para> 5364 The value could not be inserted into the array. (SQLSTATE 5365 42804) 5366 </para> 5367 </listitem> 5368 </varlistentry> 5369 5370 <varlistentry> 5371 <term>-220 (<symbol>ECPG_NO_CONN</symbol>)</term> 5372 <listitem> 5373 <para> 5374 The program tried to access a connection that does not exist. 5375 (SQLSTATE 08003) 5376 </para> 5377 </listitem> 5378 </varlistentry> 5379 5380 <varlistentry> 5381 <term>-221 (<symbol>ECPG_NOT_CONN</symbol>)</term> 5382 <listitem> 5383 <para> 5384 The program tried to access a connection that does exist but is 5385 not open. (This is an internal error.) (SQLSTATE YE002) 5386 </para> 5387 </listitem> 5388 </varlistentry> 5389 5390 <varlistentry> 5391 <term>-230 (<symbol>ECPG_INVALID_STMT</symbol>)</term> 5392 <listitem> 5393 <para> 5394 The statement you are trying to use has not been prepared. 5395 (SQLSTATE 26000) 5396 </para> 5397 </listitem> 5398 </varlistentry> 5399 5400 <varlistentry> 5401 <term>-239 (<symbol>ECPG_INFORMIX_DUPLICATE_KEY</symbol>)</term> 5402 <listitem> 5403 <para> 5404 Duplicate key error, violation of unique constraint (Informix 5405 compatibility mode). (SQLSTATE 23505) 5406 </para> 5407 </listitem> 5408 </varlistentry> 5409 5410 <varlistentry> 5411 <term>-240 (<symbol>ECPG_UNKNOWN_DESCRIPTOR</symbol>)</term> 5412 <listitem> 5413 <para> 5414 The descriptor specified was not found. The statement you are 5415 trying to use has not been prepared. (SQLSTATE 33000) 5416 </para> 5417 </listitem> 5418 </varlistentry> 5419 5420 <varlistentry> 5421 <term>-241 (<symbol>ECPG_INVALID_DESCRIPTOR_INDEX</symbol>)</term> 5422 <listitem> 5423 <para> 5424 The descriptor index specified was out of range. (SQLSTATE 5425 07009) 5426 </para> 5427 </listitem> 5428 </varlistentry> 5429 5430 <varlistentry> 5431 <term>-242 (<symbol>ECPG_UNKNOWN_DESCRIPTOR_ITEM</symbol>)</term> 5432 <listitem> 5433 <para> 5434 An invalid descriptor item was requested. (This is an internal 5435 error.) (SQLSTATE YE002) 5436 </para> 5437 </listitem> 5438 </varlistentry> 5439 5440 <varlistentry> 5441 <term>-243 (<symbol>ECPG_VAR_NOT_NUMERIC</symbol>)</term> 5442 <listitem> 5443 <para> 5444 During the execution of a dynamic statement, the database 5445 returned a numeric value and the host variable was not numeric. 5446 (SQLSTATE 07006) 5447 </para> 5448 </listitem> 5449 </varlistentry> 5450 5451 <varlistentry> 5452 <term>-244 (<symbol>ECPG_VAR_NOT_CHAR</symbol>)</term> 5453 <listitem> 5454 <para> 5455 During the execution of a dynamic statement, the database 5456 returned a non-numeric value and the host variable was numeric. 5457 (SQLSTATE 07006) 5458 </para> 5459 </listitem> 5460 </varlistentry> 5461 5462 <varlistentry> 5463 <term>-284 (<symbol>ECPG_INFORMIX_SUBSELECT_NOT_ONE</symbol>)</term> 5464 <listitem> 5465 <para> 5466 A result of the subquery is not single row (Informix 5467 compatibility mode). (SQLSTATE 21000) 5468 </para> 5469 </listitem> 5470 </varlistentry> 5471 5472 <varlistentry> 5473 <term>-400 (<symbol>ECPG_PGSQL</symbol>)</term> 5474 <listitem> 5475 <para> 5476 Some error caused by the <productname>PostgreSQL</productname> 5477 server. The message contains the error message from the 5478 <productname>PostgreSQL</productname> server. 5479 </para> 5480 </listitem> 5481 </varlistentry> 5482 5483 <varlistentry> 5484 <term>-401 (<symbol>ECPG_TRANS</symbol>)</term> 5485 <listitem> 5486 <para> 5487 The <productname>PostgreSQL</productname> server signaled that 5488 we cannot start, commit, or rollback the transaction. 5489 (SQLSTATE 08007) 5490 </para> 5491 </listitem> 5492 </varlistentry> 5493 5494 <varlistentry> 5495 <term>-402 (<symbol>ECPG_CONNECT</symbol>)</term> 5496 <listitem> 5497 <para> 5498 The connection attempt to the database did not succeed. 5499 (SQLSTATE 08001) 5500 </para> 5501 </listitem> 5502 </varlistentry> 5503 5504 <varlistentry> 5505 <term>-403 (<symbol>ECPG_DUPLICATE_KEY</symbol>)</term> 5506 <listitem> 5507 <para> 5508 Duplicate key error, violation of unique constraint. (SQLSTATE 5509 23505) 5510 </para> 5511 </listitem> 5512 </varlistentry> 5513 5514 <varlistentry> 5515 <term>-404 (<symbol>ECPG_SUBSELECT_NOT_ONE</symbol>)</term> 5516 <listitem> 5517 <para> 5518 A result for the subquery is not single row. (SQLSTATE 21000) 5519 </para> 5520 </listitem> 5521 </varlistentry> 5522 5523 <!-- currently not used by the code --> 5524<!-- 5525 <varlistentry> 5526 <term>-600 (<symbol>ECPG_WARNING_UNRECOGNIZED</symbol>)</term> 5527 <listitem> 5528 <para> 5529 An unrecognized warning was received from the server. 5530 </para> 5531 </listitem> 5532 </varlistentry> 5533 5534 <varlistentry> 5535 <term>-601 (<symbol>ECPG_WARNING_QUERY_IGNORED</symbol>)</term> 5536 <listitem> 5537 <para> 5538 Current transaction is aborted. Queries are ignored until the 5539 end of the transaction block. 5540 </para> 5541 </listitem> 5542 </varlistentry> 5543--> 5544 5545 <varlistentry> 5546 <term>-602 (<symbol>ECPG_WARNING_UNKNOWN_PORTAL</symbol>)</term> 5547 <listitem> 5548 <para> 5549 An invalid cursor name was specified. (SQLSTATE 34000) 5550 </para> 5551 </listitem> 5552 </varlistentry> 5553 5554 <varlistentry> 5555 <term>-603 (<symbol>ECPG_WARNING_IN_TRANSACTION</symbol>)</term> 5556 <listitem> 5557 <para> 5558 Transaction is in progress. (SQLSTATE 25001) 5559 </para> 5560 </listitem> 5561 </varlistentry> 5562 5563 <varlistentry> 5564 <term>-604 (<symbol>ECPG_WARNING_NO_TRANSACTION</symbol>)</term> 5565 <listitem> 5566 <para> 5567 There is no active (in-progress) transaction. (SQLSTATE 25P01) 5568 </para> 5569 </listitem> 5570 </varlistentry> 5571 5572 <varlistentry> 5573 <term>-605 (<symbol>ECPG_WARNING_PORTAL_EXISTS</symbol>)</term> 5574 <listitem> 5575 <para> 5576 An existing cursor name was specified. (SQLSTATE 42P03) 5577 </para> 5578 </listitem> 5579 </varlistentry> 5580 5581 </variablelist> 5582 </para> 5583 </sect2> 5584 </sect1> 5585 5586 <sect1 id="ecpg-preproc"> 5587 <title>Preprocessor Directives</title> 5588 5589 <para> 5590 Several preprocessor directives are available that modify how 5591 the <command>ecpg</command> preprocessor parses and processes a 5592 file. 5593 </para> 5594 5595 <sect2 id="ecpg-include"> 5596 <title>Including Files</title> 5597 5598 <para> 5599 To include an external file into your embedded SQL program, use: 5600<programlisting> 5601EXEC SQL INCLUDE <replaceable>filename</replaceable>; 5602EXEC SQL INCLUDE <<replaceable>filename</replaceable>>; 5603EXEC SQL INCLUDE "<replaceable>filename</replaceable>"; 5604</programlisting> 5605 The embedded SQL preprocessor will look for a file named 5606 <literal><replaceable>filename</replaceable>.h</literal>, 5607 preprocess it, and include it in the resulting C output. Thus, 5608 embedded SQL statements in the included file are handled correctly. 5609 </para> 5610 5611 <para> 5612 The <command>ecpg</command> preprocessor will search a file at 5613 several directories in following order: 5614 5615 <itemizedlist> 5616 <listitem><simpara>current directory</simpara></listitem> 5617 <listitem><simpara><filename>/usr/local/include</filename></simpara></listitem> 5618 <listitem><simpara>PostgreSQL include directory, defined at build time (e.g., <filename>/usr/local/pgsql/include</filename>)</simpara></listitem> 5619 <listitem><simpara><filename>/usr/include</filename></simpara></listitem> 5620 </itemizedlist> 5621 5622 But when <literal>EXEC SQL INCLUDE 5623 "<replaceable>filename</replaceable>"</literal> is used, only the 5624 current directory is searched. 5625 </para> 5626 5627 <para> 5628 In each directory, the preprocessor will first look for the file 5629 name as given, and if not found will append <literal>.h</literal> 5630 to the file name and try again (unless the specified file name 5631 already has that suffix). 5632 </para> 5633 5634 <para> 5635 Note that <command>EXEC SQL INCLUDE</command> is <emphasis>not</emphasis> the same as: 5636<programlisting> 5637#include <<replaceable>filename</replaceable>.h> 5638</programlisting> 5639 because this file would not be subject to SQL command preprocessing. 5640 Naturally, you can continue to use the C 5641 <literal>#include</literal> directive to include other header 5642 files. 5643 </para> 5644 5645 <note> 5646 <para> 5647 The include file name is case-sensitive, even though the rest of 5648 the <literal>EXEC SQL INCLUDE</literal> command follows the normal 5649 SQL case-sensitivity rules. 5650 </para> 5651 </note> 5652 </sect2> 5653 5654 <sect2 id="ecpg-define"> 5655 <title>The define and undef Directives</title> 5656 <para> 5657 Similar to the directive <literal>#define</literal> that is known from C, 5658 embedded SQL has a similar concept: 5659<programlisting> 5660EXEC SQL DEFINE <replaceable>name</replaceable>; 5661EXEC SQL DEFINE <replaceable>name</replaceable> <replaceable>value</replaceable>; 5662</programlisting> 5663 So you can define a name: 5664<programlisting> 5665EXEC SQL DEFINE HAVE_FEATURE; 5666</programlisting> 5667 And you can also define constants: 5668<programlisting> 5669EXEC SQL DEFINE MYNUMBER 12; 5670EXEC SQL DEFINE MYSTRING 'abc'; 5671</programlisting> 5672 Use <literal>undef</literal> to remove a previous definition: 5673<programlisting> 5674EXEC SQL UNDEF MYNUMBER; 5675</programlisting> 5676 </para> 5677 5678 <para> 5679 Of course you can continue to use the C versions <literal>#define</literal> 5680 and <literal>#undef</literal> in your embedded SQL program. The difference 5681 is where your defined values get evaluated. If you use <literal>EXEC SQL 5682 DEFINE</literal> then the <command>ecpg</command> preprocessor evaluates the defines and substitutes 5683 the values. For example if you write: 5684<programlisting> 5685EXEC SQL DEFINE MYNUMBER 12; 5686... 5687EXEC SQL UPDATE Tbl SET col = MYNUMBER; 5688</programlisting> 5689 then <command>ecpg</command> will already do the substitution and your C compiler will never 5690 see any name or identifier <literal>MYNUMBER</literal>. Note that you cannot use 5691 <literal>#define</literal> for a constant that you are going to use in an 5692 embedded SQL query because in this case the embedded SQL precompiler is not 5693 able to see this declaration. 5694 </para> 5695 </sect2> 5696 5697 <sect2 id="ecpg-ifdef"> 5698 <title>ifdef, ifndef, else, elif, and endif Directives</title> 5699 <para> 5700 You can use the following directives to compile code sections conditionally: 5701 5702 <variablelist> 5703 <varlistentry> 5704 <term><literal>EXEC SQL ifdef <replaceable>name</replaceable>;</literal></term> 5705 <listitem> 5706 <para> 5707 Checks a <replaceable>name</replaceable> and processes subsequent lines if 5708 <replaceable>name</replaceable> has been created with <literal>EXEC SQL define 5709 <replaceable>name</replaceable></literal>. 5710 </para> 5711 </listitem> 5712 </varlistentry> 5713 5714 <varlistentry> 5715 <term><literal>EXEC SQL ifndef <replaceable>name</replaceable>;</literal></term> 5716 <listitem> 5717 <para> 5718 Checks a <replaceable>name</replaceable> and processes subsequent lines if 5719 <replaceable>name</replaceable> has <emphasis>not</emphasis> been created with 5720 <literal>EXEC SQL define <replaceable>name</replaceable></literal>. 5721 </para> 5722 </listitem> 5723 </varlistentry> 5724 5725 <varlistentry> 5726 <term><literal>EXEC SQL else;</literal></term> 5727 <listitem> 5728 <para> 5729 Starts processing an alternative section to a section introduced by 5730 either <literal>EXEC SQL ifdef <replaceable>name</replaceable></literal> or 5731 <literal>EXEC SQL ifndef <replaceable>name</replaceable></literal>. 5732 </para> 5733 </listitem> 5734 </varlistentry> 5735 5736 <varlistentry> 5737 <term><literal>EXEC SQL elif <replaceable>name</replaceable>;</literal></term> 5738 <listitem> 5739 <para> 5740 Checks <replaceable>name</replaceable> and starts an alternative section if 5741 <replaceable>name</replaceable> has been created with <literal>EXEC SQL define 5742 <replaceable>name</replaceable></literal>. 5743 </para> 5744 </listitem> 5745 </varlistentry> 5746 5747 <varlistentry> 5748 <term><literal>EXEC SQL endif;</literal></term> 5749 <listitem> 5750 <para> 5751 Ends an alternative section. 5752 </para> 5753 </listitem> 5754 </varlistentry> 5755 </variablelist> 5756 </para> 5757 5758 <para> 5759 Example: 5760<programlisting> 5761EXEC SQL ifndef TZVAR; 5762EXEC SQL SET TIMEZONE TO 'GMT'; 5763EXEC SQL elif TZNAME; 5764EXEC SQL SET TIMEZONE TO TZNAME; 5765EXEC SQL else; 5766EXEC SQL SET TIMEZONE TO TZVAR; 5767EXEC SQL endif; 5768</programlisting> 5769 </para> 5770 5771 </sect2> 5772 </sect1> 5773 5774 <sect1 id="ecpg-process"> 5775 <title>Processing Embedded SQL Programs</title> 5776 5777 <para> 5778 Now that you have an idea how to form embedded SQL C programs, you 5779 probably want to know how to compile them. Before compiling you 5780 run the file through the embedded <acronym>SQL</acronym> 5781 <acronym>C</acronym> preprocessor, which converts the 5782 <acronym>SQL</acronym> statements you used to special function 5783 calls. After compiling, you must link with a special library that 5784 contains the needed functions. These functions fetch information 5785 from the arguments, perform the <acronym>SQL</acronym> command using 5786 the <application>libpq</application> interface, and put the result 5787 in the arguments specified for output. 5788 </para> 5789 5790 <para> 5791 The preprocessor program is called <filename>ecpg</filename> and is 5792 included in a normal <productname>PostgreSQL</productname> installation. 5793 Embedded SQL programs are typically named with an extension 5794 <filename>.pgc</filename>. If you have a program file called 5795 <filename>prog1.pgc</filename>, you can preprocess it by simply 5796 calling: 5797<programlisting> 5798ecpg prog1.pgc 5799</programlisting> 5800 This will create a file called <filename>prog1.c</filename>. If 5801 your input files do not follow the suggested naming pattern, you 5802 can specify the output file explicitly using the 5803 <option>-o</option> option. 5804 </para> 5805 5806 <para> 5807 The preprocessed file can be compiled normally, for example: 5808<programlisting> 5809cc -c prog1.c 5810</programlisting> 5811 The generated C source files include header files from the 5812 <productname>PostgreSQL</productname> installation, so if you installed 5813 <productname>PostgreSQL</productname> in a location that is not searched by 5814 default, you have to add an option such as 5815 <literal>-I/usr/local/pgsql/include</literal> to the compilation 5816 command line. 5817 </para> 5818 5819 <para> 5820 To link an embedded SQL program, you need to include the 5821 <filename>libecpg</filename> library, like so: 5822<programlisting> 5823cc -o myprog prog1.o prog2.o ... -lecpg 5824</programlisting> 5825 Again, you might have to add an option like 5826 <literal>-L/usr/local/pgsql/lib</literal> to that command line. 5827 </para> 5828 5829 <para> 5830 You can 5831 use <command>pg_config</command><indexterm><primary>pg_config</primary><secondary sortas="ecpg">with 5832 ecpg</secondary></indexterm> 5833 or <command>pkg-config</command><indexterm><primary>pkg-config</primary><secondary sortas="ecpg">with 5834 ecpg</secondary></indexterm> with package name <literal>libecpg</literal> to 5835 get the paths for your installation. 5836 </para> 5837 5838 <para> 5839 If you manage the build process of a larger project using 5840 <application>make</application>, it might be convenient to include 5841 the following implicit rule to your makefiles: 5842<programlisting> 5843ECPG = ecpg 5844 5845%.c: %.pgc 5846 $(ECPG) $< 5847</programlisting> 5848 </para> 5849 5850 <para> 5851 The complete syntax of the <command>ecpg</command> command is 5852 detailed in <xref linkend="app-ecpg"/>. 5853 </para> 5854 5855 <para> 5856 The <application>ecpg</application> library is thread-safe by 5857 default. However, you might need to use some threading 5858 command-line options to compile your client code. 5859 </para> 5860 </sect1> 5861 5862 <sect1 id="ecpg-library"> 5863 <title>Library Functions</title> 5864 5865 <para> 5866 The <filename>libecpg</filename> library primarily contains 5867 <quote>hidden</quote> functions that are used to implement the 5868 functionality expressed by the embedded SQL commands. But there 5869 are some functions that can usefully be called directly. Note that 5870 this makes your code unportable. 5871 </para> 5872 5873 <itemizedlist> 5874 <listitem> 5875 <para> 5876 <function>ECPGdebug(int <replaceable>on</replaceable>, FILE 5877 *<replaceable>stream</replaceable>)</function> turns on debug 5878 logging if called with the first argument non-zero. Debug logging 5879 is done on <replaceable>stream</replaceable>. The log contains 5880 all <acronym>SQL</acronym> statements with all the input 5881 variables inserted, and the results from the 5882 <productname>PostgreSQL</productname> server. This can be very 5883 useful when searching for errors in your <acronym>SQL</acronym> 5884 statements. 5885 </para> 5886 <note> 5887 <para> 5888 On Windows, if the <application>ecpg</application> libraries and an application are 5889 compiled with different flags, this function call will crash the 5890 application because the internal representation of the 5891 <literal>FILE</literal> pointers differ. Specifically, 5892 multithreaded/single-threaded, release/debug, and static/dynamic 5893 flags should be the same for the library and all applications using 5894 that library. 5895 </para> 5896 </note> 5897 </listitem> 5898 5899 <listitem> 5900 <para> 5901 <function>ECPGget_PGconn(const char *<replaceable>connection_name</replaceable>) 5902 </function> returns the library database connection handle identified by the given name. 5903 If <replaceable>connection_name</replaceable> is set to <literal>NULL</literal>, the current 5904 connection handle is returned. If no connection handle can be identified, the function returns 5905 <literal>NULL</literal>. The returned connection handle can be used to call any other functions 5906 from <application>libpq</application>, if necessary. 5907 </para> 5908 <note> 5909 <para> 5910 It is a bad idea to manipulate database connection handles made from <application>ecpg</application> directly 5911 with <application>libpq</application> routines. 5912 </para> 5913 </note> 5914 </listitem> 5915 5916 <listitem> 5917 <para> 5918 <function>ECPGtransactionStatus(const char *<replaceable>connection_name</replaceable>)</function> 5919 returns the current transaction status of the given connection identified by <replaceable>connection_name</replaceable>. 5920 See <xref linkend="libpq-status"/> and libpq's <function>PQtransactionStatus()</function> for details about the returned status codes. 5921 </para> 5922 </listitem> 5923 5924 <listitem> 5925 <para> 5926 <function>ECPGstatus(int <replaceable>lineno</replaceable>, 5927 const char* <replaceable>connection_name</replaceable>)</function> 5928 returns true if you are connected to a database and false if not. 5929 <replaceable>connection_name</replaceable> can be <literal>NULL</literal> 5930 if a single connection is being used. 5931 </para> 5932 </listitem> 5933 </itemizedlist> 5934 </sect1> 5935 5936 <sect1 id="ecpg-lo"> 5937 <title>Large Objects</title> 5938 5939 <para> 5940 Large objects are not directly supported by ECPG, but ECPG 5941 application can manipulate large objects through the libpq large 5942 object functions, obtaining the necessary <type>PGconn</type> 5943 object by calling the <function>ECPGget_PGconn()</function> 5944 function. (However, use of 5945 the <function>ECPGget_PGconn()</function> function and touching 5946 <type>PGconn</type> objects directly should be done very carefully 5947 and ideally not mixed with other ECPG database access calls.) 5948 </para> 5949 5950 <para> 5951 For more details about the <function>ECPGget_PGconn()</function>, see 5952 <xref linkend="ecpg-library"/>. For information about the large 5953 object function interface, see <xref linkend="largeobjects"/>. 5954 </para> 5955 5956 <para> 5957 Large object functions have to be called in a transaction block, so 5958 when autocommit is off, <command>BEGIN</command> commands have to 5959 be issued explicitly. 5960 </para> 5961 5962 <para> 5963 <xref linkend="ecpg-lo-example"/> shows an example program that 5964 illustrates how to create, write, and read a large object in an 5965 ECPG application. 5966 </para> 5967 5968 <example id="ecpg-lo-example"> 5969 <title>ECPG Program Accessing Large Objects</title> 5970<programlisting><![CDATA[ 5971#include <stdio.h> 5972#include <stdlib.h> 5973#include <libpq-fe.h> 5974#include <libpq/libpq-fs.h> 5975 5976EXEC SQL WHENEVER SQLERROR STOP; 5977 5978int 5979main(void) 5980{ 5981 PGconn *conn; 5982 Oid loid; 5983 int fd; 5984 char buf[256]; 5985 int buflen = 256; 5986 char buf2[256]; 5987 int rc; 5988 5989 memset(buf, 1, buflen); 5990 5991 EXEC SQL CONNECT TO testdb AS con1; 5992 EXEC SQL SELECT pg_catalog.set_config('search_path', '', false); EXEC SQL COMMIT; 5993 5994 conn = ECPGget_PGconn("con1"); 5995 printf("conn = %p\n", conn); 5996 5997 /* create */ 5998 loid = lo_create(conn, 0); 5999 if (loid < 0) 6000 printf("lo_create() failed: %s", PQerrorMessage(conn)); 6001 6002 printf("loid = %d\n", loid); 6003 6004 /* write test */ 6005 fd = lo_open(conn, loid, INV_READ|INV_WRITE); 6006 if (fd < 0) 6007 printf("lo_open() failed: %s", PQerrorMessage(conn)); 6008 6009 printf("fd = %d\n", fd); 6010 6011 rc = lo_write(conn, fd, buf, buflen); 6012 if (rc < 0) 6013 printf("lo_write() failed\n"); 6014 6015 rc = lo_close(conn, fd); 6016 if (rc < 0) 6017 printf("lo_close() failed: %s", PQerrorMessage(conn)); 6018 6019 /* read test */ 6020 fd = lo_open(conn, loid, INV_READ); 6021 if (fd < 0) 6022 printf("lo_open() failed: %s", PQerrorMessage(conn)); 6023 6024 printf("fd = %d\n", fd); 6025 6026 rc = lo_read(conn, fd, buf2, buflen); 6027 if (rc < 0) 6028 printf("lo_read() failed\n"); 6029 6030 rc = lo_close(conn, fd); 6031 if (rc < 0) 6032 printf("lo_close() failed: %s", PQerrorMessage(conn)); 6033 6034 /* check */ 6035 rc = memcmp(buf, buf2, buflen); 6036 printf("memcmp() = %d\n", rc); 6037 6038 /* cleanup */ 6039 rc = lo_unlink(conn, loid); 6040 if (rc < 0) 6041 printf("lo_unlink() failed: %s", PQerrorMessage(conn)); 6042 6043 EXEC SQL COMMIT; 6044 EXEC SQL DISCONNECT ALL; 6045 return 0; 6046} 6047]]></programlisting> 6048 </example> 6049 </sect1> 6050 6051 <sect1 id="ecpg-cpp"> 6052 <title><acronym>C++</acronym> Applications</title> 6053 6054 <para> 6055 ECPG has some limited support for C++ applications. This section 6056 describes some caveats. 6057 </para> 6058 6059 <para> 6060 The <command>ecpg</command> preprocessor takes an input file 6061 written in C (or something like C) and embedded SQL commands, 6062 converts the embedded SQL commands into C language chunks, and 6063 finally generates a <filename>.c</filename> file. The header file 6064 declarations of the library functions used by the C language chunks 6065 that <command>ecpg</command> generates are wrapped 6066 in <literal>extern "C" { ... }</literal> blocks when used under 6067 C++, so they should work seamlessly in C++. 6068 </para> 6069 6070 <para> 6071 In general, however, the <command>ecpg</command> preprocessor only 6072 understands C; it does not handle the special syntax and reserved 6073 words of the C++ language. So, some embedded SQL code written in 6074 C++ application code that uses complicated features specific to C++ 6075 might fail to be preprocessed correctly or might not work as 6076 expected. 6077 </para> 6078 6079 <para> 6080 A safe way to use the embedded SQL code in a C++ application is 6081 hiding the ECPG calls in a C module, which the C++ application code 6082 calls into to access the database, and linking that together with 6083 the rest of the C++ code. See <xref linkend="ecpg-cpp-and-c"/> 6084 about that. 6085 </para> 6086 6087 <sect2 id="ecpg-cpp-scope"> 6088 <title>Scope for Host Variables</title> 6089 6090 <para> 6091 The <command>ecpg</command> preprocessor understands the scope of 6092 variables in C. In the C language, this is rather simple because 6093 the scopes of variables is based on their code blocks. In C++, 6094 however, the class member variables are referenced in a different 6095 code block from the declared position, so 6096 the <command>ecpg</command> preprocessor will not understand the 6097 scope of the class member variables. 6098 </para> 6099 6100 <para> 6101 For example, in the following case, the <command>ecpg</command> 6102 preprocessor cannot find any declaration for the 6103 variable <literal>dbname</literal> in the <literal>test</literal> 6104 method, so an error will occur. 6105 6106<programlisting> 6107class TestCpp 6108{ 6109 EXEC SQL BEGIN DECLARE SECTION; 6110 char dbname[1024]; 6111 EXEC SQL END DECLARE SECTION; 6112 6113 public: 6114 TestCpp(); 6115 void test(); 6116 ~TestCpp(); 6117}; 6118 6119TestCpp::TestCpp() 6120{ 6121 EXEC SQL CONNECT TO testdb1; 6122 EXEC SQL SELECT pg_catalog.set_config('search_path', '', false); EXEC SQL COMMIT; 6123} 6124 6125void Test::test() 6126{ 6127 EXEC SQL SELECT current_database() INTO :dbname; 6128 printf("current_database = %s\n", dbname); 6129} 6130 6131TestCpp::~TestCpp() 6132{ 6133 EXEC SQL DISCONNECT ALL; 6134} 6135</programlisting> 6136 6137 This code will result in an error like this: 6138<screen> 6139<userinput>ecpg test_cpp.pgc</userinput> 6140test_cpp.pgc:28: ERROR: variable "dbname" is not declared 6141</screen> 6142 </para> 6143 6144 <para> 6145 To avoid this scope issue, the <literal>test</literal> method 6146 could be modified to use a local variable as intermediate storage. 6147 But this approach is only a poor workaround, because it uglifies 6148 the code and reduces performance. 6149 6150<programlisting> 6151void TestCpp::test() 6152{ 6153 EXEC SQL BEGIN DECLARE SECTION; 6154 char tmp[1024]; 6155 EXEC SQL END DECLARE SECTION; 6156 6157 EXEC SQL SELECT current_database() INTO :tmp; 6158 strlcpy(dbname, tmp, sizeof(tmp)); 6159 6160 printf("current_database = %s\n", dbname); 6161} 6162</programlisting> 6163 </para> 6164 </sect2> 6165 6166 <sect2 id="ecpg-cpp-and-c"> 6167 <title>C++ Application Development with External C Module</title> 6168 6169 <para> 6170 If you understand these technical limitations of 6171 the <command>ecpg</command> preprocessor in C++, you might come to 6172 the conclusion that linking C objects and C++ objects at the link 6173 stage to enable C++ applications to use ECPG features could be 6174 better than writing some embedded SQL commands in C++ code 6175 directly. This section describes a way to separate some embedded 6176 SQL commands from C++ application code with a simple example. In 6177 this example, the application is implemented in C++, while C and 6178 ECPG is used to connect to the PostgreSQL server. 6179 </para> 6180 6181 <para> 6182 Three kinds of files have to be created: a C file 6183 (<filename>*.pgc</filename>), a header file, and a C++ file: 6184 6185 <variablelist> 6186 <varlistentry> 6187 <term><filename>test_mod.pgc</filename></term> 6188 <listitem> 6189 <para> 6190 A sub-routine module to execute SQL commands embedded in C. 6191 It is going to be converted 6192 into <filename>test_mod.c</filename> by the preprocessor. 6193 6194<programlisting> 6195#include "test_mod.h" 6196#include <stdio.h> 6197 6198void 6199db_connect() 6200{ 6201 EXEC SQL CONNECT TO testdb1; 6202 EXEC SQL SELECT pg_catalog.set_config('search_path', '', false); EXEC SQL COMMIT; 6203} 6204 6205void 6206db_test() 6207{ 6208 EXEC SQL BEGIN DECLARE SECTION; 6209 char dbname[1024]; 6210 EXEC SQL END DECLARE SECTION; 6211 6212 EXEC SQL SELECT current_database() INTO :dbname; 6213 printf("current_database = %s\n", dbname); 6214} 6215 6216void 6217db_disconnect() 6218{ 6219 EXEC SQL DISCONNECT ALL; 6220} 6221</programlisting> 6222 </para> 6223 </listitem> 6224 </varlistentry> 6225 6226 <varlistentry> 6227 <term><filename>test_mod.h</filename></term> 6228 <listitem> 6229 <para> 6230 A header file with declarations of the functions in the C 6231 module (<filename>test_mod.pgc</filename>). It is included by 6232 <filename>test_cpp.cpp</filename>. This file has to have an 6233 <literal>extern "C"</literal> block around the declarations, 6234 because it will be linked from the C++ module. 6235 6236<programlisting> 6237#ifdef __cplusplus 6238extern "C" { 6239#endif 6240 6241void db_connect(); 6242void db_test(); 6243void db_disconnect(); 6244 6245#ifdef __cplusplus 6246} 6247#endif 6248</programlisting> 6249 </para> 6250 </listitem> 6251 </varlistentry> 6252 6253 <varlistentry> 6254 <term><filename>test_cpp.cpp</filename></term> 6255 <listitem> 6256 <para> 6257 The main code for the application, including 6258 the <function>main</function> routine, and in this example a 6259 C++ class. 6260 6261<programlisting> 6262#include "test_mod.h" 6263 6264class TestCpp 6265{ 6266 public: 6267 TestCpp(); 6268 void test(); 6269 ~TestCpp(); 6270}; 6271 6272TestCpp::TestCpp() 6273{ 6274 db_connect(); 6275} 6276 6277void 6278TestCpp::test() 6279{ 6280 db_test(); 6281} 6282 6283TestCpp::~TestCpp() 6284{ 6285 db_disconnect(); 6286} 6287 6288int 6289main(void) 6290{ 6291 TestCpp *t = new TestCpp(); 6292 6293 t->test(); 6294 return 0; 6295} 6296</programlisting> 6297 </para> 6298 </listitem> 6299 </varlistentry> 6300 </variablelist> 6301 </para> 6302 6303 <para> 6304 To build the application, proceed as follows. Convert 6305 <filename>test_mod.pgc</filename> into <filename>test_mod.c</filename> by 6306 running <command>ecpg</command>, and generate 6307 <filename>test_mod.o</filename> by compiling 6308 <filename>test_mod.c</filename> with the C compiler: 6309<programlisting> 6310ecpg -o test_mod.c test_mod.pgc 6311cc -c test_mod.c -o test_mod.o 6312</programlisting> 6313 </para> 6314 6315 <para> 6316 Next, generate <filename>test_cpp.o</filename> by compiling 6317 <filename>test_cpp.cpp</filename> with the C++ compiler: 6318<programlisting> 6319c++ -c test_cpp.cpp -o test_cpp.o 6320</programlisting> 6321 </para> 6322 6323 <para> 6324 Finally, link these object files, <filename>test_cpp.o</filename> 6325 and <filename>test_mod.o</filename>, into one executable, using the C++ 6326 compiler driver: 6327<programlisting> 6328c++ test_cpp.o test_mod.o -lecpg -o test_cpp 6329</programlisting> 6330 </para> 6331 </sect2> 6332 </sect1> 6333 6334 <sect1 id="ecpg-sql-commands"> 6335 <title>Embedded SQL Commands</title> 6336 6337 <para> 6338 This section describes all SQL commands that are specific to 6339 embedded SQL. Also refer to the SQL commands listed 6340 in <xref linkend="sql-commands"/>, which can also be used in 6341 embedded SQL, unless stated otherwise. 6342 </para> 6343 6344 <refentry id="ecpg-sql-allocate-descriptor"> 6345 <refnamediv> 6346 <refname>ALLOCATE DESCRIPTOR</refname> 6347 <refpurpose>allocate an SQL descriptor area</refpurpose> 6348 </refnamediv> 6349 6350 <refsynopsisdiv> 6351<synopsis> 6352ALLOCATE DESCRIPTOR <replaceable class="parameter">name</replaceable> 6353</synopsis> 6354 </refsynopsisdiv> 6355 6356 <refsect1> 6357 <title>Description</title> 6358 6359 <para> 6360 <command>ALLOCATE DESCRIPTOR</command> allocates a new named SQL 6361 descriptor area, which can be used to exchange data between the 6362 PostgreSQL server and the host program. 6363 </para> 6364 6365 <para> 6366 Descriptor areas should be freed after use using 6367 the <command>DEALLOCATE DESCRIPTOR</command> command. 6368 </para> 6369 </refsect1> 6370 6371 <refsect1> 6372 <title>Parameters</title> 6373 6374 <variablelist> 6375 <varlistentry> 6376 <term><replaceable class="parameter">name</replaceable></term> 6377 <listitem> 6378 <para> 6379 A name of SQL descriptor, case sensitive. This can be an SQL 6380 identifier or a host variable. 6381 </para> 6382 </listitem> 6383 </varlistentry> 6384 </variablelist> 6385 </refsect1> 6386 6387 <refsect1> 6388 <title>Examples</title> 6389 6390<programlisting> 6391EXEC SQL ALLOCATE DESCRIPTOR mydesc; 6392</programlisting> 6393 </refsect1> 6394 6395 <refsect1> 6396 <title>Compatibility</title> 6397 6398 <para> 6399 <command>ALLOCATE DESCRIPTOR</command> is specified in the SQL 6400 standard. 6401 </para> 6402 </refsect1> 6403 6404 <refsect1> 6405 <title>See Also</title> 6406 6407 <simplelist type="inline"> 6408 <member><xref linkend="ecpg-sql-deallocate-descriptor"/></member> 6409 <member><xref linkend="ecpg-sql-get-descriptor"/></member> 6410 <member><xref linkend="ecpg-sql-set-descriptor"/></member> 6411 </simplelist> 6412 </refsect1> 6413 </refentry> 6414 6415 <refentry id="ecpg-sql-connect"> 6416 <refnamediv> 6417 <refname>CONNECT</refname> 6418 <refpurpose>establish a database connection</refpurpose> 6419 </refnamediv> 6420 6421 <refsynopsisdiv> 6422<synopsis> 6423CONNECT TO <replaceable>connection_target</replaceable> [ AS <replaceable>connection_name</replaceable> ] [ USER <replaceable>connection_user</replaceable> ] 6424CONNECT TO DEFAULT 6425CONNECT <replaceable>connection_user</replaceable> 6426DATABASE <replaceable>connection_target</replaceable> 6427</synopsis> 6428 </refsynopsisdiv> 6429 6430 <refsect1> 6431 <title>Description</title> 6432 6433 <para> 6434 The <command>CONNECT</command> command establishes a connection 6435 between the client and the PostgreSQL server. 6436 </para> 6437 </refsect1> 6438 6439 <refsect1> 6440 <title>Parameters</title> 6441 6442 <variablelist> 6443 <varlistentry> 6444 <term><replaceable class="parameter">connection_target</replaceable></term> 6445 <listitem> 6446 <para> 6447 <replaceable class="parameter">connection_target</replaceable> 6448 specifies the target server of the connection on one of 6449 several forms. 6450 6451 <variablelist> 6452 <varlistentry> 6453 <term>[ <replaceable>database_name</replaceable> ] [ <literal>@</literal><replaceable>host</replaceable> ] [ <literal>:</literal><replaceable>port</replaceable> ]</term> 6454 <listitem> 6455 <para> 6456 Connect over TCP/IP 6457 </para> 6458 </listitem> 6459 </varlistentry> 6460 6461 <varlistentry> 6462 <term><literal>unix:postgresql://</literal><replaceable>host</replaceable> [ <literal>:</literal><replaceable>port</replaceable> ] <literal>/</literal> [ <replaceable>database_name</replaceable> ] [ <literal>?</literal><replaceable>connection_option</replaceable> ]</term> 6463 <listitem> 6464 <para> 6465 Connect over Unix-domain sockets 6466 </para> 6467 </listitem> 6468 </varlistentry> 6469 6470 <varlistentry> 6471 <term><literal>tcp:postgresql://</literal><replaceable>host</replaceable> [ <literal>:</literal><replaceable>port</replaceable> ] <literal>/</literal> [ <replaceable>database_name</replaceable> ] [ <literal>?</literal><replaceable>connection_option</replaceable> ]</term> 6472 <listitem> 6473 <para> 6474 Connect over TCP/IP 6475 </para> 6476 </listitem> 6477 </varlistentry> 6478 6479 <varlistentry> 6480 <term>SQL string constant</term> 6481 <listitem> 6482 <para> 6483 containing a value in one of the above forms 6484 </para> 6485 </listitem> 6486 </varlistentry> 6487 6488 <varlistentry> 6489 <term>host variable</term> 6490 <listitem> 6491 <para> 6492 host variable of type <type>char[]</type> 6493 or <type>VARCHAR[]</type> containing a value in one of the 6494 above forms 6495 </para> 6496 </listitem> 6497 </varlistentry> 6498 </variablelist> 6499 </para> 6500 </listitem> 6501 </varlistentry> 6502 6503 <varlistentry> 6504 <term><replaceable class="parameter">connection_name</replaceable></term> 6505 <listitem> 6506 <para> 6507 An optional identifier for the connection, so that it can be 6508 referred to in other commands. This can be an SQL identifier 6509 or a host variable. 6510 </para> 6511 </listitem> 6512 </varlistentry> 6513 6514 <varlistentry> 6515 <term><replaceable class="parameter">connection_user</replaceable></term> 6516 <listitem> 6517 <para> 6518 The user name for the database connection. 6519 </para> 6520 6521 <para> 6522 This parameter can also specify user name and password, using one the forms 6523 <literal><replaceable>user_name</replaceable>/<replaceable>password</replaceable></literal>, 6524 <literal><replaceable>user_name</replaceable> IDENTIFIED BY <replaceable>password</replaceable></literal>, or 6525 <literal><replaceable>user_name</replaceable> USING <replaceable>password</replaceable></literal>. 6526 </para> 6527 6528 <para> 6529 User name and password can be SQL identifiers, string 6530 constants, or host variables. 6531 </para> 6532 </listitem> 6533 </varlistentry> 6534 6535 <varlistentry> 6536 <term><literal>DEFAULT</literal></term> 6537 <listitem> 6538 <para> 6539 Use all default connection parameters, as defined by libpq. 6540 </para> 6541 </listitem> 6542 </varlistentry> 6543 </variablelist> 6544 </refsect1> 6545 6546 <refsect1> 6547 <title>Examples</title> 6548 6549 <para> 6550 Here a several variants for specifying connection parameters: 6551<programlisting> 6552EXEC SQL CONNECT TO "connectdb" AS main; 6553EXEC SQL CONNECT TO "connectdb" AS second; 6554EXEC SQL CONNECT TO "unix:postgresql://200.46.204.71/connectdb" AS main USER connectuser; 6555EXEC SQL CONNECT TO "unix:postgresql://localhost/connectdb" AS main USER connectuser; 6556EXEC SQL CONNECT TO 'connectdb' AS main; 6557EXEC SQL CONNECT TO 'unix:postgresql://localhost/connectdb' AS main USER :user; 6558EXEC SQL CONNECT TO :db AS :id; 6559EXEC SQL CONNECT TO :db USER connectuser USING :pw; 6560EXEC SQL CONNECT TO @localhost AS main USER connectdb; 6561EXEC SQL CONNECT TO REGRESSDB1 as main; 6562EXEC SQL CONNECT TO AS main USER connectdb; 6563EXEC SQL CONNECT TO connectdb AS :id; 6564EXEC SQL CONNECT TO connectdb AS main USER connectuser/connectdb; 6565EXEC SQL CONNECT TO connectdb AS main; 6566EXEC SQL CONNECT TO connectdb@localhost AS main; 6567EXEC SQL CONNECT TO tcp:postgresql://localhost/ USER connectdb; 6568EXEC SQL CONNECT TO tcp:postgresql://localhost/connectdb USER connectuser IDENTIFIED BY connectpw; 6569EXEC SQL CONNECT TO tcp:postgresql://localhost:20/connectdb USER connectuser IDENTIFIED BY connectpw; 6570EXEC SQL CONNECT TO unix:postgresql://localhost/ AS main USER connectdb; 6571EXEC SQL CONNECT TO unix:postgresql://localhost/connectdb AS main USER connectuser; 6572EXEC SQL CONNECT TO unix:postgresql://localhost/connectdb USER connectuser IDENTIFIED BY "connectpw"; 6573EXEC SQL CONNECT TO unix:postgresql://localhost/connectdb USER connectuser USING "connectpw"; 6574EXEC SQL CONNECT TO unix:postgresql://localhost/connectdb?connect_timeout=14 USER connectuser; 6575</programlisting> 6576 </para> 6577 6578 <para> 6579 Here is an example program that illustrates the use of host 6580 variables to specify connection parameters: 6581<programlisting> 6582int 6583main(void) 6584{ 6585EXEC SQL BEGIN DECLARE SECTION; 6586 char *dbname = "testdb"; /* database name */ 6587 char *user = "testuser"; /* connection user name */ 6588 char *connection = "tcp:postgresql://localhost:5432/testdb"; 6589 /* connection string */ 6590 char ver[256]; /* buffer to store the version string */ 6591EXEC SQL END DECLARE SECTION; 6592 6593 ECPGdebug(1, stderr); 6594 6595 EXEC SQL CONNECT TO :dbname USER :user; 6596 EXEC SQL SELECT pg_catalog.set_config('search_path', '', false); EXEC SQL COMMIT; 6597 EXEC SQL SELECT version() INTO :ver; 6598 EXEC SQL DISCONNECT; 6599 6600 printf("version: %s\n", ver); 6601 6602 EXEC SQL CONNECT TO :connection USER :user; 6603 EXEC SQL SELECT pg_catalog.set_config('search_path', '', false); EXEC SQL COMMIT; 6604 EXEC SQL SELECT version() INTO :ver; 6605 EXEC SQL DISCONNECT; 6606 6607 printf("version: %s\n", ver); 6608 6609 return 0; 6610} 6611</programlisting> 6612 </para> 6613 </refsect1> 6614 6615 <refsect1> 6616 <title>Compatibility</title> 6617 6618 <para> 6619 <command>CONNECT</command> is specified in the SQL standard, but 6620 the format of the connection parameters is 6621 implementation-specific. 6622 </para> 6623 </refsect1> 6624 6625 <refsect1> 6626 <title>See Also</title> 6627 6628 <simplelist type="inline"> 6629 <member><xref linkend="ecpg-sql-disconnect"/></member> 6630 <member><xref linkend="ecpg-sql-set-connection"/></member> 6631 </simplelist> 6632 </refsect1> 6633 </refentry> 6634 6635 <refentry id="ecpg-sql-deallocate-descriptor"> 6636 <refnamediv> 6637 <refname>DEALLOCATE DESCRIPTOR</refname> 6638 <refpurpose>deallocate an SQL descriptor area</refpurpose> 6639 </refnamediv> 6640 6641 <refsynopsisdiv> 6642<synopsis> 6643DEALLOCATE DESCRIPTOR <replaceable class="parameter">name</replaceable> 6644</synopsis> 6645 </refsynopsisdiv> 6646 6647 <refsect1> 6648 <title>Description</title> 6649 6650 <para> 6651 <command>DEALLOCATE DESCRIPTOR</command> deallocates a named SQL 6652 descriptor area. 6653 </para> 6654 </refsect1> 6655 6656 <refsect1> 6657 <title>Parameters</title> 6658 6659 <variablelist> 6660 <varlistentry> 6661 <term><replaceable class="parameter">name</replaceable></term> 6662 <listitem> 6663 <para> 6664 The name of the descriptor which is going to be deallocated. 6665 It is case sensitive. This can be an SQL identifier or a host 6666 variable. 6667 </para> 6668 </listitem> 6669 </varlistentry> 6670 </variablelist> 6671 </refsect1> 6672 6673 <refsect1> 6674 <title>Examples</title> 6675 6676<programlisting> 6677EXEC SQL DEALLOCATE DESCRIPTOR mydesc; 6678</programlisting> 6679 </refsect1> 6680 6681 <refsect1> 6682 <title>Compatibility</title> 6683 6684 <para> 6685 <command>DEALLOCATE DESCRIPTOR</command> is specified in the SQL 6686 standard. 6687 </para> 6688 </refsect1> 6689 6690 <refsect1> 6691 <title>See Also</title> 6692 6693 <simplelist type="inline"> 6694 <member><xref linkend="ecpg-sql-allocate-descriptor"/></member> 6695 <member><xref linkend="ecpg-sql-get-descriptor"/></member> 6696 <member><xref linkend="ecpg-sql-set-descriptor"/></member> 6697 </simplelist> 6698 </refsect1> 6699 </refentry> 6700 6701 <refentry id="ecpg-sql-declare"> 6702 <refnamediv> 6703 <refname>DECLARE</refname> 6704 <refpurpose>define a cursor</refpurpose> 6705 </refnamediv> 6706 6707 <refsynopsisdiv> 6708<synopsis> 6709DECLARE <replaceable class="parameter">cursor_name</replaceable> [ BINARY ] [ INSENSITIVE ] [ [ NO ] SCROLL ] CURSOR [ { WITH | WITHOUT } HOLD ] FOR <replaceable class="parameter">prepared_name</replaceable> 6710DECLARE <replaceable class="parameter">cursor_name</replaceable> [ BINARY ] [ INSENSITIVE ] [ [ NO ] SCROLL ] CURSOR [ { WITH | WITHOUT } HOLD ] FOR <replaceable class="parameter">query</replaceable> 6711</synopsis> 6712 </refsynopsisdiv> 6713 6714 <refsect1> 6715 <title>Description</title> 6716 6717 <para> 6718 <command>DECLARE</command> declares a cursor for iterating over 6719 the result set of a prepared statement. This command has 6720 slightly different semantics from the direct SQL 6721 command <command>DECLARE</command>: Whereas the latter executes a 6722 query and prepares the result set for retrieval, this embedded 6723 SQL command merely declares a name as a <quote>loop 6724 variable</quote> for iterating over the result set of a query; 6725 the actual execution happens when the cursor is opened with 6726 the <command>OPEN</command> command. 6727 </para> 6728 </refsect1> 6729 6730 <refsect1> 6731 <title>Parameters</title> 6732 <variablelist> 6733 6734 <varlistentry> 6735 <term><replaceable class="parameter">cursor_name</replaceable></term> 6736 <listitem> 6737 <para> 6738 A cursor name, case sensitive. This can be an SQL identifier 6739 or a host variable. 6740 </para> 6741 </listitem> 6742 </varlistentry> 6743 6744 <varlistentry> 6745 <term><replaceable class="parameter">prepared_name</replaceable></term> 6746 <listitem> 6747 <para> 6748 The name of a prepared query, either as an SQL identifier or a 6749 host variable. 6750 </para> 6751 </listitem> 6752 </varlistentry> 6753 6754 <varlistentry> 6755 <term><replaceable class="parameter">query</replaceable></term> 6756 <listitem> 6757 <para> 6758 A <xref linkend="sql-select"/> or 6759 <xref linkend="sql-values"/> command which will provide the 6760 rows to be returned by the cursor. 6761 </para> 6762 </listitem> 6763 </varlistentry> 6764 </variablelist> 6765 6766 <para> 6767 For the meaning of the cursor options, 6768 see <xref linkend="sql-declare"/>. 6769 </para> 6770 </refsect1> 6771 6772 <refsect1> 6773 <title>Examples</title> 6774 6775 <para> 6776 Examples declaring a cursor for a query: 6777<programlisting> 6778EXEC SQL DECLARE C CURSOR FOR SELECT * FROM My_Table; 6779EXEC SQL DECLARE C CURSOR FOR SELECT Item1 FROM T; 6780EXEC SQL DECLARE cur1 CURSOR FOR SELECT version(); 6781</programlisting> 6782 </para> 6783 6784 <para> 6785 An example declaring a cursor for a prepared statement: 6786<programlisting> 6787EXEC SQL PREPARE stmt1 AS SELECT version(); 6788EXEC SQL DECLARE cur1 CURSOR FOR stmt1; 6789</programlisting> 6790 </para> 6791 </refsect1> 6792 6793 <refsect1> 6794 <title>Compatibility</title> 6795 6796 <para> 6797 <command>DECLARE</command> is specified in the SQL standard. 6798 </para> 6799 </refsect1> 6800 6801 <refsect1> 6802 <title>See Also</title> 6803 6804 <simplelist type="inline"> 6805 <member><xref linkend="ecpg-sql-open"/></member> 6806 <member><xref linkend="sql-close"/></member> 6807 <member><xref linkend="sql-declare"/></member> 6808 </simplelist> 6809 </refsect1> 6810 </refentry> 6811 6812 <refentry id="ecpg-sql-describe"> 6813 <refnamediv> 6814 <refname>DESCRIBE</refname> 6815 <refpurpose>obtain information about a prepared statement or result set</refpurpose> 6816 </refnamediv> 6817 6818 <refsynopsisdiv> 6819<synopsis> 6820DESCRIBE [ OUTPUT ] <replaceable class="parameter">prepared_name</replaceable> USING [ SQL ] DESCRIPTOR <replaceable class="parameter">descriptor_name</replaceable> 6821DESCRIBE [ OUTPUT ] <replaceable class="parameter">prepared_name</replaceable> INTO [ SQL ] DESCRIPTOR <replaceable class="parameter">descriptor_name</replaceable> 6822DESCRIBE [ OUTPUT ] <replaceable class="parameter">prepared_name</replaceable> INTO <replaceable class="parameter">sqlda_name</replaceable> 6823</synopsis> 6824 </refsynopsisdiv> 6825 6826 <refsect1> 6827 <title>Description</title> 6828 6829 <para> 6830 <command>DESCRIBE</command> retrieves metadata information about 6831 the result columns contained in a prepared statement, without 6832 actually fetching a row. 6833 </para> 6834 </refsect1> 6835 6836 <refsect1> 6837 <title>Parameters</title> 6838 6839 <variablelist> 6840 <varlistentry> 6841 <term><replaceable class="parameter">prepared_name</replaceable></term> 6842 <listitem> 6843 <para> 6844 The name of a prepared statement. This can be an SQL 6845 identifier or a host variable. 6846 </para> 6847 </listitem> 6848 </varlistentry> 6849 6850 <varlistentry> 6851 <term><replaceable class="parameter">descriptor_name</replaceable></term> 6852 <listitem> 6853 <para> 6854 A descriptor name. It is case sensitive. It can be an SQL 6855 identifier or a host variable. 6856 </para> 6857 </listitem> 6858 </varlistentry> 6859 6860 <varlistentry> 6861 <term><replaceable class="parameter">sqlda_name</replaceable></term> 6862 <listitem> 6863 <para> 6864 The name of an SQLDA variable. 6865 </para> 6866 </listitem> 6867 </varlistentry> 6868 </variablelist> 6869 </refsect1> 6870 6871 <refsect1> 6872 <title>Examples</title> 6873 6874<programlisting> 6875EXEC SQL ALLOCATE DESCRIPTOR mydesc; 6876EXEC SQL PREPARE stmt1 FROM :sql_stmt; 6877EXEC SQL DESCRIBE stmt1 INTO SQL DESCRIPTOR mydesc; 6878EXEC SQL GET DESCRIPTOR mydesc VALUE 1 :charvar = NAME; 6879EXEC SQL DEALLOCATE DESCRIPTOR mydesc; 6880</programlisting> 6881 </refsect1> 6882 6883 <refsect1> 6884 <title>Compatibility</title> 6885 6886 <para> 6887 <command>DESCRIBE</command> is specified in the SQL standard. 6888 </para> 6889 </refsect1> 6890 6891 <refsect1> 6892 <title>See Also</title> 6893 6894 <simplelist type="inline"> 6895 <member><xref linkend="ecpg-sql-allocate-descriptor"/></member> 6896 <member><xref linkend="ecpg-sql-get-descriptor"/></member> 6897 </simplelist> 6898 </refsect1> 6899 </refentry> 6900 6901 <refentry id="ecpg-sql-disconnect"> 6902 <refnamediv> 6903 <refname>DISCONNECT</refname> 6904 <refpurpose>terminate a database connection</refpurpose> 6905 </refnamediv> 6906 6907 <refsynopsisdiv> 6908<synopsis> 6909DISCONNECT <replaceable class="parameter">connection_name</replaceable> 6910DISCONNECT [ CURRENT ] 6911DISCONNECT DEFAULT 6912DISCONNECT ALL 6913</synopsis> 6914 </refsynopsisdiv> 6915 6916 <refsect1> 6917 <title>Description</title> 6918 6919 <para> 6920 <command>DISCONNECT</command> closes a connection (or all 6921 connections) to the database. 6922 </para> 6923 </refsect1> 6924 6925 <refsect1> 6926 <title>Parameters</title> 6927 6928 <variablelist> 6929 <varlistentry> 6930 <term><replaceable class="parameter">connection_name</replaceable></term> 6931 <listitem> 6932 <para> 6933 A database connection name established by 6934 the <command>CONNECT</command> command. 6935 </para> 6936 </listitem> 6937 </varlistentry> 6938 6939 <varlistentry> 6940 <term><literal>CURRENT</literal></term> 6941 <listitem> 6942 <para> 6943 Close the <quote>current</quote> connection, which is either 6944 the most recently opened connection, or the connection set by 6945 the <command>SET CONNECTION</command> command. This is also 6946 the default if no argument is given to 6947 the <command>DISCONNECT</command> command. 6948 </para> 6949 </listitem> 6950 </varlistentry> 6951 6952 <varlistentry> 6953 <term><literal>DEFAULT</literal></term> 6954 <listitem> 6955 <para> 6956 Close the default connection. 6957 </para> 6958 </listitem> 6959 </varlistentry> 6960 6961 <varlistentry> 6962 <term><literal>ALL</literal></term> 6963 <listitem> 6964 <para> 6965 Close all open connections. 6966 </para> 6967 </listitem> 6968 </varlistentry> 6969 </variablelist> 6970 </refsect1> 6971 6972 <refsect1> 6973 <title>Examples</title> 6974 6975<programlisting> 6976int 6977main(void) 6978{ 6979 EXEC SQL CONNECT TO testdb AS DEFAULT USER testuser; 6980 EXEC SQL CONNECT TO testdb AS con1 USER testuser; 6981 EXEC SQL CONNECT TO testdb AS con2 USER testuser; 6982 EXEC SQL CONNECT TO testdb AS con3 USER testuser; 6983 6984 EXEC SQL DISCONNECT CURRENT; /* close con3 */ 6985 EXEC SQL DISCONNECT DEFAULT; /* close DEFAULT */ 6986 EXEC SQL DISCONNECT ALL; /* close con2 and con1 */ 6987 6988 return 0; 6989} 6990</programlisting> 6991 </refsect1> 6992 6993 <refsect1> 6994 <title>Compatibility</title> 6995 6996 <para> 6997 <command>DISCONNECT</command> is specified in the SQL standard. 6998 </para> 6999 </refsect1> 7000 7001 <refsect1> 7002 <title>See Also</title> 7003 7004 <simplelist type="inline"> 7005 <member><xref linkend="ecpg-sql-connect"/></member> 7006 <member><xref linkend="ecpg-sql-set-connection"/></member> 7007 </simplelist> 7008 </refsect1> 7009 </refentry> 7010 7011 <refentry id="ecpg-sql-execute-immediate"> 7012 <refnamediv> 7013 <refname>EXECUTE IMMEDIATE</refname> 7014 <refpurpose>dynamically prepare and execute a statement</refpurpose> 7015 </refnamediv> 7016 7017 <refsynopsisdiv> 7018<synopsis> 7019EXECUTE IMMEDIATE <replaceable class="parameter">string</replaceable> 7020</synopsis> 7021 </refsynopsisdiv> 7022 7023 <refsect1> 7024 <title>Description</title> 7025 7026 <para> 7027 <command>EXECUTE IMMEDIATE</command> immediately prepares and 7028 executes a dynamically specified SQL statement, without 7029 retrieving result rows. 7030 </para> 7031 </refsect1> 7032 7033 <refsect1> 7034 <title>Parameters</title> 7035 7036 <variablelist> 7037 <varlistentry> 7038 <term><replaceable class="parameter">string</replaceable></term> 7039 <listitem> 7040 <para> 7041 A literal C string or a host variable containing the SQL 7042 statement to be executed. 7043 </para> 7044 </listitem> 7045 </varlistentry> 7046 </variablelist> 7047 </refsect1> 7048 7049 <refsect1> 7050 <title>Examples</title> 7051 7052 <para> 7053 Here is an example that executes an <command>INSERT</command> 7054 statement using <command>EXECUTE IMMEDIATE</command> and a host 7055 variable named <varname>command</varname>: 7056<programlisting> 7057sprintf(command, "INSERT INTO test (name, amount, letter) VALUES ('db: ''r1''', 1, 'f')"); 7058EXEC SQL EXECUTE IMMEDIATE :command; 7059</programlisting> 7060 </para> 7061 </refsect1> 7062 7063 <refsect1> 7064 <title>Compatibility</title> 7065 7066 <para> 7067 <command>EXECUTE IMMEDIATE</command> is specified in the SQL standard. 7068 </para> 7069 </refsect1> 7070 </refentry> 7071 7072 <refentry id="ecpg-sql-get-descriptor"> 7073 <refnamediv> 7074 <refname>GET DESCRIPTOR</refname> 7075 <refpurpose>get information from an SQL descriptor area</refpurpose> 7076 </refnamediv> 7077 7078 <refsynopsisdiv> 7079<synopsis> 7080GET DESCRIPTOR <replaceable class="parameter">descriptor_name</replaceable> <replaceable class="parameter">:cvariable</replaceable> = <replaceable class="parameter">descriptor_header_item</replaceable> [, ... ] 7081GET DESCRIPTOR <replaceable class="parameter">descriptor_name</replaceable> VALUE <replaceable class="parameter">column_number</replaceable> <replaceable class="parameter">:cvariable</replaceable> = <replaceable class="parameter">descriptor_item</replaceable> [, ... ] 7082</synopsis> 7083 </refsynopsisdiv> 7084 7085 <refsect1> 7086 <title>Description</title> 7087 7088 <para> 7089 <command>GET DESCRIPTOR</command> retrieves information about a 7090 query result set from an SQL descriptor area and stores it into 7091 host variables. A descriptor area is typically populated 7092 using <command>FETCH</command> or <command>SELECT</command> 7093 before using this command to transfer the information into host 7094 language variables. 7095 </para> 7096 7097 <para> 7098 This command has two forms: The first form retrieves 7099 descriptor <quote>header</quote> items, which apply to the result 7100 set in its entirety. One example is the row count. The second 7101 form, which requires the column number as additional parameter, 7102 retrieves information about a particular column. Examples are 7103 the column name and the actual column value. 7104 </para> 7105 </refsect1> 7106 7107 <refsect1> 7108 <title>Parameters</title> 7109 7110 <variablelist> 7111 <varlistentry> 7112 <term><replaceable class="parameter">descriptor_name</replaceable></term> 7113 <listitem> 7114 <para> 7115 A descriptor name. 7116 </para> 7117 </listitem> 7118 </varlistentry> 7119 7120 <varlistentry> 7121 <term><replaceable class="parameter">descriptor_header_item</replaceable></term> 7122 <listitem> 7123 <para> 7124 A token identifying which header information item to retrieve. 7125 Only <literal>COUNT</literal>, to get the number of columns in the 7126 result set, is currently supported. 7127 </para> 7128 </listitem> 7129 </varlistentry> 7130 7131 <varlistentry> 7132 <term><replaceable class="parameter">column_number</replaceable></term> 7133 <listitem> 7134 <para> 7135 The number of the column about which information is to be 7136 retrieved. The count starts at 1. 7137 </para> 7138 </listitem> 7139 </varlistentry> 7140 7141 <varlistentry> 7142 <term><replaceable class="parameter">descriptor_item</replaceable></term> 7143 <listitem> 7144 <para> 7145 A token identifying which item of information about a column 7146 to retrieve. See <xref linkend="ecpg-named-descriptors"/> for 7147 a list of supported items. 7148 </para> 7149 </listitem> 7150 </varlistentry> 7151 7152 <varlistentry> 7153 <term><replaceable class="parameter">cvariable</replaceable></term> 7154 <listitem> 7155 <para> 7156 A host variable that will receive the data retrieved from the 7157 descriptor area. 7158 </para> 7159 </listitem> 7160 </varlistentry> 7161 </variablelist> 7162 </refsect1> 7163 7164 <refsect1> 7165 <title>Examples</title> 7166 7167 <para> 7168 An example to retrieve the number of columns in a result set: 7169<programlisting> 7170EXEC SQL GET DESCRIPTOR d :d_count = COUNT; 7171</programlisting> 7172 </para> 7173 7174 <para> 7175 An example to retrieve a data length in the first column: 7176<programlisting> 7177EXEC SQL GET DESCRIPTOR d VALUE 1 :d_returned_octet_length = RETURNED_OCTET_LENGTH; 7178</programlisting> 7179 </para> 7180 7181 <para> 7182 An example to retrieve the data body of the second column as a 7183 string: 7184<programlisting> 7185EXEC SQL GET DESCRIPTOR d VALUE 2 :d_data = DATA; 7186</programlisting> 7187 </para> 7188 7189 <para> 7190 Here is an example for a whole procedure of 7191 executing <literal>SELECT current_database();</literal> and showing the number of 7192 columns, the column data length, and the column data: 7193<programlisting> 7194int 7195main(void) 7196{ 7197EXEC SQL BEGIN DECLARE SECTION; 7198 int d_count; 7199 char d_data[1024]; 7200 int d_returned_octet_length; 7201EXEC SQL END DECLARE SECTION; 7202 7203 EXEC SQL CONNECT TO testdb AS con1 USER testuser; 7204 EXEC SQL SELECT pg_catalog.set_config('search_path', '', false); EXEC SQL COMMIT; 7205 EXEC SQL ALLOCATE DESCRIPTOR d; 7206 7207 /* Declare, open a cursor, and assign a descriptor to the cursor */ 7208 EXEC SQL DECLARE cur CURSOR FOR SELECT current_database(); 7209 EXEC SQL OPEN cur; 7210 EXEC SQL FETCH NEXT FROM cur INTO SQL DESCRIPTOR d; 7211 7212 /* Get a number of total columns */ 7213 EXEC SQL GET DESCRIPTOR d :d_count = COUNT; 7214 printf("d_count = %d\n", d_count); 7215 7216 /* Get length of a returned column */ 7217 EXEC SQL GET DESCRIPTOR d VALUE 1 :d_returned_octet_length = RETURNED_OCTET_LENGTH; 7218 printf("d_returned_octet_length = %d\n", d_returned_octet_length); 7219 7220 /* Fetch the returned column as a string */ 7221 EXEC SQL GET DESCRIPTOR d VALUE 1 :d_data = DATA; 7222 printf("d_data = %s\n", d_data); 7223 7224 /* Closing */ 7225 EXEC SQL CLOSE cur; 7226 EXEC SQL COMMIT; 7227 7228 EXEC SQL DEALLOCATE DESCRIPTOR d; 7229 EXEC SQL DISCONNECT ALL; 7230 7231 return 0; 7232} 7233</programlisting> 7234 When the example is executed, the result will look like this: 7235<screen> 7236d_count = 1 7237d_returned_octet_length = 6 7238d_data = testdb 7239</screen> 7240 </para> 7241 </refsect1> 7242 7243 <refsect1> 7244 <title>Compatibility</title> 7245 7246 <para> 7247 <command>GET DESCRIPTOR</command> is specified in the SQL standard. 7248 </para> 7249 </refsect1> 7250 7251 <refsect1> 7252 <title>See Also</title> 7253 7254 <simplelist type="inline"> 7255 <member><xref linkend="ecpg-sql-allocate-descriptor"/></member> 7256 <member><xref linkend="ecpg-sql-set-descriptor"/></member> 7257 </simplelist> 7258 </refsect1> 7259 </refentry> 7260 7261 <refentry id="ecpg-sql-open"> 7262 <refnamediv> 7263 <refname>OPEN</refname> 7264 <refpurpose>open a dynamic cursor</refpurpose> 7265 </refnamediv> 7266 7267 <refsynopsisdiv> 7268<synopsis> 7269OPEN <replaceable class="parameter">cursor_name</replaceable> 7270OPEN <replaceable class="parameter">cursor_name</replaceable> USING <replaceable class="parameter">value</replaceable> [, ... ] 7271OPEN <replaceable class="parameter">cursor_name</replaceable> USING SQL DESCRIPTOR <replaceable class="parameter">descriptor_name</replaceable> 7272</synopsis> 7273 </refsynopsisdiv> 7274 7275 <refsect1> 7276 <title>Description</title> 7277 7278 <para> 7279 <command>OPEN</command> opens a cursor and optionally binds 7280 actual values to the placeholders in the cursor's declaration. 7281 The cursor must previously have been declared with 7282 the <command>DECLARE</command> command. The execution 7283 of <command>OPEN</command> causes the query to start executing on 7284 the server. 7285 </para> 7286 </refsect1> 7287 7288 <refsect1> 7289 <title>Parameters</title> 7290 7291 <variablelist> 7292 <varlistentry> 7293 <term><replaceable class="parameter">cursor_name</replaceable></term> 7294 <listitem> 7295 <para> 7296 The name of the cursor to be opened. This can be an SQL 7297 identifier or a host variable. 7298 </para> 7299 </listitem> 7300 </varlistentry> 7301 7302 <varlistentry> 7303 <term><replaceable class="parameter">value</replaceable></term> 7304 <listitem> 7305 <para> 7306 A value to be bound to a placeholder in the cursor. This can 7307 be an SQL constant, a host variable, or a host variable with 7308 indicator. 7309 </para> 7310 </listitem> 7311 </varlistentry> 7312 7313 <varlistentry> 7314 <term><replaceable class="parameter">descriptor_name</replaceable></term> 7315 <listitem> 7316 <para> 7317 The name of a descriptor containing values to be bound to the 7318 placeholders in the cursor. This can be an SQL identifier or 7319 a host variable. 7320 </para> 7321 </listitem> 7322 </varlistentry> 7323 </variablelist> 7324 </refsect1> 7325 7326 <refsect1> 7327 <title>Examples</title> 7328 7329<programlisting> 7330EXEC SQL OPEN a; 7331EXEC SQL OPEN d USING 1, 'test'; 7332EXEC SQL OPEN c1 USING SQL DESCRIPTOR mydesc; 7333EXEC SQL OPEN :curname1; 7334</programlisting> 7335 </refsect1> 7336 7337 <refsect1> 7338 <title>Compatibility</title> 7339 7340 <para> 7341 <command>OPEN</command> is specified in the SQL standard. 7342 </para> 7343 </refsect1> 7344 7345 <refsect1> 7346 <title>See Also</title> 7347 7348 <simplelist type="inline"> 7349 <member><xref linkend="ecpg-sql-declare"/></member> 7350 <member><xref linkend="sql-close"/></member> 7351 </simplelist> 7352 </refsect1> 7353 </refentry> 7354 7355 <refentry id="ecpg-sql-prepare"> 7356 <refnamediv> 7357 <refname>PREPARE</refname> 7358 <refpurpose>prepare a statement for execution</refpurpose> 7359 </refnamediv> 7360 7361 <refsynopsisdiv> 7362<synopsis> 7363PREPARE <replaceable class="parameter">name</replaceable> FROM <replaceable class="parameter">string</replaceable> 7364</synopsis> 7365 </refsynopsisdiv> 7366 7367 <refsect1> 7368 <title>Description</title> 7369 7370 <para> 7371 <command>PREPARE</command> prepares a statement dynamically 7372 specified as a string for execution. This is different from the 7373 direct SQL statement <xref linkend="sql-prepare"/>, which can also 7374 be used in embedded programs. The <xref linkend="sql-execute"/> 7375 command is used to execute either kind of prepared statement. 7376 </para> 7377 </refsect1> 7378 7379 <refsect1> 7380 <title>Parameters</title> 7381 7382 <variablelist> 7383 <varlistentry> 7384 <term><replaceable class="parameter">prepared_name</replaceable></term> 7385 <listitem> 7386 <para> 7387 An identifier for the prepared query. 7388 </para> 7389 </listitem> 7390 </varlistentry> 7391 7392 <varlistentry> 7393 <term><replaceable class="parameter">string</replaceable></term> 7394 <listitem> 7395 <para> 7396 A literal C string or a host variable containing a preparable 7397 statement, one of the SELECT, INSERT, UPDATE, or 7398 DELETE. 7399 </para> 7400 </listitem> 7401 </varlistentry> 7402 </variablelist> 7403 </refsect1> 7404 7405 <refsect1> 7406 <title>Examples</title> 7407<programlisting> 7408char *stmt = "SELECT * FROM test1 WHERE a = ? AND b = ?"; 7409 7410EXEC SQL ALLOCATE DESCRIPTOR outdesc; 7411EXEC SQL PREPARE foo FROM :stmt; 7412 7413EXEC SQL EXECUTE foo USING SQL DESCRIPTOR indesc INTO SQL DESCRIPTOR outdesc; 7414</programlisting> 7415 </refsect1> 7416 7417 <refsect1> 7418 <title>Compatibility</title> 7419 7420 <para> 7421 <command>PREPARE</command> is specified in the SQL standard. 7422 </para> 7423 </refsect1> 7424 7425 <refsect1> 7426 <title>See Also</title> 7427 7428 <simplelist type="inline"> 7429 <member><xref linkend="sql-execute"/></member> 7430 </simplelist> 7431 </refsect1> 7432 </refentry> 7433 7434 <refentry id="ecpg-sql-set-autocommit"> 7435 <refnamediv> 7436 <refname>SET AUTOCOMMIT</refname> 7437 <refpurpose>set the autocommit behavior of the current session</refpurpose> 7438 </refnamediv> 7439 7440 <refsynopsisdiv> 7441<synopsis> 7442SET AUTOCOMMIT { = | TO } { ON | OFF } 7443</synopsis> 7444 </refsynopsisdiv> 7445 7446 <refsect1> 7447 <title>Description</title> 7448 7449 <para> 7450 <command>SET AUTOCOMMIT</command> sets the autocommit behavior of 7451 the current database session. By default, embedded SQL programs 7452 are <emphasis>not</emphasis> in autocommit mode, 7453 so <command>COMMIT</command> needs to be issued explicitly when 7454 desired. This command can change the session to autocommit mode, 7455 where each individual statement is committed implicitly. 7456 </para> 7457 </refsect1> 7458 7459 <refsect1> 7460 <title>Compatibility</title> 7461 7462 <para> 7463 <command>SET AUTOCOMMIT</command> is an extension of PostgreSQL ECPG. 7464 </para> 7465 </refsect1> 7466 </refentry> 7467 7468 <refentry id="ecpg-sql-set-connection"> 7469 <refnamediv> 7470 <refname>SET CONNECTION</refname> 7471 <refpurpose>select a database connection</refpurpose> 7472 </refnamediv> 7473 7474 <refsynopsisdiv> 7475<synopsis> 7476SET CONNECTION [ TO | = ] <replaceable class="parameter">connection_name</replaceable> 7477</synopsis> 7478 </refsynopsisdiv> 7479 7480 <refsect1> 7481 <title>Description</title> 7482 7483 <para> 7484 <command>SET CONNECTION</command> sets the <quote>current</quote> 7485 database connection, which is the one that all commands use 7486 unless overridden. 7487 </para> 7488 </refsect1> 7489 7490 <refsect1> 7491 <title>Parameters</title> 7492 7493 <variablelist> 7494 <varlistentry> 7495 <term><replaceable class="parameter">connection_name</replaceable></term> 7496 <listitem> 7497 <para> 7498 A database connection name established by 7499 the <command>CONNECT</command> command. 7500 </para> 7501 </listitem> 7502 </varlistentry> 7503 7504 <varlistentry> 7505 <term><literal>DEFAULT</literal></term> 7506 <listitem> 7507 <para> 7508 Set the connection to the default connection. 7509 </para> 7510 </listitem> 7511 </varlistentry> 7512 </variablelist> 7513 </refsect1> 7514 7515 <refsect1> 7516 <title>Examples</title> 7517 7518<programlisting> 7519EXEC SQL SET CONNECTION TO con2; 7520EXEC SQL SET CONNECTION = con1; 7521</programlisting> 7522 </refsect1> 7523 7524 <refsect1> 7525 <title>Compatibility</title> 7526 7527 <para> 7528 <command>SET CONNECTION</command> is specified in the SQL standard. 7529 </para> 7530 </refsect1> 7531 7532 <refsect1> 7533 <title>See Also</title> 7534 7535 <simplelist type="inline"> 7536 <member><xref linkend="ecpg-sql-connect"/></member> 7537 <member><xref linkend="ecpg-sql-disconnect"/></member> 7538 </simplelist> 7539 </refsect1> 7540 </refentry> 7541 7542 <refentry id="ecpg-sql-set-descriptor"> 7543 <refnamediv> 7544 <refname>SET DESCRIPTOR</refname> 7545 <refpurpose>set information in an SQL descriptor area</refpurpose> 7546 </refnamediv> 7547 7548 <refsynopsisdiv> 7549<synopsis> 7550SET DESCRIPTOR <replaceable class="parameter">descriptor_name</replaceable> <replaceable class="parameter">descriptor_header_item</replaceable> = <replaceable>value</replaceable> [, ... ] 7551SET DESCRIPTOR <replaceable class="parameter">descriptor_name</replaceable> VALUE <replaceable class="parameter">number</replaceable> <replaceable class="parameter">descriptor_item</replaceable> = <replaceable>value</replaceable> [, ...] 7552</synopsis> 7553 </refsynopsisdiv> 7554 7555 <refsect1> 7556 <title>Description</title> 7557 7558 <para> 7559 <command>SET DESCRIPTOR</command> populates an SQL descriptor 7560 area with values. The descriptor area is then typically used to 7561 bind parameters in a prepared query execution. 7562 </para> 7563 7564 <para> 7565 This command has two forms: The first form applies to the 7566 descriptor <quote>header</quote>, which is independent of a 7567 particular datum. The second form assigns values to particular 7568 datums, identified by number. 7569 </para> 7570 </refsect1> 7571 7572 <refsect1> 7573 <title>Parameters</title> 7574 7575 <variablelist> 7576 <varlistentry> 7577 <term><replaceable class="parameter">descriptor_name</replaceable></term> 7578 <listitem> 7579 <para> 7580 A descriptor name. 7581 </para> 7582 </listitem> 7583 </varlistentry> 7584 7585 <varlistentry> 7586 <term><replaceable class="parameter">descriptor_header_item</replaceable></term> 7587 <listitem> 7588 <para> 7589 A token identifying which header information item to set. 7590 Only <literal>COUNT</literal>, to set the number of descriptor 7591 items, is currently supported. 7592 </para> 7593 </listitem> 7594 </varlistentry> 7595 7596 <varlistentry> 7597 <term><replaceable class="parameter">number</replaceable></term> 7598 <listitem> 7599 <para> 7600 The number of the descriptor item to set. The count starts at 7601 1. 7602 </para> 7603 </listitem> 7604 </varlistentry> 7605 7606 <varlistentry> 7607 <term><replaceable class="parameter">descriptor_item</replaceable></term> 7608 <listitem> 7609 <para> 7610 A token identifying which item of information to set in the 7611 descriptor. See <xref linkend="ecpg-named-descriptors"/> for a 7612 list of supported items. 7613 </para> 7614 </listitem> 7615 </varlistentry> 7616 7617 <varlistentry> 7618 <term><replaceable class="parameter">value</replaceable></term> 7619 <listitem> 7620 <para> 7621 A value to store into the descriptor item. This can be an SQL 7622 constant or a host variable. 7623 </para> 7624 </listitem> 7625 </varlistentry> 7626 </variablelist> 7627 </refsect1> 7628 7629 <refsect1> 7630 <title>Examples</title> 7631<programlisting> 7632EXEC SQL SET DESCRIPTOR indesc COUNT = 1; 7633EXEC SQL SET DESCRIPTOR indesc VALUE 1 DATA = 2; 7634EXEC SQL SET DESCRIPTOR indesc VALUE 1 DATA = :val1; 7635EXEC SQL SET DESCRIPTOR indesc VALUE 2 INDICATOR = :val1, DATA = 'some string'; 7636EXEC SQL SET DESCRIPTOR indesc VALUE 2 INDICATOR = :val2null, DATA = :val2; 7637</programlisting> 7638 </refsect1> 7639 7640 <refsect1> 7641 <title>Compatibility</title> 7642 7643 <para> 7644 <command>SET DESCRIPTOR</command> is specified in the SQL standard. 7645 </para> 7646 </refsect1> 7647 7648 <refsect1> 7649 <title>See Also</title> 7650 7651 <simplelist type="inline"> 7652 <member><xref linkend="ecpg-sql-allocate-descriptor"/></member> 7653 <member><xref linkend="ecpg-sql-get-descriptor"/></member> 7654 </simplelist> 7655 </refsect1> 7656 </refentry> 7657 7658 <refentry id="ecpg-sql-type"> 7659 <refnamediv> 7660 <refname>TYPE</refname> 7661 <refpurpose>define a new data type</refpurpose> 7662 </refnamediv> 7663 7664 <refsynopsisdiv> 7665<synopsis> 7666TYPE <replaceable class="parameter">type_name</replaceable> IS <replaceable class="parameter">ctype</replaceable> 7667</synopsis> 7668 </refsynopsisdiv> 7669 7670 <refsect1> 7671 <title>Description</title> 7672 7673 <para> 7674 The <command>TYPE</command> command defines a new C type. It is 7675 equivalent to putting a <literal>typedef</literal> into a declare 7676 section. 7677 </para> 7678 7679 <para> 7680 This command is only recognized when <command>ecpg</command> is 7681 run with the <option>-c</option> option. 7682 </para> 7683 </refsect1> 7684 7685 <refsect1> 7686 <title>Parameters</title> 7687 7688 <variablelist> 7689 <varlistentry> 7690 <term><replaceable class="parameter">type_name</replaceable></term> 7691 <listitem> 7692 <para> 7693 The name for the new type. It must be a valid C type name. 7694 </para> 7695 </listitem> 7696 </varlistentry> 7697 7698 <varlistentry> 7699 <term><replaceable class="parameter">ctype</replaceable></term> 7700 <listitem> 7701 <para> 7702 A C type specification. 7703 </para> 7704 </listitem> 7705 </varlistentry> 7706 </variablelist> 7707 </refsect1> 7708 7709 <refsect1> 7710 <title>Examples</title> 7711 7712<programlisting> 7713EXEC SQL TYPE customer IS 7714 struct 7715 { 7716 varchar name[50]; 7717 int phone; 7718 }; 7719 7720EXEC SQL TYPE cust_ind IS 7721 struct ind 7722 { 7723 short name_ind; 7724 short phone_ind; 7725 }; 7726 7727EXEC SQL TYPE c IS char reference; 7728EXEC SQL TYPE ind IS union { int integer; short smallint; }; 7729EXEC SQL TYPE intarray IS int[AMOUNT]; 7730EXEC SQL TYPE str IS varchar[BUFFERSIZ]; 7731EXEC SQL TYPE string IS char[11]; 7732</programlisting> 7733 7734 <para> 7735 Here is an example program that uses <command>EXEC SQL 7736 TYPE</command>: 7737<programlisting> 7738EXEC SQL WHENEVER SQLERROR SQLPRINT; 7739 7740EXEC SQL TYPE tt IS 7741 struct 7742 { 7743 varchar v[256]; 7744 int i; 7745 }; 7746 7747EXEC SQL TYPE tt_ind IS 7748 struct ind { 7749 short v_ind; 7750 short i_ind; 7751 }; 7752 7753int 7754main(void) 7755{ 7756EXEC SQL BEGIN DECLARE SECTION; 7757 tt t; 7758 tt_ind t_ind; 7759EXEC SQL END DECLARE SECTION; 7760 7761 EXEC SQL CONNECT TO testdb AS con1; 7762 EXEC SQL SELECT pg_catalog.set_config('search_path', '', false); EXEC SQL COMMIT; 7763 7764 EXEC SQL SELECT current_database(), 256 INTO :t:t_ind LIMIT 1; 7765 7766 printf("t.v = %s\n", t.v.arr); 7767 printf("t.i = %d\n", t.i); 7768 7769 printf("t_ind.v_ind = %d\n", t_ind.v_ind); 7770 printf("t_ind.i_ind = %d\n", t_ind.i_ind); 7771 7772 EXEC SQL DISCONNECT con1; 7773 7774 return 0; 7775} 7776</programlisting> 7777 7778 The output from this program looks like this: 7779<screen> 7780t.v = testdb 7781t.i = 256 7782t_ind.v_ind = 0 7783t_ind.i_ind = 0 7784</screen> 7785 </para> 7786 </refsect1> 7787 7788 <refsect1> 7789 <title>Compatibility</title> 7790 7791 <para> 7792 The <command>TYPE</command> command is a PostgreSQL extension. 7793 </para> 7794 </refsect1> 7795 </refentry> 7796 7797 <refentry id="ecpg-sql-var"> 7798 <refnamediv> 7799 <refname>VAR</refname> 7800 <refpurpose>define a variable</refpurpose> 7801 </refnamediv> 7802 7803 <refsynopsisdiv> 7804<synopsis> 7805VAR <replaceable>varname</replaceable> IS <replaceable>ctype</replaceable> 7806</synopsis> 7807 </refsynopsisdiv> 7808 7809 <refsect1> 7810 <title>Description</title> 7811 7812 <para> 7813 The <command>VAR</command> command assigns a new C data type 7814 to a host variable. The host variable must be previously 7815 declared in a declare section. 7816 </para> 7817 </refsect1> 7818 7819 <refsect1> 7820 <title>Parameters</title> 7821 7822 <variablelist> 7823 <varlistentry> 7824 <term><replaceable class="parameter">varname</replaceable></term> 7825 <listitem> 7826 <para> 7827 A C variable name. 7828 </para> 7829 </listitem> 7830 </varlistentry> 7831 7832 <varlistentry> 7833 <term><replaceable class="parameter">ctype</replaceable></term> 7834 <listitem> 7835 <para> 7836 A C type specification. 7837 </para> 7838 </listitem> 7839 </varlistentry> 7840 </variablelist> 7841 </refsect1> 7842 7843 <refsect1> 7844 <title>Examples</title> 7845 7846<programlisting> 7847Exec sql begin declare section; 7848short a; 7849exec sql end declare section; 7850EXEC SQL VAR a IS int; 7851</programlisting> 7852 </refsect1> 7853 7854 <refsect1> 7855 <title>Compatibility</title> 7856 7857 <para> 7858 The <command>VAR</command> command is a PostgreSQL extension. 7859 </para> 7860 </refsect1> 7861 </refentry> 7862 7863 <refentry id="ecpg-sql-whenever"> 7864 <refnamediv> 7865 <refname>WHENEVER</refname> 7866 <refpurpose>specify the action to be taken when an SQL statement causes a specific class condition to be raised</refpurpose> 7867 </refnamediv> 7868 7869 <refsynopsisdiv> 7870<synopsis> 7871WHENEVER { NOT FOUND | SQLERROR | SQLWARNING } <replaceable class="parameter">action</replaceable> 7872</synopsis> 7873 </refsynopsisdiv> 7874 7875 <refsect1> 7876 <title>Description</title> 7877 7878 <para> 7879 Define a behavior which is called on the special cases (Rows not 7880 found, SQL warnings or errors) in the result of SQL execution. 7881 </para> 7882 </refsect1> 7883 7884 <refsect1> 7885 <title>Parameters</title> 7886 7887 <para> 7888 See <xref linkend="ecpg-whenever"/> for a description of the 7889 parameters. 7890 </para> 7891 </refsect1> 7892 7893 <refsect1> 7894 <title>Examples</title> 7895 7896<programlisting> 7897EXEC SQL WHENEVER NOT FOUND CONTINUE; 7898EXEC SQL WHENEVER NOT FOUND DO BREAK; 7899EXEC SQL WHENEVER NOT FOUND DO CONTINUE; 7900EXEC SQL WHENEVER SQLWARNING SQLPRINT; 7901EXEC SQL WHENEVER SQLWARNING DO warn(); 7902EXEC SQL WHENEVER SQLERROR sqlprint; 7903EXEC SQL WHENEVER SQLERROR CALL print2(); 7904EXEC SQL WHENEVER SQLERROR DO handle_error("select"); 7905EXEC SQL WHENEVER SQLERROR DO sqlnotice(NULL, NONO); 7906EXEC SQL WHENEVER SQLERROR DO sqlprint(); 7907EXEC SQL WHENEVER SQLERROR GOTO error_label; 7908EXEC SQL WHENEVER SQLERROR STOP; 7909</programlisting> 7910 7911 <para> 7912 A typical application is the use of <literal>WHENEVER NOT FOUND 7913 BREAK</literal> to handle looping through result sets: 7914<programlisting> 7915int 7916main(void) 7917{ 7918 EXEC SQL CONNECT TO testdb AS con1; 7919 EXEC SQL SELECT pg_catalog.set_config('search_path', '', false); EXEC SQL COMMIT; 7920 EXEC SQL ALLOCATE DESCRIPTOR d; 7921 EXEC SQL DECLARE cur CURSOR FOR SELECT current_database(), 'hoge', 256; 7922 EXEC SQL OPEN cur; 7923 7924 /* when end of result set reached, break out of while loop */ 7925 EXEC SQL WHENEVER NOT FOUND DO BREAK; 7926 7927 while (1) 7928 { 7929 EXEC SQL FETCH NEXT FROM cur INTO SQL DESCRIPTOR d; 7930 ... 7931 } 7932 7933 EXEC SQL CLOSE cur; 7934 EXEC SQL COMMIT; 7935 7936 EXEC SQL DEALLOCATE DESCRIPTOR d; 7937 EXEC SQL DISCONNECT ALL; 7938 7939 return 0; 7940} 7941</programlisting> 7942 </para> 7943 </refsect1> 7944 7945 <refsect1> 7946 <title>Compatibility</title> 7947 7948 <para> 7949 <command>WHENEVER</command> is specified in the SQL standard, but 7950 most of the actions are PostgreSQL extensions. 7951 </para> 7952 </refsect1> 7953 </refentry> 7954 </sect1> 7955 7956 <sect1 id="ecpg-informix-compat"> 7957 <title><productname>Informix</productname> Compatibility Mode</title> 7958 <para> 7959 <command>ecpg</command> can be run in a so-called <firstterm>Informix compatibility mode</firstterm>. If 7960 this mode is active, it tries to behave as if it were the <productname>Informix</productname> 7961 precompiler for <productname>Informix</productname> E/SQL. Generally spoken this will allow you to use 7962 the dollar sign instead of the <literal>EXEC SQL</literal> primitive to introduce 7963 embedded SQL commands: 7964<programlisting> 7965$int j = 3; 7966$CONNECT TO :dbname; 7967$CREATE TABLE test(i INT PRIMARY KEY, j INT); 7968$INSERT INTO test(i, j) VALUES (7, :j); 7969$COMMIT; 7970</programlisting> 7971 </para> 7972 7973 <note> 7974 <para> 7975 There must not be any white space between the <literal>$</literal> 7976 and a following preprocessor directive, that is, 7977 <literal>include</literal>, <literal>define</literal>, <literal>ifdef</literal>, 7978 etc. Otherwise, the preprocessor will parse the token as a host 7979 variable. 7980 </para> 7981 </note> 7982 7983 <para> 7984 There are two compatibility modes: <literal>INFORMIX</literal>, <literal>INFORMIX_SE</literal> 7985 </para> 7986 <para> 7987 When linking programs that use this compatibility mode, remember to link 7988 against <literal>libcompat</literal> that is shipped with ECPG. 7989 </para> 7990 <para> 7991 Besides the previously explained syntactic sugar, the <productname>Informix</productname> compatibility 7992 mode ports some functions for input, output and transformation of data as 7993 well as embedded SQL statements known from E/SQL to ECPG. 7994 </para> 7995 <para> 7996 <productname>Informix</productname> compatibility mode is closely connected to the pgtypeslib library 7997 of ECPG. pgtypeslib maps SQL data types to data types within the C host 7998 program and most of the additional functions of the <productname>Informix</productname> compatibility 7999 mode allow you to operate on those C host program types. Note however that 8000 the extent of the compatibility is limited. It does not try to copy <productname>Informix</productname> 8001 behavior; it allows you to do more or less the same operations and gives 8002 you functions that have the same name and the same basic behavior but it is 8003 no drop-in replacement if you are using <productname>Informix</productname> at the moment. Moreover, 8004 some of the data types are different. For example, 8005 <productname>PostgreSQL's</productname> datetime and interval types do not 8006 know about ranges like for example <literal>YEAR TO MINUTE</literal> so you won't 8007 find support in ECPG for that either. 8008 </para> 8009 8010 <sect2 id="ecpg-informix-types"> 8011 <title>Additional Types</title> 8012 <para> 8013 The Informix-special "string" pseudo-type for storing right-trimmed character string data is now 8014 supported in Informix-mode without using <literal>typedef</literal>. In fact, in Informix-mode, 8015 ECPG refuses to process source files that contain <literal>typedef sometype string;</literal> 8016<programlisting> 8017EXEC SQL BEGIN DECLARE SECTION; 8018string userid; /* this variable will contain trimmed data */ 8019EXEC SQL END DECLARE SECTION; 8020 8021EXEC SQL FETCH MYCUR INTO :userid; 8022</programlisting> 8023 </para> 8024 </sect2> 8025 8026 <sect2 id="ecpg-informix-statements"> 8027 <title>Additional/Missing Embedded SQL Statements</title> 8028 <para> 8029 <variablelist> 8030 <varlistentry> 8031 <term><literal>CLOSE DATABASE</literal></term> 8032 <listitem> 8033 <para> 8034 This statement closes the current connection. In fact, this is a 8035 synonym for ECPG's <literal>DISCONNECT CURRENT</literal>: 8036<programlisting> 8037$CLOSE DATABASE; /* close the current connection */ 8038EXEC SQL CLOSE DATABASE; 8039</programlisting> 8040 </para> 8041 </listitem> 8042 </varlistentry> 8043 <varlistentry> 8044 <term><literal>FREE cursor_name</literal></term> 8045 <listitem> 8046 <para> 8047 Due to the differences how ECPG works compared to Informix's ESQL/C (i.e., which steps 8048 are purely grammar transformations and which steps rely on the underlying run-time library) 8049 there is no <literal>FREE cursor_name</literal> statement in ECPG. This is because in ECPG, 8050 <literal>DECLARE CURSOR</literal> doesn't translate to a function call into 8051 the run-time library that uses to the cursor name. This means that there's no run-time 8052 bookkeeping of SQL cursors in the ECPG run-time library, only in the PostgreSQL server. 8053 </para> 8054 </listitem> 8055 </varlistentry> 8056 <varlistentry> 8057 <term><literal>FREE statement_name</literal></term> 8058 <listitem> 8059 <para> 8060 <literal>FREE statement_name</literal> is a synonym for <literal>DEALLOCATE PREPARE statement_name</literal>. 8061 </para> 8062 </listitem> 8063 </varlistentry> 8064 </variablelist> 8065 </para> 8066 </sect2> 8067 8068 <sect2 id="ecpg-informix-sqlda"> 8069 <title>Informix-compatible SQLDA Descriptor Areas</title> 8070 <para> 8071 Informix-compatible mode supports a different structure than the one described in 8072 <xref linkend="ecpg-sqlda-descriptors"/>. See below: 8073<programlisting> 8074struct sqlvar_compat 8075{ 8076 short sqltype; 8077 int sqllen; 8078 char *sqldata; 8079 short *sqlind; 8080 char *sqlname; 8081 char *sqlformat; 8082 short sqlitype; 8083 short sqlilen; 8084 char *sqlidata; 8085 int sqlxid; 8086 char *sqltypename; 8087 short sqltypelen; 8088 short sqlownerlen; 8089 short sqlsourcetype; 8090 char *sqlownername; 8091 int sqlsourceid; 8092 char *sqlilongdata; 8093 int sqlflags; 8094 void *sqlreserved; 8095}; 8096 8097struct sqlda_compat 8098{ 8099 short sqld; 8100 struct sqlvar_compat *sqlvar; 8101 char desc_name[19]; 8102 short desc_occ; 8103 struct sqlda_compat *desc_next; 8104 void *reserved; 8105}; 8106 8107typedef struct sqlvar_compat sqlvar_t; 8108typedef struct sqlda_compat sqlda_t; 8109</programlisting> 8110 </para> 8111 8112 <para> 8113 The global properties are: 8114 <variablelist> 8115 8116 <varlistentry> 8117 <term><literal>sqld</literal></term> 8118 <listitem> 8119 <para> 8120 The number of fields in the <literal>SQLDA</literal> descriptor. 8121 </para> 8122 </listitem> 8123 </varlistentry> 8124 8125 <varlistentry> 8126 <term><literal>sqlvar</literal></term> 8127 <listitem> 8128 <para> 8129 Pointer to the per-field properties. 8130 </para> 8131 </listitem> 8132 </varlistentry> 8133 8134 <varlistentry> 8135 <term><literal>desc_name</literal></term> 8136 <listitem> 8137 <para> 8138 Unused, filled with zero-bytes. 8139 </para> 8140 </listitem> 8141 </varlistentry> 8142 8143 <varlistentry> 8144 <term><literal>desc_occ</literal></term> 8145 <listitem> 8146 <para> 8147 Size of the allocated structure. 8148 </para> 8149 </listitem> 8150 </varlistentry> 8151 8152 <varlistentry> 8153 <term><literal>desc_next</literal></term> 8154 <listitem> 8155 <para> 8156 Pointer to the next SQLDA structure if the result set contains more than one record. 8157 </para> 8158 </listitem> 8159 </varlistentry> 8160 8161 <varlistentry> 8162 <term><literal>reserved</literal></term> 8163 <listitem> 8164 <para> 8165 Unused pointer, contains NULL. Kept for Informix-compatibility. 8166 </para> 8167 </listitem> 8168 </varlistentry> 8169 8170 </variablelist> 8171 8172 The per-field properties are below, they are stored in the <literal>sqlvar</literal> array: 8173 8174 <variablelist> 8175 8176 <varlistentry> 8177 <term><literal>sqltype</literal></term> 8178 <listitem> 8179 <para> 8180 Type of the field. Constants are in <literal>sqltypes.h</literal> 8181 </para> 8182 </listitem> 8183 </varlistentry> 8184 8185 <varlistentry> 8186 <term><literal>sqllen</literal></term> 8187 <listitem> 8188 <para> 8189 Length of the field data. 8190 </para> 8191 </listitem> 8192 </varlistentry> 8193 8194 <varlistentry> 8195 <term><literal>sqldata</literal></term> 8196 <listitem> 8197 <para> 8198 Pointer to the field data. The pointer is of <literal>char *</literal> type, 8199 the data pointed by it is in a binary format. Example: 8200<programlisting> 8201int intval; 8202 8203switch (sqldata->sqlvar[i].sqltype) 8204{ 8205 case SQLINTEGER: 8206 intval = *(int *)sqldata->sqlvar[i].sqldata; 8207 break; 8208 ... 8209} 8210</programlisting> 8211 </para> 8212 </listitem> 8213 </varlistentry> 8214 8215 <varlistentry> 8216 <term><literal>sqlind</literal></term> 8217 <listitem> 8218 <para> 8219 Pointer to the NULL indicator. If returned by DESCRIBE or FETCH then it's always a valid pointer. 8220 If used as input for <literal>EXECUTE ... USING sqlda;</literal> then NULL-pointer value means 8221 that the value for this field is non-NULL. Otherwise a valid pointer and <literal>sqlitype</literal> 8222 has to be properly set. Example: 8223<programlisting> 8224if (*(int2 *)sqldata->sqlvar[i].sqlind != 0) 8225 printf("value is NULL\n"); 8226</programlisting> 8227 </para> 8228 </listitem> 8229 </varlistentry> 8230 8231 <varlistentry> 8232 <term><literal>sqlname</literal></term> 8233 <listitem> 8234 <para> 8235 Name of the field. 0-terminated string. 8236 </para> 8237 </listitem> 8238 </varlistentry> 8239 8240 <varlistentry> 8241 <term><literal>sqlformat</literal></term> 8242 <listitem> 8243 <para> 8244 Reserved in Informix, value of <function>PQfformat()</function> for the field. 8245 </para> 8246 </listitem> 8247 </varlistentry> 8248 8249 <varlistentry> 8250 <term><literal>sqlitype</literal></term> 8251 <listitem> 8252 <para> 8253 Type of the NULL indicator data. It's always SQLSMINT when returning data from the server. 8254 When the <literal>SQLDA</literal> is used for a parameterized query, the data is treated 8255 according to the set type. 8256 </para> 8257 </listitem> 8258 </varlistentry> 8259 8260 <varlistentry> 8261 <term><literal>sqlilen</literal></term> 8262 <listitem> 8263 <para> 8264 Length of the NULL indicator data. 8265 </para> 8266 </listitem> 8267 </varlistentry> 8268 8269 <varlistentry> 8270 <term><literal>sqlxid</literal></term> 8271 <listitem> 8272 <para> 8273 Extended type of the field, result of <function>PQftype()</function>. 8274 </para> 8275 </listitem> 8276 </varlistentry> 8277 8278 <varlistentry> 8279 <term><literal>sqltypename</literal></term> 8280 <term><literal>sqltypelen</literal></term> 8281 <term><literal>sqlownerlen</literal></term> 8282 <term><literal>sqlsourcetype</literal></term> 8283 <term><literal>sqlownername</literal></term> 8284 <term><literal>sqlsourceid</literal></term> 8285 <term><literal>sqlflags</literal></term> 8286 <term><literal>sqlreserved</literal></term> 8287 <listitem> 8288 <para> 8289 Unused. 8290 </para> 8291 </listitem> 8292 </varlistentry> 8293 8294 <varlistentry> 8295 <term><literal>sqlilongdata</literal></term> 8296 <listitem> 8297 <para> 8298 It equals to <literal>sqldata</literal> if <literal>sqllen</literal> is larger than 32kB. 8299 </para> 8300 </listitem> 8301 </varlistentry> 8302 8303 </variablelist> 8304 8305 Example: 8306<programlisting> 8307EXEC SQL INCLUDE sqlda.h; 8308 8309 sqlda_t *sqlda; /* This doesn't need to be under embedded DECLARE SECTION */ 8310 8311 EXEC SQL BEGIN DECLARE SECTION; 8312 char *prep_stmt = "select * from table1"; 8313 int i; 8314 EXEC SQL END DECLARE SECTION; 8315 8316 ... 8317 8318 EXEC SQL PREPARE mystmt FROM :prep_stmt; 8319 8320 EXEC SQL DESCRIBE mystmt INTO sqlda; 8321 8322 printf("# of fields: %d\n", sqlda->sqld); 8323 for (i = 0; i < sqlda->sqld; i++) 8324 printf("field %d: \"%s\"\n", sqlda->sqlvar[i]->sqlname); 8325 8326 EXEC SQL DECLARE mycursor CURSOR FOR mystmt; 8327 EXEC SQL OPEN mycursor; 8328 EXEC SQL WHENEVER NOT FOUND GOTO out; 8329 8330 while (1) 8331 { 8332 EXEC SQL FETCH mycursor USING sqlda; 8333 } 8334 8335 EXEC SQL CLOSE mycursor; 8336 8337 free(sqlda); /* The main structure is all to be free(), 8338 * sqlda and sqlda->sqlvar is in one allocated area */ 8339</programlisting> 8340 For more information, see the <literal>sqlda.h</literal> header and the 8341 <literal>src/interfaces/ecpg/test/compat_informix/sqlda.pgc</literal> regression test. 8342 </para> 8343 </sect2> 8344 8345 <sect2 id="ecpg-informix-functions"> 8346 <title>Additional Functions</title> 8347 <para> 8348 <variablelist> 8349 <varlistentry> 8350 <term><function>decadd</function></term> 8351 <listitem> 8352 <para> 8353 Add two decimal type values. 8354<synopsis> 8355int decadd(decimal *arg1, decimal *arg2, decimal *sum); 8356</synopsis> 8357 The function receives a pointer to the first operand of type decimal 8358 (<literal>arg1</literal>), a pointer to the second operand of type decimal 8359 (<literal>arg2</literal>) and a pointer to a value of type decimal that will 8360 contain the sum (<literal>sum</literal>). On success, the function returns 0. 8361 <symbol>ECPG_INFORMIX_NUM_OVERFLOW</symbol> is returned in case of overflow and 8362 <symbol>ECPG_INFORMIX_NUM_UNDERFLOW</symbol> in case of underflow. -1 is returned for 8363 other failures and <varname>errno</varname> is set to the respective <varname>errno</varname> number of the 8364 pgtypeslib. 8365 </para> 8366 </listitem> 8367 </varlistentry> 8368 8369 <varlistentry> 8370 <term><function>deccmp</function></term> 8371 <listitem> 8372 <para> 8373 Compare two variables of type decimal. 8374<synopsis> 8375int deccmp(decimal *arg1, decimal *arg2); 8376</synopsis> 8377 The function receives a pointer to the first decimal value 8378 (<literal>arg1</literal>), a pointer to the second decimal value 8379 (<literal>arg2</literal>) and returns an integer value that indicates which is 8380 the bigger value. 8381 <itemizedlist> 8382 <listitem> 8383 <para> 8384 1, if the value that <literal>arg1</literal> points to is bigger than the 8385 value that <literal>var2</literal> points to 8386 </para> 8387 </listitem> 8388 <listitem> 8389 <para> 8390 -1, if the value that <literal>arg1</literal> points to is smaller than the 8391 value that <literal>arg2</literal> points to </para> 8392 </listitem> 8393 <listitem> 8394 <para> 8395 0, if the value that <literal>arg1</literal> points to and the value that 8396 <literal>arg2</literal> points to are equal 8397 </para> 8398 </listitem> 8399 </itemizedlist> 8400 </para> 8401 </listitem> 8402 </varlistentry> 8403 8404 <varlistentry> 8405 <term><function>deccopy</function></term> 8406 <listitem> 8407 <para> 8408 Copy a decimal value. 8409<synopsis> 8410void deccopy(decimal *src, decimal *target); 8411</synopsis> 8412 The function receives a pointer to the decimal value that should be 8413 copied as the first argument (<literal>src</literal>) and a pointer to the 8414 target structure of type decimal (<literal>target</literal>) as the second 8415 argument. 8416 </para> 8417 </listitem> 8418 </varlistentry> 8419 8420 <varlistentry> 8421 <term><function>deccvasc</function></term> 8422 <listitem> 8423 <para> 8424 Convert a value from its ASCII representation into a decimal type. 8425<synopsis> 8426int deccvasc(char *cp, int len, decimal *np); 8427</synopsis> 8428 The function receives a pointer to string that contains the string 8429 representation of the number to be converted (<literal>cp</literal>) as well 8430 as its length <literal>len</literal>. <literal>np</literal> is a pointer to the 8431 decimal value that saves the result of the operation. 8432 </para> 8433 <para> 8434 Valid formats are for example: 8435 <literal>-2</literal>, 8436 <literal>.794</literal>, 8437 <literal>+3.44</literal>, 8438 <literal>592.49E07</literal> or 8439 <literal>-32.84e-4</literal>. 8440 </para> 8441 <para> 8442 The function returns 0 on success. If overflow or underflow occurred, 8443 <literal>ECPG_INFORMIX_NUM_OVERFLOW</literal> or 8444 <literal>ECPG_INFORMIX_NUM_UNDERFLOW</literal> is returned. If the ASCII 8445 representation could not be parsed, 8446 <literal>ECPG_INFORMIX_BAD_NUMERIC</literal> is returned or 8447 <literal>ECPG_INFORMIX_BAD_EXPONENT</literal> if this problem occurred while 8448 parsing the exponent. 8449 </para> 8450 </listitem> 8451 </varlistentry> 8452 8453 <varlistentry> 8454 <term><function>deccvdbl</function></term> 8455 <listitem> 8456 <para> 8457 Convert a value of type double to a value of type decimal. 8458<synopsis> 8459int deccvdbl(double dbl, decimal *np); 8460</synopsis> 8461 The function receives the variable of type double that should be 8462 converted as its first argument (<literal>dbl</literal>). As the second 8463 argument (<literal>np</literal>), the function receives a pointer to the 8464 decimal variable that should hold the result of the operation. 8465 </para> 8466 <para> 8467 The function returns 0 on success and a negative value if the 8468 conversion failed. 8469 </para> 8470 </listitem> 8471 </varlistentry> 8472 8473 <varlistentry> 8474 <term><function>deccvint</function></term> 8475 <listitem> 8476 <para> 8477 Convert a value of type int to a value of type decimal. 8478<synopsis> 8479int deccvint(int in, decimal *np); 8480</synopsis> 8481 The function receives the variable of type int that should be 8482 converted as its first argument (<literal>in</literal>). As the second 8483 argument (<literal>np</literal>), the function receives a pointer to the 8484 decimal variable that should hold the result of the operation. 8485 </para> 8486 <para> 8487 The function returns 0 on success and a negative value if the 8488 conversion failed. 8489 </para> 8490 </listitem> 8491 </varlistentry> 8492 8493 <varlistentry> 8494 <term><function>deccvlong</function></term> 8495 <listitem> 8496 <para> 8497 Convert a value of type long to a value of type decimal. 8498<synopsis> 8499int deccvlong(long lng, decimal *np); 8500</synopsis> 8501 The function receives the variable of type long that should be 8502 converted as its first argument (<literal>lng</literal>). As the second 8503 argument (<literal>np</literal>), the function receives a pointer to the 8504 decimal variable that should hold the result of the operation. 8505 </para> 8506 <para> 8507 The function returns 0 on success and a negative value if the 8508 conversion failed. 8509 </para> 8510 </listitem> 8511 </varlistentry> 8512 8513 <varlistentry> 8514 <term><function>decdiv</function></term> 8515 <listitem> 8516 <para> 8517 Divide two variables of type decimal. 8518<synopsis> 8519int decdiv(decimal *n1, decimal *n2, decimal *result); 8520</synopsis> 8521 The function receives pointers to the variables that are the first 8522 (<literal>n1</literal>) and the second (<literal>n2</literal>) operands and 8523 calculates <literal>n1</literal>/<literal>n2</literal>. <literal>result</literal> is a 8524 pointer to the variable that should hold the result of the operation. 8525 </para> 8526 <para> 8527 On success, 0 is returned and a negative value if the division fails. 8528 If overflow or underflow occurred, the function returns 8529 <literal>ECPG_INFORMIX_NUM_OVERFLOW</literal> or 8530 <literal>ECPG_INFORMIX_NUM_UNDERFLOW</literal> respectively. If an attempt to 8531 divide by zero is observed, the function returns 8532 <literal>ECPG_INFORMIX_DIVIDE_ZERO</literal>. 8533 </para> 8534 </listitem> 8535 </varlistentry> 8536 8537 <varlistentry> 8538 <term><function>decmul</function></term> 8539 <listitem> 8540 <para> 8541 Multiply two decimal values. 8542<synopsis> 8543int decmul(decimal *n1, decimal *n2, decimal *result); 8544</synopsis> 8545 The function receives pointers to the variables that are the first 8546 (<literal>n1</literal>) and the second (<literal>n2</literal>) operands and 8547 calculates <literal>n1</literal>*<literal>n2</literal>. <literal>result</literal> is a 8548 pointer to the variable that should hold the result of the operation. 8549 </para> 8550 <para> 8551 On success, 0 is returned and a negative value if the multiplication 8552 fails. If overflow or underflow occurred, the function returns 8553 <literal>ECPG_INFORMIX_NUM_OVERFLOW</literal> or 8554 <literal>ECPG_INFORMIX_NUM_UNDERFLOW</literal> respectively. 8555 </para> 8556 </listitem> 8557 </varlistentry> 8558 8559 <varlistentry> 8560 <term><function>decsub</function></term> 8561 <listitem> 8562 <para> 8563 Subtract one decimal value from another. 8564<synopsis> 8565int decsub(decimal *n1, decimal *n2, decimal *result); 8566</synopsis> 8567 The function receives pointers to the variables that are the first 8568 (<literal>n1</literal>) and the second (<literal>n2</literal>) operands and 8569 calculates <literal>n1</literal>-<literal>n2</literal>. <literal>result</literal> is a 8570 pointer to the variable that should hold the result of the operation. 8571 </para> 8572 <para> 8573 On success, 0 is returned and a negative value if the subtraction 8574 fails. If overflow or underflow occurred, the function returns 8575 <literal>ECPG_INFORMIX_NUM_OVERFLOW</literal> or 8576 <literal>ECPG_INFORMIX_NUM_UNDERFLOW</literal> respectively. 8577 </para> 8578 </listitem> 8579 </varlistentry> 8580 8581 <varlistentry> 8582 <term><function>dectoasc</function></term> 8583 <listitem> 8584 <para> 8585 Convert a variable of type decimal to its ASCII representation in a C 8586 char* string. 8587<synopsis> 8588int dectoasc(decimal *np, char *cp, int len, int right) 8589</synopsis> 8590 The function receives a pointer to a variable of type decimal 8591 (<literal>np</literal>) that it converts to its textual representation. 8592 <literal>cp</literal> is the buffer that should hold the result of the 8593 operation. The parameter <literal>right</literal> specifies, how many digits 8594 right of the decimal point should be included in the output. The result 8595 will be rounded to this number of decimal digits. Setting 8596 <literal>right</literal> to -1 indicates that all available decimal digits 8597 should be included in the output. If the length of the output buffer, 8598 which is indicated by <literal>len</literal> is not sufficient to hold the 8599 textual representation including the trailing zero byte, only a 8600 single <literal>*</literal> character is stored in the result and -1 is 8601 returned. 8602 </para> 8603 <para> 8604 The function returns either -1 if the buffer <literal>cp</literal> was too 8605 small or <literal>ECPG_INFORMIX_OUT_OF_MEMORY</literal> if memory was 8606 exhausted. 8607 </para> 8608 </listitem> 8609 </varlistentry> 8610 8611 <varlistentry> 8612 <term><function>dectodbl</function></term> 8613 <listitem> 8614 <para> 8615 Convert a variable of type decimal to a double. 8616<synopsis> 8617int dectodbl(decimal *np, double *dblp); 8618</synopsis> 8619 The function receives a pointer to the decimal value to convert 8620 (<literal>np</literal>) and a pointer to the double variable that 8621 should hold the result of the operation (<literal>dblp</literal>). 8622 </para> 8623 <para> 8624 On success, 0 is returned and a negative value if the conversion 8625 failed. 8626 </para> 8627 </listitem> 8628 </varlistentry> 8629 8630 <varlistentry> 8631 <term><function>dectoint</function></term> 8632 <listitem> 8633 <para> 8634 Convert a variable to type decimal to an integer. 8635<synopsis> 8636int dectoint(decimal *np, int *ip); 8637</synopsis> 8638 The function receives a pointer to the decimal value to convert 8639 (<literal>np</literal>) and a pointer to the integer variable that 8640 should hold the result of the operation (<literal>ip</literal>). 8641 </para> 8642 <para> 8643 On success, 0 is returned and a negative value if the conversion 8644 failed. If an overflow occurred, <literal>ECPG_INFORMIX_NUM_OVERFLOW</literal> 8645 is returned. 8646 </para> 8647 <para> 8648 Note that the ECPG implementation differs from the <productname>Informix</productname> 8649 implementation. <productname>Informix</productname> limits an integer to the range from -32767 to 8650 32767, while the limits in the ECPG implementation depend on the 8651 architecture (<literal>INT_MIN .. INT_MAX</literal>). 8652 </para> 8653 </listitem> 8654 </varlistentry> 8655 8656 <varlistentry> 8657 <term><function>dectolong</function></term> 8658 <listitem> 8659 <para> 8660 Convert a variable to type decimal to a long integer. 8661<synopsis> 8662int dectolong(decimal *np, long *lngp); 8663</synopsis> 8664 The function receives a pointer to the decimal value to convert 8665 (<literal>np</literal>) and a pointer to the long variable that 8666 should hold the result of the operation (<literal>lngp</literal>). 8667 </para> 8668 <para> 8669 On success, 0 is returned and a negative value if the conversion 8670 failed. If an overflow occurred, <literal>ECPG_INFORMIX_NUM_OVERFLOW</literal> 8671 is returned. 8672 </para> 8673 <para> 8674 Note that the ECPG implementation differs from the <productname>Informix</productname> 8675 implementation. <productname>Informix</productname> limits a long integer to the range from 8676 -2,147,483,647 to 2,147,483,647, while the limits in the ECPG 8677 implementation depend on the architecture (<literal>-LONG_MAX .. 8678 LONG_MAX</literal>). 8679 </para> 8680 </listitem> 8681 </varlistentry> 8682 8683 <varlistentry> 8684 <term><function>rdatestr</function></term> 8685 <listitem> 8686 <para> 8687 Converts a date to a C char* string. 8688<synopsis> 8689int rdatestr(date d, char *str); 8690</synopsis> 8691 The function receives two arguments, the first one is the date to 8692 convert (<literal>d</literal>) and the second one is a pointer to the target 8693 string. The output format is always <literal>yyyy-mm-dd</literal>, so you need 8694 to allocate at least 11 bytes (including the zero-byte terminator) for the 8695 string. 8696 </para> 8697 <para> 8698 The function returns 0 on success and a negative value in case of 8699 error. 8700 </para> 8701 <para> 8702 Note that ECPG's implementation differs from the <productname>Informix</productname> 8703 implementation. In <productname>Informix</productname> the format can be influenced by setting 8704 environment variables. In ECPG however, you cannot change the output 8705 format. 8706 </para> 8707 </listitem> 8708 </varlistentry> 8709 8710 <varlistentry> 8711 <term><function>rstrdate</function></term> 8712 <listitem> 8713 <para> 8714 Parse the textual representation of a date. 8715<synopsis> 8716int rstrdate(char *str, date *d); 8717</synopsis> 8718 The function receives the textual representation of the date to convert 8719 (<literal>str</literal>) and a pointer to a variable of type date 8720 (<literal>d</literal>). This function does not allow you to specify a format 8721 mask. It uses the default format mask of <productname>Informix</productname> which is 8722 <literal>mm/dd/yyyy</literal>. Internally, this function is implemented by 8723 means of <function>rdefmtdate</function>. Therefore, <function>rstrdate</function> is 8724 not faster and if you have the choice you should opt for 8725 <function>rdefmtdate</function> which allows you to specify the format mask 8726 explicitly. 8727 </para> 8728 <para> 8729 The function returns the same values as <function>rdefmtdate</function>. 8730 </para> 8731 </listitem> 8732 </varlistentry> 8733 8734 <varlistentry> 8735 <term><function>rtoday</function></term> 8736 <listitem> 8737 <para> 8738 Get the current date. 8739<synopsis> 8740void rtoday(date *d); 8741</synopsis> 8742 The function receives a pointer to a date variable (<literal>d</literal>) 8743 that it sets to the current date. 8744 </para> 8745 <para> 8746 Internally this function uses the <xref linkend="pgtypesdatetoday"/> 8747 function. 8748 </para> 8749 </listitem> 8750 </varlistentry> 8751 8752 <varlistentry> 8753 <term><function>rjulmdy</function></term> 8754 <listitem> 8755 <para> 8756 Extract the values for the day, the month and the year from a variable 8757 of type date. 8758<synopsis> 8759int rjulmdy(date d, short mdy[3]); 8760</synopsis> 8761 The function receives the date <literal>d</literal> and a pointer to an array 8762 of 3 short integer values <literal>mdy</literal>. The variable name indicates 8763 the sequential order: <literal>mdy[0]</literal> will be set to contain the 8764 number of the month, <literal>mdy[1]</literal> will be set to the value of the 8765 day and <literal>mdy[2]</literal> will contain the year. 8766 </para> 8767 <para> 8768 The function always returns 0 at the moment. 8769 </para> 8770 <para> 8771 Internally the function uses the <xref linkend="pgtypesdatejulmdy"/> 8772 function. 8773 </para> 8774 </listitem> 8775 </varlistentry> 8776 8777 <varlistentry> 8778 <term><function>rdefmtdate</function></term> 8779 <listitem> 8780 <para> 8781 Use a format mask to convert a character string to a value of type 8782 date. 8783<synopsis> 8784int rdefmtdate(date *d, char *fmt, char *str); 8785</synopsis> 8786 The function receives a pointer to the date value that should hold the 8787 result of the operation (<literal>d</literal>), the format mask to use for 8788 parsing the date (<literal>fmt</literal>) and the C char* string containing 8789 the textual representation of the date (<literal>str</literal>). The textual 8790 representation is expected to match the format mask. However you do not 8791 need to have a 1:1 mapping of the string to the format mask. The 8792 function only analyzes the sequential order and looks for the literals 8793 <literal>yy</literal> or <literal>yyyy</literal> that indicate the 8794 position of the year, <literal>mm</literal> to indicate the position of 8795 the month and <literal>dd</literal> to indicate the position of the 8796 day. 8797 </para> 8798 <para> 8799 The function returns the following values: 8800 <itemizedlist> 8801 <listitem> 8802 <para> 8803 0 - The function terminated successfully. 8804 </para> 8805 </listitem> 8806 <listitem> 8807 <para> 8808 <literal>ECPG_INFORMIX_ENOSHORTDATE</literal> - The date does not contain 8809 delimiters between day, month and year. In this case the input 8810 string must be exactly 6 or 8 bytes long but isn't. 8811 </para> 8812 </listitem> 8813 <listitem> 8814 <para> 8815 <literal>ECPG_INFORMIX_ENOTDMY</literal> - The format string did not 8816 correctly indicate the sequential order of year, month and day. 8817 </para> 8818 </listitem> 8819 <listitem> 8820 <para> 8821 <literal>ECPG_INFORMIX_BAD_DAY</literal> - The input string does not 8822 contain a valid day. 8823 </para> 8824 </listitem> 8825 <listitem> 8826 <para> 8827 <literal>ECPG_INFORMIX_BAD_MONTH</literal> - The input string does not 8828 contain a valid month. 8829 </para> 8830 </listitem> 8831 <listitem> 8832 <para> 8833 <literal>ECPG_INFORMIX_BAD_YEAR</literal> - The input string does not 8834 contain a valid year. 8835 </para> 8836 </listitem> 8837 </itemizedlist> 8838 </para> 8839 <para> 8840 Internally this function is implemented to use the <xref 8841 linkend="pgtypesdatedefmtasc"/> function. See the reference there for a 8842 table of example input. 8843 </para> 8844 </listitem> 8845 </varlistentry> 8846 8847 <varlistentry> 8848 <term><function>rfmtdate</function></term> 8849 <listitem> 8850 <para> 8851 Convert a variable of type date to its textual representation using a 8852 format mask. 8853<synopsis> 8854int rfmtdate(date d, char *fmt, char *str); 8855</synopsis> 8856 The function receives the date to convert (<literal>d</literal>), the format 8857 mask (<literal>fmt</literal>) and the string that will hold the textual 8858 representation of the date (<literal>str</literal>). 8859 </para> 8860 <para> 8861 On success, 0 is returned and a negative value if an error occurred. 8862 </para> 8863 <para> 8864 Internally this function uses the <xref linkend="pgtypesdatefmtasc"/> 8865 function, see the reference there for examples. 8866 </para> 8867 </listitem> 8868 </varlistentry> 8869 8870 <varlistentry> 8871 <term><function>rmdyjul</function></term> 8872 <listitem> 8873 <para> 8874 Create a date value from an array of 3 short integers that specify the 8875 day, the month and the year of the date. 8876<synopsis> 8877int rmdyjul(short mdy[3], date *d); 8878</synopsis> 8879 The function receives the array of the 3 short integers 8880 (<literal>mdy</literal>) and a pointer to a variable of type date that should 8881 hold the result of the operation. 8882 </para> 8883 <para> 8884 Currently the function returns always 0. 8885 </para> 8886 <para> 8887 Internally the function is implemented to use the function <xref 8888 linkend="pgtypesdatemdyjul"/>. 8889 </para> 8890 </listitem> 8891 </varlistentry> 8892 8893 <varlistentry> 8894 <term><function>rdayofweek</function></term> 8895 <listitem> 8896 <para> 8897 Return a number representing the day of the week for a date value. 8898<synopsis> 8899int rdayofweek(date d); 8900</synopsis> 8901 The function receives the date variable <literal>d</literal> as its only 8902 argument and returns an integer that indicates the day of the week for 8903 this date. 8904 <itemizedlist> 8905 <listitem> 8906 <para> 8907 0 - Sunday 8908 </para> 8909 </listitem> 8910 <listitem> 8911 <para> 8912 1 - Monday 8913 </para> 8914 </listitem> 8915 <listitem> 8916 <para> 8917 2 - Tuesday 8918 </para> 8919 </listitem> 8920 <listitem> 8921 <para> 8922 3 - Wednesday 8923 </para> 8924 </listitem> 8925 <listitem> 8926 <para> 8927 4 - Thursday 8928 </para> 8929 </listitem> 8930 <listitem> 8931 <para> 8932 5 - Friday 8933 </para> 8934 </listitem> 8935 <listitem> 8936 <para> 8937 6 - Saturday 8938 </para> 8939 </listitem> 8940 </itemizedlist> 8941 </para> 8942 <para> 8943 Internally the function is implemented to use the function <xref 8944 linkend="pgtypesdatedayofweek"/>. 8945 </para> 8946 </listitem> 8947 </varlistentry> 8948 8949 <varlistentry> 8950 <term><function>dtcurrent</function></term> 8951 <listitem> 8952 <para> 8953 Retrieve the current timestamp. 8954<synopsis> 8955void dtcurrent(timestamp *ts); 8956</synopsis> 8957 The function retrieves the current timestamp and saves it into the 8958 timestamp variable that <literal>ts</literal> points to. 8959 </para> 8960 </listitem> 8961 </varlistentry> 8962 8963 <varlistentry> 8964 <term><function>dtcvasc</function></term> 8965 <listitem> 8966 <para> 8967 Parses a timestamp from its textual representation 8968 into a timestamp variable. 8969<synopsis> 8970int dtcvasc(char *str, timestamp *ts); 8971</synopsis> 8972 The function receives the string to parse (<literal>str</literal>) and a 8973 pointer to the timestamp variable that should hold the result of the 8974 operation (<literal>ts</literal>). 8975 </para> 8976 <para> 8977 The function returns 0 on success and a negative value in case of 8978 error. 8979 </para> 8980 <para> 8981 Internally this function uses the <xref 8982 linkend="pgtypestimestampfromasc"/> function. See the reference there 8983 for a table with example inputs. 8984 </para> 8985 </listitem> 8986 </varlistentry> 8987 8988 <varlistentry> 8989 <term><function>dtcvfmtasc</function></term> 8990 <listitem> 8991 <para> 8992 Parses a timestamp from its textual representation 8993 using a format mask into a timestamp variable. 8994<synopsis> 8995dtcvfmtasc(char *inbuf, char *fmtstr, timestamp *dtvalue) 8996</synopsis> 8997 The function receives the string to parse (<literal>inbuf</literal>), the 8998 format mask to use (<literal>fmtstr</literal>) and a pointer to the timestamp 8999 variable that should hold the result of the operation 9000 (<literal>dtvalue</literal>). 9001 </para> 9002 <para> 9003 This function is implemented by means of the <xref 9004 linkend="pgtypestimestampdefmtasc"/> function. See the documentation 9005 there for a list of format specifiers that can be used. 9006 </para> 9007 <para> 9008 The function returns 0 on success and a negative value in case of 9009 error. 9010 </para> 9011 </listitem> 9012 </varlistentry> 9013 9014 <varlistentry> 9015 <term><function>dtsub</function></term> 9016 <listitem> 9017 <para> 9018 Subtract one timestamp from another and return a variable of type 9019 interval. 9020<synopsis> 9021int dtsub(timestamp *ts1, timestamp *ts2, interval *iv); 9022</synopsis> 9023 The function will subtract the timestamp variable that <literal>ts2</literal> 9024 points to from the timestamp variable that <literal>ts1</literal> points to 9025 and will store the result in the interval variable that <literal>iv</literal> 9026 points to. 9027 </para> 9028 <para> 9029 Upon success, the function returns 0 and a negative value if an 9030 error occurred. 9031 </para> 9032 </listitem> 9033 </varlistentry> 9034 9035 <varlistentry> 9036 <term><function>dttoasc</function></term> 9037 <listitem> 9038 <para> 9039 Convert a timestamp variable to a C char* string. 9040<synopsis> 9041int dttoasc(timestamp *ts, char *output); 9042</synopsis> 9043 The function receives a pointer to the timestamp variable to convert 9044 (<literal>ts</literal>) and the string that should hold the result of the 9045 operation (<literal>output</literal>). It converts <literal>ts</literal> to its 9046 textual representation according to the SQL standard, which is 9047 be <literal>YYYY-MM-DD HH:MM:SS</literal>. 9048 </para> 9049 <para> 9050 Upon success, the function returns 0 and a negative value if an 9051 error occurred. 9052 </para> 9053 </listitem> 9054 </varlistentry> 9055 9056 <varlistentry> 9057 <term><function>dttofmtasc</function></term> 9058 <listitem> 9059 <para> 9060 Convert a timestamp variable to a C char* using a format mask. 9061<synopsis> 9062int dttofmtasc(timestamp *ts, char *output, int str_len, char *fmtstr); 9063</synopsis> 9064 The function receives a pointer to the timestamp to convert as its 9065 first argument (<literal>ts</literal>), a pointer to the output buffer 9066 (<literal>output</literal>), the maximal length that has been allocated for 9067 the output buffer (<literal>str_len</literal>) and the format mask to 9068 use for the conversion (<literal>fmtstr</literal>). 9069 </para> 9070 <para> 9071 Upon success, the function returns 0 and a negative value if an 9072 error occurred. 9073 </para> 9074 <para> 9075 Internally, this function uses the <xref 9076 linkend="pgtypestimestampfmtasc"/> function. See the reference there for 9077 information on what format mask specifiers can be used. 9078 </para> 9079 </listitem> 9080 </varlistentry> 9081 9082 <varlistentry> 9083 <term><function>intoasc</function></term> 9084 <listitem> 9085 <para> 9086 Convert an interval variable to a C char* string. 9087<synopsis> 9088int intoasc(interval *i, char *str); 9089</synopsis> 9090 The function receives a pointer to the interval variable to convert 9091 (<literal>i</literal>) and the string that should hold the result of the 9092 operation (<literal>str</literal>). It converts <literal>i</literal> to its 9093 textual representation according to the SQL standard, which is 9094 be <literal>YYYY-MM-DD HH:MM:SS</literal>. 9095 </para> 9096 <para> 9097 Upon success, the function returns 0 and a negative value if an 9098 error occurred. 9099 </para> 9100 </listitem> 9101 </varlistentry> 9102 9103 <varlistentry> 9104 <term><function>rfmtlong</function></term> 9105 <listitem> 9106 <para> 9107 Convert a long integer value to its textual representation using a 9108 format mask. 9109<synopsis> 9110int rfmtlong(long lng_val, char *fmt, char *outbuf); 9111</synopsis> 9112 The function receives the long value <literal>lng_val</literal>, the format 9113 mask <literal>fmt</literal> and a pointer to the output buffer 9114 <literal>outbuf</literal>. It converts the long value according to the format 9115 mask to its textual representation. 9116 </para> 9117 <para> 9118 The format mask can be composed of the following format specifying 9119 characters: 9120 <itemizedlist> 9121 <listitem> 9122 <para> 9123 <literal>*</literal> (asterisk) - if this position would be blank 9124 otherwise, fill it with an asterisk. 9125 </para> 9126 </listitem> 9127 <listitem> 9128 <para> 9129 <literal>&</literal> (ampersand) - if this position would be 9130 blank otherwise, fill it with a zero. 9131 </para> 9132 </listitem> 9133 <listitem> 9134 <para> 9135 <literal>#</literal> - turn leading zeroes into blanks. 9136 </para> 9137 </listitem> 9138 <listitem> 9139 <para> 9140 <literal><</literal> - left-justify the number in the string. 9141 </para> 9142 </listitem> 9143 <listitem> 9144 <para> 9145 <literal>,</literal> (comma) - group numbers of four or more digits 9146 into groups of three digits separated by a comma. 9147 </para> 9148 </listitem> 9149 <listitem> 9150 <para> 9151 <literal>.</literal> (period) - this character separates the 9152 whole-number part of the number from the fractional part. 9153 </para> 9154 </listitem> 9155 <listitem> 9156 <para> 9157 <literal>-</literal> (minus) - the minus sign appears if the number 9158 is a negative value. 9159 </para> 9160 </listitem> 9161 <listitem> 9162 <para> 9163 <literal>+</literal> (plus) - the plus sign appears if the number is 9164 a positive value. 9165 </para> 9166 </listitem> 9167 <listitem> 9168 <para> 9169 <literal>(</literal> - this replaces the minus sign in front of the 9170 negative number. The minus sign will not appear. 9171 </para> 9172 </listitem> 9173 <listitem> 9174 <para> 9175 <literal>)</literal> - this character replaces the minus and is 9176 printed behind the negative value. 9177 </para> 9178 </listitem> 9179 <listitem> 9180 <para> 9181 <literal>$</literal> - the currency symbol. 9182 </para> 9183 </listitem> 9184 </itemizedlist> 9185 </para> 9186 </listitem> 9187 </varlistentry> 9188 9189 <varlistentry> 9190 <term><function>rupshift</function></term> 9191 <listitem> 9192 <para> 9193 Convert a string to upper case. 9194<synopsis> 9195void rupshift(char *str); 9196</synopsis> 9197 The function receives a pointer to the string and transforms every 9198 lower case character to upper case. 9199 </para> 9200 </listitem> 9201 </varlistentry> 9202 9203 <varlistentry> 9204 <term><function>byleng</function></term> 9205 <listitem> 9206 <para> 9207 Return the number of characters in a string without counting trailing 9208 blanks. 9209<synopsis> 9210int byleng(char *str, int len); 9211</synopsis> 9212 The function expects a fixed-length string as its first argument 9213 (<literal>str</literal>) and its length as its second argument 9214 (<literal>len</literal>). It returns the number of significant characters, 9215 that is the length of the string without trailing blanks. 9216 </para> 9217 </listitem> 9218 </varlistentry> 9219 9220 <varlistentry> 9221 <term><function>ldchar</function></term> 9222 <listitem> 9223 <para> 9224 Copy a fixed-length string into a null-terminated string. 9225<synopsis> 9226void ldchar(char *src, int len, char *dest); 9227</synopsis> 9228 The function receives the fixed-length string to copy 9229 (<literal>src</literal>), its length (<literal>len</literal>) and a pointer to the 9230 destination memory (<literal>dest</literal>). Note that you need to reserve at 9231 least <literal>len+1</literal> bytes for the string that <literal>dest</literal> 9232 points to. The function copies at most <literal>len</literal> bytes to the new 9233 location (less if the source string has trailing blanks) and adds the 9234 null-terminator. 9235 </para> 9236 </listitem> 9237 </varlistentry> 9238 9239 <varlistentry> 9240 <term><function>rgetmsg</function></term> 9241 <listitem> 9242 <para> 9243<synopsis> 9244int rgetmsg(int msgnum, char *s, int maxsize); 9245</synopsis> 9246 This function exists but is not implemented at the moment! 9247 </para> 9248 </listitem> 9249 </varlistentry> 9250 9251 <varlistentry> 9252 <term><function>rtypalign</function></term> 9253 <listitem> 9254 <para> 9255<synopsis> 9256int rtypalign(int offset, int type); 9257</synopsis> 9258 This function exists but is not implemented at the moment! 9259 </para> 9260 </listitem> 9261 </varlistentry> 9262 9263 <varlistentry> 9264 <term><function>rtypmsize</function></term> 9265 <listitem> 9266 <para> 9267<synopsis> 9268int rtypmsize(int type, int len); 9269</synopsis> 9270 This function exists but is not implemented at the moment! 9271 </para> 9272 </listitem> 9273 </varlistentry> 9274 9275 <varlistentry> 9276 <term><function>rtypwidth</function></term> 9277 <listitem> 9278 <para> 9279<synopsis> 9280int rtypwidth(int sqltype, int sqllen); 9281</synopsis> 9282 This function exists but is not implemented at the moment! 9283 </para> 9284 </listitem> 9285 </varlistentry> 9286 9287 <varlistentry id="rsetnull"> 9288 <term><function>rsetnull</function></term> 9289 <listitem> 9290 <para> 9291 Set a variable to NULL. 9292<synopsis> 9293int rsetnull(int t, char *ptr); 9294</synopsis> 9295 The function receives an integer that indicates the type of the 9296 variable and a pointer to the variable itself that is cast to a C 9297 char* pointer. 9298 </para> 9299 <para> 9300 The following types exist: 9301 <itemizedlist> 9302 <listitem> 9303 <para> 9304 <literal>CCHARTYPE</literal> - For a variable of type <type>char</type> or <type>char*</type> 9305 </para> 9306 </listitem> 9307 <listitem> 9308 <para> 9309 <literal>CSHORTTYPE</literal> - For a variable of type <type>short int</type> 9310 </para> 9311 </listitem> 9312 <listitem> 9313 <para> 9314 <literal>CINTTYPE</literal> - For a variable of type <type>int</type> 9315 </para> 9316 </listitem> 9317 <listitem> 9318 <para> 9319 <literal>CBOOLTYPE</literal> - For a variable of type <type>boolean</type> 9320 </para> 9321 </listitem> 9322 <listitem> 9323 <para> 9324 <literal>CFLOATTYPE</literal> - For a variable of type <type>float</type> 9325 </para> 9326 </listitem> 9327 <listitem> 9328 <para> 9329 <literal>CLONGTYPE</literal> - For a variable of type <type>long</type> 9330 </para> 9331 </listitem> 9332 <listitem> 9333 <para> 9334 <literal>CDOUBLETYPE</literal> - For a variable of type <type>double</type> 9335 </para> 9336 </listitem> 9337 <listitem> 9338 <para> 9339 <literal>CDECIMALTYPE</literal> - For a variable of type <type>decimal</type> 9340 </para> 9341 </listitem> 9342 <listitem> 9343 <para> 9344 <literal>CDATETYPE</literal> - For a variable of type <type>date</type> 9345 </para> 9346 </listitem> 9347 <listitem> 9348 <para> 9349 <literal>CDTIMETYPE</literal> - For a variable of type <type>timestamp</type> 9350 </para> 9351 </listitem> 9352 </itemizedlist> 9353 </para> 9354 9355 <para> 9356 Here is an example of a call to this function: 9357<programlisting><![CDATA[ 9358$char c[] = "abc "; 9359$short s = 17; 9360$int i = -74874; 9361 9362rsetnull(CCHARTYPE, (char *) c); 9363rsetnull(CSHORTTYPE, (char *) &s); 9364rsetnull(CINTTYPE, (char *) &i); 9365]]> 9366</programlisting> 9367 </para> 9368 </listitem> 9369 </varlistentry> 9370 9371 <varlistentry> 9372 <term><function>risnull</function></term> 9373 <listitem> 9374 <para> 9375 Test if a variable is NULL. 9376<synopsis> 9377int risnull(int t, char *ptr); 9378</synopsis> 9379 The function receives the type of the variable to test (<literal>t</literal>) 9380 as well a pointer to this variable (<literal>ptr</literal>). Note that the 9381 latter needs to be cast to a char*. See the function <xref 9382 linkend="rsetnull"/> for a list of possible variable types. 9383 </para> 9384 <para> 9385 Here is an example of how to use this function: 9386<programlisting><![CDATA[ 9387$char c[] = "abc "; 9388$short s = 17; 9389$int i = -74874; 9390 9391risnull(CCHARTYPE, (char *) c); 9392risnull(CSHORTTYPE, (char *) &s); 9393risnull(CINTTYPE, (char *) &i); 9394]]> 9395</programlisting> 9396 </para> 9397 </listitem> 9398 </varlistentry> 9399 </variablelist> 9400 </para> 9401 </sect2> 9402 9403 <sect2 id="ecpg-informix-constants"> 9404 <title>Additional Constants</title> 9405 <para> 9406 Note that all constants here describe errors and all of them are defined 9407 to represent negative values. In the descriptions of the different 9408 constants you can also find the value that the constants represent in the 9409 current implementation. However you should not rely on this number. You can 9410 however rely on the fact all of them are defined to represent negative 9411 values. 9412 <variablelist> 9413 <varlistentry> 9414 <term><literal>ECPG_INFORMIX_NUM_OVERFLOW</literal></term> 9415 <listitem> 9416 <para> 9417 Functions return this value if an overflow occurred in a 9418 calculation. Internally it is defined as -1200 (the <productname>Informix</productname> 9419 definition). 9420 </para> 9421 </listitem> 9422 </varlistentry> 9423 9424 <varlistentry> 9425 <term><literal>ECPG_INFORMIX_NUM_UNDERFLOW</literal></term> 9426 <listitem> 9427 <para> 9428 Functions return this value if an underflow occurred in a calculation. 9429 Internally it is defined as -1201 (the <productname>Informix</productname> definition). 9430 </para> 9431 </listitem> 9432 </varlistentry> 9433 9434 <varlistentry> 9435 <term><literal>ECPG_INFORMIX_DIVIDE_ZERO</literal></term> 9436 <listitem> 9437 <para> 9438 Functions return this value if an attempt to divide by zero is 9439 observed. Internally it is defined as -1202 (the <productname>Informix</productname> definition). 9440 </para> 9441 </listitem> 9442 </varlistentry> 9443 9444 <varlistentry> 9445 <term><literal>ECPG_INFORMIX_BAD_YEAR</literal></term> 9446 <listitem> 9447 <para> 9448 Functions return this value if a bad value for a year was found while 9449 parsing a date. Internally it is defined as -1204 (the <productname>Informix</productname> 9450 definition). 9451 </para> 9452 </listitem> 9453 </varlistentry> 9454 9455 <varlistentry> 9456 <term><literal>ECPG_INFORMIX_BAD_MONTH</literal></term> 9457 <listitem> 9458 <para> 9459 Functions return this value if a bad value for a month was found while 9460 parsing a date. Internally it is defined as -1205 (the <productname>Informix</productname> 9461 definition). 9462 </para> 9463 </listitem> 9464 </varlistentry> 9465 9466 <varlistentry> 9467 <term><literal>ECPG_INFORMIX_BAD_DAY</literal></term> 9468 <listitem> 9469 <para> 9470 Functions return this value if a bad value for a day was found while 9471 parsing a date. Internally it is defined as -1206 (the <productname>Informix</productname> 9472 definition). 9473 </para> 9474 </listitem> 9475 </varlistentry> 9476 9477 <varlistentry> 9478 <term><literal>ECPG_INFORMIX_ENOSHORTDATE</literal></term> 9479 <listitem> 9480 <para> 9481 Functions return this value if a parsing routine needs a short date 9482 representation but did not get the date string in the right length. 9483 Internally it is defined as -1209 (the <productname>Informix</productname> definition). 9484 </para> 9485 </listitem> 9486 </varlistentry> 9487 9488 <varlistentry> 9489 <term><literal>ECPG_INFORMIX_DATE_CONVERT</literal></term> 9490 <listitem> 9491 <para> 9492 Functions return this value if an error occurred during date 9493 formatting. Internally it is defined as -1210 (the 9494 <productname>Informix</productname> definition). 9495 </para> 9496 </listitem> 9497 </varlistentry> 9498 9499 <varlistentry> 9500 <term><literal>ECPG_INFORMIX_OUT_OF_MEMORY</literal></term> 9501 <listitem> 9502 <para> 9503 Functions return this value if memory was exhausted during 9504 their operation. Internally it is defined as -1211 (the 9505 <productname>Informix</productname> definition). 9506 </para> 9507 </listitem> 9508 </varlistentry> 9509 9510 <varlistentry> 9511 <term><literal>ECPG_INFORMIX_ENOTDMY</literal></term> 9512 <listitem> 9513 <para> 9514 Functions return this value if a parsing routine was supposed to get a 9515 format mask (like <literal>mmddyy</literal>) but not all fields were listed 9516 correctly. Internally it is defined as -1212 (the <productname>Informix</productname> definition). 9517 </para> 9518 </listitem> 9519 </varlistentry> 9520 9521 <varlistentry> 9522 <term><literal>ECPG_INFORMIX_BAD_NUMERIC</literal></term> 9523 <listitem> 9524 <para> 9525 Functions return this value either if a parsing routine cannot parse 9526 the textual representation for a numeric value because it contains 9527 errors or if a routine cannot complete a calculation involving numeric 9528 variables because at least one of the numeric variables is invalid. 9529 Internally it is defined as -1213 (the <productname>Informix</productname> definition). 9530 </para> 9531 </listitem> 9532 </varlistentry> 9533 9534 <varlistentry> 9535 <term><literal>ECPG_INFORMIX_BAD_EXPONENT</literal></term> 9536 <listitem> 9537 <para> 9538 Functions return this value if a parsing routine cannot parse 9539 an exponent. Internally it is defined as -1216 (the 9540 <productname>Informix</productname> definition). 9541 </para> 9542 </listitem> 9543 </varlistentry> 9544 9545 <varlistentry> 9546 <term><literal>ECPG_INFORMIX_BAD_DATE</literal></term> 9547 <listitem> 9548 <para> 9549 Functions return this value if a parsing routine cannot parse 9550 a date. Internally it is defined as -1218 (the 9551 <productname>Informix</productname> definition). 9552 </para> 9553 </listitem> 9554 </varlistentry> 9555 9556 <varlistentry> 9557 <term><literal>ECPG_INFORMIX_EXTRA_CHARS</literal></term> 9558 <listitem> 9559 <para> 9560 Functions return this value if a parsing routine is passed extra 9561 characters it cannot parse. Internally it is defined as -1264 (the 9562 <productname>Informix</productname> definition). 9563 </para> 9564 </listitem> 9565 </varlistentry> 9566 </variablelist> 9567 </para> 9568 </sect2> 9569 </sect1> 9570 9571 <sect1 id="ecpg-develop"> 9572 <title>Internals</title> 9573 9574 <para> 9575 This section explains how <application>ECPG</application> works 9576 internally. This information can occasionally be useful to help 9577 users understand how to use <application>ECPG</application>. 9578 </para> 9579 9580 <para> 9581 The first four lines written by <command>ecpg</command> to the 9582 output are fixed lines. Two are comments and two are include 9583 lines necessary to interface to the library. Then the 9584 preprocessor reads through the file and writes output. Normally 9585 it just echoes everything to the output. 9586 </para> 9587 9588 <para> 9589 When it sees an <command>EXEC SQL</command> statement, it 9590 intervenes and changes it. The command starts with <command>EXEC 9591 SQL</command> and ends with <command>;</command>. Everything in 9592 between is treated as an <acronym>SQL</acronym> statement and 9593 parsed for variable substitution. 9594 </para> 9595 9596 <para> 9597 Variable substitution occurs when a symbol starts with a colon 9598 (<literal>:</literal>). The variable with that name is looked up 9599 among the variables that were previously declared within a 9600 <literal>EXEC SQL DECLARE</literal> section. 9601 </para> 9602 9603 <para> 9604 The most important function in the library is 9605 <function>ECPGdo</function>, which takes care of executing most 9606 commands. It takes a variable number of arguments. This can easily 9607 add up to 50 or so arguments, and we hope this will not be a 9608 problem on any platform. 9609 </para> 9610 9611 <para> 9612 The arguments are: 9613 9614 <variablelist> 9615 <varlistentry> 9616 <term>A line number</term> 9617 <listitem> 9618 <para> 9619 This is the line number of the original line; used in error 9620 messages only. 9621 </para> 9622 </listitem> 9623 </varlistentry> 9624 9625 <varlistentry> 9626 <term>A string</term> 9627 <listitem> 9628 <para> 9629 This is the <acronym>SQL</acronym> command that is to be issued. 9630 It is modified by the input variables, i.e., the variables that 9631 where not known at compile time but are to be entered in the 9632 command. Where the variables should go the string contains 9633 <literal>?</literal>. 9634 </para> 9635 </listitem> 9636 </varlistentry> 9637 9638 <varlistentry> 9639 <term>Input variables</term> 9640 <listitem> 9641 <para> 9642 Every input variable causes ten arguments to be created. (See below.) 9643 </para> 9644 </listitem> 9645 </varlistentry> 9646 9647 <varlistentry> 9648 <term><parameter>ECPGt_EOIT</parameter></term> 9649 <listitem> 9650 <para> 9651 An <type>enum</type> telling that there are no more input 9652 variables. 9653 </para> 9654 </listitem> 9655 </varlistentry> 9656 9657 <varlistentry> 9658 <term>Output variables</term> 9659 <listitem> 9660 <para> 9661 Every output variable causes ten arguments to be created. 9662 (See below.) These variables are filled by the function. 9663 </para> 9664 </listitem> 9665 </varlistentry> 9666 9667 <varlistentry> 9668 <term><parameter>ECPGt_EORT</parameter></term> 9669 <listitem> 9670 <para> 9671 An <type>enum</type> telling that there are no more variables. 9672 </para> 9673 </listitem> 9674 </varlistentry> 9675 </variablelist> 9676 </para> 9677 9678 <para> 9679 For every variable that is part of the <acronym>SQL</acronym> 9680 command, the function gets ten arguments: 9681 9682 <orderedlist> 9683 <listitem> 9684 <para> 9685 The type as a special symbol. 9686 </para> 9687 </listitem> 9688 9689 <listitem> 9690 <para> 9691 A pointer to the value or a pointer to the pointer. 9692 </para> 9693 </listitem> 9694 9695 <listitem> 9696 <para> 9697 The size of the variable if it is a <type>char</type> or <type>varchar</type>. 9698 </para> 9699 </listitem> 9700 9701 <listitem> 9702 <para> 9703 The number of elements in the array (for array fetches). 9704 </para> 9705 </listitem> 9706 9707 <listitem> 9708 <para> 9709 The offset to the next element in the array (for array fetches). 9710 </para> 9711 </listitem> 9712 9713 <listitem> 9714 <para> 9715 The type of the indicator variable as a special symbol. 9716 </para> 9717 </listitem> 9718 9719 <listitem> 9720 <para> 9721 A pointer to the indicator variable. 9722 </para> 9723 </listitem> 9724 9725 <listitem> 9726 <para> 9727 0 9728 </para> 9729 </listitem> 9730 9731 <listitem> 9732 <para> 9733 The number of elements in the indicator array (for array fetches). 9734 </para> 9735 </listitem> 9736 9737 <listitem> 9738 <para> 9739 The offset to the next element in the indicator array (for 9740 array fetches). 9741 </para> 9742 </listitem> 9743 </orderedlist> 9744 </para> 9745 9746 <para> 9747 Note that not all SQL commands are treated in this way. For 9748 instance, an open cursor statement like: 9749<programlisting> 9750EXEC SQL OPEN <replaceable>cursor</replaceable>; 9751</programlisting> 9752 is not copied to the output. Instead, the cursor's 9753 <command>DECLARE</command> command is used at the position of the <command>OPEN</command> command 9754 because it indeed opens the cursor. 9755 </para> 9756 9757 <para> 9758 Here is a complete example describing the output of the 9759 preprocessor of a file <filename>foo.pgc</filename> (details might 9760 change with each particular version of the preprocessor): 9761<programlisting> 9762EXEC SQL BEGIN DECLARE SECTION; 9763int index; 9764int result; 9765EXEC SQL END DECLARE SECTION; 9766... 9767EXEC SQL SELECT res INTO :result FROM mytable WHERE index = :index; 9768</programlisting> 9769 is translated into: 9770<programlisting><![CDATA[ 9771/* Processed by ecpg (2.6.0) */ 9772/* These two include files are added by the preprocessor */ 9773#include <ecpgtype.h>; 9774#include <ecpglib.h>; 9775 9776/* exec sql begin declare section */ 9777 9778#line 1 "foo.pgc" 9779 9780 int index; 9781 int result; 9782/* exec sql end declare section */ 9783... 9784ECPGdo(__LINE__, NULL, "SELECT res FROM mytable WHERE index = ? ", 9785 ECPGt_int,&(index),1L,1L,sizeof(int), 9786 ECPGt_NO_INDICATOR, NULL , 0L, 0L, 0L, ECPGt_EOIT, 9787 ECPGt_int,&(result),1L,1L,sizeof(int), 9788 ECPGt_NO_INDICATOR, NULL , 0L, 0L, 0L, ECPGt_EORT); 9789#line 147 "foo.pgc" 9790]]> 9791</programlisting> 9792 (The indentation here is added for readability and not 9793 something the preprocessor does.) 9794 </para> 9795 </sect1> 9796</chapter> 9797