バージョンごとのドキュメント一覧

36.4. ホスト変数の使用 #

<title>Using Host Variables</title>

In <xref linkend="ecpg-commands"/> you saw how you can execute SQL statements from an embedded SQL program. Some of those statements only used fixed values and did not provide a way to insert user-supplied values into statements or have the program process the values returned by the query. Those kinds of statements are not really useful in real applications. This section explains in detail how you can pass data between your C program and the embedded SQL statements using a simple mechanism called <firstterm>host variables</firstterm>. In an embedded SQL program we consider the SQL statements to be <firstterm>guests</firstterm> in the C program code which is the <firstterm>host language</firstterm>. Therefore the variables of the C program are called <firstterm>host variables</firstterm>. 36.3では、埋め込みSQLプログラムでどのようにSQL文を実行するのかについて説明しました。 このSQL文の中には固定値しか使用しないものや、ユーザが指定する値をSQL文の中に挿入する手段を提供しないもの、問い合わせが返す値をプログラムで処理する手段を提供しないものがありました。 この種のSQL文は実際のアプリケーションでは役に立ちません。 本節では、ホスト変数という単純な機構を使用した、Cプログラムと埋め込みSQL文との間でデータをやり取りする方法を詳細に説明します。 埋め込みSQLプログラムでは、SQL文をホスト言語となるCプログラムコードにおけるゲストとみなします。 したがって、Cプログラムの変数はホスト変数と呼ばれます。

Another way to exchange values between PostgreSQL backends and ECPG applications is the use of SQL descriptors, described in <xref linkend="ecpg-descriptors"/>. PostgreSQLバックエンドとECPGアプリケーションの間で値をやり取りするその他の方法は、 36.7 で説明されているSQLデスクリプタを使う方法です。

36.4.1. 概要 #

<title>Overview</title>

Passing data between the C program and the SQL statements is particularly simple in embedded SQL. Instead of having the program paste the data into the statement, which entails various complications, such as properly quoting the value, you can simply write the name of a C variable into the SQL statement, prefixed by a colon. For example: 埋め込みSQLにおけるCプログラムとSQL文との間でのデータのやり取りは特に単純です。 値に適切な引用符を付与するといった、様々な複雑な処理を伴う、プログラムにデータを文中に貼り付けさせるという方法はなく、単にSQL文の中に、先頭にコロンを付けたC変数名を書くだけです。 以下に例を示します。

EXEC SQL INSERT INTO sometable VALUES (:v1, 'foo', :v2);

This statement refers to two C variables named <varname>v1</varname> and <varname>v2</varname> and also uses a regular SQL string literal, to illustrate that you are not restricted to use one kind of data or the other. このSQL文は、v1v2という2つのC変数を参照し、また、通常のSQL文字列リテラルも使用しています。 これは、使用できるデータの種類は1つだけという制限がないことを表しています。

This style of inserting C variables in SQL statements works anywhere a value expression is expected in an SQL statement. SQL文内にCの変数を挿入するこの様式は、SQL文で値式が想定されている所であればどこでも動作します。

36.4.2. 宣言セクション #

<title>Declare Sections</title>

To pass data from the program to the database, for example as parameters in a query, or to pass data from the database back to the program, the C variables that are intended to contain this data need to be declared in specially marked sections, so the embedded SQL preprocessor is made aware of them. 例えば問い合わせ内のパラメータとして、プログラムからデータベースへデータを渡す、もしくは、データベースからプログラムへデータを渡すためには、このようなデータを含むように意図されたC変数を、埋め込みSQLプリプロセッサが管理できるように、特殊な印のついたセクションで宣言する必要があります。

This section starts with: このセクションは以下で始まります。

EXEC SQL BEGIN DECLARE SECTION;

and ends with: そして、以下で終わります。

EXEC SQL END DECLARE SECTION;

Between those lines, there must be normal C variable declarations, such as: この行の間は、以下のような通常のC変数宣言でなければなりません。

int   x = 4;
char  foo[16], bar[16];

As you can see, you can optionally assign an initial value to the variable. The variable's scope is determined by the location of its declaring section within the program. You can also declare variables with the following syntax which implicitly creates a declare section: 見てわかるとおり、省略可能ですが、変数に初期値を代入することができます。 変数のスコープはプログラム内の宣言セクションの場所により決まります。 また、以下のような暗黙的に宣言セクションを生成する構文を使って変数を宣言することもできます。

EXEC SQL int i = 4;

You can have as many declare sections in a program as you like. プログラム内に複数の宣言セクションを持たせることができます。

The declarations are also echoed to the output file as normal C variables, so there's no need to declare them again. Variables that are not intended to be used in SQL commands can be declared normally outside these special sections. また、宣言は普通のC変数としてそのまま出力ファイルに出力されます。 ですので、これらを再度宣言する必要はありません。 通常、SQLコマンドで使用する予定がない変数はこの特別なセクションの外側で宣言されます。

The definition of a structure or union also must be listed inside a <literal>DECLARE</literal> section. Otherwise the preprocessor cannot handle these types since it does not know the definition. 構造体や共用体の定義もまた、DECLAREセクションの内側で表す必要があります。 さもないと、プリプロセッサはその定義が不明であるために、これらの型を扱うことができません。

36.4.3. クエリ実行結果の受け取り #

<title>Retrieving Query Results</title>

Now you should be able to pass data generated by your program into an SQL command. But how do you retrieve the results of a query? For that purpose, embedded SQL provides special variants of the usual commands <command>SELECT</command> and <command>FETCH</command>. These commands have a special <literal>INTO</literal> clause that specifies which host variables the retrieved values are to be stored in. <command>SELECT</command> is used for a query that returns only single row, and <command>FETCH</command> is used for a query that returns multiple rows, using a cursor. ここまでで、プログラムで生成したデータをSQLコマンドに渡すことができるようになりました。 しかし、どのように問い合わせの結果を取り出すのでしょうか? この目的のために、埋め込みSQLでは、通常のSELECTFETCHを派生した、特殊なコマンドを提供しています。 これらのコマンドは特別なINTO句を持ち、ここで返された値をどのホスト変数に格納すればよいかを指定します。 SELECT は単一行を返却する問い合わせに使用され、FETCH は複数の行を返却する問い合わせにおいてカーソルとともに使用されます。

