CI. PostgreSQL 関数

導入

PostgreSQLデータベースはオープンソースのプロダクツであり、無料で 使用可能できます。Postgresは元々UCB(カリフォルニア大学バークレイ校) コンピュータ・サイエンス学部で開発されたものです。このPostgresは、 現在、いくつかの商用データベースにおいてサポートされつつあるオブジェク トリレーショナルデータベース的概念の多くの先駆けでした。 Postgresは、SQL92/SQL3言語サポート、トランザクションインテグリティ、 拡張可能な型を提供しています。PostgreSQLは、Postgresのオリジナルの バークレイ・コードのオープンソースの子孫にあたります。

要件

PostgreSQLサポートを使用するには、PostgreSQL 6.5以降が必要です。 PostgreSQL 7.0以降ではPostgreSQLモジュールの全ての機能を使用可能 です。PostgreSQLは、マルチバイト文字エンコーディングを含む多くの 文字エンコーディングをサポートしています。現在のバージョン及び PostgreSQLに関するより詳細な情報は、 http://www.postgresql.org/http://techdocs.postgresql.org/ で入手可能です。

インストール手順

PostgreSQLサポートを利用可能とするには、PHPコンパイル時に --with-pgsql[=DIR] を指定することが必要です。 共有オブジェクトモジュールが利用可能な場合、php.iniextension ディレクティブ または dl() 関数によりPostgreSQLモジュール をロードすることが可能です。

実行用の設定

これらの関数の動作は、php.iniの設定により変化します。

表 1. PostgreSQL設定オプション

名前デフォルト変更の可否
pgsql.allow_persistent"1"PHP_INI_SYSTEM
pgsql.max_persistent"-1"PHP_INI_SYSTEM
pgsql.max_links"-1"PHP_INI_SYSTEM
pgsql.auto_reset_persistent"0"PHP_INI_SYSTEM
pgsql.ignore_notice"0"PHP_INI_ALL
pgsql.log_notice"0"PHP_INI_ALL
PHP_INI_* 定数の詳細と定義については、 ini_set()を参照してください。

以下に設定ディレクティブに関す る簡単な説明を示します。

pgsql.allow_persistent boolean

持続的なPostgres接続を可能にするかどうか。

pgsql.max_persistent integer

プロセス毎の持続的Postgres接続の最大数。

pgsql.max_links integer

持続的接続を含むプロセス毎のPostgres接続の最大数。

pgsql.auto_reset_persistent integer

Detect broken persistent links with pg_pconnect(). Needs a little overhead.

pgsql.ignore_notice integer

Whether or not to ignore PostgreSQL backend notices.

pgsql.log_notice integer

Whether or not to log PostgreSQL backends notice messages. The PHP directive pgsql.ignore_notice must be off in order to log notice messages.

使用法およびヒント

警告

通知メッセージを処理するコードにバグがあるため、PHP 4.0.6で PostgreSQLモジュールを使用することは推奨されません。 4.1.0以降を使用してください。

警告

PostgreSQLモジュールの関数名は、現在のコーディング標準に準拠する ために 4.2.0以降変更されます。新しい関数名の多くには、 pg_lo_open()のようにアンダースコアが付きます。 いくつかの関数は、pg_exec()からpg_query()というように、統一を とるために関数名が変更されます。 古い名前も4.2.0とそれに続くいくつかのバージョンで使用可能ですが、 将来的には削除される可能性があります。

表 2. 変更された関数名

古い関数名新しい関数名
pg_exec()pg_query()
pg_getlastoid()pg_last_oid()
pg_cmdtuples()pg_affected_rows()
pg_numrows()pg_num_rows()
pg_numfields()pg_num_fields()
pg_fieldname()pg_field_name()
pg_fieldsize()pg_field_size()
pg_fieldnum()pg_field_num()
pg_fieldprtlen()pg_field_prtlen()
pg_fieldisnull()pg_field_is_null()
pg_freeresult()pg_free_result()
pg_result()pg_fetch_result()
pg_loreadall()pg_lo_read_all()
pg_locreate()pg_lo_create()
pg_lounlink()pg_lo_unlink()
pg_loopen()pg_lo_open()
pg_loclose()pg_lo_close()
pg_loread()pg_lo_read()
pg_lowrite()pg_lo_write()
pg_loimport()pg_lo_import()
pg_loexport()pg_lo_export()

