I inherited a web application written in PHP that uses PostgresSQL as a database server.
I have no experience whatsoever with PHP and PostgresSQL, I come from a Java / C# background.
I’m studying how it works and while I was profiling it I noticed that the old programmer, during every page request, instantiate a class named Database in which he opens a connection to the database using something like this:
$this->connection = pg_connect($qs, PGSQL_CONNECT_FORCE_NEW)
the profiler tells me this is a very expensive call (the page loads in 2.7 seconds…) and I was wondering if and when the flag PGSQL_CONNECT_FORCE_NEW is actually needed. Since the connection string is always the same I tried to use pg_pconnect instead (or even pg_connect without that flag) and the page loaded in just 741 milliseconds.
Everything seems to work just fine right now but I’m kind of worried this could break the application somewhere, and since I’m not experienced in PHP I would like to know if the practice of using that flags could have a sense in a certain scenario that I need to check. Obviously, there are no unit tests to rely on.
As a side note, do you know good resources about how this pg_(p)connect really works? The official documentation doesnt seem to be deep enough.
Thank you!
Warning: pg_pconnect will maintain one connection for the lifetime of each Apache backend, so don’t be surprised if you end up with lots of connections. If they all end up issuing a query at the same time that’ll clog the database server up.
I’ve never heard of a connection to the database taking 2 seconds though. I can start psql, connect, issue a query and get a response in 0.2s and that’s on my old netbook. Check your networking setup or some such – there’s something odd going on here.