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

34.3. コマンド実行関数 #

<title>Command Execution Functions</title>

Once a connection to a database server has been successfully established, the functions described here are used to perform SQL queries and commands. いったんデータベースサーバへの接続の確立が成功すれば、本節で説明する関数を使ってSQLの問い合わせやコマンドを実行します。

34.3.1. 主要な関数 #

<title>Main Functions</title>

PQexec #

Submits a command to the server and waits for the result. コマンドをサーバに送信し、結果を待機します。

PGresult *PQexec(PGconn *conn, const char *command);

Returns a <structname>PGresult</structname> pointer or possibly a null pointer. A non-null pointer will generally be returned except in out-of-memory conditions or serious errors such as inability to send the command to the server. The <xref linkend="libpq-PQresultStatus"/> function should be called to check the return value for any errors (including the value of a null pointer, in which case it will return <symbol>PGRES_FATAL_ERROR</symbol>). Use <xref linkend="libpq-PQerrorMessage"/> to get more information about such errors. 戻り値はPGresultへのポインタ、場合によってはNULLポインタです。 メモリ不足の状態、あるいはサーバへのコマンド送信が不可能といった深刻なエラーの場合を除けば、通常非NULLのポインタが返ります。 PQresultStatus関数を呼び出して、何かエラー(NULLポインタ値を含むエラー。この場合はPGRES_FATAL_ERRORが返されます)がないか戻り値を検査しなければなりません。 こうしたエラーの詳しい情報はPQerrorMessageで得ることができます。

The command string can include multiple SQL commands (separated by semicolons). Multiple queries sent in a single <xref linkend="libpq-PQexec"/> call are processed in a single transaction, unless there are explicit <command>BEGIN</command>/<command>COMMIT</command> commands included in the query string to divide it into multiple transactions. (See <xref linkend="protocol-flow-multi-statement"/> for more details about how the server handles multi-query strings.) Note however that the returned <structname>PGresult</structname> structure describes only the result of the last command executed from the string. Should one of the commands fail, processing of the string stops with it and the returned <structname>PGresult</structname> describes the error condition. コマンド文字列には(セミコロンで区切られた)複数のSQLコマンドを含めることができます。 単一のPQexec呼び出しで送信された複数の問い合わせは、単一トランザクションで処理されます。 ただし、問い合わせ文字列内に明示的なBEGIN/COMMITコマンドがある場合は、複数のトランザクションに分離されます。 (サーバがどのように複数問い合わせを処理するかの更なる詳細は55.2.2.1を参照してください。) しかし、返されるPGresult構造体には、その文字列内で最後に実行されたコマンドの結果のみが含まれることに注意してください。 そのコマンドの1つが失敗したとすると、文字列の処理はそこで中断し、エラー条件が含まれるPGresultが返されます。

PQexecParams #

Submits a command to the server and waits for the result, with the ability to pass parameters separately from the SQL command text. サーバにコマンドを送信し、結果を待ちます。 ただし、SQLコマンドテキストとは別にパラメータを渡すことができます。

PGresult *PQexecParams(PGconn *conn,
                       const char *command,
                       int nParams,
                       const Oid *paramTypes,
                       const char * const *paramValues,
                       const int *paramLengths,
                       const int *paramFormats,
                       int resultFormat);

<xref linkend="libpq-PQexecParams"/> is like <xref linkend="libpq-PQexec"/>, but offers additional functionality: parameter values can be specified separately from the command string proper, and query results can be requested in either text or binary format. PQexecParamsPQexecは似ていますが、前者は次の機能が追加されています。 パラメータ値をコマンド文字列とは別に適切に指定することができ、また、問い合わせの結果をテキスト書式としてでもバイナリ書式としてでも要求できます。

The function arguments are: この関数の引数を以下に示します。

conn

The connection object to send the command through. 接続オブジェクトです。これを通してコマンドを送信します。

command

The SQL command string to be executed. If parameters are used, they are referred to in the command string as <literal>$1</literal>, <literal>$2</literal>, etc. 実行させるSQLコマンド文字列です。 パラメータが使用される場合は、コマンド文字列内で$1$2などのように参照されます。

nParams

The number of parameters supplied; it is the length of the arrays <parameter>paramTypes[]</parameter>, <parameter>paramValues[]</parameter>, <parameter>paramLengths[]</parameter>, and <parameter>paramFormats[]</parameter>. (The array pointers can be <symbol>NULL</symbol> when <parameter>nParams</parameter> is zero.) 提供されるパラメータ数です。 これは配列paramTypes[]paramValues[]paramLengths[]paramFormats[]の要素数です。 (この配列ポインタは、nParamsが0の場合、NULLとすることができます。)

paramTypes[]

Specifies, by OID, the data types to be assigned to the parameter symbols. If <parameter>paramTypes</parameter> is <symbol>NULL</symbol>, or any particular element in the array is zero, the server infers a data type for the parameter symbol in the same way it would do for an untyped literal string. パラメータシンボルに代入されるデータ型をOIDで指定したものです。 paramTypesNULL、または、ある配列要素が0の場合、サーバは、型指定のないリテラル文字列に対して行う推定方法と同じ方法を使用して、パラメータシンボルのデータ型を推定します。

paramValues[]

Specifies the actual values of the parameters. A null pointer in this array means the corresponding parameter is null; otherwise the pointer points to a zero-terminated text string (for text format) or binary data in the format expected by the server (for binary format). パラメータの実際の値を指定します。 配列内のNULLポインタは対応するパラメータがNULLであることを意味します。 さもなくば、このポインタはゼロ終端のテキスト文字列(テキスト書式)、または、サーバで想定している書式によるバイナリデータ(バイナリ書式)を指し示します。

paramLengths[]

Specifies the actual data lengths of binary-format parameters. It is ignored for null parameters and text-format parameters. The array pointer can be null when there are no binary parameters. バイナリ書式のパラメータの実データ長を指定します。 NULLパラメータおよびテキスト書式のパラメータでは無視されます。 バイナリパラメータが存在しない場合、この配列ポインタはNULLとしてもかまいません。

paramFormats[]

Specifies whether parameters are text (put a zero in the array entry for the corresponding parameter) or binary (put a one in the array entry for the corresponding parameter). If the array pointer is null then all parameters are presumed to be text strings. パラメータがテキスト(パラメータに対応する配列要素に0を設定)か、バイナリ(パラメータに対応する配列要素に1を設定)かを指定します。 この配列ポインタがNULLの場合、すべてのパラメータはテキスト文字列であると仮定されます。

Values passed in binary format require knowledge of the internal representation expected by the backend. For example, integers must be passed in network byte order. Passing <type>numeric</type> values requires knowledge of the server storage format, as implemented in <filename>src/backend/utils/adt/numeric.c::numeric_send()</filename> and <filename>src/backend/utils/adt/numeric.c::numeric_recv()</filename>. バイナリ書式で渡された値は、バックエンドが想定する内部表現の知識を必要とします。 例えば、整数はネットワークバイト順に渡されなければなりません。 numericによる値は、src/backend/utils/adt/numeric.c::numeric_send()およびsrc/backend/utils/adt/numeric.c::numeric_recv()で実装されたようにサーバストレージ書式の知識を必要とします。

resultFormat

Specify zero to obtain results in text format, or one to obtain results in binary format. (There is not currently a provision to obtain different result columns in different formats, although that is possible in the underlying protocol.) 結果をテキスト書式で取り出したい場合は0を、バイナリ書式で取り出したい場合は1を指定します。 (現時点では、プロトコル内部では実現可能ですが、結果の列ごとに異なる書式を指定して取り出す機構は存在しません。)

The primary advantage of <xref linkend="libpq-PQexecParams"/> over <xref linkend="libpq-PQexec"/> is that parameter values can be separated from the command string, thus avoiding the need for tedious and error-prone quoting and escaping. PQexecに対するPQexecParamsの主要な利点は、コマンド文字列とパラメータ値を分離することができることです。 これにより、面倒でエラーを招きやすい引用符付けやエスケープ処理を行なう必要がなくなります。

Unlike <xref linkend="libpq-PQexec"/>, <xref linkend="libpq-PQexecParams"/> allows at most one SQL command in the given string. (There can be semicolons in it, but not more than one nonempty command.) This is a limitation of the underlying protocol, but has some usefulness as an extra defense against SQL-injection attacks. PQexecと異なり、PQexecParamsは、文字列内に最大でも1つのSQLコマンドを入れることができます。 (セミコロンを入れることはできますが、空でないコマンドを2つ以上入れることはできません。) これは、プロトコル自体の制限ですが、SQLインジェクション攻撃に対する追加の防御となりますので、多少役に立ちます。

ヒント

Specifying parameter types via OIDs is tedious, particularly if you prefer not to hard-wire particular OID values into your program. However, you can avoid doing so even in cases where the server by itself cannot determine the type of the parameter, or chooses a different type than you want. In the SQL command text, attach an explicit cast to the parameter symbol to show what data type you will send. For example: OID経由のパラメータ型の指定は、特にプログラムの中で特定のOID値がソースに直接書き込まれることを好まない場合には退屈です。 しかしながら、パラメータの型をサーバ自身で決定できない場合や、望む型と異なる型を選択する場合であっても、これを避けることができます。 SQLコマンドテキストでどのデータ型を送信するかを示すためにパラメータシンボルに明示的なキャストをつけてください。 以下が例です。

SELECT * FROM mytable WHERE x = $1::bigint;

