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

34.10. COPYコマンド関連関数 #

<title>Functions Associated with the <command>COPY</command> Command</title>

The <command>COPY</command> command in <productname>PostgreSQL</productname> has options to read from or write to the network connection used by <application>libpq</application>. The functions described in this section allow applications to take advantage of this capability by supplying or consuming copied data. PostgreSQLCOPYコマンドでは、libpqが使っているネットワーク接続に対して読み込み、あるいは書き込みを選ぶことができるようになっています。 本節で説明する関数により、アプリケーションはコピーするデータの提供やコピーされるデータの使用が可能になるという利点を持ちます。

The overall process is that the application first issues the SQL <command>COPY</command> command via <xref linkend="libpq-PQexec"/> or one of the equivalent functions. The response to this (if there is no error in the command) will be a <structname>PGresult</structname> object bearing a status code of <literal>PGRES_COPY_OUT</literal> or <literal>PGRES_COPY_IN</literal> (depending on the specified copy direction). The application should then use the functions of this section to receive or transmit data rows. When the data transfer is complete, another <structname>PGresult</structname> object is returned to indicate success or failure of the transfer. Its status will be <literal>PGRES_COMMAND_OK</literal> for success or <literal>PGRES_FATAL_ERROR</literal> if some problem was encountered. At this point further SQL commands can be issued via <xref linkend="libpq-PQexec"/>. (It is not possible to execute other SQL commands using the same connection while the <command>COPY</command> operation is in progress.) 全体的な処理として、アプリケーションはまずPQexecもしくは同等な関数経由でCOPY SQLコマンドを発行します。 (コマンドでエラーが発生しなければ)この応答は、(指定したコピーの方向に応じて)PGRES_COPY_OUTもしくはPGRES_COPY_INという状態コードを持ったPGresultになります。 その後、アプリケーションは本節の関数を使用して、行データを受信、もしくは、送信しなければなりません。 データの転送が完了した時、転送に成功したか失敗したかを示す別のPGresultオブジェクトが返されます。 その状態は、成功時にはPGRES_COMMAND_OKになり、何らかの問題が起きていた時には PGRES_FATAL_ERRORになります。 この時点で、別のSQLコマンドをPQexec経由で発行することができます。 (COPY操作の実行中は、同じ接続を使用して他のSQLコマンドを実行することはできません。)

If a <command>COPY</command> command is issued via <xref linkend="libpq-PQexec"/> in a string that could contain additional commands, the application must continue fetching results via <xref linkend="libpq-PQgetResult"/> after completing the <command>COPY</command> sequence. Only when <xref linkend="libpq-PQgetResult"/> returns <symbol>NULL</symbol> is it certain that the <xref linkend="libpq-PQexec"/> command string is done and it is safe to issue more commands. COPYコマンドが、他にもコマンドを含んだ文字列としてPQexec経由で発行された場合、アプリケーションはCOPY処理を終えた後に、PQgetResult経由で結果の取り出しを続けなければなりません。 PQexecコマンド文字列が完了し、その後のコマンドが安全に発行できることが確実になるのは、PQgetResultNULLを返す時のみです。

The functions of this section should be executed only after obtaining a result status of <literal>PGRES_COPY_OUT</literal> or <literal>PGRES_COPY_IN</literal> from <xref linkend="libpq-PQexec"/> or <xref linkend="libpq-PQgetResult"/>. 本節の関数は、PQexecもしくはPQgetResultからPGRES_COPY_OUTもしくはPGRES_COPY_INという結果状態を得た後のみに実行されなければなりません。

A <structname>PGresult</structname> object bearing one of these status values carries some additional data about the <command>COPY</command> operation that is starting. This additional data is available using functions that are also used in connection with query results: これらの状態値の一つを持つPGresultオブジェクトは、開始したCOPY操作に関する追加データを持ちます。 この追加データは、以下の問い合わせ結果を持つ接続で使用される関数を使用して利用することができます。

PQnfields #

Returns the number of columns (fields) to be copied. コピーされる列(フィールド)数を返します。

PQbinaryTuples #

