(PHP 5 >= 5.1.0, PHP 7, PHP 8)
pg_transaction_status — サーバー上で実行中のトランザクションの状態を返す
サーバー上で実行中のトランザクションの状態を返します。
PostgreSQL 7.3 サーバーで autocommit
を off に
設定している場合、pg_transaction_status() は
不正確な値を返します。サーバー側での自動コミット機能は非推奨と
されており、最近のバージョンのサーバーでは存在しません。
PGSQL_TRANSACTION_IDLE
(アイドル状態)、
PGSQL_TRANSACTION_ACTIVE
(コマンドの実行中)、
PGSQL_TRANSACTION_INTRANS
(正常なトランザクション内でアイドル状態)、
あるいは PGSQL_TRANSACTION_INERROR
(失敗したトランザクション内でアイドル状態)
のいずれかを返します。
接続が異常な場合は PGSQL_TRANSACTION_UNKNOWN
を返します。
PGSQL_TRANSACTION_ACTIVE
が返されるのは、クエリを
サーバーに送信した後まだそれが完了していない場合のみです。
バージョン | 説明 |
---|---|
8.1.0 |
connection は、PgSql\Connection クラスのインスタンスを期待するようになりました。
これより前のバージョンでは、resource を期待していました。
|
例1 pg_transaction_status() の例
<?php
$dbconn = pg_connect("dbname=publisher") or die("Could not connect");
$stat = pg_transaction_status($dbconn);
if ($stat === PGSQL_TRANSACTION_UNKNOWN) {
echo 'Connection is bad';
} else if ($stat === PGSQL_TRANSACTION_IDLE) {
echo 'Connection is currently idle';
} else {
echo 'Connection is in a transaction state';
}
?>
After one of the asynchronous functions (pg_send_query(), pg_send_query_params()...) has been used, pg_transaction_status() will always report PGSQL_TRANSACTION_ACTIVE, no matter if a transaction was started or not.
Even after the first call (or all valid calls) to pg_get_result() the transaction status will stay PGSQL_TRANSACTION_ACTIVE, until either
- a synchronous function like pq_query() was used, or
- another call to pg_get_result() was made, which returns false.
Note: calling pg_free_result() does not change anything.
<?php
$conn = pg_connect("dbname=publisher") or die("Could not connect");
$status = pg_transaction_status($conn); // PGSQL_TRANSACTION_IDLE
pg_send_query($conn, 'SELECT 1');
$status = pg_transaction_status($conn); // PGSQL_TRANSACTION_ACTIVE
$res = pg_get_result($conn);
$status = pg_transaction_status($conn); // PGSQL_TRANSACTION_ACTIVE
$res = pg_get_result($conn); // false
$status = pg_transaction_status($conn); // PGSQL_TRANSACTION_IDLE
?>
This function is implemented in C, so there's no way to mimic it in SQL for older versions of PHP. But you can mimic some of the functionality by using a wrapper which keeps track of when you begin and commit/rollback transactions.