Pg - Perl5 extension for PostgreSQL 邦訳


NAME - 名前

Translator:綾乃介 aya@big.or.jp

Pg - Perl5 extension for PostgreSQL
Pg - PostgreSQLのための Perl5 エクステンション(拡張機能)

SYNOPSIS -

Translator:綾乃介 aya@big.or.jp
new style:
新しいスタイル:
use Pg;
$conn = Pg::connectdb("dbname=template1");
$result = $conn->exec("create database pgtest");

old style (depreciated):
古いスタイル (depreciated):
use Pg;
$conn = PQsetdb('', '', '', '', template1);
$result = PQexec($conn, "create database pgtest");
PQclear($result);
PQfinish($conn);

DESCRIPTION - 特徴・説明

Translator:綾乃介 aya@big.or.jp

The Pg module permits you to access all functions of the Libpq interface of PostgreSQL. Libpq is the programmer's interface to PostgreSQL. Pg tries to resemble this interface as close as possible. For examples of how to use this module, look at the file test.pl. For further examples look at the Libpq applications in ../src/test/examples and ../src/test/regress.
Pgモジュールは、PostgreSQLのLibpqすべての関数にアクセスできるようにします。 Libpqは、PostgreSQLへのプログラマーのためのインタフェースです。 Pgはそのインタフェースをできるだけ似ているように設計されています。(多分間違い) このモジュールの使い方の例は、test.plを見てください。それ以上のサンプルは、../src/test/examples と ../src/test/regressにある、Libpqアプリケーションを見てください。


You have the choice between the old C-style and a new, more Perl-ish style. The old style has the benefit, that existing Libpq applications can be ported to perl just by prepending every variable with a '$'. The new style uses class packages and might be more familiar for C++-programmers.
 あなたは、古いC-styleとよりPerlらしい新しいスタイルを選択することができます。 古いスタイル(old style)は、すでにあるLibpqアプリケーションを、すべての 変数に$をつけるだけで移植することができるという利益があります。(多分あってる) 新しいスタイル(new style)は、クラスパッケージを使います。 そして、C++プログラマーにとって(old styleよりも(訳注))、より親しみやすいでしょう。

GUIDELINES - ガイドライン

Translator: 眞崎 hide@fact-real.com
new style

The new style uses blessed references as objects. After creating a new connection or result object, the relevant Libpq functions serve as virtual methods.
new styleはオブジェクトとして"bless"されているリファレンスを扱います。
新たにDBとのコネクションを確立したり、リザルトオブジェクトを生成した後、関連するLibpq関数群は仮想メソッドとして提供されます。

One benefit of the new style: you do not have to care about freeing the connection- and result-structures. Perl calls the destructor whenever the last reference to an object goes away.
new styleの利点: コネクションや、リザルト構造を開放するのに気を使わなくてよいということ。つまり、new styleでは、最後のリファレンスがなくなった時点で、デストラクタが働き(訳注:、自動的に接続を切断し)ます。

The method fetchrow can be used to fetch the next row from the server: while (@row = $result->fetchrow).
fetchrowメソッドはサーバから一行づつ順にフェッチするのに使われます。
使用例:while (@row = $result->fetchrow)

Columnswhich have NULL as value will be set to undef.
値がNULLであるカラムはundefがセットされます。

old style

All functions and constants are imported into the calling constants start with 'PGRES_' (e.g. PGRES_CONNECTION_OK).
すべての関数と定数は'PGRES_'で始まる呼出し定数にインポートされます。(例:PGRES_CONNECTION_OK)

There are two functions, which allocate memory, that has to be freed by the user:
二つのメモリ割り当て関数(PQsedtb, PQexec)はユーザによって明示的な 開放がなされなければなりません。PQsetdbはPQfinishによって、PQexecは PQclearによってそれぞれ開放されます。