従来のpg_connect()()/pg_pconnect()() 構文は、将来的に非同期接続 機能をサポートするために過去のものとなる可能性があります。 pg_connect()pg_pconnect() では、接続文字列を使用してください。

全ての関数が全ての構築環境でサポートされるわけではありません。サ ポートされる関数は、使用するlibpq(PostgreSQLのCクライアントインター フェイス)のバージョンとlibpqのコンパイル方法に依存します。足りな い関数がある場合、libpqはその関数を必要とする機能をサポートしませ ん。

接続するPostgreSQLサーバーよりも新しいlibpqを使用することも重要で す。使用するlibpqのバージョンがPostgreSQLサーバが期待するよりも古 い場合、問題を生じる可能性があります。

バージョン6.3(1998/3/2)以降、PostgreSQLはUNIXドメインソケットを 使用しています。これらの新しいコネクションの使用例を以下に示す表に 示します。このソケットは/tmp/.s.PGSQL.5432に あります。このオプションはpostmasterに対して'- i'フラグを指定することで有効となります。これは "Unixドメインソケッ ト以外のTCP/IPソケットもlisten する"という意味です。

表 3. postmasterとPHP

postmasterPHPステータス
postmaster &pg_connect("dbname=MyDbName");OK
postmaster -i &pg_connect("dbname=MyDbName");OK
postmaster &pg_connect("host=localhost dbname=MyDbName"); Unable to connect to PostgreSQL server: connectDB() failed: Is the postmaster running and accepting TCP/IP (with -i) connection at 'localhost' on port '5432'? in /path/to/file.php3 on line 20.
postmaster -i &pg_connect("host=localhost dbname=MyDbName");OK

PostgreSQL サーバへの接続は、以下のようにコマンド文字列の中に 値の組を羅列することにより、確立することができます。 $conn = pg_Connect("host=myHost port=myPort tty=myTTY options=myOptions dbname=myDB user=myUser password=myPassword");

以前の構文: $conn = pg_connect ("host", "port", "options", "tty", "dbname") は古い構文であり、推奨されません。

環境変数は、PostgreSQLサーバ/クライアントの動作に影響を与えます。 例えば、PostgreSQLモジュールは、ホスト名が接続文字列で省略された場 合、環境変数PGHOSTを探します。サポートされる環境変数は、バージョン 毎に異なります。詳細は、PostgreSQLプログラマ用マニュアル(libpq - 環境変数)を参照ください。

適切なユーザ用に環境変数が設定されていることを確認してください。 カレントのプロセスで利用可能な環境変数を確認するには、 $_ENV または getenv() を使用してください。

例 1. デフォルトのパラメータを設定する

PGHOST=pgsql.example.com
PGPORT=7890
PGDATABASE=web-system
PGUSER=web-user
PGPASSWORD=secret
PGDATESTYLE=ISO
PGTZ=JST
PGCLIENTENCODING=EUC-JP

export PGHOST PGPORT PGDATABASE PGUSER PGPASSWORD PGDATESTYLE PGTZ PGCLIENTENCODING

定義済みの定数

これらの定数は、この拡張モジュールで定義されており、 この拡張モジュールがPHP内部にコンパイルされているか実行時に動的にロー ドされるかのどちらかの場合のみ使用可能です。

PGSQL_ASSOC (integer)

Passed to pg_fetch_array(). Return an associative array of field names and values.

PGSQL_NUM (integer)

Passed to pg_fetch_array(). Return a numerically indexed array of field numbers and values.

PGSQL_BOTH (integer)

Passed to pg_fetch_array(). Return an array of field values that is both numerically indexed (by field number) and associated (by field name).