0 indicates the overall copy format is textual (rows separated by newlines, columns separated by separator characters, etc.). 1 indicates the overall copy format is binary. See <xref linkend="sql-copy"/> for more information. 0は、コピー全体の書式がテキスト(改行で区切られた行、区切り文字で区切られた列など)であることを示します。 1は、コピー全体の書式がバイナリであることを示します。 詳細はCOPYを参照してください。

PQfformat #

Returns the format code (0 for text, 1 for binary) associated with each column of the copy operation. The per-column format codes will always be zero when the overall copy format is textual, but the binary format can support both text and binary columns. (However, as of the current implementation of <command>COPY</command>, only binary columns appear in a binary copy; so the per-column formats always match the overall format at present.) コピー操作対象の列それぞれに関した書式コード(テキストでは0、バイナリでは1)を返します。 コピー全体の書式がテキストの場合は、列単位の書式コードは常にゼロです。 しかし、バイナリ書式はテキスト列もバイナリ列もサポートすることができます。 (しかし、現在のCOPY実装では、バイナリコピーでのみバイナリ列が発生します。 そのため、今の所列単位の書式は常に全体の書式と一致します。)

34.10.1. COPYデータ送信用関数 #

<title>Functions for Sending <command>COPY</command> Data</title>

These functions are used to send data during <literal>COPY FROM STDIN</literal>. They will fail if called when the connection is not in <literal>COPY_IN</literal> state. これらの関数は、COPY FROM STDIN期間にデータを送信するために使用されます。 接続がCOPY_IN状態でない時に呼び出された場合、これらは失敗します。

PQputCopyData #

Sends data to the server during <literal>COPY_IN</literal> state. COPY_IN状態の間、サーバにデータを送信します。

int PQputCopyData(PGconn *conn,
                  const char *buffer,
                  int nbytes);

Transmits the <command>COPY</command> data in the specified <parameter>buffer</parameter>, of length <parameter>nbytes</parameter>, to the server. The result is 1 if the data was queued, zero if it was not queued because of full buffers (this will only happen in nonblocking mode), or -1 if an error occurred. (Use <xref linkend="libpq-PQerrorMessage"/> to retrieve details if the return value is -1. If the value is zero, wait for write-ready and try again.) 指定したbufferにあるCOPYデータをnbytes長分、サーバに送信します。 データがキューに入れられた場合、この結果は1になります。 バッファが一杯でキューに入らなかった場合はゼロになります。 (これは、接続が非ブロックモードの場合にのみ起こります。) エラーが発生した場合は-1になります。 (戻り値が-1の場合、詳細を取り出すためにはPQerrorMessageを使用してください。 戻り値がゼロの場合は書き込み準備が整うまで待ち、再実行してください。)

The application can divide the <command>COPY</command> data stream into buffer loads of any convenient size. Buffer-load boundaries have no semantic significance when sending. The contents of the data stream must match the data format expected by the <command>COPY</command> command; see <xref linkend="sql-copy"/> for details. アプリケーションはCOPYデータストリームを使いやすい大きさのバッファに分けて読み込むことができます。 送信時の読み込みバッファの境界には意味的な重要性はありません。 データストリームの内容は、COPYコマンドで想定しているデータ書式に一致している必要があります。 詳細はCOPYを参照してください。

PQputCopyEnd #

Sends end-of-data indication to the server during <literal>COPY_IN</literal> state. COPY_IN状態の間に、サーバにデータ終了指示を送信します。

int PQputCopyEnd(PGconn *conn,
                 const char *errormsg);

Ends the <literal>COPY_IN</literal> operation successfully if <parameter>errormsg</parameter> is <symbol>NULL</symbol>. If <parameter>errormsg</parameter> is not <symbol>NULL</symbol> then the <command>COPY</command> is forced to fail, with the string pointed to by <parameter>errormsg</parameter> used as the error message. (One should not assume that this exact error message will come back from the server, however, as the server might have already failed the <command>COPY</command> for its own reasons.) errormsgNULLなら、COPY_INを成功として終了させます。 errormsgNULLではないなら、errmsgの指し示す文字列をエラーメッセージとして用いてCOPYを強制的に失敗させます。 (しかし、このエラーメッセージがサーバからそのまま返ってくると仮定すべきではありません。サーバは既に別の原因でCOPYに失敗していた可能性があります。)