Pg.pm contains one convenience function: doQuery. It fills a two-dimensional array with the result of your query.
Pg.pmモジュールはdoQueryという便利な関数を含んでいます。これによって、 クエリーに対する結果を2次元配列によって取り扱うことが出来ます。


       Usage:

           Pg::doQuery($conn, "select attr1, attr2 from tbl", \@ary);

           for $i ( 0 .. $#ary ) {
               for $j ( 0 .. $#{$ary[$i]} ) {
                   print "$ary[$i][$j]\t";
               }
    
               print "\n";
           }

       Notice the inner loop !
       内部ループに注目!

CAVEATS - 注意

Translator:門脇 gate@blue.b-city.net

There are few exceptions, where the perl-functions differs from the C-counterpart: PQprint, PQnotifies and PQconndefaults. These functions deal with structures, which have been implemented in perl using lists or hash.
Perlの関数が対応するCの関数と異なるものが少しだけあります。 PQprint、PQnotifies、PQconndefaultsです。 これらの関数はCでは構造体を扱っていますが、Perlではリストやハッシュを 使って実装されています。

FUNCTIONS - 関数

Translator: 眞崎 hide@fact-real.com

The functions have been divided into three sections:
Connection, Result, Large Objects. For details please read the libpq manpage.
 この「関数」の章は3つのセクションに区切られています。
 「接続」、「結果」、「ラージオブジェクト」です。詳細についてはlibpqのmanページを見てください。

1. Connection
Translator: 眞崎 hide@fact-real.com

With these functions you can establish and close a connection to a database. In Libpq a connection is represented by a structure called PGconn.
これらの関数を使うことで、データベースに接続したり、接続を切ったりできます。
libpqでは、データベースとの接続は「PGconn」という名前の構造体で表されます。


When opening a connection a given database name is always converted to lower-case, unless it is surrounded by double quotes. All unspecified parameters are replaced by environment variables or by hard coded defaults:
データベースに接続するとき、ダブルクォーテーションで囲まない限り、 指定したデータベースの名前は全て小文字に変換されます。 接続時にパラメーターが明示されない場合は環境変数や、 ハードコードされたデフォルト値が使われます。

パラメータ環境変数デフォルト値
host PGHOST localhost
port PGPORT 5432
options PGOPTIONS ""
tty PGTTY ""
dbname PGDATABASE 現在のユーザー名
user PGUSER 現在のユーザー名
password PGPASSWORD ""

Using appropriate methods you can access almost all fields of the returned PGconn structure.
適切な関数を使うことで、PGconn構造体に含まれるほぼ全てのデータにアクセスできます。

$conn = Pg::setdbLogin($pghost, $pgport, $pgoptions, $pgtty, $dbname, $login, $pwd)

Opens a new connection to the backend. The connection identifier $conn ( a pointer to the PGconn structure ) must be used in subsequent commands for unique identification. Before using $conn you should call $conn->status to ensure, that the connection was properly made.
バックエンドに対して新規に接続します。$conn(PGconn構造体に対するポインター) をバックエンドに対する接続のIDとして、その後の関数で使用します。
$connを実際に使う前に $conn->status を呼び出して、接続が正常かどうか確認する必要があります。


$conn = Pg::setdb($pghost, $pgport, $pgoptions, $pgtty, $dbname)

The method setdb should be used when username/password authentication is not needed.
関数setdbはユーザー名/パスワードによる認証が必要ない時に使ってください。

$conn = Pg::connectdb("option1=value option2=value ...")

Opens a new connection to the backend using connection
information in a string. Possible options are: host, port,
options, tty, dbname, user, password. The connection
identifier $conn (a pointer to the PGconn structure) must
be used in subsequent commands for unique identification.
Before using $conn you should call $conn->status to
ensure, that the connection was properly made.
文字列でパラメーターを指定してバックエンドに接続します。有効なパラメーターは host、port、options、tty、dbname、user、passwordです。$conn(PGconn構造体に対するポインター) をバックエンドに対する接続のIDとして、その後の関数で使用します。 $connを実際に使う前に $conn->status を呼び出して、接続が正常かどうか確認する必要があります。