This forces parameter <literal>$1</literal> to be treated as <type>bigint</type>, whereas by default it would be assigned the same type as <literal>x</literal>. Forcing the parameter type decision, either this way or by specifying a numeric type OID, is strongly recommended when sending parameter values in binary format, because binary format has less redundancy than text format and so there is less chance that the server will detect a type mismatch mistake for you. デフォルトではパラメータ$1の型はxと同じデータ型に割り当てられますが、これにより強制的にbigintとして扱われます。 この方法または型のOIDを数字で指定する方法で、パラメータの型を強制的に決定することがバイナリ書式においてパラメータ値を送る時に強く推奨されます。 これは、バイナリ書式はテキスト書式より情報が少なく、そのために、サーバが型の不一致という問題を検出する機会が少なくなるためです。

PQprepare #

Submits a request to create a prepared statement with the given parameters, and waits for completion. 指定パラメータを持つプリペアド文の作成要求を送信し、その完了を待ちます。

PGresult *PQprepare(PGconn *conn,
                    const char *stmtName,
                    const char *query,
                    int nParams,
                    const Oid *paramTypes);

<xref linkend="libpq-PQprepare"/> creates a prepared statement for later execution with <xref linkend="libpq-PQexecPrepared"/>. This feature allows commands to be executed repeatedly without being parsed and planned each time; see <xref linkend="sql-prepare"/> for details. PQprepareは、後でPQexecPreparedを使用して実行するプリペアド文を作成します。 この機能を使用すると、コマンドを実行の度に解析して計画することなく、繰り返し実行することができます。 詳しくはPREPAREを参照してください。

The function creates a prepared statement named <parameter>stmtName</parameter> from the <parameter>query</parameter> string, which must contain a single SQL command. <parameter>stmtName</parameter> can be <literal>""</literal> to create an unnamed statement, in which case any pre-existing unnamed statement is automatically replaced; otherwise it is an error if the statement name is already defined in the current session. If any parameters are used, they are referred to in the query as <literal>$1</literal>, <literal>$2</literal>, etc. <parameter>nParams</parameter> is the number of parameters for which types are pre-specified in the array <parameter>paramTypes[]</parameter>. (The array pointer can be <symbol>NULL</symbol> when <parameter>nParams</parameter> is zero.) <parameter>paramTypes[]</parameter> specifies, by OID, the data types to be assigned to the parameter symbols. If <parameter>paramTypes</parameter> is <symbol>NULL</symbol>, or any particular element in the array is zero, the server assigns a data type to the parameter symbol in the same way it would do for an untyped literal string. Also, the query can use parameter symbols with numbers higher than <parameter>nParams</parameter>; data types will be inferred for these symbols as well. (See <xref linkend="libpq-PQdescribePrepared"/> for a means to find out what data types were inferred.) この関数はquery文字列からstmtNameという名前のプリペアド文を作成します。 queryは単一のSQLコマンドでなければなりません。 stmtName""にして、無名の文を作成することができます。 もし、無名の文が既に存在していた場合は自動的に置き換えられます。 その他の場合、文の名前が現在のセッションで既に存在するとエラーになります。 何らかのパラメータが使用される場合、問い合わせ内では$1$2などで参照します。 nParamsはパラメータ数です。 その型については事前にparamTypes[]配列で指定されています。 (nParamsがゼロの場合、この配列ポインタはNULLにすることができます。) paramTypes[]は、OIDによりパラメータシンボルに割り当てるデータ型を指定します。 paramTypesNULLの場合、もしくは、配列内の特定要素がゼロの場合、サーバはそのパラメータシンボルに対して、型指定の無いリテラル文字列に対する処理と同等の方法でデータ型を割り当てます。 また、問い合わせではnParamsより多くのパラメータシンボルを使用することができます。 これらのシンボルに対するデータ型も同様に推測されます。 (どのようなデータ型が推測されるかを検出する手法についてはPQdescribePreparedを参照してください。)

As with <xref linkend="libpq-PQexec"/>, the result is normally a <structname>PGresult</structname> object whose contents indicate server-side success or failure. A null result indicates out-of-memory or inability to send the command at all. Use <xref linkend="libpq-PQerrorMessage"/> to get more information about such errors. PQexec同様、結果は通常PGresultオブジェクトで、その内容でサーバ側の成功や失敗を示します。 NULLという結果はメモリ不足や全くコマンドを送信することができなかったことを示します。 こうしたエラーの詳細情報を入手するにはPQerrorMessageを使用してください。

Prepared statements for use with <xref linkend="libpq-PQexecPrepared"/> can also be created by executing SQL <xref linkend="sql-prepare"/> statements. Also, although there is no <application>libpq</application> function for deleting a prepared statement, the SQL <xref linkend="sql-deallocate"/> statement can be used for that purpose. PQexecPreparedで使用するためのプリペアド文は、PREPARE SQL文を実行することでも作成可能です。 また、プリペアド文を削除するlibpq関数はありませんが、この目的のためにDEALLOCATESQL文を使用することができます。

PQexecPrepared #

Sends a request to execute a prepared statement with given parameters, and waits for the result. 指定パラメータによるプリペアド文の実行要求を送信し、結果を待ちます。

PGresult *PQexecPrepared(PGconn *conn,
                         const char *stmtName,
                         int nParams,
                         const char * const *paramValues,
                         const int *paramLengths,
                         const int *paramFormats,
                         int resultFormat);

<xref linkend="libpq-PQexecPrepared"/> is like <xref linkend="libpq-PQexecParams"/>, but the command to be executed is specified by naming a previously-prepared statement, instead of giving a query string. This feature allows commands that will be used repeatedly to be parsed and planned just once, rather than each time they are executed. The statement must have been prepared previously in the current session. PQexecPreparedPQexecParamsは似ていますが、前者では実行されるコマンドは、問い合わせ文字列を与えるのではなく、事前にプリペアド文を指名することで指定されます。 この機能により、繰り返し使用する予定のコマンドを実行する度にではなく、一度だけ解析、計画作成を行うことができます。 この文は現在のセッションで事前に準備されていなければなりません。