The result is 1 if the termination message was sent; or in nonblocking mode, this may only indicate that the termination message was successfully queued. (In nonblocking mode, to be certain that the data has been sent, you should next wait for write-ready and call <xref linkend="libpq-PQflush"/>, repeating until it returns zero.) Zero indicates that the function could not queue the termination message because of full buffers; this will only happen in nonblocking mode. (In this case, wait for write-ready and try the <xref linkend="libpq-PQputCopyEnd"/> call again.) If a hard error occurs, -1 is returned; you can use <xref linkend="libpq-PQerrorMessage"/> to retrieve details. 終端メッセージが送信された場合は結果は1になります。 非ブロックモードでは、終端メッセージがキューに入れられたことしか意味しないかもしれません。 (非ブロックモードでデータが送信されたことを確認するには、次に書き込み準備ができるまで待ち、PQflushを呼ぶことを、それが0を返すまでくり返します。) バッファが一杯で終端メッセージがキューに入れられなかった場合はゼロになります。 これは、接続が非ブロックモードの場合にのみ起こります。 (この場合、書き込み準備ができるまで待ち、再度PQputCopyEndを呼び出してみてください。) ハードエラーが発生した場合は-1になります。 このとき、詳細を取得するためにPQerrorMessageを使用できます。

After successfully calling <xref linkend="libpq-PQputCopyEnd"/>, call <xref linkend="libpq-PQgetResult"/> to obtain the final result status of the <command>COPY</command> command. One can wait for this result to be available in the usual way. Then return to normal operation. PQputCopyEndの呼び出しに成功した後、PQgetResultを呼び出してCOPYコマンドの最終的な結果状態を取り出してください。 通常の方法でこの結果が使用できるようになるまで待機しても構いません。 そして、通常の操作に戻ってください。

34.10.2. COPYデータ受信用関数 #

<title>Functions for Receiving <command>COPY</command> Data</title>

These functions are used to receive data during <literal>COPY TO STDOUT</literal>. They will fail if called when the connection is not in <literal>COPY_OUT</literal> state. これらの関数はCOPY TO STDOUT時にデータを受信するために使用されます。 COPY_OUT状態以外の接続で呼び出すと、失敗します。

PQgetCopyData #

Receives data from the server during <literal>COPY_OUT</literal> state. COPY_OUT状態時にサーバからデータを受信します。

int PQgetCopyData(PGconn *conn,
                  char **buffer,
                  int async);

Attempts to obtain another row of data from the server during a <command>COPY</command>. Data is always returned one data row at a time; if only a partial row is available, it is not returned. Successful return of a data row involves allocating a chunk of memory to hold the data. The <parameter>buffer</parameter> parameter must be non-<symbol>NULL</symbol>. <parameter>*buffer</parameter> is set to point to the allocated memory, or to <symbol>NULL</symbol> in cases where no buffer is returned. A non-<symbol>NULL</symbol> result buffer should be freed using <xref linkend="libpq-PQfreemem"/> when no longer needed. COPY期間中、サーバから別の行データの入手を試みます。 常に1度に1つの行データが返されます。 部分的な行のみが利用可能な場合は返されません。 行データの取得に成功することは、そのデータを保持するためのメモリチャンクの割り当てを意味します。 bufferパラメータは非NULLでなければなりません。 *bufferは割り当てられたメモリへのポインタに、バッファが返されなかった場合はNULLに設定されます。 非NULLの結果バッファは、不要になったらPQfreememを使用して解放しなければなりません。

When a row is successfully returned, the return value is the number of data bytes in the row (this will always be greater than zero). The returned string is always null-terminated, though this is probably only useful for textual <command>COPY</command>. A result of zero indicates that the <command>COPY</command> is still in progress, but no row is yet available (this is only possible when <parameter>async</parameter> is true). A result of -1 indicates that the <command>COPY</command> is done. A result of -2 indicates that an error occurred (consult <xref linkend="libpq-PQerrorMessage"/> for the reason). 行の取り込みに成功した時、戻り値は行内のデータのバイト数になります。 (これは常に0より大きくなります。) 返された文字列は常にNULL終端ですが、おそらくテキストCOPYでのみ有用になるでしょう。 ゼロという結果は、COPYが進行中で、行がまだ利用できない状態であることを示します。 (asyncが真の場合にのみ発生することがあります。) -1という結果は、COPYが完了したことを示します。 -2という結果はエラーが発生したことを示します。 (その理由についてはPQerrorMessageを参照してください。)