Here is an example: 以下にサンプルを示します。

/*

 * assume this table:

 * 以下のテーブルを前提とする
 * CREATE TABLE test1 (a int, b varchar(50));
 */

EXEC SQL BEGIN DECLARE SECTION;
int v1;
VARCHAR v2;
EXEC SQL END DECLARE SECTION;

 ...

EXEC SQL SELECT a, b INTO :v1, :v2 FROM test;

So the <literal>INTO</literal> clause appears between the select list and the <literal>FROM</literal> clause. The number of elements in the select list and the list after <literal>INTO</literal> (also called the target list) must be equal. INTO句が選択リストとFROM句の間に現れます。 選択リスト内の要素数とINTO直後のリスト(目的リストとも呼ばれます)の要素数は等しくなければなりません。

Here is an example using the command <command>FETCH</command>: 以下にFETCHコマンドの使用例を示します。

EXEC SQL BEGIN DECLARE SECTION;
int v1;
VARCHAR v2;
EXEC SQL END DECLARE SECTION;

 ...

EXEC SQL DECLARE foo CURSOR FOR SELECT a, b FROM test;

 ...

do
{
    ...
    EXEC SQL FETCH NEXT FROM foo INTO :v1, :v2;
    ...
} while (...);

Here the <literal>INTO</literal> clause appears after all the normal clauses. ここでは、INTO句が通常のすべての句の後ろに現れています。

36.4.4. データ型の対応 #

<title>Type Mapping</title>

When ECPG applications exchange values between the PostgreSQL server and the C application, such as when retrieving query results from the server or executing SQL statements with input parameters, the values need to be converted between PostgreSQL data types and host language variable types (C language data types, concretely). One of the main points of ECPG is that it takes care of this automatically in most cases. ECPGアプリケーションがPostgreSQLバックエンドとCアプリケーションの間で値をやり取りする際、例えばサーバからクエリの結果を受け取る、または入力パラメータとともにSQL文を実行する場合、それらの値はPostgreSQLのデータ型とホスト言語の変数の型(具体的にはC言語のデータ型)の間で変換される必要があります。 ECPGの重要な点のひとつは、ほとんどの場合においてECPGがこれらを自動的に扱うということです。

In this respect, there are two kinds of data types: Some simple PostgreSQL data types, such as <type>integer</type> and <type>text</type>, can be read and written by the application directly. Other PostgreSQL data types, such as <type>timestamp</type> and <type>numeric</type> can only be accessed through special library functions; see <xref linkend="ecpg-special-types"/>. この点において、2つのデータ型があります: いくつかの単純なPostgreSQLのデータ型、integertext などは、アプリケーションから直接読んだり書いたりすることができます。 その他のPostgreSQLのデータ型、timestampnumeric などは、特別なライブラリ関数によってしかアクセスすることができません; 36.4.4.2 を参照してください。

<xref linkend="ecpg-datatype-hostvars-table"/> shows which PostgreSQL data types correspond to which C data types. When you wish to send or receive a value of a given PostgreSQL data type, you should declare a C variable of the corresponding C data type in the declare section. 表 36.1には、PostgreSQLのどのデータ型がC言語のデータ型に対応するかが示されています。 与えられたPostgreSQLのデータ型へ値を書き込みまたは読み込みしたい場合には、対応するC言語のデータ型の変数を宣言セクションにおいて宣言しなければなりません。

表36.1 PostgreSQLデータ型とC言語変数型の対応

<title>Mapping Between PostgreSQL Data Types and C Variable Types</title>
PostgreSQLデータ型ホスト変数型
smallintshort
integerint
bigintlong long int
decimaldecimal[a]
numericnumeric[a]
realfloat
double precisiondouble
smallserialshort
serialint
bigseriallong long int
oidunsigned int
character(n), varchar(n), textchar[n+1], VARCHAR[n+1]
namechar[NAMEDATALEN]
timestamptimestamp[a]
intervalinterval[a]
datedate[a]
booleanbool[b]
byteachar *, bytea[n]

[a] この型は特別なライブラリ関数を通してのみアクセスできます; 36.4.4.2 を参照。

[b] ネイティブでなければ ecpglib.h で宣言。


36.4.4.1. 文字列の処理 #

<title>Handling Character Strings</title>

To handle SQL character string data types, such as <type>varchar</type> and <type>text</type>, there are two possible ways to declare the host variables. varchartextのような文字列のデータ型を扱うため、ホスト変数を宣言するための2つの方法があります。

One way is using <type>char[]</type>, an array of <type>char</type>, which is the most common way to handle character data in C. ひとつは char の配列 char[] を使うことで、C言語において文字列データを扱うもっとも一般的な方法です。

EXEC SQL BEGIN DECLARE SECTION;
    char str[50];
EXEC SQL END DECLARE SECTION;

Note that you have to take care of the length yourself. If you use this host variable as the target variable of a query which returns a string with more than 49 characters, a buffer overflow occurs. 文字列の長さについて、自分自身で気を付けておく必要があります。 上記のホスト変数を49文字以上の文字列を返すクエリのターゲット変数として使った場合、バッファオーバーフローが発生します。

The other way is using the <type>VARCHAR</type> type, which is a special type provided by ECPG. The definition on an array of type <type>VARCHAR</type> is converted into a named <type>struct</type> for every variable. A declaration like: その他の方法は、ECPGによって提供される特殊なデータ型 VARCHAR を使う方法です。 VARCHAR の配列の定義は、すべての変数が名前の付いた struct に変換されます。 以下のような宣言は:

VARCHAR var[180];

is converted into: 次のように変換されます:

struct varchar_var { int len; char arr[180]; } var;