The parameters are identical to <xref linkend="libpq-PQexecParams"/>, except that the name of a prepared statement is given instead of a query string, and the <parameter>paramTypes[]</parameter> parameter is not present (it is not needed since the prepared statement's parameter types were determined when it was created). パラメータは、問い合わせ文字列ではなく指定されたプリペアド文の名前を与える点を除き、PQexecParamsと同じです。 また、paramTypes[]パラメータは存在しません。 (プリペアド文のパラメータ型はその作成時点で決定されているため、これは不要です。)

PQdescribePrepared #

Submits a request to obtain information about the specified prepared statement, and waits for completion. 指定したプリペアド文に関する情報入手要求を送り、入手完了まで待機します。

PGresult *PQdescribePrepared(PGconn *conn, const char *stmtName);

<xref linkend="libpq-PQdescribePrepared"/> allows an application to obtain information about a previously prepared statement. PQdescribePreparedにより、アプリケーションは事前にプリペアド文に関する情報を入手できます。

<parameter>stmtName</parameter> can be <literal>""</literal> or <symbol>NULL</symbol> to reference the unnamed statement, otherwise it must be the name of an existing prepared statement. On success, a <structname>PGresult</structname> with status <literal>PGRES_COMMAND_OK</literal> is returned. The functions <xref linkend="libpq-PQnparams"/> and <xref linkend="libpq-PQparamtype"/> can be applied to this <structname>PGresult</structname> to obtain information about the parameters of the prepared statement, and the functions <xref linkend="libpq-PQnfields"/>, <xref linkend="libpq-PQfname"/>, <xref linkend="libpq-PQftype"/>, etc. provide information about the result columns (if any) of the statement. stmtName""またはNULLとすることで、無名の文を参照することができます。 これ以外では、存在するプリペアド文の名前でなければなりません。 成功すると、PGRES_COMMAND_OKというステータスのPGresultが返されます。 PQnparamsおよびPQparamtype関数をこのPGresultに適用して、プリペアド文のパラメータに関する情報を得ることができます。 また、PQnfieldsPQfnamePQftype関数などを使用して、文の結果列(もしあれば)に関する情報を提供できます。

PQdescribePortal #

Submits a request to obtain information about the specified portal, and waits for completion. 指定したポータルに関する情報入手要求を送信し、完了まで待機します。

PGresult *PQdescribePortal(PGconn *conn, const char *portalName);

<xref linkend="libpq-PQdescribePortal"/> allows an application to obtain information about a previously created portal. (<application>libpq</application> does not provide any direct access to portals, but you can use this function to inspect the properties of a cursor created with a <command>DECLARE CURSOR</command> SQL command.) PQdescribePortalにより、アプリケーションは事前に作成されたポータルの情報を入手することができます。 (libpqはポータルへの直接アクセスする方法を提供していませんが、この関数を使用してDECLARE CURSOR SQLコマンドで作成したカーソルの属性を確認することができます。)

<parameter>portalName</parameter> can be <literal>""</literal> or <symbol>NULL</symbol> to reference the unnamed portal, otherwise it must be the name of an existing portal. On success, a <structname>PGresult</structname> with status <literal>PGRES_COMMAND_OK</literal> is returned. The functions <xref linkend="libpq-PQnfields"/>, <xref linkend="libpq-PQfname"/>, <xref linkend="libpq-PQftype"/>, etc. can be applied to the <structname>PGresult</structname> to obtain information about the result columns (if any) of the portal. portalName""またはNULLを指定して、無名のポータルを参照することができます。 これ以外では、既存のポータルの名前でなければなりません。 成功すると、PGRES_COMMAND_OKというステータスのPGresultが返されます。 PQnfieldsPQfnamePQftype関数などをこのPGresultに適用して、ポータルの結果列(もしあれば)に関する情報を得ることができます。

The <structname>PGresult</structname><indexterm><primary>PGresult</primary></indexterm> structure encapsulates the result returned by the server. <application>libpq</application> application programmers should be careful to maintain the <structname>PGresult</structname> abstraction. Use the accessor functions below to get at the contents of <structname>PGresult</structname>. Avoid directly referencing the fields of the <structname>PGresult</structname> structure because they are subject to change in the future. PGresult構造体はサーバから返された結果をカプセル化します。 libpqアプリケーションのプログラマは注意してPGresultという抽象化を維持してください。 以下のアクセス用関数を使用して、PGresultの内容を取り出してください。 将来の変更に影響されますので、PGresult構造体のフィールドを直接参照することは避けてください。

PQresultStatus #

Returns the result status of the command. コマンドの結果状態を返します。

ExecStatusType PQresultStatus(const PGresult *res);

<xref linkend="libpq-PQresultStatus"/> can return one of the following values: PQresultStatusは以下のいずれかの値を返します。

PGRES_EMPTY_QUERY #

The string sent to the server was empty. サーバに送信された文字列が空でした。

PGRES_COMMAND_OK #

Successful completion of a command returning no data. データを返さないコマンドが正常終了しました。

PGRES_TUPLES_OK #

Successful completion of a command returning data (such as a <command>SELECT</command> or <command>SHOW</command>). データを返すコマンド(SELECTSHOWなど)が正常終了しました。

PGRES_COPY_OUT #

Copy Out (from server) data transfer started. (サーバからの)コピーアウトデータ転送が始まりました。

PGRES_COPY_IN #

Copy In (to server) data transfer started. (サーバへの)コピーインデータ転送が始まりました。

PGRES_BAD_RESPONSE #

The server's response was not understood. サーバが不明な応答を返しました。

PGRES_NONFATAL_ERROR #

A nonfatal error (a notice or warning) occurred. 致命的ではない(注意喚起もしくは警告)エラーが発生しました。

PGRES_FATAL_ERROR #

A fatal error occurred. 致命的なエラーが発生しました。

PGRES_COPY_BOTH #

Copy In/Out (to and from server) data transfer started. This feature is currently used only for streaming replication, so this status should not occur in ordinary applications. (サーバからおよびサーバへの)コピーイン/アウトデータ転送が始まりました。 現在こればストリーミングレプリケーションのみで使用されます。 このためこの状態は通常のアプリケーションでは起こりません。

PGRES_SINGLE_TUPLE #

The <structname>PGresult</structname> contains a single result tuple from the current command. This status occurs only when single-row mode has been selected for the query (see <xref linkend="libpq-single-row-mode"/>). PGresultには現在のコマンドからの結果タプルが1つ含まれます。 この状態は問い合わせで単一行モードが選択された場合(34.6参照)のみ起こります。

PGRES_PIPELINE_SYNC #

The <structname>PGresult</structname> represents a synchronization point in pipeline mode, requested by <xref linkend="libpq-PQpipelineSync"/>. This status occurs only when pipeline mode has been selected. PGresultは、PQpipelineSyncによって要求されたパイプラインモードの同期ポイントを表します。 この状態はパイプラインモードが選択されている場合のみ起こります。

PGRES_PIPELINE_ABORTED #

The <structname>PGresult</structname> represents a pipeline that has received an error from the server. <function>PQgetResult</function> must be called repeatedly, and each time it will return this status code until the end of the current pipeline, at which point it will return <literal>PGRES_PIPELINE_SYNC</literal> and normal processing can resume. PGresultは、サーバからエラーを受信したパイプラインを表します。 PQgetResultは繰り返し呼び出されなければなりません。 現在のパイプラインが終了するまでこのステータスコードを返す度にPGRES_PIPELINE_SYNCを返し、通常の処理を再開できます。

If the result status is <literal>PGRES_TUPLES_OK</literal> or <literal>PGRES_SINGLE_TUPLE</literal>, then the functions described below can be used to retrieve the rows returned by the query. Note that a <command>SELECT</command> command that happens to retrieve zero rows still shows <literal>PGRES_TUPLES_OK</literal>. <literal>PGRES_COMMAND_OK</literal> is for commands that can never return rows (<command>INSERT</command> or <command>UPDATE</command> without a <literal>RETURNING</literal> clause, etc.). A response of <literal>PGRES_EMPTY_QUERY</literal> might indicate a bug in the client software. 結果状態がPGRES_TUPLES_OKまたはPGRES_SINGLE_TUPLEであれば、以下で説明する関数を使って問い合わせが返した行を取り出すことができます。 ただし、たまたまSELECTコマンドが返す行が0個だったような場合でもPGRES_TUPLES_OKとなることに注意してください。 PGRES_COMMAND_OKは、行を決して返さない(RETURNING句の無いINSERTまたはUPDATEなど)コマンド用です。 PGRES_EMPTY_QUERYという応答はクライアントソフトウェアの不具合を示しているかもしれません。

A result of status <symbol>PGRES_NONFATAL_ERROR</symbol> will never be returned directly by <xref linkend="libpq-PQexec"/> or other query execution functions; results of this kind are instead passed to the notice processor (see <xref linkend="libpq-notice-processing"/>). PGRES_NONFATAL_ERROR状態の場合、結果はPQexecや他の問い合わせ実行関数によって直接返されません。 その代わりに、この種の結果は注意喚起プロセッサ(34.13を参照)に渡されます。

PQresStatus #

Converts the enumerated type returned by <xref linkend="libpq-PQresultStatus"/> into a string constant describing the status code. The caller should not free the result. PQresultStatusが返す列挙型から状態コードを説明する文字列定数に変換します。 呼び出し元はこの結果を解放してはいけません。

char *PQresStatus(ExecStatusType status);

PQresultErrorMessage #

Returns the error message associated with the command, or an empty string if there was no error. コマンドに関するエラーメッセージを返します。 エラーが何もなければ、空の文字列を返します。

char *PQresultErrorMessage(const PGresult *res);

If there was an error, the returned string will include a trailing newline. The caller should not free the result directly. It will be freed when the associated <structname>PGresult</structname> handle is passed to <xref linkend="libpq-PQclear"/>. エラーがあった場合、返される文字列の最後には改行が含まれます。 呼び出し元はこの結果を直接解放してはいけません。 関連するPGresultハンドルがPQclearに渡された時にこれは解放されます。

Immediately following a <xref linkend="libpq-PQexec"/> or <xref linkend="libpq-PQgetResult"/> call, <xref linkend="libpq-PQerrorMessage"/> (on the connection) will return the same string as <xref linkend="libpq-PQresultErrorMessage"/> (on the result). However, a <structname>PGresult</structname> will retain its error message until destroyed, whereas the connection's error message will change when subsequent operations are done. Use <xref linkend="libpq-PQresultErrorMessage"/> when you want to know the status associated with a particular <structname>PGresult</structname>; use <xref linkend="libpq-PQerrorMessage"/> when you want to know the status from the latest operation on the connection. (接続に対する)PQerrorMessageも、PQexecまたはPQgetResult呼び出しの直後なら(結果に対する)PQresultErrorMessageと同じ文字列を返します。 しかし、接続に対するエラーメッセージは続いて操作を行うと変化してしまうのに対し、PGresultは自身が破棄されるまでそのエラーメッセージを維持し続けます。 このPQresultErrorMessageは個々のPGresultに結び付けられた状態を確認する時に、そしてPQerrorMessageは接続における最後の操作の状態を確認する時に使用してください。

PQresultVerboseErrorMessage #

Returns a reformatted version of the error message associated with a <structname>PGresult</structname> object. PGresultオブジェクトに関連したエラーメッセージの再フォーマットしたバージョンを返します。

char *PQresultVerboseErrorMessage(const PGresult *res,
                                  PGVerbosity verbosity,
                                  PGContextVisibility show_context);

In some situations a client might wish to obtain a more detailed version of a previously-reported error. <xref linkend="libpq-PQresultVerboseErrorMessage"/> addresses this need by computing the message that would have been produced by <xref linkend="libpq-PQresultErrorMessage"/> if the specified verbosity settings had been in effect for the connection when the given <structname>PGresult</structname> was generated. If the <structname>PGresult</structname> is not an error result, <quote>PGresult is not an error result</quote> is reported instead. The returned string includes a trailing newline. 状況によっては、クライアントは以前に報告されたエラーのより詳細なバージョンを取得したいと思うかもしれません。 PQresultVerboseErrorMessageは、指定のPGresultが生成されたときに、指定した冗長設定がその接続で使われていたならPQresultErrorMessageが生成したであろうメッセージを計算することで、この要請に応えます。 PGresultがエラーの結果ではない場合は、PGresult is not an error resultが代わりに報告されます。 返される文字列は行末に改行コードが含まれます。

Unlike most other functions for extracting data from a <structname>PGresult</structname>, the result of this function is a freshly allocated string. The caller must free it using <function>PQfreemem()</function> when the string is no longer needed. PGresultからデータを抽出する他の多くの関数と異なり、この関数の結果は新しく割り当てられた文字列です。 その文字列が必要なくなったときは、呼び出し側がPQfreemem()を使ってそれを解放しなければなりません。

A NULL return is possible if there is insufficient memory. 十分なメモリがないときは、NULLが返されることもありえます。

PQresultErrorField #

Returns an individual field of an error report. エラー報告の個々のフィールドを返します。

char *PQresultErrorField(const PGresult *res, int fieldcode);

<parameter>fieldcode</parameter> is an error field identifier; see the symbols listed below. <symbol>NULL</symbol> is returned if the <structname>PGresult</structname> is not an error or warning result, or does not include the specified field. Field values will normally not include a trailing newline. The caller should not free the result directly. It will be freed when the associated <structname>PGresult</structname> handle is passed to <xref linkend="libpq-PQclear"/>. fieldcodeはエラーフィールド識別子です。 以下に示すシンボルを参照してください。 PGresultがエラーではない、もしくは、警告付きの結果である場合や指定したフィールドを含まない場合、NULLが返されます。 通常フィールド値には改行が含まれません。 フィールド値は関連するPGresultハンドルがPQclearに渡された時に解放されます。

The following field codes are available: 以下のフィールドコードが使用できます。

PG_DIAG_SEVERITY #

The severity; the field contents are <literal>ERROR</literal>, <literal>FATAL</literal>, or <literal>PANIC</literal> (in an error message), or <literal>WARNING</literal>, <literal>NOTICE</literal>, <literal>DEBUG</literal>, <literal>INFO</literal>, or <literal>LOG</literal> (in a notice message), or a localized translation of one of these. Always present. 深刻度。 このフィールドの内容は(エラーメッセージの場合)ERRORFATAL、もしくは、PANIC、(注意喚起メッセージの場合)WARNINGNOTICEDEBUGINFO、もしくは、LOGです。 これらは、多言語化により翻訳されている可能性があります。 常に存在します。

PG_DIAG_SEVERITY_NONLOCALIZED #

The severity; the field contents are <literal>ERROR</literal>, <literal>FATAL</literal>, or <literal>PANIC</literal> (in an error message), or <literal>WARNING</literal>, <literal>NOTICE</literal>, <literal>DEBUG</literal>, <literal>INFO</literal>, or <literal>LOG</literal> (in a notice message). This is identical to the <symbol>PG_DIAG_SEVERITY</symbol> field except that the contents are never localized. This is present only in reports generated by <productname>PostgreSQL</productname> versions 9.6 and later. 深刻度。 このフィールドの内容は(エラーメッセージの場合)ERRORFATAL、もしくは、PANIC、(注意喚起メッセージの場合)WARNINGNOTICEDEBUGINFO、もしくは、LOGです。 これは、内容が多言語化されないことを除き、PG_DIAG_SEVERITYと同一です。 これはPostgreSQLのバージョン9.6以降で生成された報告にのみ存在します。

PG_DIAG_SQLSTATE #

The SQLSTATE code for the error. The SQLSTATE code identifies the type of error that has occurred; it can be used by front-end applications to perform specific operations (such as error handling) in response to a particular database error. For a list of the possible SQLSTATE codes, see <xref linkend="errcodes-appendix"/>. This field is not localizable, and is always present. エラーのSQLSTATEコードです。 SQLSTATEコードは発生したエラーの種類を識別します。 フロントエンドアプリケーションにより、特定のデータベースエラーに対して所定の操作(エラー処理など)を行うために使用できます。 起こり得るSQLSTATEコードの一覧については付録Aを参照してください。 このフィールドは多言語化されず、また、常に存在します。

PG_DIAG_MESSAGE_PRIMARY #

The primary human-readable error message (typically one line). Always present. 可読性を高めた主要エラーメッセージです。 (通常は1行です。) 常に存在します。

PG_DIAG_MESSAGE_DETAIL #

Detail: an optional secondary error message carrying more detail about the problem. Might run to multiple lines. 詳細です。 問題に関するより詳細を表す補助的なエラーメッセージです。 複数行に跨る可能性があります。

PG_DIAG_MESSAGE_HINT #

Hint: an optional suggestion what to do about the problem. This is intended to differ from detail in that it offers advice (potentially inappropriate) rather than hard facts. Might run to multiple lines. ヒントです。 問題の対応方法についての補助的な提言です。 これは、詳細(detail)とは異なり、問題の事象ではなく、(適切でない可能性がありますが)アドバイスを提供することを目的としています。 複数行に跨る可能性があります。

PG_DIAG_STATEMENT_POSITION #

A string containing a decimal integer indicating an error cursor position as an index into the original statement string. The first character has index 1, and positions are measured in characters not bytes. 元の問い合わせ文字列のインデックスとなる、エラーが発生したカーソル位置を示す10進整数を持つ文字列です。 先頭文字がインデックス1となり、また、バイトではなく、文字数で数えた位置です。

PG_DIAG_INTERNAL_POSITION #

This is defined the same as the <symbol>PG_DIAG_STATEMENT_POSITION</symbol> field, but it is used when the cursor position refers to an internally generated command rather than the one submitted by the client. The <symbol>PG_DIAG_INTERNAL_QUERY</symbol> field will always appear when this field appears. この定義はPG_DIAG_STATEMENT_POSITIONフィールドと同じです。 しかし、これは、クライアントが発行したコマンドではなく、カーソル位置が内部生成コマンドを参照する場合に使用されます。 このフィールドが存在する時は常にPG_DIAG_INTERNAL_QUERYフィールドが存在します。

PG_DIAG_INTERNAL_QUERY #

The text of a failed internally-generated command. This could be, for example, an SQL query issued by a PL/pgSQL function. 失敗した内部生成コマンドのテキストです。 これは、例えば、PL/pgSQL関数で発行されたSQL問い合わせになります。

PG_DIAG_CONTEXT #

An indication of the context in which the error occurred. Presently this includes a call stack traceback of active procedural language functions and internally-generated queries. The trace is one entry per line, most recent first. エラーが発生した文脈を示すものです。 今の所、これは活動中の手続き言語関数や内部生成問い合わせの呼び出しスタックの追跡情報が含まれます。 この追跡は行単位で1項目であり、その順番は呼び出し順の反対になります。

PG_DIAG_SCHEMA_NAME #

If the error was associated with a specific database object, the name of the schema containing that object, if any. そのエラーが特定のデータベースオブジェクトに付随する場合、もしあれば、そのオブジェクトを含むスキーマ名です。

PG_DIAG_TABLE_NAME #

If the error was associated with a specific table, the name of the table. (Refer to the schema name field for the name of the table's schema.) そのエラーが特定のテーブルに付随する場合のテーブル名です。 (テーブルのスキーマ名についてはスキーマ名フィールドを参照してください。)

PG_DIAG_COLUMN_NAME #

If the error was associated with a specific table column, the name of the column. (Refer to the schema and table name fields to identify the table.) そのエラーが特定のテーブル列に付随する場合の列名です。 (テーブルを識別するにはスキーマとテーブル名フィールドを参照してください。)

PG_DIAG_DATATYPE_NAME #

If the error was associated with a specific data type, the name of the data type. (Refer to the schema name field for the name of the data type's schema.) そのエラーが特定のデータ型に付随する場合のデータ型名です。 (データ型のスキーマ名についてはスキーマ名フィールドを参照してください。)

PG_DIAG_CONSTRAINT_NAME #

If the error was associated with a specific constraint, the name of the constraint. Refer to fields listed above for the associated table or domain. (For this purpose, indexes are treated as constraints, even if they weren't created with constraint syntax.) そのエラーが特定の制約に付随する場合の制約名です。 付随するテーブルまたはドメインについては上記にリストされたフィールドを参照してください。 (この目的のために、制約は制約構文で作成されていなくてもインデックスは制約として扱われます。)

PG_DIAG_SOURCE_FILE #

The file name of the source-code location where the error was reported. エラーが報告された場所のソースコードのファイル名です。

PG_DIAG_SOURCE_LINE #

The line number of the source-code location where the error was reported. エラーが報告された場所のソースコードにおける行番号です。

PG_DIAG_SOURCE_FUNCTION #

The name of the source-code function reporting the error. エラーを報告した、ソースコードにおける関数名です。

注記

The fields for schema name, table name, column name, data type name, and constraint name are supplied only for a limited number of error types; see <xref linkend="errcodes-appendix"/>. Do not assume that the presence of any of these fields guarantees the presence of another field. Core error sources observe the interrelationships noted above, but user-defined functions may use these fields in other ways. In the same vein, do not assume that these fields denote contemporary objects in the current database. スキーマ名、テーブル名、列名、データ型名、および制約名に対するフィールドは限定的なエラー型に対してのみ提供されます。付録Aを参照してください。 これらのフィールドのいかなる存在もその他のフィールドの存在を保証すると推測してはなりません。 コアエラーの出所は上に記載の相互関係を監視しますが、ユーザ定義関数はこれらフィールドを別目的で使用しているかもしれません。 同様の脈絡で、使用しているデータベースで これらのフィールドが同時に存在するオブジェクトを意味すると推測してはなりません。

The client is responsible for formatting displayed information to meet its needs; in particular it should break long lines as needed. Newline characters appearing in the error message fields should be treated as paragraph breaks, not line breaks. 表示情報の必要に応じた整形はクライアントの責任です。 具体的には、必要に応じて長い行を分割しなければなりません。 エラーメッセージフィールド内の改行文字は、改行としてではなく段落として分かれたものとして取扱うべきです。

Errors generated internally by <application>libpq</application> will have severity and primary message, but typically no other fields. libpqで内部的に生成されたエラーは、深刻度と主要メッセージを持ちますが、通常は他のフィールドを持ちません。

Note that error fields are only available from <structname>PGresult</structname> objects, not <structname>PGconn</structname> objects; there is no <function>PQerrorField</function> function. エラーフィールドはPGresultからのみ利用でき、PGconnからは利用できません。 PQerrorFieldという関数はありません。

PQclear #

Frees the storage associated with a <structname>PGresult</structname>. Every command result should be freed via <xref linkend="libpq-PQclear"/> when it is no longer needed. PGresultに割り当てられた記憶領域を解放します。 個々の問い合わせ結果は、必要なくなった時にPQclearで解放するべきです。

void PQclear(PGresult *res);

If the argument is a NULL pointer, no operation is performed.

You can keep a <structname>PGresult</structname> object around for as long as you need it; it does not go away when you issue a new command, nor even if you close the connection. To get rid of it, you must call <xref linkend="libpq-PQclear"/>. Failure to do this will result in memory leaks in your application. PGresultオブジェクトは必要な間保持することができます。 新しい問い合わせを発行する場合でも、接続を閉じてしまうまではPGresultは消えません。 PGresultを解放するには、PQclearを呼び出さなくてはいけません。 その操作に失敗してしまうと、アプリケーションのメモリリークを引き起こしてしまいます。

34.3.2. 問い合わせ結果の情報の取り出し #

<title>Retrieving Query Result Information</title>

These functions are used to extract information from a <structname>PGresult</structname> object that represents a successful query result (that is, one that has status <literal>PGRES_TUPLES_OK</literal> or <literal>PGRES_SINGLE_TUPLE</literal>). They can also be used to extract information from a successful Describe operation: a Describe's result has all the same column information that actual execution of the query would provide, but it has zero rows. For objects with other status values, these functions will act as though the result has zero rows and zero columns. これらの関数を使用して、正常終了した問い合わせ結果を示す(つまり、その状態がPGRES_TUPLES_OKまたはPGRES_SINGLE_TUPLEとなっている)PGresultオブジェクトから情報を抽出することができます。 また、成功したDescribe操作から情報を抽出することもできます。 Describeの結果はすべて、実際に問い合わせを実行した時に提供されるものと同じ列情報を持ちますが、行はありません。 他の状態値を持つオブジェクトでは、これらの関数は、結果が0行0列であるものと同様に動作します。

PQntuples #

Returns the number of rows (tuples) in the query result. (Note that <structname>PGresult</structname> objects are limited to no more than <literal>INT_MAX</literal> rows, so an <type>int</type> result is sufficient.) 問い合わせ結果内の行(タプル)数を返します。 ( PGresultオブジェクトはINT_MAX行に制限されているため、intの結果で十分です。)

int PQntuples(const PGresult *res);

PQnfields #

Returns the number of columns (fields) in each row of the query result. 問い合わせ結果の各行の列(フィールド)の数を返します。

int PQnfields(const PGresult *res);

PQfname #

Returns the column name associated with the given column number. Column numbers start at 0. The caller should not free the result directly. It will be freed when the associated <structname>PGresult</structname> handle is passed to <xref linkend="libpq-PQclear"/>. 指定した列番号に対応する列の名前を返します。 列番号は0から始まります。 呼び出し元はこの結果を直接解放してはいけません。 関連するPGresultハンドルがPQclearに渡された時にこれは解放されます。

char *PQfname(const PGresult *res,
              int column_number);

<symbol>NULL</symbol> is returned if the column number is out of range. 列番号が範囲外であった場合、NULLが返ります。

PQfnumber #

Returns the column number associated with the given column name. 指定した列名に関連する列番号を返します。

int PQfnumber(const PGresult *res,
              const char *column_name);

-1 is returned if the given name does not match any column. 指定した名前に一致する列がなければ、-1が返ります。

The given name is treated like an identifier in an SQL command, that is, it is downcased unless double-quoted. For example, given a query result generated from the SQL command: 指定した名前はSQLコマンドの識別子同様に扱われます。 つまり、二重引用符でくくられていない限り、小文字化されます。 例えば、以下のSQLで生成された問い合わせ結果を考えます。

SELECT 1 AS FOO, 2 AS "BAR";

we would have the results: 以下により、結果を取り出すことができます。

PQfname(res, 0)              foo
PQfname(res, 1)              BAR
PQfnumber(res, "FOO")        0
PQfnumber(res, "foo")        0
PQfnumber(res, "BAR")        -1
PQfnumber(res, "\"BAR\"")    1

PQftable #

Returns the OID of the table from which the given column was fetched. Column numbers start at 0. 指定した列の抽出元であるテーブルのOIDを返します。 列番号は0から始まります。

Oid PQftable(const PGresult *res,
             int column_number);

<literal>InvalidOid</literal> is returned if the column number is out of range, or if the specified column is not a simple reference to a table column. You can query the system table <literal>pg_class</literal> to determine exactly which table is referenced. 列番号が範囲外の場合や指定した列がテーブル列への単純な参照でない場合、InvalidOidが返されます。 pg_classシステムテーブルに問い合わせ、どのテーブルが参照されているのかを正確に求めることができます。

The type <type>Oid</type> and the constant <literal>InvalidOid</literal> will be defined when you include the <application>libpq</application> header file. They will both be some integer type. libpqヘッダファイルをインクルードすると、Oid型とInvalidOid定数が定義されます。 これらは両方とも何らかの整数型です。

PQftablecol #

Returns the column number (within its table) of the column making up the specified query result column. Query-result column numbers start at 0, but table columns have nonzero numbers. 指定した問い合わせ結果の列を作成した列の(それが属するテーブル内での)列番号を返します。 問い合わせ結果の列番号は0から始まりますが、テーブル列には0以外の番号が付けられています。

int PQftablecol(const PGresult *res,
                int column_number);

Zero is returned if the column number is out of range, or if the specified column is not a simple reference to a table column. 列番号が範囲外の場合や指定した列がテーブル列への単純な参照でなかった場合、ゼロが返されます。

PQfformat #

Returns the format code indicating the format of the given column. Column numbers start at 0. 指定した列の書式を示す書式コードを返します。 列番号は0から始まります。

int PQfformat(const PGresult *res,
              int column_number);

Format code zero indicates textual data representation, while format code one indicates binary representation. (Other codes are reserved for future definition.) ゼロという書式コードはテキストデータ表現を示し、1という書式コードはバイナリ表現を示します。 (他のコードは将来の定義のために予約されています。)

PQftype #

Returns the data type associated with the given column number. The integer returned is the internal OID number of the type. Column numbers start at 0. 指定した列番号に関連したデータ型を返します。 返された整数はその型の内部的なOID番号です。 列番号は0から始まります。

Oid PQftype(const PGresult *res,
            int column_number);

You can query the system table <literal>pg_type</literal> to obtain the names and properties of the various data types. The <acronym>OID</acronym>s of the built-in data types are defined in the file <filename>catalog/pg_type_d.h</filename> in the <productname>PostgreSQL</productname> installation's <filename>include</filename> directory. pg_typeシステムテーブルに問い合わせて、各種データ型の名前や属性を得ることができます。 組み込みデータ型のOIDは、PostgreSQLがインストールされたincludeディレクトリ内のcatalog/pg_type_d.hファイルに定義されています。

PQfmod #

Returns the type modifier of the column associated with the given column number. Column numbers start at 0. 指定した列番号に関連した列の型修飾子を返します。 列番号は0から始まります。

int PQfmod(const PGresult *res,
           int column_number);

The interpretation of modifier values is type-specific; they typically indicate precision or size limits. The value -1 is used to indicate <quote>no information available</quote>. Most data types do not use modifiers, in which case the value is always -1. 修飾子の値の解釈は型に固有なものです。 通常これらは精度やサイズの制限を示します。 -1という値は使用できる情報がないことを示します。 ほとんどのデータ型は修飾子を使用しません。 この場合は常に-1という値になります。

PQfsize #

Returns the size in bytes of the column associated with the given column number. Column numbers start at 0. 指定した列番号に関連した列のバイト単位のサイズを返します。 列番号は0から始まります。

int PQfsize(const PGresult *res,
            int column_number);

<xref linkend="libpq-PQfsize"/> returns the space allocated for this column in a database row, in other words the size of the server's internal representation of the data type. (Accordingly, it is not really very useful to clients.) A negative value indicates the data type is variable-length. PQfsizeはデータベース行内でその列用に割り当てられる領域を返します。 言い替えると、そのデータ型についてのサーバでの内部表現のサイズです。 (従って、実際にはクライアントから見るとあまり役には立ちません。) 負の値は可変長データ型を示します。

PQbinaryTuples #

Returns 1 if the <structname>PGresult</structname> contains binary data and 0 if it contains text data. PGresultがバイナリデータを持つ場合は1を、テキストデータを持つ場合は0を返します。

int PQbinaryTuples(const PGresult *res);

This function is deprecated (except for its use in connection with <command>COPY</command>), because it is possible for a single <structname>PGresult</structname> to contain text data in some columns and binary data in others. <xref linkend="libpq-PQfformat"/> is preferred. <xref linkend="libpq-PQbinaryTuples"/> returns 1 only if all columns of the result are binary (format 1). この関数は廃れたものです。 (COPYを行う接続での使用を除きます。) 単一のPGresultで、ある列はテキストデータを持ち、他の列ではバイナリデータを持つことが可能であるためです。 PQfformatの利用が推奨されます。 結果のすべての列がバイナリ(書式1)の場合のみPQbinaryTuplesは1を返します。

PQgetvalue #

Returns a single field value of one row of a <structname>PGresult</structname>. Row and column numbers start at 0. The caller should not free the result directly. It will be freed when the associated <structname>PGresult</structname> handle is passed to <xref linkend="libpq-PQclear"/>. PGresultの1行における単一フィールドの値を返します。 行番号と列番号は0から始まります。 呼び出し元はこの結果を直接解放してはいけません。 関連するPGresultハンドルがPQclearに渡された時に、これは解放されます。

char *PQgetvalue(const PGresult *res,
                 int row_number,
                 int column_number);

For data in text format, the value returned by <xref linkend="libpq-PQgetvalue"/> is a null-terminated character string representation of the field value. For data in binary format, the value is in the binary representation determined by the data type's <function>typsend</function> and <function>typreceive</function> functions. (The value is actually followed by a zero byte in this case too, but that is not ordinarily useful, since the value is likely to contain embedded nulls.) テキスト書式のデータでは、PQgetvalueで返される値はフィールド値のNULL終端の文字列表現となります。 バイナリ書式のデータでは、この値はデータ型のtypsend関数とtypreceive関数で決まるバイナリ表現となります。 (実際にはこの場合でも値の終わりにゼロというバイトが付与されます。 しかし、この値の内部には大抵の場合NULLが埋め込まれていますので、通常このバイトは有用ではありません。)

An empty string is returned if the field value is null. See <xref linkend="libpq-PQgetisnull"/> to distinguish null values from empty-string values. フィールド値がNULLの場合、空文字列が返されます。 NULL値と空文字列という値とを区別する方法はPQgetisnullを参照してください。

The pointer returned by <xref linkend="libpq-PQgetvalue"/> points to storage that is part of the <structname>PGresult</structname> structure. One should not modify the data it points to, and one must explicitly copy the data into other storage if it is to be used past the lifetime of the <structname>PGresult</structname> structure itself. PQgetvalueによって返されるポインタはPGresult構造体の一部の格納領域を指し示します。 このポインタが指し示すデータを変更すべきではありません。 また、PGresult構造体を解放した後も使用し続ける場合は、データを別の格納領域に明示的にコピーしなければなりません。

PQgetisnull #

Tests a field for a null value. Row and column numbers start at 0. フィールドがNULL値かどうか検査します。 行番号と列番号は0から始まります。

int PQgetisnull(const PGresult *res,
                int row_number,
                int column_number);

This function returns 1 if the field is null and 0 if it contains a non-null value. (Note that <xref linkend="libpq-PQgetvalue"/> will return an empty string, not a null pointer, for a null field.) この関数は、フィールドがNULLの場合に1を、フィールドが非NULL値を持つ場合は0を返します。 (PQgetvalueでは、NULLフィールドはNULLポインタではなく空文字列を返すことに注意してください。)

PQgetlength #

Returns the actual length of a field value in bytes. Row and column numbers start at 0. 実際のフィールド値の長さをバイト単位で返します。 行番号と列番号は0から始まります。

int PQgetlength(const PGresult *res,
                int row_number,
                int column_number);

This is the actual data length for the particular data value, that is, the size of the object pointed to by <xref linkend="libpq-PQgetvalue"/>. For text data format this is the same as <function>strlen()</function>. For binary format this is essential information. Note that one should <emphasis>not</emphasis> rely on <xref linkend="libpq-PQfsize"/> to obtain the actual data length. これは特定のデータ値についての実際のデータ長です。 つまり、PQgetvalueによって指し示されるオブジェクトのサイズです。 テキストデータ書式ではstrlen()と同一です。 バイナリ書式ではこれは重要な情報です。 実際のデータ長を取り出すためにPQfsizeを信用してはなりません

PQnparams #

Returns the number of parameters of a prepared statement. プリペアド文のパラメータ数を返します。

int PQnparams(const PGresult *res);

This function is only useful when inspecting the result of <xref linkend="libpq-PQdescribePrepared"/>. For other types of results it will return zero. 《マッチ度[82.000000]》この関数はPQdescribePreparedの結果を確認する時にのみ有用です。 他の種類の問い合わせではゼロを返します。 《機械翻訳》この関数は、PQdescribePreparedの結果を調べる場合にのみ有用です。 他のタイプの結果では、ゼロが返されます。

PQparamtype #

Returns the data type of the indicated statement parameter. Parameter numbers start at 0. 指定された文パラメータのデータ型を返します。 パラメータ番号は0から始まります。

Oid PQparamtype(const PGresult *res, int param_number);

This function is only useful when inspecting the result of <xref linkend="libpq-PQdescribePrepared"/>. For other types of results it will return zero. 《マッチ度[82.000000]》この関数はPQdescribePreparedの結果を確認する時にのみ有用です。 他の種類の問い合わせではゼロを返します。 《機械翻訳》この関数は、PQdescribePreparedの結果を調べる場合にのみ有用です。 他のタイプの結果では、ゼロが返されます。

PQprint #

Prints out all the rows and, optionally, the column names to the specified output stream. すべての行と列名(省略可能)を指定した出力ストリームに表示します。


void PQprint(FILE *fout,      /* output stream */
             const PGresult *res,
             const PQprintOpt *po);
typedef struct
{
    pqbool  header;      /* print output field headings and row count */
    pqbool  align;       /* fill align the fields */
    pqbool  standard;    /* old brain dead format */
    pqbool  html3;       /* output HTML tables */
    pqbool  expanded;    /* expand tables */
    pqbool  pager;       /* use pager for output if needed */
    char    *fieldSep;   /* field separator */
    char    *tableOpt;   /* attributes for HTML table element */
    char    *caption;    /* HTML table caption */
    char    **fieldName; /* null-terminated array of replacement field names */
} PQprintOpt;

void PQprint(FILE *fout,      /* 出力ストリーム */
             const PGresult *res,
             const PQprintOpt *po);
typedef struct
{
    pqbool  header;      /* フィールドヘッダ情報と行数の表示出力 */
    pqbool  align;       /* 位置揃えのためのフィールドへの埋め込み */
    pqbool  standard;    /* 古い、無くなりそうな書式 */
    pqbool  html3;       /* HTML表出力 */
    pqbool  expanded;    /* 拡張テーブル */
    pqbool  pager;       /* 必要に応じたページャの使用 */
    char    *fieldSep;   /* フィールド区切り文字 */
    char    *tableOpt;   /* HTML表要素の属性 */
    char    *caption;    /* HTML 表の表題 */
    char    **fieldName; /* フィールド名を置き換えるNULL終端の配列 */
} PQprintOpt;

This function was formerly used by <application>psql</application> to print query results, but this is no longer the case. Note that it assumes all the data is in text format. この関数は以前に問い合わせ結果を表示するためにpsqlで使用されていましたが、今ではもう使用されていません。 これはすべてのデータがテキスト書式であるという前提で動作することに注意してください。

34.3.3. 他の結果情報の取り出し #

<title>Retrieving Other Result Information</title>

These functions are used to extract other information from <structname>PGresult</structname> objects. これらの関数はPGresultオブジェクトからその他の情報を取り出すために使用されます。

PQcmdStatus #

Returns the command status tag from the SQL command that generated the <structname>PGresult</structname>. PGresultを生成したSQLコマンドのコマンド状態タグを返します。

char *PQcmdStatus(PGresult *res);

Commonly this is just the name of the command, but it might include additional data such as the number of rows processed. The caller should not free the result directly. It will be freed when the associated <structname>PGresult</structname> handle is passed to <xref linkend="libpq-PQclear"/>. これは通常単なるコマンド名ですが、処理行数など追加情報が含まれる場合もあります。 呼び出し元はこの戻り値を直接解放してはいけません。 関連するPGresultハンドルがPQclearに渡された時にこれは解放されます。

PQcmdTuples #

Returns the number of rows affected by the SQL command. SQLコマンドにより影響を受けた行数を返します。

char *PQcmdTuples(PGresult *res);

This function returns a string containing the number of rows affected by the <acronym>SQL</acronym> statement that generated the <structname>PGresult</structname>. This function can only be used following the execution of a <command>SELECT</command>, <command>CREATE TABLE AS</command>, <command>INSERT</command>, <command>UPDATE</command>, <command>DELETE</command>, <command>MERGE</command>, <command>MOVE</command>, <command>FETCH</command>, or <command>COPY</command> statement, or an <command>EXECUTE</command> of a prepared query that contains an <command>INSERT</command>, <command>UPDATE</command>, <command>DELETE</command>, or <command>MERGE</command> statement. If the command that generated the <structname>PGresult</structname> was anything else, <xref linkend="libpq-PQcmdTuples"/> returns an empty string. The caller should not free the return value directly. It will be freed when the associated <structname>PGresult</structname> handle is passed to <xref linkend="libpq-PQclear"/>. この関数はPGresultを生成したSQLコマンドにより影響を受けた行数を含む文字列を返します。 この関数はSELECTCREATE TABLE ASINSERTUPDATEDELETEMERGEMOVEFETCHCOPY文の実行、あるいは、INSERTUPDATEDELETEMERGEを含むプリペアド問い合わせのEXECUTE文の後でのみ使用することができます。 PGresultを生成したコマンドが他のコマンドであった場合、PQcmdTuplesは空文字列を返します。 呼び出し元はこの戻り値を直接解放してはいけません。 関連するPGresultハンドルがPQclearに渡された時にこれは解放されます。

PQoidValue #

Returns the OID<indexterm><primary>OID</primary><secondary>in libpq</secondary></indexterm> of the inserted row, if the <acronym>SQL</acronym> command was an <command>INSERT</command> that inserted exactly one row into a table that has OIDs, or a <command>EXECUTE</command> of a prepared query containing a suitable <command>INSERT</command> statement. Otherwise, this function returns <literal>InvalidOid</literal>. This function will also return <literal>InvalidOid</literal> if the table affected by the <command>INSERT</command> statement does not contain OIDs. SQLコマンドが、OIDを持つテーブル内に1行のみを挿入するINSERTだった場合、あるいは、適切なINSERTを持つプリペアド問い合わせのEXECUTEだった場合に、挿入された行のOIDを返します。 さもなくばInvalidOidを返します。 また、INSERT文の影響を受けたテーブルがOIDを持たなかった場合、この関数はInvalidOidを返します。

Oid PQoidValue(const PGresult *res);

PQoidStatus #

This function is deprecated in favor of <xref linkend="libpq-PQoidValue"/> and is not thread-safe. It returns a string with the OID of the inserted row, while <xref linkend="libpq-PQoidValue"/> returns the OID value. この関数はPQoidValueのため廃止予定になりました。 またこれはスレッドセーフではありません。 これは挿入された行のOIDを文字列として返します。 一方PQoidValueはOID値を返します。

char *PQoidStatus(const PGresult *res);

34.3.4. SQLコマンドに含めるための文字列のエスケープ処理 #

<title>Escaping Strings for Inclusion in SQL Commands</title>
PQescapeLiteral #

char *PQescapeLiteral(PGconn *conn, const char *str, size_t length);

<xref linkend="libpq-PQescapeLiteral"/> escapes a string for use within an SQL command. This is useful when inserting data values as literal constants in SQL commands. Certain characters (such as quotes and backslashes) must be escaped to prevent them from being interpreted specially by the SQL parser. <xref linkend="libpq-PQescapeLiteral"/> performs this operation. PQescapeLiteralは、SQLコマンド内で使用するために文字列をエスケープします。 これは、SQLコマンド内のリテラル定数としてデータ値を挿入する時に有用です。 特定の文字(引用符やバックスラッシュ)は、SQLパーサによって特殊な解釈がなされないようにエスケープされなければなりません。 PQescapeLiteralはこの操作を行います。

<xref linkend="libpq-PQescapeLiteral"/> returns an escaped version of the <parameter>str</parameter> parameter in memory allocated with <function>malloc()</function>. This memory should be freed using <function>PQfreemem()</function> when the result is no longer needed. A terminating zero byte is not required, and should not be counted in <parameter>length</parameter>. (If a terminating zero byte is found before <parameter>length</parameter> bytes are processed, <xref linkend="libpq-PQescapeLiteral"/> stops at the zero; the behavior is thus rather like <function>strncpy</function>.) The return string has all special characters replaced so that they can be properly processed by the <productname>PostgreSQL</productname> string literal parser. A terminating zero byte is also added. The single quotes that must surround <productname>PostgreSQL</productname> string literals are included in the result string. PQescapeLiteralstrパラメータをエスケープしたものをmalloc()で割り当てたメモリ内に返します。 その結果が不要になったら、そのメモリをPQfreemem()を使用して解放しなければなりません。 ゼロバイト終端は必要なく、lengthに含めて数えてはいけません。 (lengthバイトを処理する前にゼロバイト終端が見つかると、PQescapeLiteralはそのゼロで終了します。 この動作はstrncpyと似ています。) 返される文字列では、PostgreSQL文字列リテラルパーサで適切に処理することができるように、すべての特殊文字は置換されます。 ゼロバイト終端も追加されます。 PostgreSQLの文字列リテラルでは前後に必要となる単一引用符も、その結果文字列には含まれています。

On error, <xref linkend="libpq-PQescapeLiteral"/> returns <symbol>NULL</symbol> and a suitable message is stored in the <parameter>conn</parameter> object. エラー時、PQescapeLiteralNULLを返し、connオブジェクト内に適切なメッセージを残します。

ヒント

It is especially important to do proper escaping when handling strings that were received from an untrustworthy source. Otherwise there is a security risk: you are vulnerable to <quote>SQL injection</quote> attacks wherein unwanted SQL commands are fed to your database. 信用できない入力元から受けとった文字列を扱う場合に適切なエスケープ処理を行なうことは非常に重要です。 さもなくば、セキュリティ上の危険性が発生します。 SQLインジェクション攻撃という弱点となり、好ましくないSQLコマンドがデータベースに流れてしまいます。

Note that it is neither necessary nor correct to do escaping when a data value is passed as a separate parameter in <xref linkend="libpq-PQexecParams"/> or its sibling routines. PQexecParamsまたは同義のルーチン内で別のパラメータとしてデータ値が渡される場合は、エスケープすることは必要でもなければ正しくもないことに注意してください。

PQescapeIdentifier #

char *PQescapeIdentifier(PGconn *conn, const char *str, size_t length);

<xref linkend="libpq-PQescapeIdentifier"/> escapes a string for use as an SQL identifier, such as a table, column, or function name. This is useful when a user-supplied identifier might contain special characters that would otherwise not be interpreted as part of the identifier by the SQL parser, or when the identifier might contain upper case characters whose case should be preserved. PQescapeIdentifierは、テーブル、列、関数名などのSQL識別子として使用できるように文字列をエスケープします。 これはユーザが提供した識別子に、そのままではSQLパーサで識別子として解釈されない特殊な文字が含まれる可能性がある場合、または、大文字小文字の違いを維持しなければならない状況で識別子に大文字が含まれる可能性がある場合に有用です。

<xref linkend="libpq-PQescapeIdentifier"/> returns a version of the <parameter>str</parameter> parameter escaped as an SQL identifier in memory allocated with <function>malloc()</function>. This memory must be freed using <function>PQfreemem()</function> when the result is no longer needed. A terminating zero byte is not required, and should not be counted in <parameter>length</parameter>. (If a terminating zero byte is found before <parameter>length</parameter> bytes are processed, <xref linkend="libpq-PQescapeIdentifier"/> stops at the zero; the behavior is thus rather like <function>strncpy</function>.) The return string has all special characters replaced so that it will be properly processed as an SQL identifier. A terminating zero byte is also added. The return string will also be surrounded by double quotes. PQescapeIdentifierstrパラメータをSQL識別子としてエスケープしたものをmalloc()で割り当てたメモリ内に返します。 その結果が不要になったら、そのメモリをPQfreemem()を使用して解放しなければなりません。 ゼロバイト終端は必要なく、lengthに含めて数えてはいけません。 (lengthバイトを処理する前にゼロバイト終端が見つかると、PQescapeIdentifierはそのゼロで終了します。 この動作はstrncpyと似ています。) 返される文字列では、SQL識別子として適切に処理することができるように、すべての特殊文字は置換されます。 ゼロバイト終端も追加されます。 その結果文字列の前後には二重引用符が付与されます。

On error, <xref linkend="libpq-PQescapeIdentifier"/> returns <symbol>NULL</symbol> and a suitable message is stored in the <parameter>conn</parameter> object. エラー時、PQescapeIdentifierNULLを返し、connオブジェクト内に適切なメッセージを残します。

ヒント

As with string literals, to prevent SQL injection attacks, SQL identifiers must be escaped when they are received from an untrustworthy source. 文字列リテラルと同様、SQLインジェクション攻撃を防ぐために、信頼できない入力元から受けとる場合にはSQL識別子をエスケープしなければなりません。

PQescapeStringConn #

size_t PQescapeStringConn(PGconn *conn,
                          char *to, const char *from, size_t length,
                          int *error);

<xref linkend="libpq-PQescapeStringConn"/> escapes string literals, much like <xref linkend="libpq-PQescapeLiteral"/>. Unlike <xref linkend="libpq-PQescapeLiteral"/>, the caller is responsible for providing an appropriately sized buffer. Furthermore, <xref linkend="libpq-PQescapeStringConn"/> does not generate the single quotes that must surround <productname>PostgreSQL</productname> string literals; they should be provided in the SQL command that the result is inserted into. The parameter <parameter>from</parameter> points to the first character of the string that is to be escaped, and the <parameter>length</parameter> parameter gives the number of bytes in this string. A terminating zero byte is not required, and should not be counted in <parameter>length</parameter>. (If a terminating zero byte is found before <parameter>length</parameter> bytes are processed, <xref linkend="libpq-PQescapeStringConn"/> stops at the zero; the behavior is thus rather like <function>strncpy</function>.) <parameter>to</parameter> shall point to a buffer that is able to hold at least one more byte than twice the value of <parameter>length</parameter>, otherwise the behavior is undefined. Behavior is likewise undefined if the <parameter>to</parameter> and <parameter>from</parameter> strings overlap. PQescapeStringConnは、PQescapeLiteralとほぼ同様に文字列リテラルをエスケープします。 PQescapeLiteralとは異なり、呼び出し元が適切な大きさのバッファを提供することに責任を持ちます。 さらにPQescapeStringConnPostgreSQLの文字リテラルとして囲まれなければならない単一引用符を生成しません。 これは、結果をSQLコマンドに挿入するときに付与しなければなりません。 fromパラメータはエスケープ対象の文字列の先頭を指すポインタです。 lengthパラメータはこの文字列のバイト数を示します。 ゼロバイト終端は必要なく、また、lengthではこれを数えてはなりません。 (もしlengthバイト処理する前にゼロバイト終端が存在すると、PQescapeStringConnはそのゼロで終了します。 この動作はstrncpyと同様です。) toは、最低でもlengthの2倍よりも1バイト多い文字を保持可能なバッファへのポインタにしなければなりません。 さもないと、動作は不定になります。 tofrom文字領域が重なる場合の動作も不定です。

If the <parameter>error</parameter> parameter is not <symbol>NULL</symbol>, then <literal>*error</literal> is set to zero on success, nonzero on error. Presently the only possible error conditions involve invalid multibyte encoding in the source string. The output string is still generated on error, but it can be expected that the server will reject it as malformed. On error, a suitable message is stored in the <parameter>conn</parameter> object, whether or not <parameter>error</parameter> is <symbol>NULL</symbol>. errorパラメータがNULLでなければ、*errorには成功の0か、エラーの0以外が設定されます。 現時点であり得る唯一のエラー条件は、元文字列に無効なマルチバイト符号が含まれている場合です。 出力文字列はエラーであっても生成されますが、サーバが不整合として却下することが想定できます。 エラーの際、適切なメッセージはerrorNULLかどうかにかかわらずconnオブジェクト内に格納されます。

<xref linkend="libpq-PQescapeStringConn"/> returns the number of bytes written to <parameter>to</parameter>, not including the terminating zero byte. PQescapeStringConntoに書き出したバイト数を返します。 ただし、文字数にはゼロバイト終端は含まれません。

PQescapeString #

<xref linkend="libpq-PQescapeString"/> is an older, deprecated version of <xref linkend="libpq-PQescapeStringConn"/>. PQescapeStringPQescapeStringConnの推奨されない古いものです。

size_t PQescapeString (char *to, const char *from, size_t length);

The only difference from <xref linkend="libpq-PQescapeStringConn"/> is that <xref linkend="libpq-PQescapeString"/> does not take <structname>PGconn</structname> or <parameter>error</parameter> parameters. Because of this, it cannot adjust its behavior depending on the connection properties (such as character encoding) and therefore <emphasis>it might give the wrong results</emphasis>. Also, it has no way to report error conditions. PQescapeStringConnとの唯一の違いは、PQescapeStringPGconnerrorパラメータを取らないことです。 このため(文字符号化方式のような)接続属性に依存する振舞いを調整できません。 その結果間違った結果を返す可能性があります。 また、エラー状態を通知する機能がありません。

<xref linkend="libpq-PQescapeString"/> can be used safely in client programs that work with only one <productname>PostgreSQL</productname> connection at a time (in this case it can find out what it needs to know <quote>behind the scenes</quote>). In other contexts it is a security hazard and should be avoided in favor of <xref linkend="libpq-PQescapeStringConn"/>. PQescapeStringは、一度に1つのPostgreSQL接続のみで動作するクライアントプログラムでは安全に利用できます。 (この場合知らなければならない裏側に隠された情報を知ることができるからです。) 他の場合には、セキュリティ要因でありPQescapeStringConnを利用することで避けなければなりません。

PQescapeByteaConn #

Escapes binary data for use within an SQL command with the type <type>bytea</type>. As with <xref linkend="libpq-PQescapeStringConn"/>, this is only used when inserting data directly into an SQL command string. bytea型としてSQLコマンド内で使用するバイナリデータをエスケープします。 PQescapeStringConnと同様、これは、SQLコマンド文字列にデータを直接含める場合にのみに使用されます。

unsigned char *PQescapeByteaConn(PGconn *conn,
                                 const unsigned char *from,
                                 size_t from_length,
                                 size_t *to_length);

Certain byte values must be escaped when used as part of a <type>bytea</type> literal in an <acronym>SQL</acronym> statement. <xref linkend="libpq-PQescapeByteaConn"/> escapes bytes using either hex encoding or backslash escaping. See <xref linkend="datatype-binary"/> for more information. SQL文内のbyteaリテラルの一部として使用する場合、特定のバイト値はエスケープされなければなりません。 PQescapeByteaConnは16進数符号化またはバックスラッシュエスケープ処理を使用してバイトをエスケープします。 詳しくは8.4を参照してください。

The <parameter>from</parameter> parameter points to the first byte of the string that is to be escaped, and the <parameter>from_length</parameter> parameter gives the number of bytes in this binary string. (A terminating zero byte is neither necessary nor counted.) The <parameter>to_length</parameter> parameter points to a variable that will hold the resultant escaped string length. This result string length includes the terminating zero byte of the result. fromパラメータはエスケープ対象の文字列の先頭バイトを指し示すポインタです。 from_lengthパラメータは、このバイナリ列内のバイト数を指定します。 (ゼロバイト終端は不要、かつ、数えられません。) to_lengthパラメータは結果となるエスケープされた文字列の長さを保持する変数へのポインタです。 この結果文字列長は、結果内のゼロバイト終端を含みます。

<xref linkend="libpq-PQescapeByteaConn"/> returns an escaped version of the <parameter>from</parameter> parameter binary string in memory allocated with <function>malloc()</function>. This memory should be freed using <function>PQfreemem()</function> when the result is no longer needed. The return string has all special characters replaced so that they can be properly processed by the <productname>PostgreSQL</productname> string literal parser, and the <type>bytea</type> input function. A terminating zero byte is also added. The single quotes that must surround <productname>PostgreSQL</productname> string literals are not part of the result string. PQescapeByteaConnは、fromパラメータが示すバイナリ文字列をエスケープしたものをmalloc()で確保したメモリ内に返します。 その結果が不要になったら、このメモリをPQfreemem()を使用して解放しなければなりません。 返される文字列では、PostgreSQLリテラル文字列パーサとbytea入力関数によって適切に処理できるように、すべての特殊な文字が置換されています。 ゼロバイト終端も追加されます。 PostgreSQLのリテラル文字列をくくる単一引用符は結果文字列には含まれません。

On error, a null pointer is returned, and a suitable error message is stored in the <parameter>conn</parameter> object. Currently, the only possible error is insufficient memory for the result string. エラー時、NULLポインタを返し適切なエラーメッセージをconnオブジェクトに格納します。 現在、唯一あり得るエラーは結果文字列のメモリ不足です。

PQescapeBytea #

<xref linkend="libpq-PQescapeBytea"/> is an older, deprecated version of <xref linkend="libpq-PQescapeByteaConn"/>. PQescapeByteaは、PQescapeByteaConnの推奨されない古いものです。

unsigned char *PQescapeBytea(const unsigned char *from,
                             size_t from_length,
                             size_t *to_length);

The only difference from <xref linkend="libpq-PQescapeByteaConn"/> is that <xref linkend="libpq-PQescapeBytea"/> does not take a <structname>PGconn</structname> parameter. Because of this, <xref linkend="libpq-PQescapeBytea"/> can only be used safely in client programs that use a single <productname>PostgreSQL</productname> connection at a time (in this case it can find out what it needs to know <quote>behind the scenes</quote>). It <emphasis>might give the wrong results</emphasis> if used in programs that use multiple database connections (use <xref linkend="libpq-PQescapeByteaConn"/> in such cases). PQescapeByteaPQescapeByteaConnとの唯一の違いは、PGconnパラメータです。 このためPQescapeByteaは、一度に1つのPostgreSQL接続を使用するクライアントプログラムのみで安全に利用することができます。 (この場合知らなければならない裏側に隠された情報を知ることができるからです。) 複数のデータベース接続を使用するプログラムでは間違った結果を返す可能性があります。 (このような場合はPQescapeByteaConnを使用してください。)

PQunescapeBytea #

Converts a string representation of binary data into binary data &mdash; the reverse of <xref linkend="libpq-PQescapeBytea"/>. This is needed when retrieving <type>bytea</type> data in text format, but not when retrieving it in binary format. バイナリデータの文字列表現をバイナリデータに変換します。 つまり、PQescapeByteaの逆です。 これは、byteaデータをテキスト書式で受けとった場合に必要とされます。 しかし、バイナリ書式で受けとった場合は不要です。

unsigned char *PQunescapeBytea(const unsigned char *from, size_t *to_length);

The <parameter>from</parameter> parameter points to a string such as might be returned by <xref linkend="libpq-PQgetvalue"/> when applied to a <type>bytea</type> column. <xref linkend="libpq-PQunescapeBytea"/> converts this string representation into its binary representation. It returns a pointer to a buffer allocated with <function>malloc()</function>, or <symbol>NULL</symbol> on error, and puts the size of the buffer in <parameter>to_length</parameter>. The result must be freed using <xref linkend="libpq-PQfreemem"/> when it is no longer needed. fromパラメータは、例えば、bytea列にPQgetvalueを行なった場合に返される可能性がある、文字列を指し示すポインタです。 PQunescapeByteaは、この文字列表現をバイナリ表現に変換します。 malloc()で確保したバッファへのポインタを返します。 エラー時はNULLです。 また、このバッファのサイズをto_lengthに格納します。 不要になったら、この結果をPQfreememを使用して解放しなければなりません。

This conversion is not exactly the inverse of <xref linkend="libpq-PQescapeBytea"/>, because the string is not expected to be <quote>escaped</quote> when received from <xref linkend="libpq-PQgetvalue"/>. In particular this means there is no need for string quoting considerations, and so no need for a <structname>PGconn</structname> parameter. この変換は、PQescapeByteaの逆ではありません。 文字列はPQgetvalueから受け取る場合エスケープされたことを予想しないためです。 特にこれは、文字列の引用符付けを意識する必要がなく、そのためPGconnパラメータを持つ必要がないことを意味します。