When <parameter>async</parameter> is true (not zero), <xref linkend="libpq-PQgetCopyData"/> will not block waiting for input; it will return zero if the <command>COPY</command> is still in progress but no complete row is available. (In this case wait for read-ready and then call <xref linkend="libpq-PQconsumeInput"/> before calling <xref linkend="libpq-PQgetCopyData"/> again.) When <parameter>async</parameter> is false (zero), <xref linkend="libpq-PQgetCopyData"/> will block until data is available or the operation completes. asyncが真(非0)の場合、PQgetCopyDataは入力待ちのためのブロックを行いません。 COPY実行中で完全な行を取り出せない場合PQgetCopyDataは0を返します。 (この場合、再試行の前に読み込み準備が整うまで待機してください。 PQconsumeInput を呼び出したかどうかは関係ありません。) asyncが偽(0)の場合、PQgetCopyDataはデータが利用できるようになるまで、もしくは、操作が完了するまでブロックします。

After <xref linkend="libpq-PQgetCopyData"/> returns -1, call <xref linkend="libpq-PQgetResult"/> to obtain the final result status of the <command>COPY</command> command. One can wait for this result to be available in the usual way. Then return to normal operation. PQgetCopyDataが-1を返した後、PQgetResultを呼び出して、COPYコマンドの最終結果状態を取り出してください。 通常の方法で結果が利用できるようになるまで待機しても構いません。 そして、通常の操作に戻ってください。

34.10.3. 廃れたCOPY用関数 #

<title>Obsolete Functions for <command>COPY</command></title>

These functions represent older methods of handling <command>COPY</command>. Although they still work, they are deprecated due to poor error handling, inconvenient methods of detecting end-of-data, and lack of support for binary or nonblocking transfers. 以下の関数はCOPYを取扱う、古めの手法を行います。 これらはまだ動作しますが、エラーの取扱いが貧弱であることやデータの終端を検知する方法が不便であることより使用を奨めません。

PQgetline #

Reads a newline-terminated line of characters (transmitted by the server) into a buffer string of size <parameter>length</parameter>. 改行で終端する文字列(サーバから送信されたもの)を長さlengthのバッファ用文字列に読み込みます。

int PQgetline(PGconn *conn,
              char *buffer,
              int length);

This function copies up to <parameter>length</parameter>-1 characters into the buffer and converts the terminating newline into a zero byte. <xref linkend="libpq-PQgetline"/> returns <symbol>EOF</symbol> at the end of input, 0 if the entire line has been read, and 1 if the buffer is full but the terminating newline has not yet been read. この関数はバッファにlength-1個までの文字をコピーし、終端の改行を1バイトのゼロに置き換えます。 PQgetlineは、入力の終端ではEOFを、行全体が読み込まれれば0を返します。 そしてまだ終端の改行が読み込まれていないうちにバッファがいっぱいになってしまった場合は1を返します。

Note that the application must check to see if a new line consists of the two characters <literal>\.</literal>, which indicates that the server has finished sending the results of the <command>COPY</command> command. If the application might receive lines that are more than <parameter>length</parameter>-1 characters long, care is needed to be sure it recognizes the <literal>\.</literal> line correctly (and does not, for example, mistake the end of a long data line for a terminator line). アプリケーションは新しく読み込んだ行が、\.という2文字であるかどうか確認しなければいけません。 この2文字は、COPYコマンドの結果をサーバが送信し終えたことを示すものです。 アプリケーションには、仮にlength-1文字より長い行を受け取るようなことがあっても、間違いなく\.行を認識するような配慮が必要です (また例えば長いデータの行の終端を、最終行と取り違えないようにもしてください)。

PQgetlineAsync #

Reads a row of <command>COPY</command> data (transmitted by the server) into a buffer without blocking. COPYデータ行(サーバから送信されたもの)を、ブロッキングなしでバッファに読み込みます。

int PQgetlineAsync(PGconn *conn,
                   char *buffer,
                   int bufsize);