例)
  $Option_ref = Pg::conndefaults();
  while(($key, $val) = each %$Option_ref){
    print "$key, $val\n";
  }

Returns a reference to a hash containing as keys all
possible options for connectdb(). The values are the
current defaults. This function differs from his
C-counterpart, which returns the complete conninfoOption
structure.
connectdb()に渡すことのできるオプションをキーとして持つハッシュへの参照を返します。 ハッシュの値は現在のデフォルトの値です。この関数は対応するCの関数と異なります。 (Cの関数ではconninfoOption構造体を返します。)

PQfinish($conn)

Old style only ! Closes the connection to the backend and
frees the connection data structure.
古い方の形式のみです! バックエンドとの接続を解除し、接続を表す構造体を解放します。

$conn->reset

Resets the communication port with the backend and tries to establish a new connection.
バックエンドに接続しているポートを一度切断して、再び新規の接続を試みます。

$ret = $conn->requestCancel

Abandon processing of the current query. Regardless of
the return value of requestCancel, the application must
continue with the normal result-reading sequence using
getResult. If the current query is part of a transaction,
cancellation will abort the whole transaction.
現在の処理を中断します。requestCancelの返り値に関わらず、アプリケーションは getResultを使った通常の結果処理を行わなければいけません。
もし、現在の処理がトランザクションの途中だった場合は、トランザクション 全体がキャンセルされます。


$dbname = $conn->db

Returns the database name of the connection.
接続しているデータベース名を返します。

$pguser = $conn->user

Returns the Postgres user name of the connection.
接続しているPostgreSQLユーザー名を返します。

$pguser = $conn->pass

Returns the Postgres password of the connection.
接続しているPostgreSQLパスワードを返します。

$pghost = $conn->host

Returns the host name of the connection.
接続しているホスト名を返します。

$pgport = $conn->port

Returns the port of the connection.
接続しているポート番号を返します。

$pgtty = $conn->tty

Returns the tty of the connection.
接続しているtty(端末)を返します。

$pgoptions = $conn->options

Returns the options used in the connection.
接続で使われているオプションを返します。

$status = $conn->status

Returns the status of the connection. For comparing the status you may use the following constants:
接続の状態を返します。状態を見るには、返り値を以下の定数と比較します。

- PGRES_CONNECTION_OK
- PGRES_CONNECTION_BAD
$errorMessage = $conn->errorMessage

Returns the last error message associated with this connection.
この接続における最後のエラーメッセージを返します。

$fd = $conn->socket

connection socket. A result of -1 indicates that no backend connection is currently open.
バックエンドとの接続に使われているソケットのファイルディスクリプター番号を取得します。 返り値が -1 の時はバックエンドと接続されていないことを表しています。

$pid = $conn->backendPID

Returns the process-id of the corresponding backend proceess.
接続しているバックエンドのプロセス番号を返します。

$conn->trace(debug_port)

Messages passed between frontend and backend are echoed to the debug_port file stream.
フロントエンドとバックエンドの間でやりとりされるメッセージを debug_port で表されるファイルストリームに書き込みます。

$conn->untrace

Disables tracing.
traceを中止します。

$result = $conn->exec($query)

Submits a query to the backend. The return value is a pointer to the PGresult structure, which contains the complete query-result returned by the backend. In case of failure, the pointer points to an empty structure. In this, the perl implementation differs from the C-implementation. Using the old style, even the empty structure has to be freed using PQfree. Before using $result you should call resultStatus to ensure, that the query was properly executed.
クエリー(PostgreSQLが解釈して実行できるコマンド)$query を バックエンドに送って実行します。返り値はPGresult構造体へのポインターであり、 バックエンドから返された結果を全て持っています。失敗したときは返り値のポインターは 空の構造体を指しています。この点でPerlの実装はCの実装と異なります。 古い方の形式では空の構造体であってもPQfreeを使って解放しなければなりません。 実際に $result を使う前に resultStatus を呼び出してコマンドの実行が正常に行われたことを 確認する必要があります。