The member <structfield>arr</structfield> hosts the string including a terminating zero byte. Thus, to store a string in a <type>VARCHAR</type> host variable, the host variable has to be declared with the length including the zero byte terminator. The member <structfield>len</structfield> holds the length of the string stored in the <structfield>arr</structfield> without the terminating zero byte. When a host variable is used as input for a query, if <literal>strlen(arr)</literal> and <structfield>len</structfield> are different, the shorter one is used. メンバー変数 arr は終端のゼロの1バイトを含む文字列を保持します。 よって、文字列を VARCHAR ホスト変数に格納する場合には、ホスト変数はゼロ終端を含んだ長さで宣言されなければなりません。 メンバー変数 lenarr に格納された文字列のゼロ終端を含まない長さを保持します。 ホスト変数をクエリの入力として使用する際、strlen(arr)len が違った場合には短いものが使用されます。

<type>VARCHAR</type> can be written in upper or lower case, but not in mixed case. VARCHAR は大文字でも小文字でも記述することができますが、混在して記述することはできません。

<type>char</type> and <type>VARCHAR</type> host variables can also hold values of other SQL types, which will be stored in their string forms. charVARCHAR ホスト変数は、他のSQLのデータ型の値を文字列表現として保持することもできます。

36.4.4.2. 特殊なデータ型へのアクセス #

<title>Accessing Special Data Types</title>

ECPG contains some special types that help you to interact easily with some special data types from the PostgreSQL server. In particular, it has implemented support for the <type>numeric</type>, <type>decimal</type>, <type>date</type>, <type>timestamp</type>, and <type>interval</type> types. These data types cannot usefully be mapped to primitive host variable types (such as <type>int</type>, <type>long long int</type>, or <type>char[]</type>), because they have a complex internal structure. Applications deal with these types by declaring host variables in special types and accessing them using functions in the pgtypes library. The pgtypes library, described in detail in <xref linkend="ecpg-pgtypes"/> contains basic functions to deal with those types, such that you do not need to send a query to the SQL server just for adding an interval to a time stamp for example. ECPGには、PostgreSQLサーバからのいくつかの特殊なデータ型とやりとりするための特殊なデータ型があります。 特に、numeric, decimal, date, timestamp, interval 型へのサポートを実装しています。 これらのデータ型は複雑な内部構造を持つため、ホスト変数のプリミティブ型(int, long long int, または char[])に対応させることはできません。 アプリケーションは特別な型としてホスト変数を宣言し、pgtypesライブラリ内の関数を使ってアクセスすることで、これらの型を扱います。 36.6 で詳細を解説されるpgtypesライブラリは、例えばタイムスタンプにインターバルを加算する際にクエリをSQLサーバに送らずに済ますような、これらの型を扱うための基本的な関数を含んでいます。

The follow subsections describe these special data types. For more details about pgtypes library functions, see <xref linkend="ecpg-pgtypes"/>. 以降のサブセクションは、これらの特殊なデータ型を説明します。 pgtypesライブラリ関数についての詳細は36.6を参照してください。

36.4.4.2.1. timestamp, date #

Here is a pattern for handling <type>timestamp</type> variables in the ECPG host application. 以下は、timestamp 変数をECPGホストアプリケーションで扱う典型的なパターンです。

First, the program has to include the header file for the <type>timestamp</type> type: 最初に、プログラムは timestamp 型のためのヘッダファイルをインクルードする必要があります:

#include <pgtypes_timestamp.h>

Next, declare a host variable as type <type>timestamp</type> in the declare section: 次に、宣言セクションで timestamp 型のホスト変数を宣言します:

EXEC SQL BEGIN DECLARE SECTION;
timestamp ts;
EXEC SQL END DECLARE SECTION;

And after reading a value into the host variable, process it using pgtypes library functions. In following example, the <type>timestamp</type> value is converted into text (ASCII) form with the <function>PGTYPEStimestamp_to_asc()</function> function: そして、ホスト変数へ値を読み込んだら、pgtypesライブラリ関数を使って処理をします。 以降の例では、timestamp の値は PGTYPEStimestamp_to_asc() 関数によって text (ASCII) 形式に変換されます:

EXEC SQL SELECT now()::timestamp INTO :ts;

printf("ts = %s\n", PGTYPEStimestamp_to_asc(ts));

This example will show some result like following: この例は、以下のような結果を表示します。

ts = 2010-06-27 18:03:56.949343

In addition, the DATE type can be handled in the same way. The program has to include <filename>pgtypes_date.h</filename>, declare a host variable as the date type and convert a DATE value into a text form using <function>PGTYPESdate_to_asc()</function> function. For more details about the pgtypes library functions, see <xref linkend="ecpg-pgtypes"/>. また、DATE型も同じ方法で扱うことができます。 プログラムは pgtypes_date.h をインクルードし、ホスト変数を date 型として宣言し、PGTYPESdate_to_asc() 関数によって DATE の値を text 形式に変換します。 pgtypesライブラリ関数についての詳細は、36.6 を参照してください。

36.4.4.2.2. interval #

The handling of the <type>interval</type> type is also similar to the <type>timestamp</type> and <type>date</type> types. It is required, however, to allocate memory for an <type>interval</type> type value explicitly. In other words, the memory space for the variable has to be allocated in the heap memory, not in the stack memory. interval 型の扱い方は timestampdate 型と似ています。 但し、interval 型の値のために明示的にメモリを確保する必要があります。 言い換えると、この変数のためのメモリ領域はスタックではなくヒープ上に確保されます。

Here is an example program: 以下にプログラム例を示します:

#include <stdio.h>
#include <stdlib.h>
#include <pgtypes_interval.h>

int
main(void)
{
EXEC SQL BEGIN DECLARE SECTION;
    interval *in;
EXEC SQL END DECLARE SECTION;

    EXEC SQL CONNECT TO testdb;
    EXEC SQL SELECT pg_catalog.set_config('search_path', '', false); EXEC SQL COMMIT;

    in = PGTYPESinterval_new();
    EXEC SQL SELECT '1 min'::interval INTO :in;
    printf("interval = %s\n", PGTYPESinterval_to_asc(in));
    PGTYPESinterval_free(in);

    EXEC SQL COMMIT;
    EXEC SQL DISCONNECT ALL;
    return 0;
}

36.4.4.2.3. numeric, decimal #

