You should not use pg_pconnect - it's broken. It will work but it doesn't really pool, and it's behaviour is unpredictable. It will only make you rise the max_connections parameter in postgresql.conf file until you run out of resources (which will slow your database down).
If you have many concurrent connections to your database, you should use the PostgreSQL connection pooler PgBouncer (developed by the Skype-team). When using pgbouncer, make sure you use pg_connect and NOT pg_pconnect. Also, make sure you close your connections with pg_close.
* PGBouncer homepage:
http://developer.skype.com/SkypeGarage/DbProjects/PgBouncer
* PostgreSQL pooling article by Last.fm:
http://www.last.fm/user/Russ/journal/2008/02/21
/zd_postgres_connection_pools:_pgpool_vs._pgbouncer
pg_pconnect
(PHP 4, PHP 5)
pg_pconnect — Otwiera trwałe połączenie z serwerem PostgreSQL
Opis
pg_pconnect() otwiera trwałe połączenie z serwerem PostgreSQL. Zwraca identyfikator połączenia używany przez inne funkcje PostgreSQL-a.
Ponowne wywołanie funkcji pg_pconnect() z identycznym parametrem łańcuch_połączenia , jak w połączeniu już istniejącym, zwróci identyfikator istniejącego połączenia, chyba, że podasz PGSQL_CONNECT_FORCE_NEW jako parametr typ_połączenia .
Aby zezwolić na używanie stałych połączeń, należy ustawić dyrektywę php.ini pgsql.allow_persistent na "On" (jest to ustawienie domyślne). Maksymalna liczba jednoczesnych trwałych połączeń może być zdefiniowana przez dyrektywę php.ini pgsql.max_persistent (domyślnia wartość to -1 oznacza brak ograniczeń). Maksymalna liczba wszystkich połączeń może być ustawiona przez dyrektywę php.ini pgsql.max_links.
pg_close() nie zamyka trwałych połączeń otwartych przez pg_pconnect().
Parametry
- connection_string
-
Parametr łańcuch_połączenia może zostać pusty w celu użycia domyślnych parametrów, lub może zawierać jedno, lub więcej ustawień oddzielonych spacją. Każde ustawienie ma format klucz = wartość. Spacje po obu stronach znaku równości są opcjonalne. Aby stworzyć wartość pustą, lub zawierającą spacje, otocz ją pojedynczymi znakami cudzysłowia, np. klucz = 'wartość'. Pojedyncze cudzysłowy, oraz backslashe wewnątrz wartości muszą być poprzedzone znakiem ucieczki "\", np., \' oraz \\.
Aktualnie rozpoznawanymi parametrami są: host , hostaddr , port dbname , user , password , connect_timeout , options , tty (ignorowany), sslm requiressl (zdeprecjonowany na korzyść sslmode ), oraz service . Niektóre z tych argumentów są zależne od używanej wersji PostgreSQL.
- connect_type
-
Jeśli podano PGSQL_CONNECT_FORCE_NEW, zostanie stworzone nowe połączenie, nawet gdy łańcuch_połączenia jest identyczny, jak w jakimś istniejącym połączeniu.
Zwracane wartości
Nawiązanie połączenie z serwerem PostgreSQL w przypadku sukcesu, FALSE w razie niepowodzenia.
Przykłady
Przykład #1 Używanie pg_pconnect()
<?php
$polaczenie = pg_pconnect("dbname=mary");
//Połączenie z bazą o nazwie "mary"
$polaczenie2 = pg_pconnect("host=localhost port=5432 dbname=mary");
//Połączenie z bazą o nazwie "mary" na "localhost" portem "5432"
$polaczenie3 = pg_pconnect("host=owca port=5432 dbname=mary user=jagnie password=foo");
//Połączenie z bazą o nazwie "mary" na hoście "owca" z nazwą użytkownika i hasłem
$lancuch_polaczenia = "host=owca port=5432 dbname=test user=jagnie password=bar";
$polaczenie4 = pg_pconnect($lancuch_polaczenia);
//Połączenie z bazą o nazwie "test" na hoście "owca" z nazwą użytkownika i hasłem
?>
Zobacz też:
- pg_connect() - Otwiera tymczasowe połączenie do PostgreSQL-a
- Trwałe połączenia z serwerem baz danych
pg_pconnect
10-Dec-2008 08:54
28-Oct-2007 10:22
<?php
//
// Using pg_pconnect in a class.
//
// Why this? Because the manual says:
//
// If a second call is made to pg_pconnect() with the same
// connection_string as an existing connection, the existing
// connection will be returned unless you pass
// PGSQL_CONNECT_FORCE_NEW as connect_type.
//
// This is not always true.
//
/**
* MyClassA creates a postgresql connection using pg_pconnect
* and stores the resulting resource id to $this->conn
*/
class MyClassA
{
function __construct($connection_string)
{
$this->conn =
pg_pconnect($connection_string)
or die('Wrong CONN_STRING');
}
}
//
// Showing current php.ini settings to be sure
// that persistent connections s are allowed.
// -1 means 'unlimited'
//
echo '<br>pgsql.allow_persistent: ' . ini_get('pgsql.allow_persistent');
echo '<br>pgsql.max_persistent: ' . ini_get('pgsql.max_persistent');
echo '<br>pgsql.max_links: ' . ini_get('pgsql.max_links');
echo '<br><br>';
// setting one custom connection string for all objects
// (modify $connection_string to fit your needs)
$connection_string =
'host=localhost port=5432' .
' dbname=test user=test password=test';
//
// Creating 10 MyClassA objects using the same $connection_string
//
$objArr = Array();
for ($i = 0; $i < 10; $i++)
{
$objArr[] = new MyClassA($connection_string);
}
//
// Human readable result:
//
foreach($objArr as $id => $object)
{
printf(
'%s: Object %s: using db %s<br>',
get_class($object), $id, $object->conn
);
}
/* ------------------------------------------------------------- */
// The result
// pgsql.allow_persistent: 1
// pgsql.max_persistent: -1
// pgsql.max_links: -1
//
// MyClassA: Object 0: using db Resource id #2
// MyClassA: Object 1: using db Resource id #3
// MyClassA: Object 2: using db Resource id #4
// MyClassA: Object 3: using db Resource id #5
// MyClassA: Object 4: using db Resource id #6
// MyClassA: Object 5: using db Resource id #7
// MyClassA: Object 6: using db Resource id #8
// MyClassA: Object 7: using db Resource id #9
// MyClassA: Object 8: using db Resource id #10
// MyClassA: Object 9: using db Resource id #11
//
/* ------------------------------------------------------------- */
//
// Each MyClassA object will use its _own_ database Resource id
//
?>
13-Oct-2007 08:27
As of Aug 2007, some suggestions from the postgresql forums
on pg_pconnect(), faster postgres connections, and connection pooling:
Summary:
http://archives.postgresql.org/pgsql-general/2007-08/msg01406.php
Good details: http://archives.postgresql.org/pgsql-general/2007-08/msg00660.php
Also: http://archives.postgresql.org/pgsql-general/2007-08/msg01489.php
06-Oct-2003 11:05
A contribution to the transaction issue raised by "garrett at bgb dot cc".
In a German book about PostgreSQL in connection with PHP (Cornelia Boenigk, PostgreSQL - Grundlagen, Praxis, Anwendungsentwicklung mit PHP) one can read in chapter 19.3 about persistent connections:
If the page processing aborts and the transaction is not finished yet, the next script using the same persistent connection will be considered as the continuation of the transaction. In particular a lock of a table will persist. The explanation is as follows: After the abort of the script no COMMIT or ROLLBACK was sent to the db server.
The author describes a hint to avoid the scenario above:
You can create a function for resolving transactions and locks erroneously not closed. For invoking the function after execution of a script it has to be registered with the function register_shutdown_function():
http://de2.php.net/manual/en/function.register-shutdown-function.php
30-Jan-2003 01:40
Instead of reducing MaxClients in apache you may try to
reduce pgsql.max_links in php to at least the number of
postmasters. It should work and leave
you with more available httpds for static html pages.
29-Mar-2002 04:03
Be careful when using Apache/PHP dynamic module/PostgreSQL :
in httpd.conf (Apache conf) default MaxClients is 150, whereas default PG's max_connections is 32 which is much fewer than 150. You have to set max_connections to at least MaxClients (and pg's shared_buffers to 2*max_connections at least) to avoid PG's errors with pg_pconnect like : "Sorry, too many clients already connected"
10-Mar-2002 09:56
To setup a high availability server with apache as a static module and postgreSQL, change httpd.conf and set MaxClients to less than max postgreSQL simultaneous connections (like 32 or 64).
This way pg_pconnect will allways return a valid handle under heavy traffic or under a request flow attack without wasting resources and without connection problems.
09-Feb-2002 12:39
If a transaction is in progress when page processing ends, is it aborted before the connection placed bak in the pool? Or is the connection added "as is"?
It would seem that the correct thing to do is to always 'ABORT' before adding to the pool.
As a note, this would be a good time to check and see if the connection is still open before readding it. Thus allowing closed connections to be cleaned up over time, instead of hanging around for ever as they do now.
04-Dec-2000 02:14
For resetting an apache web server and in same time the persistent connections you may use :
./apachectl graceful
10-May-2000 11:12
How to reset persistent connections:
killall -USR1 httpd
30-Mar-2000 01:39
Well, pg_pconnect is ALMOST identical to pg_Connect. The difference is that when you make something nasty with the PSQL server (like reseting it) then pg_pConnect still tryes to use the previous connection. This creates some nice broken_pipe errors (and maybe some more). I do not know that resetting the http server would help it, I think it would. As pg_connect creates a new connection every time (that is why it is \"so slow\") this error does not occurs with it. Really this is not a bug, but perphaps you could do something with it, and it may help some people working with recently changing pg security settings... Good bug hunting...