($table, $pid) = $conn->notifies

Checks for asynchronous notifications. This functions differs from the C-counterpart which returns a pointer to a new allocated structure, whereas the perl implementation returns a list. $table is the table which has been listened to and $pid is the process id of the backend.
フロントエンドからバックエンドの情報を得るのに使います。 Cの対応する関数では新しく確保された構造体へのポインターを返すのに対し、 Perlではリストを返します。 $table は問い合わせたテーブルを表し、$pid は バックエンドのプロセスIDを表します。

$ret = $conn->sendQuery($string, $query)

Submit a query to Postgres without waiting for the result(s). After successfully calling PQsendQuery, call PQgetResult one or more times to obtain the query results. PQsendQuery may not be called again until getResult has returned NULL, indicating that the query is done. PostgreSQLバックエンドに対してクエリーを発行しますが、結果が帰ってくるのを待ちません。 sendQuery を実行した後に、その結果を得るには getResult 関数を1回以上呼び出します。 getResult が NULL を返すのはコマンドの実行が終了したことを表すので、それまでは さらに別の sendQuery を呼び出してはいけません。

$result = $conn->getResult

Wait for the next result from a prior PQsendQuery, and return it. NULL is returned when the query is complete and there will be no more results. getResult will block only if a query is active and the necessary response data has not yet been read by PQconsumeInput.
前に呼び出された sendQuery の結果が帰ってくるのを待ち、その結果を返します。 sendQuery によるコマンドが完了して、これ以上返す結果がないときは NULL を返します。 getResultはコマンドが実行中で、consumeInput による必要なデータ読み出しが完了していない 時しかアプリケーションの実行を中断しません。

Returns TRUE if a query is busy, that is, PQgetResult would block waiting for input. A FALSE return indicates that PQgetResult can be called with assurance of not blocking.
コマンドが実行中の時は TRUE を返します。この時はgetResultは入力を待って アプリケーションの実行を中断します。FALSE が返ってきた場合は getResult によってアプリケーションの実行を中断することなく結果を 得られることが保証されます。

$result = $conn->consumeInput

If input is available from the backend, consume it. After calling consumeInput, the application may check isBusy and/or notifies to see if their state has changed.
バックエンドからの入力が利用できるときはそれを使用します。 consumeInput を呼び出した後で、アプリケーションは isBusy と notifies の 片方または両方を呼び出して状態が変わったかどうかを調べることができます。

$ret = $conn->getline($string, $length)

Reads a string up to $length - 1 characters from the backend. getline returns EOF at EOF, 0 if the entire line has been read, and 1 if the buffer is full. If a line consists of the two characters "\." the backend has finished sending the results of the copy command.
バックエンドから文字列を最大 ($length-1) 文字(訳者注:バイト?)読み込みます。 getline は EOF に達したときは EOF を、全ての行がすでに読み込まれているときは 0 を、 バッファーがいっぱいになったときは 1 を返します。一行が「\.」の2文字の時は これでバックエンドから送られる結果が終わりであることを表します。

$ret = $conn->putline($string)

Sends a string to the backend. The application must explicitly send the two characters "\." to indicate to the backend that it has finished sending its data.
バックエンドに文字列 $string を送ります。アプリケーションはバックエンドに これ以上送るデータがないということを示すために「\.」の2文字を 明示的に送る必要があります。

$ret = $conn->getlineAsync($buffer, $bufsize)

Non-blocking version of getline. It reads up to $bufsize characters from the backend. getlineAsync returns -1 if the end-of-copy-marker has been recognized, 0 if no data is avilable, and >0 the number of bytes returned.
getline のアプリケーション実行を中断しない版です。この関数はバックエンドから 最大 $bufsize 文字(訳者注:バイト?)を $buffer に読み込みます。
getlineAsync は「読み込み終わりの印」が見つかったときは -1 を、 読み込むデータがないときは 0 を、データを読み込んだときは読み込んだバイト数を (この時は当然正の値を)返します。