The handling of the <type>numeric</type> and <type>decimal</type> types is similar to the <type>interval</type> type: It requires defining a pointer, allocating some memory space on the heap, and accessing the variable using the pgtypes library functions. For more details about the pgtypes library functions, see <xref linkend="ecpg-pgtypes"/>. numericdecimal 型の扱い方は interval 型と似ています: ポインタ宣言を必要とし、ヒープメモリを確保する必要があり、pgtypesライブラリ関数を使って変数にアクセスします。 pgtypesライブラリ関数の詳細については、36.6 を参照してください。

No functions are provided specifically for the <type>decimal</type> type. An application has to convert it to a <type>numeric</type> variable using a pgtypes library function to do further processing. decimal 型に対する専用の関数は提供されていません。 アプリケーションは処理を行うために pgtypesライブラリ関数を使って numeric 変数に変換する必要があります。

Here is an example program handling <type>numeric</type> and <type>decimal</type> type variables. 以下に numeric および decimal 型の変数の処理の例を示します。

#include <stdio.h>
#include <stdlib.h>
#include <pgtypes_numeric.h>

EXEC SQL WHENEVER SQLERROR STOP;

int
main(void)
{
EXEC SQL BEGIN DECLARE SECTION;
    numeric *num;
    numeric *num2;
    decimal *dec;
EXEC SQL END DECLARE SECTION;

    EXEC SQL CONNECT TO testdb;
    EXEC SQL SELECT pg_catalog.set_config('search_path', '', false); EXEC SQL COMMIT;

    num = PGTYPESnumeric_new();
    dec = PGTYPESdecimal_new();

    EXEC SQL SELECT 12.345::numeric(4,2), 23.456::decimal(4,2) INTO :num, :dec;

    printf("numeric = %s\n", PGTYPESnumeric_to_asc(num, 0));
    printf("numeric = %s\n", PGTYPESnumeric_to_asc(num, 1));
    printf("numeric = %s\n", PGTYPESnumeric_to_asc(num, 2));


    /* Convert decimal to numeric to show a decimal value. */

    /* decimalの値を表示するためdecimalをnumericに変換する。 */
    num2 = PGTYPESnumeric_new();
    PGTYPESnumeric_from_decimal(dec, num2);

    printf("decimal = %s\n", PGTYPESnumeric_to_asc(num2, 0));
    printf("decimal = %s\n", PGTYPESnumeric_to_asc(num2, 1));
    printf("decimal = %s\n", PGTYPESnumeric_to_asc(num2, 2));

    PGTYPESnumeric_free(num2);
    PGTYPESdecimal_free(dec);
    PGTYPESnumeric_free(num);

    EXEC SQL COMMIT;
    EXEC SQL DISCONNECT ALL;
    return 0;
}

36.4.4.2.4. bytea #

The handling of the <type>bytea</type> type is similar to that of <type>VARCHAR</type>. The definition on an array of type <type>bytea</type> is converted into a named struct for every variable. A declaration like: bytea型の扱いは、VARCHARと似ています。 bytea型の配列の定義は、すべての変数が名前の付いたstructに変換されます。 以下のような宣言は:

bytea var[180];

is converted into: 次のように変換されます:

struct bytea_var { int len; char arr[180]; } var;

The member <structfield>arr</structfield> hosts binary format data. It can also handle <literal>'\0'</literal> as part of data, unlike <type>VARCHAR</type>. The data is converted from/to hex format and sent/received by ecpglib. メンバ変数arrはバイナリフォーマットデータを保持します VARCHARとは異なり、'\0'をデータの一部として扱うこともできます。 データは、ecpglibによりhex書式から、またはhex書式に変換されて、送信または受信されます。

注記

<type>bytea</type> variable can be used only when <xref linkend="guc-bytea-output"/> is set to <literal>hex</literal>. bytea変数は、bytea_outputhexに設定されている場合にのみ使うことができます。

36.4.4.3. 非プリミティブ型のホスト変数 #

<title>Host Variables with Nonprimitive Types</title>

As a host variable you can also use arrays, typedefs, structs, and pointers. ホスト変数として、配列、typedef、構造体およびポインタも使うことができます。

36.4.4.3.1. 配列 #
<title>Arrays</title>

There are two use cases for arrays as host variables. The first is a way to store some text string in <type>char[]</type> or <type>VARCHAR[]</type>, as explained in <xref linkend="ecpg-char"/>. The second use case is to retrieve multiple rows from a query result without using a cursor. Without an array, to process a query result consisting of multiple rows, it is required to use a cursor and the <command>FETCH</command> command. But with array host variables, multiple rows can be received at once. The length of the array has to be defined to be able to accommodate all rows, otherwise a buffer overflow will likely occur. ホスト変数としての配列の使い方には二通りの利用方法があります。 一つ目の使い方は、36.4.4.1 で説明されたように char[] または VARCHAR[] の何らかのテキスト文字列を保持するための方法です。 二つ目の使い方は、カーソルを用いずに複数行を返却するクエリ結果を受け取るために使う方法です。 配列を使わない場合、複数行からなるクエリの実行結果を処理するには、カーソルと FETCH コマンドを使用する必要があります。 しかし、配列のホスト変数を使うと、複数行を一括して受け取ることができます。 配列の長さはすべての行を受け入れられるように定義されなければなりません。でなければバッファーオーバーフローが発生するでしょう。

Following example scans the <literal>pg_database</literal> system table and shows all OIDs and names of the available databases: 以下の例は pg_database システムテーブルをスキャンし、利用可能なデータベースのすべてのOIDとデータベース名を表示します:

int
main(void)
{
EXEC SQL BEGIN DECLARE SECTION;
    int dbid[8];
    char dbname[8][16];
    int i;
EXEC SQL END DECLARE SECTION;

    memset(dbname, 0, sizeof(char)* 16 * 8);
    memset(dbid, 0, sizeof(int) * 8);

    EXEC SQL CONNECT TO testdb;
    EXEC SQL SELECT pg_catalog.set_config('search_path', '', false); EXEC SQL COMMIT;


    /* Retrieve multiple rows into arrays at once. */

    /* 複数行を一度に配列へと取り出す。 */
    EXEC SQL SELECT oid,datname INTO :dbid, :dbname FROM pg_database;

    for (i = 0; i < 8; i++)
        printf("oid=%d, dbname=%s\n", dbid[i], dbname[i]);

    EXEC SQL COMMIT;
    EXEC SQL DISCONNECT ALL;
    return 0;
}

