MysqliConnection.php 7.2 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
<?php
/*
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * This software consists of voluntary contributions made by many individuals
Benjamin Eberlei's avatar
Benjamin Eberlei committed
16
 * and is licensed under the MIT license. For more information, see
17 18 19 20 21
 * <http://www.doctrine-project.org>.
 */

namespace Doctrine\DBAL\Driver\Mysqli;

22
use Doctrine\DBAL\Driver\Connection as Connection;
Steve Müller's avatar
Steve Müller committed
23
use Doctrine\DBAL\Driver\PingableConnection;
24
use Doctrine\DBAL\Driver\ServerInfoAwareConnection;
25 26

/**
27
 * @author Kim Hemsø Rasmussen <kimhemsoe@gmail.com>
till's avatar
till committed
28
 * @author Till Klampaeckel <till@php.net>
29
 */
30
class MysqliConnection implements Connection, PingableConnection, ServerInfoAwareConnection
31 32
{
    /**
33
     * Name of the option to set connection flags
34
     */
35
    const OPTION_FLAGS = 'flags';
36 37 38 39 40 41

    /**
     * @var \mysqli
     */
    private $_conn;

Benjamin Morel's avatar
Benjamin Morel committed
42 43 44 45 46 47 48 49
    /**
     * @param array  $params
     * @param string $username
     * @param string $password
     * @param array  $driverOptions
     *
     * @throws \Doctrine\DBAL\Driver\Mysqli\MysqliException
     */
50 51 52
    public function __construct(array $params, $username, $password, array $driverOptions = array())
    {
        $port = isset($params['port']) ? $params['port'] : ini_get('mysqli.default_port');
53 54 55 56 57 58

        // Fallback to default MySQL port if not given.
        if ( ! $port) {
            $port = 3306;
        }

59
        $socket = isset($params['unix_socket']) ? $params['unix_socket'] : ini_get('mysqli.default_socket');
60
        $dbname = isset($params['dbname']) ? $params['dbname'] : null;
61

62
        $flags = isset($driverOptions[static::OPTION_FLAGS]) ? $driverOptions[static::OPTION_FLAGS] : null;
63

64
        $this->_conn = mysqli_init();
65

66 67
        $this->setDriverOptions($driverOptions);

68 69 70
        $previousHandler = set_error_handler(function () {
        });

71
        if ( ! $this->_conn->real_connect($params['host'], $username, $password, $dbname, $port, $socket, $flags)) {
72 73
            set_error_handler($previousHandler);

74 75 76 77 78 79
            $sqlState = 'HY000';
            if (@$this->_conn->sqlstate) {
                $sqlState = $this->_conn->sqlstate;
            }

            throw new MysqliException($this->_conn->connect_error, $sqlState, $this->_conn->connect_errno);
80
        }
81

82 83
        set_error_handler($previousHandler);

84
        if (isset($params['charset'])) {
85 86 87 88
            $this->_conn->set_charset($params['charset']);
        }
    }

89
    /**
Benjamin Morel's avatar
Benjamin Morel committed
90
     * Retrieves mysqli native resource handle.
91
     *
Benjamin Morel's avatar
Benjamin Morel committed
92
     * Could be used if part of your application is not using DBAL.
93
     *
94
     * @return \mysqli
95 96 97 98 99 100
     */
    public function getWrappedResourceHandle()
    {
        return $this->_conn;
    }

101 102 103 104 105 106 107
    /**
     * {@inheritdoc}
     */
    public function getServerVersion()
    {
        $majorVersion = floor($this->_conn->server_version / 10000);
        $minorVersion = floor(($this->_conn->server_version - $majorVersion * 10000) / 100);
108
        $patchVersion = floor($this->_conn->server_version - $majorVersion * 10000 - $minorVersion * 100);
109 110 111 112 113 114 115 116 117 118 119 120

        return $majorVersion . '.' . $minorVersion . '.' . $patchVersion;
    }

    /**
     * {@inheritdoc}
     */
    public function requiresQueryForServerVersion()
    {
        return false;
    }

121 122 123
    /**
     * {@inheritdoc}
     */
124 125 126 127 128
    public function prepare($prepareString)
    {
        return new MysqliStatement($this->_conn, $prepareString);
    }

129 130 131
    /**
     * {@inheritdoc}
     */
132 133 134 135 136 137 138 139 140
    public function query()
    {
        $args = func_get_args();
        $sql = $args[0];
        $stmt = $this->prepare($sql);
        $stmt->execute();
        return $stmt;
    }

141 142 143
    /**
     * {@inheritdoc}
     */
144 145 146 147 148
    public function quote($input, $type=\PDO::PARAM_STR)
    {
        return "'". $this->_conn->escape_string($input) ."'";
    }

149 150 151
    /**
     * {@inheritdoc}
     */
152 153
    public function exec($statement)
    {
154 155 156 157
        if (false === $this->_conn->query($statement)) {
            throw new MysqliException($this->_conn->error, $this->_conn->sqlstate, $this->_conn->errno);
        }

158 159 160
        return $this->_conn->affected_rows;
    }

161 162 163
    /**
     * {@inheritdoc}
     */
164 165 166 167 168
    public function lastInsertId($name = null)
    {
        return $this->_conn->insert_id;
    }

169 170 171
    /**
     * {@inheritdoc}
     */
172 173 174 175 176 177
    public function beginTransaction()
    {
        $this->_conn->query('START TRANSACTION');
        return true;
    }

178 179 180
    /**
     * {@inheritdoc}
     */
181 182 183 184 185
    public function commit()
    {
        return $this->_conn->commit();
    }

186 187 188
    /**
     * {@inheritdoc}non-PHPdoc)
     */
189 190 191 192 193
    public function rollBack()
    {
        return $this->_conn->rollback();
    }

194 195 196
    /**
     * {@inheritdoc}
     */
197 198 199 200 201
    public function errorCode()
    {
        return $this->_conn->errno;
    }

202 203 204
    /**
     * {@inheritdoc}
     */
205 206 207 208
    public function errorInfo()
    {
        return $this->_conn->error;
    }
209 210 211 212 213 214 215 216 217

    /**
     * Apply the driver options to the connection.
     *
     * @param array $driverOptions
     *
     * @throws MysqliException When one of of the options is not supported.
     * @throws MysqliException When applying doesn't work - e.g. due to incorrect value.
     */
218
    private function setDriverOptions(array $driverOptions = array())
219
    {
220 221 222 223 224 225 226 227
        $supportedDriverOptions = array(
            \MYSQLI_OPT_CONNECT_TIMEOUT,
            \MYSQLI_OPT_LOCAL_INFILE,
            \MYSQLI_INIT_COMMAND,
            \MYSQLI_READ_DEFAULT_FILE,
            \MYSQLI_READ_DEFAULT_GROUP,
        );

228
        if (defined('MYSQLI_SERVER_PUBLIC_KEY')) {
229 230
            $supportedDriverOptions[] = \MYSQLI_SERVER_PUBLIC_KEY;
        }
231

232
        $exceptionMsg = "%s option '%s' with value '%s'";
233 234 235

        foreach ($driverOptions as $option => $value) {

236
            if ($option === static::OPTION_FLAGS) {
237 238 239
                continue;
            }

240
            if (!in_array($option, $supportedDriverOptions, true)) {
241 242 243 244 245
                throw new MysqliException(
                    sprintf($exceptionMsg, 'Unsupported', $option, $value)
                );
            }

246 247
            if (@mysqli_options($this->_conn, $option, $value)) {
                continue;
248
            }
249 250 251 252 253 254

            $msg  = sprintf($exceptionMsg, 'Failed to set', $option, $value);
            $msg .= sprintf(', error: %s (%d)', mysqli_error($this->_conn), mysqli_errno($this->_conn));

            throw new MysqliException(
                $msg,
255 256
                $this->_conn->sqlstate,
                $this->_conn->errno
257
            );
258 259
        }
    }
260 261 262 263 264 265 266 267 268 269

    /**
     * Pings the server and re-connects when `mysqli.reconnect = 1`
     *
     * @return bool
     */
    public function ping()
    {
        return $this->_conn->ping();
    }
270
}