$ret = $conn->putnbytes($buffer, $nbytes)

Sends n bytes to the backend. Returns 0 if OK, EOF if not.
バックエンドに $nbytes バイトのデータを $buffer から送ります。 成功したときは 0 を、そうでないときは EOF を返します。

$ret = $conn->endcopy

This function waits until the backend has finished the copy. It should either be issued when the last string has been sent to the backend using putline or when the last string has been received from the backend using getline. endcopy returns 0 on success, 1 on failure.

この関数はバックエンドとの間でデータのやりとりが終わるまで待ちます。 putline を使ってバックエンドに最後のデータを送った時や、getline を使って バックエンドから最後のデータを受け取った時には endcopy を呼び出すべきです。 成功したときは 0 を、失敗したときは 1 を返します。

$result = $conn->makeEmptyPGresult($status);

Returns a newly allocated, initialized result with given status.
$status で表された状態において新規に確保されて初期化された、結果を表す構造体を返します。

       2. Result
Translator: 綾乃介 aya@big.or.jp
With these functions you can send commands to a database and investigate the results. In Libpq the result of a command is represented by a structure called PGresult. Using the appropriate methods you can access almost all fields of this structure. $result_status = $result->resultStatus Returns the status of the result. For comparing the status you may use one of the following constants depending upon the command executed: 結果のステータス(状態)を返します。コマンドの実行結果は、次の定数と比較をしてください。 ステータス一覧 - PGRES_EMPTY_QUERY 空の問い合わせ? - PGRES_COMMAND_OK 問い合わせはコマンドでした - PGRES_TUPLES_OK 問い合わせは成功して結果セット0個以上 - PGRES_COPY_OUT 入力からコピー開始 - PGRES_COPY_IN 出力へコピー開始 - PGRES_BAD_RESPONSE 予期せぬ応答 - PGRES_NONFATAL_ERROR 致命的でないエラー? - PGRES_FATAL_ERROR 致命的なエラー Use the functions below to access the contents of the PGresult structure. PGresult構造体の要素にアクセスするには、以下の関数を利用します。 $ntuples = $result->ntuples Returns the number of tuples in the query result. 問い合わせ結果(結果セット)のタプル数(行数)を返す。(行番号は先頭行はゼロである) $nfields = $result->nfields Returns the number of fields in the query result. 問い合わせ結果のカラム数(列数)を返します。 $ret = $result->binaryTuples Returns 1 if the tuples in the query result are bianry. 問い合わせ結果がバイナリであれば、1を返します。 $fname = $result->fname($field_num) Returns the field name associated with the given field number. $field_numで指定したカラムのフィールド名を返します。(意訳) $fnumber = $result->fnumber($field_name) Returns the field number associated with the given field name. $field_nameで指定したカラムのフィールド番号を返します。 $ftype = $result->ftype($field_num) Returns the oid of the type of the given field number. $field_numで指定されたカラムのデータ型のoidを返します。 ただし、oidは環境依存であるため、通常は使わないほうがよい。 $fsize = $result->fsize($field_num) number. It returns -1 if the field has a variable length. $field_numで指定したカラムのサイズを返します。(意訳) -1であれば、可変長のフィールドである。 $fmod = $result->fmod($field_num) Returns the type-specific modification data of the field associated with the given field index. Field indices start at 0. $cmdStatus = $result->cmdStatus Returns the command status of the last query command. In case of DELETE it returns also the number of deleted tuples. In case of INSERT it returns also the OID of the inserted tuple followed by 1 (the number of affected tuples). 最後の問い合わせコマンドのコマンドステータスを返します。 DELETEの場合には、削除したタプル数も帰ります。 INSERTの場合には、影響を受けたタプル数 $oid = $result->oidStatus In case the last query was an INSERT command it returns the oid of the inserted tuple. $oid = $result->cmdTuples In case the last query was an INSERT or DELETE command it returns the number of affected tuples. 最後に実行したINSERTもしくはDELETEコマンドのクエリーが、影響を及ぼしたタプル数を返します。 $value = $result->getvalue($tup_num, $field_num) Returns the value of the given tuple and field. This is a null-terminated ASCII string. Binary cursors will not work. 指定されたタプルとフィールドの値を返します。これは、nullで終わるアスキー文字列です。... $length = $result->getlength($tup_num, $field_num) Returns the length of the value for a given tuple and field. 指定されたタプルとフィールドの長さを返します。 $null_status = $result->getisnull($tup_num, $field_num) Returns the NULL status for a given tuple and field. 指定されたタプルとフィールドがNULLであるかどうか返します。 PQclear($result) Old style only ! Frees all memory of the given result. $res->fetchrow New style only ! Fetches the next row from the server and returns NULL if all rows have been processed. Columns which have NULL as value will be set to undef. 新しいスタイルのみです! $result->print($fout, $header, $align, $standard, $html3, $expanded, $pager, $fieldSep, $tableOpt, $caption, ...) function differs from the C-counterpart. The struct PQprintOpt has been implemented with a list. This list is of variable length, in order to care for the character array fieldName in PQprintOpt. The arguments $header, $align, $standard, $html3, $expanded, $pager are boolean flags. The arguments $fieldSep, $tableOpt, $caption are strings. You may append additional strings, which will be taken as replacement for the field names. $result->displayTuples($fp, $fillAlign, $fieldSep, $printHeader, qiet) Kept for backward compatibility. Use print. $result->printTuples($fout, $printAttName, $terseOutput, $width) Kept for backward compatibility. Use print. 3. Large Objects
Translator:門脇 gate@blue.b-city.net
These functions provide file-oriented access to user data. The large object interface is modeled after the Unix file system interface with analogies of open, close, read, write, lseek, tell. In order to get a consistent naming, all function names have been prepended with 'PQ' (old style only). $lobj_fd = $conn->lo_open($lobjId, $mode) Opens an existing large object and returns an object id. For the mode bits see lo_create. Returns -1 upon failure. $ret = $conn->lo_close($lobj_fd) Closes an existing large object. Returns 0 upon success and -1 upon failure. $nbytes = $conn->lo_read($lobj_fd, $buf, $len) Reads $len bytes into $buf from large object $lobj_fd. Returns the number of bytes read and -1 upon failure. $nbytes = $conn->lo_write($lobj_fd, $buf, $len) Writes $len bytes of $buf into the large object $lobj_fd. Returns the number of bytes written and -1 upon failure. $ret = $conn->lo_lseek($lobj_fd, $offset, $whence) Change the current read or write location on the large object $obj_id. Currently $whence can only be 0 (L_SET). $lobjId = $conn->lo_creat($mode) different attributes of the new object. Use the following constants: - PGRES_INV_SMGRMASK - PGRES_INV_ARCHIVE - PGRES_INV_WRITE - PGRES_INV_READ Upon failure it returns PGRES_InvalidOid. $location = $conn->lo_tell($lobj_fd) Returns the current read or write location on the large object $lobj_fd. $ret = $conn->lo_unlink($lobjId) Deletes a large object. Returns -1 upon failure. $lobjId = $conn->lo_import($filename) Imports a Unix file as large object and returns the object id of the new object. $ret = $conn->lo_export($lobjId, $filename) Exports a large object into a Unix file. Returns -1 upon failure, 1 otherwise.

AUTHOR - 作者

           Edmund Mergl <E.Mergl@bawue.de>

SEE ALSO - 参考

the libpq manpage, the large_objects manpage
libpq の mabpage, large_objects の manpage


Man(1) output converted with man2html