This example shows following result. (The exact values depend on local circumstances.) この例は、以下の結果を表示します。(実際の値はローカルな環境に依存します)

oid=1, dbname=template1
oid=11510, dbname=template0
oid=11511, dbname=postgres
oid=313780, dbname=testdb
oid=0, dbname=
oid=0, dbname=
oid=0, dbname=

36.4.4.3.2. 構造体 #
<title>Structures</title>

A structure whose member names match the column names of a query result, can be used to retrieve multiple columns at once. The structure enables handling multiple column values in a single host variable. メンバー変数の名前がクエリ結果のカラム名に合致する構造体は、複数のカラムを一括して受け取るために利用することができます。 構造体は複数のカラムの値を単一のホスト変数で扱うことを可能にします。

The following example retrieves OIDs, names, and sizes of the available databases from the <literal>pg_database</literal> system table and using the <function>pg_database_size()</function> function. In this example, a structure variable <varname>dbinfo_t</varname> with members whose names match each column in the <literal>SELECT</literal> result is used to retrieve one result row without putting multiple host variables in the <literal>FETCH</literal> statement. 以下の例は、pg_databaseシステムテーブルおよびpg_database_size()関数を使って、利用可能なデータベースのOID、名前、サイズを取得します。 この例では、メンバー変数の名前がSELECT結果の各カラムに合致する構造体dbinfo_tが、複数のホスト変数に格納することなくFETCH文の一行の結果を受け取るために使用されています。

EXEC SQL BEGIN DECLARE SECTION;
    typedef struct
    {
       int oid;
       char datname[65];
       long long int size;
    } dbinfo_t;

    dbinfo_t dbval;
EXEC SQL END DECLARE SECTION;

    memset(&dbval, 0, sizeof(dbinfo_t));

    EXEC SQL DECLARE cur1 CURSOR FOR SELECT oid, datname, pg_database_size(oid) AS size FROM pg_database;
    EXEC SQL OPEN cur1;


    /* when end of result set reached, break out of while loop */

    /* 結果集合の最後に到達したら、whileループから抜ける */
    EXEC SQL WHENEVER NOT FOUND DO BREAK;

    while (1)
    {

        /* Fetch multiple columns into one structure. */

        /* 複数列を1つの構造体に取り込む。 */
        EXEC SQL FETCH FROM cur1 INTO :dbval;


        /* Print members of the structure. */

        /* 構造体のメンバを表示する。 */
        printf("oid=%d, datname=%s, size=%lld\n", dbval.oid, dbval.datname, dbval.size);
    }

    EXEC SQL CLOSE cur1;

This example shows following result. (The exact values depend on local circumstances.) この例は、次の結果を示します(実際の値はローカルな環境に依存します)

oid=1, datname=template1, size=4324580
oid=11510, datname=template0, size=4243460
oid=11511, datname=postgres, size=4324580
oid=313780, datname=testdb, size=8183012

Structure host variables <quote>absorb</quote> as many columns as the structure as fields. Additional columns can be assigned to other host variables. For example, the above program could also be restructured like this, with the <varname>size</varname> variable outside the structure: 構造体のホスト変数は、多数のカラムを構造体のフィールドとして吸収します。 追加のカラムは他のホスト変数に割り当てることができます。 例えば、上記のプログラムは構造体に含まれない size 変数を使って以下のように書き換えることができます。

EXEC SQL BEGIN DECLARE SECTION;
    typedef struct
    {
       int oid;
       char datname[65];
    } dbinfo_t;

    dbinfo_t dbval;
    long long int size;
EXEC SQL END DECLARE SECTION;

    memset(&dbval, 0, sizeof(dbinfo_t));

    EXEC SQL DECLARE cur1 CURSOR FOR SELECT oid, datname, pg_database_size(oid) AS size FROM pg_database;
    EXEC SQL OPEN cur1;


    /* when end of result set reached, break out of while loop */

    /* 結果集合の最後に到達したら、whileループから抜ける */
    EXEC SQL WHENEVER NOT FOUND DO BREAK;

    while (1)
    {

        /* Fetch multiple columns into one structure. */

        /* 複数列を1つの構造体に取り込む。 */
        EXEC SQL FETCH FROM cur1 INTO :dbval, :size;


        /* Print members of the structure. */

        /* 構造体のメンバを表示する。 */
        printf("oid=%d, datname=%s, size=%lld\n", dbval.oid, dbval.datname, size);
    }

    EXEC SQL CLOSE cur1;

36.4.4.3.3. typedef #
<title>Typedefs</title>

Use the <literal>typedef</literal> keyword to map new types to already existing types. 新しい型と既存の型を対応付けるためには typedef キーワードを使ってください。

EXEC SQL BEGIN DECLARE SECTION;
    typedef char mychartype[40];
    typedef long serial_t;
EXEC SQL END DECLARE SECTION;

Note that you could also use: また、同様に以下を使うこともできます:

EXEC SQL TYPE serial_t IS long;

This declaration does not need to be part of a declare section; that is, you can also write typedefs as normal C statements. この宣言は、宣言セクションの一部である必要はありません。 つまり、typedefを通常のCステートメントとしても書けます。

Any word you declare as a typedef cannot be used as an SQL keyword in <literal>EXEC SQL</literal> commands later in the same program. For example, this won't work: typedefとして宣言したワードは、同じプログラム内で後でEXEC SQLコマンドのSQLキーワードとして使用できません。 例えば、これは機能しません。

EXEC SQL BEGIN DECLARE SECTION;
    typedef int start;
EXEC SQL END DECLARE SECTION;
...
EXEC SQL START TRANSACTION;

