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