This function is similar to <xref linkend="libpq-PQgetline"/>, but it can be used by applications that must read <command>COPY</command> data asynchronously, that is, without blocking. Having issued the <command>COPY</command> command and gotten a <literal>PGRES_COPY_OUT</literal> response, the application should call <xref linkend="libpq-PQconsumeInput"/> and <xref linkend="libpq-PQgetlineAsync"/> until the end-of-data signal is detected. PQgetlineと似ていますが、COPYのデータを非同期的に、つまりブロッキングなしで読み出さなければならないアプリケーションで使用することができます。 COPYコマンドを発行し、そしてPGRES_COPY_OUT応答を受け取ったら、アプリケーションはデータ終了の合図を受け取るまでPQconsumeInput PQgetlineAsyncを呼び出します。

Unlike <xref linkend="libpq-PQgetline"/>, this function takes responsibility for detecting end-of-data. PQgetlineと違い、この関数はデータ終了の検出に対して責任を持ちます。

On each call, <xref linkend="libpq-PQgetlineAsync"/> will return data if a complete data row is available in <application>libpq</application>'s input buffer. Otherwise, no data is returned until the rest of the row arrives. The function returns -1 if the end-of-copy-data marker has been recognized, or 0 if no data is available, or a positive number giving the number of bytes of data returned. If -1 is returned, the caller must next call <xref linkend="libpq-PQendcopy"/>, and then return to normal processing. PQgetlineAsyncの個々の呼び出しでは、libpqの入力バッファ内で完全な行データが利用できる場合にデータを返します。 さもなければ、行の残りが届くまでデータは返されません。 この関数は、コピーデータの終端を示す符号を認識すると-1を、また何もデータがなければ0を、そしてデータを返す場合はそのバイト数を正の値で返します。 もし-1が返されたら、呼び出し側は次にPQendcopyを呼び出さなければいけません。 それから通常の処理に戻ります。

The data returned will not extend beyond a data-row boundary. If possible a whole row will be returned at one time. But if the buffer offered by the caller is too small to hold a row sent by the server, then a partial data row will be returned. With textual data this can be detected by testing whether the last returned byte is <literal>\n</literal> or not. (In a binary <command>COPY</command>, actual parsing of the <command>COPY</command> data format will be needed to make the equivalent determination.) The returned string is not null-terminated. (If you want to add a terminating null, be sure to pass a <parameter>bufsize</parameter> one smaller than the room actually available.) 返されるデータは行データの境界を越えて拡張されることはありません。 可能であれば行全体を一度に返します。 しかし呼び出し側が準備したバッファが少なすぎ、サーバから送られてくる行を保持しておくことができない場合には、分割された行データを返します。 テキストデータでは、これは最後の1バイトが\nかどうかを確認すれば検出できます。 (バイナリCOPYの場合に同様の検出を行うためには、実際にCOPYデータの書式を解析しなければなりません。) なお、返される文字列はNULL終端ではありません。 (NULL終端を後から付け加えるのであれば、実際に確保するバッファサイズ-1をbufsizeとして渡すようにしてください。)

PQputline #

Sends a null-terminated string to the server. Returns 0 if OK and <symbol>EOF</symbol> if unable to send the string. サーバにNULL終端の文字列を送信します。 問題なければ0を返します。 文字列の送信ができなかった場合はEOFを返します。

int PQputline(PGconn *conn,
              const char *string);

The <command>COPY</command> data stream sent by a series of calls to <xref linkend="libpq-PQputline"/> has the same format as that returned by <xref linkend="libpq-PQgetlineAsync"/>, except that applications are not obliged to send exactly one data row per <xref linkend="libpq-PQputline"/> call; it is okay to send a partial line or multiple lines per call. PQputlineの呼び出しによって送信されるCOPYデータストリームは、PQgetlineAsyncで返される書式と同じ書式を持ちます。 ただし、アプリケーションは、PQputline毎に正確に1つのデータ行を送信するように強制されていません。 呼び出し毎に行の一部や複数の行を送信しても問題ありません。

注記