ECPG will report a syntax error for <literal>START TRANSACTION</literal>, because it no longer recognizes <literal>START</literal> as an SQL keyword, only as a typedef. (If you have such a conflict, and renaming the typedef seems impractical, you could write the SQL command using <link linkend="ecpg-dynamic">dynamic SQL</link>.) ECPGは、START TRANSACTIONの構文エラーを報告します。 なぜなら、それはもはやSQLのキーワードとしてではなく、typedefとして認識するSTARTであるからです。 (もし、 競合があり、typedefの名前を変更することが現実的でないと思われる場合は、動的SQLを使用して書くことができます。)

注記

In <productname>PostgreSQL</productname> releases before v16, use of SQL keywords as typedef names was likely to result in syntax errors associated with use of the typedef itself, rather than use of the name as an SQL keyword. The new behavior is less likely to cause problems when an existing ECPG application is recompiled in a new <productname>PostgreSQL</productname> release with new keywords. PostgreSQL v16より前では、typedef名としてSQLキーワードを使用すると、構文キーワードとして自分自身を使用するのではなく、typedef名前の使用に関連するSQLエラーが発生する可能性がありました。 新しい動作では、既存のECPGアプリケーションが新しいキーワードを使用して新しいPostgreSQLのリリースで再コンパイルされる場合に問題が発生する可能性が低くなりました。

36.4.4.3.4. ポインタ #
<title>Pointers</title>

You can declare pointers to the most common types. Note however that you cannot use pointers as target variables of queries without auto-allocation. See <xref linkend="ecpg-descriptors"/> for more information on auto-allocation. ほとんどの一般的な型のポインタを宣言することができます。 但し、自動メモリ確保を使わずにクエリのターゲット変数として使うことはできません。 自動メモリ確保については 36.7 を参照してください。

EXEC SQL BEGIN DECLARE SECTION;
    int   *intp;
    char **charp;
EXEC SQL END DECLARE SECTION;

36.4.5. 非プリミティブSQLデータ型の扱い方 #

<title>Handling Nonprimitive SQL Data Types</title>

This section contains information on how to handle nonscalar and user-defined SQL-level data types in ECPG applications. Note that this is distinct from the handling of host variables of nonprimitive types, described in the previous section. 本節では、非スカラー型およびユーザ定義のSQLデータ型をECPGアプリケーションで扱う方法を示します。 この内容は、前の説で説明した非プリミティブ型のホスト変数の扱い方とは別のものです。

36.4.5.1. 配列 #

<title>Arrays</title>

Multi-dimensional SQL-level arrays are not directly supported in ECPG. One-dimensional SQL-level arrays can be mapped into C array host variables and vice-versa. However, when creating a statement ecpg does not know the types of the columns, so that it cannot check if a C array is input into a corresponding SQL-level array. When processing the output of an SQL statement, ecpg has the necessary information and thus checks if both are arrays. SQLの多次元配列は、ECPGにおいては直接的にはサポートされていません。 SQLの1次元配列をC言語の配列のホスト変数に対応させることはできますし、その逆もできます。 しかし、文の作成時にはecpgがその列の型を知らないので、C言語の配列を対応するSQLの配列に入力できるか確かめられません。 SQL文の出力を処理する時には、ecpgは必要な情報を持っていますので、どちらも配列であるか確かめます。

If a query accesses <emphasis>elements</emphasis> of an array separately, then this avoids the use of arrays in ECPG. Then, a host variable with a type that can be mapped to the element type should be used. For example, if a column type is array of <type>integer</type>, a host variable of type <type>int</type> can be used. Also if the element type is <type>varchar</type> or <type>text</type>, a host variable of type <type>char[]</type> or <type>VARCHAR[]</type> can be used. もし、クエリが配列の 要素 に対して個別にアクセスした場合、ECPGにおける配列の利用を避けることができます。 その際、要素に対応させることができる型のホスト変数を利用しなければなりません。 例えば、カラムの型が integer の配列の場合、int 型のホスト変数を使用することができます。 同様に、要素の型が varchar または text の場合、 char[] ないし VARCHAR[] 型のホスト変数を使用することができます。

Here is an example. Assume the following table: 以下に例を示します。次のようなテーブルを仮定します:

CREATE TABLE t3 (
    ii integer[]
);

testdb=> SELECT * FROM t3;
     ii
-------------
 {1,2,3,4,5}
(1 row)

The following example program retrieves the 4th element of the array and stores it into a host variable of type <type>int</type>: 以下のプログラム例は、配列の4番目の要素を取得し、それを int 型のホスト変数に保存します:

EXEC SQL BEGIN DECLARE SECTION;
int ii;
EXEC SQL END DECLARE SECTION;

EXEC SQL DECLARE cur1 CURSOR FOR SELECT ii[4] FROM t3;
EXEC SQL OPEN cur1;

EXEC SQL WHENEVER NOT FOUND DO BREAK;

while (1)
{
    EXEC SQL FETCH FROM cur1 INTO :ii ;
    printf("ii=%d\n", ii);
}

EXEC SQL CLOSE cur1;

This example shows the following result: この例は以下のような結果を示します:

ii=4

To map multiple array elements to the multiple elements in an array type host variables each element of array column and each element of the host variable array have to be managed separately, for example: 複数の配列の要素を、配列型のホスト変数の複数の要素にマッピングするためには、配列型のカラムの各要素とホスト変数配列の各要素は、以下の例のように別々に管理されなければなりません:

EXEC SQL BEGIN DECLARE SECTION;
int ii_a[8];
EXEC SQL END DECLARE SECTION;

EXEC SQL DECLARE cur1 CURSOR FOR SELECT ii[1], ii[2], ii[3], ii[4] FROM t3;
EXEC SQL OPEN cur1;

EXEC SQL WHENEVER NOT FOUND DO BREAK;

while (1)
{
    EXEC SQL FETCH FROM cur1 INTO :ii_a[0], :ii_a[1], :ii_a[2], :ii_a[3];
    ...
}

Note again that 繰り返しになりますが、以下の例は

EXEC SQL BEGIN DECLARE SECTION;
int ii_a[8];
EXEC SQL END DECLARE SECTION;