PGSQL_CONNECT_FORCE_NEW (integer)

Passed to pg_connect() to force the creation of a new connection, rather then re-using an existing identical connection.

PGSQL_CONNECTION_BAD (integer)

Returned by pg_connection_status() indicating that the database connection is in an invalid state.

PGSQL_CONNECTION_OK (integer)

Returned by pg_connection_status() indicating that the database connection is in a valid state.

PGSQL_SEEK_SET (integer)

Passed to pg_lo_seek(). Seek operation is to begin from the start of the object.

PGSQL_SEEK_CUR (integer)

Passed to pg_lo_seek(). Seek operation is to begin from the current position.

PGSQL_SEEK_END (integer)

Passed to pg_lo_seek(). Seek operation is to begin from the end of the object.

PGSQL_EMPTY_QUERY (integer)

Returned by pg_result_status(). The string sent to the server was empty.

PGSQL_COMMAND_OK (integer)

Returned by pg_result_status(). Successful completion of a command returning no data.

PGSQL_TUPLES_OK (integer)

Returned by pg_result_status(). Successful completion of a command returning data (such as a SELECT or SHOW).

PGSQL_COPY_OUT (integer)

Returned by pg_result_status(). Copy Out (from server) data transfer started.

PGSQL_COPY_IN (integer)

Returned by pg_result_status(). Copy In (to server) data transfer started.

PGSQL_BAD_RESPONSE (integer)

Returned by pg_result_status(). The server's response was not understood.

PGSQL_NONFATAL_ERROR (integer)

Returned by pg_result_status(). A nonfatal error (a notice or warning) occurred.

PGSQL_FATAL_ERROR (integer)

Returned by pg_result_status(). A fatal error occurred.

PGSQL_TRANSACTION_IDLE (integer)

Returned by pg_transaction_status(). Connection is currently idle, not in a transaction.

PGSQL_TRANSACTION_ACTIVE (integer)

Returned by pg_transaction_status(). A command is in progress on the connection. A query has been sent via the connection and not yet completed.

PGSQL_TRANSACTION_INTRANS (integer)

Returned by pg_transaction_status(). The connection is idle, in a transaction block.

PGSQL_TRANSACTION_INERROR (integer)

Returned by pg_transaction_status(). The connection is idle, in a failed transaction block.

PGSQL_TRANSACTION_UNKNOWN (integer)

Returned by pg_transaction_status(). The connection is bad.

PGSQL_DIAG_SEVERITY (integer)

Passed to pg_result_error_field(). The severity; the field contents are ERROR, FATAL, or PANIC (in an error message), or WARNING, NOTICE, DEBUG, INFO, or LOG (in a notice message), or a localized translation of one of these. Always present.

PGSQL_DIAG_SQLSTATE (integer)

Passed to pg_result_error_field(). 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. This field is not localizable, and is always present.

PGSQL_DIAG_MESSAGE_PRIMARY (integer)

Passed to pg_result_error_field(). The primary human-readable error message (typically one line). Always present.

PGSQL_DIAG_MESSAGE_DETAIL (integer)

Passed to pg_result_error_field(). Detail: an optional secondary error message carrying more detail about the problem. May run to multiple lines.

PGSQL_DIAG_MESSAGE_HINT (integer)

Passed to pg_result_error_field(). 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. May run to multiple lines.

PGSQL_DIAG_STATEMENT_POSITION (integer)

Passed to pg_result_error_field(). 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.

PGSQL_DIAG_INTERNAL_POSITION (integer)

Passed to pg_result_error_field(). This is defined the same as the PG_DIAG_STATEMENT_POSITION field, but it is used when the cursor position refers to an internally generated command rather than the one submitted by the client. The PG_DIAG_INTERNAL_QUERY field will always appear when this field appears.

PGSQL_DIAG_INTERNAL_QUERY (integer)

Passed to pg_result_error_field(). The text of a failed internally-generated command. This could be, for example, a SQL query issued by a PL/pgSQL function.

PGSQL_DIAG_CONTEXT (integer)

