MysqliConnection.php 7.03 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
        set_error_handler(function () {});
69

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

73
            throw new MysqliException($this->_conn->connect_error, @$this->_conn->sqlstate ?: 'HY000', $this->_conn->connect_errno);
74
        }
75

76
        restore_error_handler();
77

78
        if (isset($params['charset'])) {
79 80 81 82
            $this->_conn->set_charset($params['charset']);
        }
    }

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

95 96 97 98 99 100 101
    /**
     * {@inheritdoc}
     */
    public function getServerVersion()
    {
        $majorVersion = floor($this->_conn->server_version / 10000);
        $minorVersion = floor(($this->_conn->server_version - $majorVersion * 10000) / 100);
102
        $patchVersion = floor($this->_conn->server_version - $majorVersion * 10000 - $minorVersion * 100);
103 104 105 106 107 108 109 110 111 112 113 114

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

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

115 116 117
    /**
     * {@inheritdoc}
     */
118 119 120 121 122
    public function prepare($prepareString)
    {
        return new MysqliStatement($this->_conn, $prepareString);
    }

123 124 125
    /**
     * {@inheritdoc}
     */
126 127 128 129 130 131
    public function query()
    {
        $args = func_get_args();
        $sql = $args[0];
        $stmt = $this->prepare($sql);
        $stmt->execute();
132

133 134 135
        return $stmt;
    }

136 137 138
    /**
     * {@inheritdoc}
     */
139 140 141 142 143
    public function quote($input, $type=\PDO::PARAM_STR)
    {
        return "'". $this->_conn->escape_string($input) ."'";
    }

144 145 146
    /**
     * {@inheritdoc}
     */
147 148
    public function exec($statement)
    {
149 150 151 152
        if (false === $this->_conn->query($statement)) {
            throw new MysqliException($this->_conn->error, $this->_conn->sqlstate, $this->_conn->errno);
        }

153 154 155
        return $this->_conn->affected_rows;
    }

156 157 158
    /**
     * {@inheritdoc}
     */
159 160 161 162 163
    public function lastInsertId($name = null)
    {
        return $this->_conn->insert_id;
    }

164 165 166
    /**
     * {@inheritdoc}
     */
167 168 169
    public function beginTransaction()
    {
        $this->_conn->query('START TRANSACTION');
170

171 172 173
        return true;
    }

174 175 176
    /**
     * {@inheritdoc}
     */
177 178 179 180 181
    public function commit()
    {
        return $this->_conn->commit();
    }

182 183 184
    /**
     * {@inheritdoc}non-PHPdoc)
     */
185 186 187 188 189
    public function rollBack()
    {
        return $this->_conn->rollback();
    }

190 191 192
    /**
     * {@inheritdoc}
     */
193 194 195 196 197
    public function errorCode()
    {
        return $this->_conn->errno;
    }

198 199 200
    /**
     * {@inheritdoc}
     */
201 202 203 204
    public function errorInfo()
    {
        return $this->_conn->error;
    }
205 206 207 208 209 210 211 212 213

    /**
     * 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.
     */
214
    private function setDriverOptions(array $driverOptions = array())
215
    {
216 217 218 219 220 221 222 223
        $supportedDriverOptions = array(
            \MYSQLI_OPT_CONNECT_TIMEOUT,
            \MYSQLI_OPT_LOCAL_INFILE,
            \MYSQLI_INIT_COMMAND,
            \MYSQLI_READ_DEFAULT_FILE,
            \MYSQLI_READ_DEFAULT_GROUP,
        );

224
        if (defined('MYSQLI_SERVER_PUBLIC_KEY')) {
225 226
            $supportedDriverOptions[] = \MYSQLI_SERVER_PUBLIC_KEY;
        }
227

228
        $exceptionMsg = "%s option '%s' with value '%s'";
229 230 231

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

232
            if ($option === static::OPTION_FLAGS) {
233 234 235
                continue;
            }

236
            if (!in_array($option, $supportedDriverOptions, true)) {
237 238 239 240 241
                throw new MysqliException(
                    sprintf($exceptionMsg, 'Unsupported', $option, $value)
                );
            }

242 243
            if (@mysqli_options($this->_conn, $option, $value)) {
                continue;
244
            }
245 246 247 248 249 250

            $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,
251 252
                $this->_conn->sqlstate,
                $this->_conn->errno
253
            );
254 255
        }
    }
256 257 258 259 260 261 262 263 264 265

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