EXEC SQL DECLARE cur1 CURSOR FOR SELECT ii FROM t3;
EXEC SQL OPEN cur1;

EXEC SQL WHENEVER NOT FOUND DO BREAK;

while (1)
{

    /* WRONG */

    /* 間違い */
    EXEC SQL FETCH FROM cur1 INTO :ii_a;
    ...
}

would not work correctly in this case, because you cannot map an array type column to an array host variable directly. この場合は正しく動作しません。なぜなら、配列型のカラムをホストの配列変数に直接対応させることはできないからです。

Another workaround is to store arrays in their external string representation in host variables of type <type>char[]</type> or <type>VARCHAR[]</type>. For more details about this representation, see <xref linkend="arrays-input"/>. Note that this means that the array cannot be accessed naturally as an array in the host program (without further processing that parses the text representation). もうひとつの回避策は、配列をホスト変数の char[] または VARCHAR[] 型に文字列表現として保存することです。 この表現方法についての詳細は 8.15.2 を参照してください。 このことは、配列にはホストプログラム内で自然な形ではアクセスできないことを意味しています(文字列表現を解析する追加処理が無ければ)。

36.4.5.2. 複合型 #

<title>Composite Types</title>

Composite types are not directly supported in ECPG, but an easy workaround is possible. The available workarounds are similar to the ones described for arrays above: Either access each attribute separately or use the external string representation. 複合型はECPGでは直接はサポートされていませんが、簡単な回避方法が利用可能です。 利用可能なワークアラウンドは、先に配列において説明されたものと似ています: 各属性に個別にアクセスするか、外部の文字列表現を使います。

For the following examples, assume the following type and table: 以降の例のため、以下の型とテーブルを仮定します:

CREATE TYPE comp_t AS (intval integer, textval varchar(32));
CREATE TABLE t4 (compval comp_t);
INSERT INTO t4 VALUES ( (256, 'PostgreSQL') );

The most obvious solution is to access each attribute separately. The following program retrieves data from the example table by selecting each attribute of the type <type>comp_t</type> separately: もっとも分かりやすい解決法は、各属性に個別にアクセスすることです。 以下のプログラムは、comp_t型の各要素を個別に選択することによってサンプルのテーブルからデータを受け取ります:

EXEC SQL BEGIN DECLARE SECTION;
int intval;
varchar textval[33];
EXEC SQL END DECLARE SECTION;


/* Put each element of the composite type column in the SELECT list. */

/* SELECTリストに複合型の列の各要素を書く。 */
EXEC SQL DECLARE cur1 CURSOR FOR SELECT (compval).intval, (compval).textval FROM t4;
EXEC SQL OPEN cur1;

EXEC SQL WHENEVER NOT FOUND DO BREAK;

while (1)
{

    /* Fetch each element of the composite type column into host variables. */

    /* 複合型の列の各要素をホスト変数に取り出す。 */
    EXEC SQL FETCH FROM cur1 INTO :intval, :textval;

    printf("intval=%d, textval=%s\n", intval, textval.arr);
}

EXEC SQL CLOSE cur1;

To enhance this example, the host variables to store values in the <command>FETCH</command> command can be gathered into one structure. For more details about the host variable in the structure form, see <xref linkend="ecpg-variables-struct"/>. To switch to the structure, the example can be modified as below. The two host variables, <varname>intval</varname> and <varname>textval</varname>, become members of the <structname>comp_t</structname> structure, and the structure is specified on the <command>FETCH</command> command. この例を拡張して、 FETCH コマンドの値を格納するホスト変数を一つの構造体にまとめることができます。 構造体の形のホスト変数の詳細については 36.4.4.3.2 を参照してください。 構造体に変更するために、この例は以下のように変更することができます。 二つのホスト変数 intvaltextvalcomp_t 構造体のメンバー変数とし、構造体を FETCH コマンドで指定します。

EXEC SQL BEGIN DECLARE SECTION;
typedef struct
{
    int intval;
    varchar textval[33];
} comp_t;

comp_t compval;
EXEC SQL END DECLARE SECTION;


/* Put each element of the composite type column in the SELECT list. */

/* SELECTリストに複合型の列の各要素を書く。 */
EXEC SQL DECLARE cur1 CURSOR FOR SELECT (compval).intval, (compval).textval FROM t4;
EXEC SQL OPEN cur1;

EXEC SQL WHENEVER NOT FOUND DO BREAK;

while (1)
{

    /* Put all values in the SELECT list into one structure. */

    /* SELECTリストの値をすべて1つの構造体に取り込む。 */
    EXEC SQL FETCH FROM cur1 INTO :compval;

    printf("intval=%d, textval=%s\n", compval.intval, compval.textval.arr);
}

EXEC SQL CLOSE cur1;

Although a structure is used in the <command>FETCH</command> command, the attribute names in the <command>SELECT</command> clause are specified one by one. This can be enhanced by using a <literal>*</literal> to ask for all attributes of the composite type value. 構造体が FETCH コマンドで使われていますが、属性名は SELECT 句において各々が指定されています。 これは、複合型の値のすべての属性を示す * を用いることで拡張することができます。

...
EXEC SQL DECLARE cur1 CURSOR FOR SELECT (compval).* FROM t4;
EXEC SQL OPEN cur1;

EXEC SQL WHENEVER NOT FOUND DO BREAK;

while (1)
{

    /* Put all values in the SELECT list into one structure. */

    /* SELECTリストの値をすべて1つの構造体に取り込む。 */
    EXEC SQL FETCH FROM cur1 INTO :compval;

    printf("intval=%d, textval=%s\n", compval.intval, compval.textval.arr);
}
...

This way, composite types can be mapped into structures almost seamlessly, even though ECPG does not understand the composite type itself. この方法であれば、ECPGが複合型そのものを理解できないとしても、複合型はほぼシームレスに構造体に対応させることができます。

Finally, it is also possible to store composite type values in their external string representation in host variables of type <type>char[]</type> or <type>VARCHAR[]</type>. But that way, it is not easily possible to access the fields of the value from the host program. 最後に、char[] または VARCHAR[] 型のホスト変数に外部の文字列表現として複合型の値を格納することもできます。 しかし、この方法ではホストプログラムから値のフィールドにアクセスするのは簡単ではありません。

