dshafik / php7-mysql-shim

A shim for ext/mysql in PHP 7+
MIT License
392 stars 101 forks source link

mysql_connect() is pooling non persistent connections. #111

Open jkbzh opened 1 year ago

jkbzh commented 1 year ago

Hello,

Maybe I misunderstood something in the code but it seems the shim is managing a connection pool for non-persistent connections. For persistent connections, it relays on the mysqli extension.

Is this to reproduce behavior from the deprecated mysql extension? If not, why is the shim caching non persistent connections? Would it be unadvisable to switch off this behavior?

From the mysqli doc with respect to persistent connections:

The mysqli extension supports persistent database connections, which are a special kind of pooled connections. By default, every database connection opened by a script is either explicitly closed by the user during runtime or released automatically at the end of the script. A persistent connection is not. Instead it is put into a pool for later reuse, if a connection to the same server using the same username, password, socket, port and default database is opened. Reuse saves connection overhead.

In the shim , for non-persistent connections, mysql_connect() is looking up in a pool if the connection already exists using a hash of the connection characteristics. If it exists, it increases a reference counter and returns the existing connection (lines 66-76), thus making a connection pool:

https://github.com/dshafik/php7-mysql-shim/blob/98f835008ed931df507e86424a770e32d6b18ecb/lib/mysql.php#L66-L76

Further down in mysql_connect(), the hash is always associated with the connection:

https://github.com/dshafik/php7-mysql-shim/blob/98f835008ed931df507e86424a770e32d6b18ecb/lib/mysql.php#L90-L91 https://github.com/dshafik/php7-mysql-shim/blob/98f835008ed931df507e86424a770e32d6b18ecb/lib/mysql.php#L118-L119

In mysql_close(), the references to the connection are decreased by one and if the connection has zero references, then it is closed. Again, this is managing a connection pool.

https://github.com/dshafik/php7-mysql-shim/blob/98f835008ed931df507e86424a770e32d6b18ecb/lib/mysql.php#L153-L161

Note that there is a potential error in that code as the there is no check to see if the hash exists. I think it should be factorized as:

            if (isset(MySQL::$connections[$link->hash])) {
                MySQL::$connections[$link->hash]['refcount'] -= 1;
                if (MySQL::$connections[$link->hash]['refcount'] === 0) {
                   $return = mysqli_close($link);
                  unset(MySQL::$connections[$link->hash]);
               } else {
                 $return = true;
              }
           }

Thanks for your consideration.