Passed to pg_result_error_field(). 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.

PGSQL_DIAG_SOURCE_FILE (integer)

Passed to pg_result_error_field(). The file name of the PostgreSQL source-code location where the error was reported.

PGSQL_DIAG_SOURCE_LINE (integer)

Passed to pg_result_error_field(). The line number of the PostgreSQL source-code location where the error was reported.

PGSQL_DIAG_SOURCE_FUNCTION (integer)

Passed to pg_result_error_field(). The name of the PostgreSQL source-code function reporting the error.

PGSQL_ERRORS_TERSE (integer)

Passed to pg_set_error_verbosity(). Specified that returned messages include severity, primary text, and position only; this will normally fit on a single line.

PGSQL_ERRORS_DEFAULT (integer)

Passed to pg_set_error_verbosity(). The default mode produces messages that include the above plus any detail, hint, or context fields (these may span multiple lines).

PGSQL_ERRORS_VERBOSE (integer)

Passed to pg_set_error_verbosity(). The verbose mode includes all available fields.

PGSQL_STATUS_LONG (integer)

Passed to pg_result_status(). Indicates that numerical result code is desired.

PGSQL_STATUS_STRING (integer)

Passed to pg_result_status(). Indicates that textual result command tag is desired.

PGSQL_CONV_IGNORE_DEFAULT (integer)

Passed to pg_convert(). Ignore default values in the table during conversion.

PGSQL_CONV_FORCE_NULL (integer)

Passed to pg_convert(). Use SQL NULL in place of an empty string.

PGSQL_CONV_IGNORE_DEFAULT (integer)

Passed to pg_convert(). Ignore conversion of NULL into SQL NOT NULL columns.

PostgreSQL 7.1.0から、textデータ型の最大サイズは1GBとなっています。 古いPostgreSQLのtextデータ型はブロックサイズ(デフォルトは8KB、最大 32KBをコンパイル時に定義可能)の制限を受けていました。

ラージオブジェクト(lo)インターフェースを使用するには、そのクエリーを トランザクション・ブロックの中に入れてやる必要があります。 トランザクション・ブロックはBEGINで始まり、 そのトランザクションが有効な場合はCOMMITまたは ENDで終わります。トランザクションが失敗した場合、 そのトランザクションはROLLBACKまたは ABORTにより閉じる必要があります。

例 2. ラージオブジェクトの使用例

<?php
   $database
= pg_connect ("dbname=jacarta");
    
pg_exec ($database, "begin");
    
$oid = pg_locreate ($database);
    echo (
"$oid\n");
    
$handle = pg_loopen ($database, $oid, "w");
    echo (
"$handle\n");
    
pg_lowrite ($handle, "large object data");
    
pg_loclose ($handle);
    
pg_exec ($database, "commit");
?>
ラージオブジェクトリソースを閉じる前にPostgreSQLサーバへの接続を 閉じないようにしてください。