36.4.5.3. ユーザ定義の基本型 #

<title>User-Defined Base Types</title>

New user-defined base types are not directly supported by ECPG. You can use the external string representation and host variables of type <type>char[]</type> or <type>VARCHAR[]</type>, and this solution is indeed appropriate and sufficient for many types. 新しいユーザ定義の基本型は、ECPGでは直接的にはサポートされていません。 外部の文字列表現、char[]またはVARCHAR[] 型のホスト変数を使うことができ、この解決法は多くの型について確かに適切かつ十分です。

Here is an example using the data type <type>complex</type> from the example in <xref linkend="xtypes"/>. The external string representation of that type is <literal>(%f,%f)</literal>, which is defined in the functions <function>complex_in()</function> and <function>complex_out()</function> functions in <xref linkend="xtypes"/>. The following example inserts the complex type values <literal>(1,1)</literal> and <literal>(3,3)</literal> into the columns <literal>a</literal> and <literal>b</literal>, and select them from the table after that. 以下に38.13に含まれるcomplex型を使った例を示します。 この型の外部文字列表現は(%f,%f)で、38.13complex_in()関数およびcomplex_out()関数で定義されています。 以下の例は、カラムabに、complex型の値(1,1)および(3,3)を挿入し、その後、それらをテーブルからSELECTします。

EXEC SQL BEGIN DECLARE SECTION;
    varchar a[64];
    varchar b[64];
EXEC SQL END DECLARE SECTION;

    EXEC SQL INSERT INTO test_complex VALUES ('(1,1)', '(3,3)');

    EXEC SQL DECLARE cur1 CURSOR FOR SELECT a, b FROM test_complex;
    EXEC SQL OPEN cur1;

    EXEC SQL WHENEVER NOT FOUND DO BREAK;

    while (1)
    {
        EXEC SQL FETCH FROM cur1 INTO :a, :b;
        printf("a=%s, b=%s\n", a.arr, b.arr);
    }

    EXEC SQL CLOSE cur1;

This example shows following result: この例は、以下の結果を示します。

a=(1,1), b=(3,3)

Another workaround is avoiding the direct use of the user-defined types in ECPG and instead create a function or cast that converts between the user-defined type and a primitive type that ECPG can handle. Note, however, that type casts, especially implicit ones, should be introduced into the type system very carefully. その他の回避方法は、ユーザ定義型をECPGにおいて直接的に使うことを避けることであり、ユーザ定義型とECPGが扱えるプリミティブ型を変換する関数またはキャストを作成することです。 ただし、型のキャスト、特に暗黙のものは型システムにおいて慎重に導入されなければなりません。

For example, 例を示します。

CREATE FUNCTION create_complex(r double, i double) RETURNS complex
LANGUAGE SQL
IMMUTABLE
AS $$ SELECT $1 * complex '(1,0')' + $2 * complex '(0,1)' $$;

After this definition, the following この定義の後、以下の例は

EXEC SQL BEGIN DECLARE SECTION;
double a, b, c, d;
EXEC SQL END DECLARE SECTION;

a = 1;
b = 2;
c = 3;
d = 4;

EXEC SQL INSERT INTO test_complex VALUES (create_complex(:a, :b), create_complex(:c, :d));

has the same effect as 以下と同じ効果をもたらします。

EXEC SQL INSERT INTO test_complex VALUES ('(1,2)', '(3,4)');

36.4.6. 指示子 #

<title>Indicators</title>

The examples above do not handle null values. In fact, the retrieval examples will raise an error if they fetch a null value from the database. To be able to pass null values to the database or retrieve null values from the database, you need to append a second host variable specification to each host variable that contains data. This second host variable is called the <firstterm>indicator</firstterm> and contains a flag that tells whether the datum is null, in which case the value of the real host variable is ignored. Here is an example that handles the retrieval of null values correctly: 上の例ではNULL値を扱いません。 実際、取り出し例では、もしデータベースからNULL値が取り出された場合にはエラーが発生します。 データベースへNULL値を渡す、または、データベースからNULL値を取り出すためには、第二のホスト変数指定をデータを格納するホスト変数それぞれに追加しなければなりません。 第二のホスト変数は指示子と呼ばれ、データがNULLかどうかを表すフラグが含まれます。 NULLの場合、実際のホスト変数の値は無視されます。 以下に、NULL値の取り出しを正しく扱う例を示します。

EXEC SQL BEGIN DECLARE SECTION;
VARCHAR val;
int val_ind;
EXEC SQL END DECLARE SECTION:

 ...

EXEC SQL SELECT b INTO :val :val_ind FROM test1;

The indicator variable <varname>val_ind</varname> will be zero if the value was not null, and it will be negative if the value was null. (See <xref linkend="ecpg-oracle-compat"/> to enable Oracle-specific behavior.) 値がNULLでなければ、指示子変数val_indは0となります。 値がNULLならば負の値となります。 (Oracle特有の振舞いを有効にするには36.16を参照してください。)

The indicator has another function: if the indicator value is positive, it means that the value is not null, but it was truncated when it was stored in the host variable. 指示子は他の機能を持ちます。 指示子の値が正ならば、値がNULLではありませんが、ホスト変数に格納する際に一部切り詰められたことを示します。

If the argument <literal>-r no_indicator</literal> is passed to the preprocessor <command>ecpg</command>, it works in <quote>no-indicator</quote> mode. In no-indicator mode, if no indicator variable is specified, null values are signaled (on input and output) for character string types as empty string and for integer types as the lowest possible value for type (for example, <symbol>INT_MIN</symbol> for <type>int</type>). プリプロセッサ ecpg に引数 -r no_indicator が渡された場合、no-indicator モードで動作します。 no-indicator モードでは、指示子変数が指定されなかった場合、(入力および出力において)文字列型に対して空の文字列としてnull値が、整数型に対してはもっとも小さな値が割り当てられます(例えば、int の場合 INT_MIN です)。