Before <productname>PostgreSQL</productname> protocol 3.0, it was necessary for the application to explicitly send the two characters <literal>\.</literal> as a final line to indicate to the server that it had finished sending <command>COPY</command> data. While this still works, it is deprecated and the special meaning of <literal>\.</literal> can be expected to be removed in a future release. It is sufficient to call <xref linkend="libpq-PQendcopy"/> after having sent the actual data. PostgreSQLプロトコル3.0より前では、アプリケーションは、サーバに対してCOPYデータの送信を完了したことを通知するために、最終の行として\.という2文字を明示的に送信する必要がありました。 これはまだ動作します。 しかし、これは廃れたものとして、\.の特殊な意味は将来のリリースで無くなることが予想されます。 実際のデータの送信完了後にPQendcopyを呼び出すことが重要です。

PQputnbytes #

Sends a non-null-terminated string to the server. Returns 0 if OK and <symbol>EOF</symbol> if unable to send the string. NULL終端ではない文字列をサーバに送信します。 問題なければ0を返します。 文字列の送信ができなかった場合はEOFを返します。

int PQputnbytes(PGconn *conn,
                const char *buffer,
                int nbytes);

This is exactly like <xref linkend="libpq-PQputline"/>, except that the data buffer need not be null-terminated since the number of bytes to send is specified directly. Use this procedure when sending binary data. これはまさにPQputlineと同様です。 ただし、直接送信バイト数を指定するため、NULL終端である必要がありません。 バイナリデータを送信する時はこのプロシージャを使用してください。

PQendcopy #

Synchronizes with the server. サーバと同期します。

int PQendcopy(PGconn *conn);

This function waits until the server has finished the copying. It should either be issued when the last string has been sent to the server using <xref linkend="libpq-PQputline"/> or when the last string has been received from the server using <function>PQgetline</function>. It must be issued or the server will get <quote>out of sync</quote> with the client. Upon return from this function, the server is ready to receive the next SQL command. The return value is 0 on successful completion, nonzero otherwise. (Use <xref linkend="libpq-PQerrorMessage"/> to retrieve details if the return value is nonzero.) この関数はサーバがコピーを完了するのを待ちます。 この関数は、PQputlineを使ったサーバへの文字列送信が完了した時点、あるいはPQgetlineを使ったサーバからの文字列受信が完了した時点のいずれでも呼び出さなければなりません。 これを発行しないと、サーバはクライアントとの同期がずれた状態になってしまいます。 この関数から戻った時点で、サーバは次のSQLコマンドを受ける準備が整います。 正常に終了した場合、返り値は0です。 さもなくば、非ゼロです。 (戻り値が非ゼロの場合、PQerrorMessageを使用して詳細を取り出してください。)

When using <xref linkend="libpq-PQgetResult"/>, the application should respond to a <literal>PGRES_COPY_OUT</literal> result by executing <xref linkend="libpq-PQgetline"/> repeatedly, followed by <xref linkend="libpq-PQendcopy"/> after the terminator line is seen. It should then return to the <xref linkend="libpq-PQgetResult"/> loop until <xref linkend="libpq-PQgetResult"/> returns a null pointer. Similarly a <literal>PGRES_COPY_IN</literal> result is processed by a series of <xref linkend="libpq-PQputline"/> calls followed by <xref linkend="libpq-PQendcopy"/>, then return to the <xref linkend="libpq-PQgetResult"/> loop. This arrangement will ensure that a <command>COPY</command> command embedded in a series of <acronym>SQL</acronym> commands will be executed correctly. PQgetResultを使う場合、アプリケーションはPQgetlineを繰り返し呼び出してPGRES_COPY_OUTに応答し、終端行を見つけたら続いてPQendcopyを呼び出さなければなりません。 それから、PQgetResultがNULLポインタを返すまで、PQgetResultのループに戻らなければなりません。 同じように PGRES_COPY_INは連続したPQputlineで処理し、それからPQendcopyで締めくくった後にPQgetResultのループに戻ります。 このようにすることで、一連のSQLコマンド群に含めたCOPYコマンドを確実に、また正しく実行できるはずです。

Older applications are likely to submit a <command>COPY</command> via <xref linkend="libpq-PQexec"/> and assume that the transaction is done after <xref linkend="libpq-PQendcopy"/>. This will work correctly only if the <command>COPY</command> is the only <acronym>SQL</acronym> command in the command string. 比較的古いアプリケーションでは、COPYPQexecで実行し、PQendcopyの実行でトランザクションは完了する、と想定していることがよくあります。 これはコマンド文字列中のSQLCOPYだけであった時にのみ正しく動作します。