目次
pg_affected_rows -- 変更されたレコード(タプル)の数を返す
pg_cancel_query --  非同期クエリを取り消す
pg_client_encoding --  PostgreSQLクライアントのエンコーディングを取得する
pg_close -- PostgreSQL接続を閉じる
pg_connect -- PostgreSQL接続を開く
pg_connection_busy --  接続がビジーかどうか調べる
pg_connection_reset --  接続をリセット(再接続)する
pg_connection_status --  接続ステータスを取得する
pg_convert --  SQL命令として実行可能な形式の連想配列の値に変換する
pg_copy_from --  配列からテーブルをコピーする
pg_copy_to --  配列にテーブルをコピーする
pg_dbname -- データベース名の取得
pg_delete --  レコードを削除する
pg_end_copy -- PostgreSQLバックエンドに同期する
pg_escape_bytea --  bytea型にバイナリをエスケープする
pg_escape_string --  テキスト/文字型用の文字列をエスケープする
pg_execute -- Sends a request to execute a prepared statement with given parameters, and waits for the result.
pg_fetch_all -- 取得されたすべての行を配列として取得
pg_fetch_array -- 行を配列として取得する
pg_fetch_assoc -- 行を配列として取得する
pg_fetch_object -- 行をオブジェクトとして得る
pg_fetch_result -- 結果リソースから値を返す
pg_fetch_row -- 数字をインデックスとする配列として行を得る
pg_field_is_null -- フィールドがNULLかどうか調べる
pg_field_name -- フィールドの名前を返す
pg_field_num -- 指定されたフィールドのフィールド番号を返す
pg_field_prtlen -- 表示される長さを返す
pg_field_size --  指定したフィールドの内部記憶領域におけるサイズを返す
pg_field_type_oid --  Returns the type ID (OID) for the corresponding field number
pg_field_type --  フィールド番号に対応する型名を返す
pg_free_result -- メモリを開放する
pg_get_notify -- データベース接続にpingを行う
pg_get_pid -- データベース接続にpingを行う
pg_get_result --  非同期クエリの結果を取得する
pg_host -- ホスト名を返す
pg_insert --  テーブルに配列を挿入する
pg_last_error -- 特定の接続から直近のエラーメッセージ文字列を取得する
pg_last_notice --  PostgreSQLサーバからの直近の通知メッセージを返す
pg_last_oid -- 直近のオブジェクトIDを返す
pg_lo_close -- ラージオブジェクトをクローズする
pg_lo_create -- ラージオブジェクトを生成する
pg_lo_export -- ラージオブジェクトをファイルにエクスポートする
pg_lo_import -- ファイルからラージオブジェクトをインポートする
pg_lo_open -- ラージオブジェクトをオープンする
pg_lo_read_all --  ラージオブジェクト全体を読み込みブラウザに直接送信する
pg_lo_read -- ラージオブジェクトを読み込む
pg_lo_seek --  ラージオブジェクトの位置をシークする
pg_lo_tell --  ラージオブジェクトのカレントの位置を返す
pg_lo_unlink -- ラージオブジェクトを削除する
pg_lo_write -- ラージオブジェクトを書く
pg_meta_data --  テーブルからメタデータを取得する
pg_num_fields -- フィールド数を返す
pg_num_rows -- 行数を返す
pg_options -- 接続に関連するオプションを取得する
pg_parameter_status -- Looks up a current parameter setting of the server.
pg_pconnect -- 持続的なデータベース接続をオープンする
pg_ping -- データベース接続を調べる
pg_port -- 接続に関連するポート番号を返す
pg_prepare --  Submits a request to create a prepared statement with the given parameters, and waits for completion.
pg_put_line --  NULLで終る文字列をPostgreSQLバックエンドに送信する
pg_query_params -- Submits a command to the server and waits for the result, with the ability to pass parameters separately from the SQL command text.
pg_query -- クエリを実行する
pg_result_error_field -- Returns an individual field of an error report.
pg_result_error --  結果に関連するエラーメッセージを取得する
pg_result_seek -- 結果リソースの内部レコード(行)オフセットを設定する
pg_result_status --  クエリ結果のステータスを取得する
pg_select --  レコードを選択する
pg_send_execute -- Sends a request to execute a prepared statement with given parameters, without waiting for the result(s).
pg_send_prepare -- Sends a request to create a prepared statement with the given parameters, without waiting for completion.
pg_send_query_params -- Submits a command and separate parameters to the server without waiting for the result(s).
pg_send_query --  非同期クエリを送信する
pg_set_client_encoding --  PostgreSQLクライアントのエンコーディングを設定する
pg_set_error_verbosity --  Determines the verbosity of messages returned by pg_last_error() and pg_result_error().
pg_trace -- PostgreSQLサーバーへの接続をトレースする
pg_transaction_status -- Returns the current in-transaction status of the server.
pg_tty -- tty名を返す
pg_unescape_bytea --  bytea型のバイナリをアンエスケープする
pg_untrace --  PostgreSQLサーバーへの接続のトレースを無効にする
pg_update --  テーブルを更新する
pg_version --  Returns an array with client, protocol and server version (when available)