MysqliConnection.php 6.46 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 34 35 36
{
    /**
     * @var \mysqli
     */
    private $_conn;

Benjamin Morel's avatar
Benjamin Morel committed
37 38 39 40 41 42 43 44
    /**
     * @param array  $params
     * @param string $username
     * @param string $password
     * @param array  $driverOptions
     *
     * @throws \Doctrine\DBAL\Driver\Mysqli\MysqliException
     */
45 46 47 48 49
    public function __construct(array $params, $username, $password, array $driverOptions = array())
    {
        $port = isset($params['port']) ? $params['port'] : ini_get('mysqli.default_port');
        $socket = isset($params['unix_socket']) ? $params['unix_socket'] : ini_get('mysqli.default_socket');

50
        $this->_conn = mysqli_init();
51

52 53
        $this->setDriverOptions($driverOptions);

54 55 56
        $previousHandler = set_error_handler(function () {
        });

57
        if ( ! $this->_conn->real_connect($params['host'], $username, $password, $params['dbname'], $port, $socket)) {
58 59
            set_error_handler($previousHandler);

60
            throw new MysqliException($this->_conn->connect_error, $this->_conn->sqlstate, $this->_conn->connect_errno);
61
        }
62

63 64
        set_error_handler($previousHandler);

65
        if (isset($params['charset'])) {
66 67 68 69
            $this->_conn->set_charset($params['charset']);
        }
    }

70
    /**
Benjamin Morel's avatar
Benjamin Morel committed
71
     * Retrieves mysqli native resource handle.
72
     *
Benjamin Morel's avatar
Benjamin Morel committed
73
     * Could be used if part of your application is not using DBAL.
74
     *
75
     * @return \mysqli
76 77 78 79 80 81
     */
    public function getWrappedResourceHandle()
    {
        return $this->_conn;
    }

82 83 84 85 86 87 88
    /**
     * {@inheritdoc}
     */
    public function getServerVersion()
    {
        $majorVersion = floor($this->_conn->server_version / 10000);
        $minorVersion = floor(($this->_conn->server_version - $majorVersion * 10000) / 100);
89
        $patchVersion = floor($this->_conn->server_version - $majorVersion * 10000 - $minorVersion * 100);
90 91 92 93 94 95 96 97 98 99 100 101

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

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

102 103 104
    /**
     * {@inheritdoc}
     */
105 106 107 108 109
    public function prepare($prepareString)
    {
        return new MysqliStatement($this->_conn, $prepareString);
    }

110 111 112
    /**
     * {@inheritdoc}
     */
113 114 115 116 117 118 119 120 121
    public function query()
    {
        $args = func_get_args();
        $sql = $args[0];
        $stmt = $this->prepare($sql);
        $stmt->execute();
        return $stmt;
    }

122 123 124
    /**
     * {@inheritdoc}
     */
125 126 127 128 129
    public function quote($input, $type=\PDO::PARAM_STR)
    {
        return "'". $this->_conn->escape_string($input) ."'";
    }

130 131 132
    /**
     * {@inheritdoc}
     */
133 134 135 136 137 138
    public function exec($statement)
    {
        $this->_conn->query($statement);
        return $this->_conn->affected_rows;
    }

139 140 141
    /**
     * {@inheritdoc}
     */
142 143 144 145 146
    public function lastInsertId($name = null)
    {
        return $this->_conn->insert_id;
    }

147 148 149
    /**
     * {@inheritdoc}
     */
150 151 152 153 154 155
    public function beginTransaction()
    {
        $this->_conn->query('START TRANSACTION');
        return true;
    }

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

164 165 166
    /**
     * {@inheritdoc}non-PHPdoc)
     */
167 168 169 170 171
    public function rollBack()
    {
        return $this->_conn->rollback();
    }

172 173 174
    /**
     * {@inheritdoc}
     */
175 176 177 178 179
    public function errorCode()
    {
        return $this->_conn->errno;
    }

180 181 182
    /**
     * {@inheritdoc}
     */
183 184 185 186
    public function errorInfo()
    {
        return $this->_conn->error;
    }
187 188 189 190 191 192 193 194 195

    /**
     * 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.
     */
196
    private function setDriverOptions(array $driverOptions = array())
197
    {
198 199 200 201 202 203 204 205
        $supportedDriverOptions = array(
            \MYSQLI_OPT_CONNECT_TIMEOUT,
            \MYSQLI_OPT_LOCAL_INFILE,
            \MYSQLI_INIT_COMMAND,
            \MYSQLI_READ_DEFAULT_FILE,
            \MYSQLI_READ_DEFAULT_GROUP,
        );

206
        if (defined('MYSQLI_SERVER_PUBLIC_KEY')) {
207 208
            $supportedDriverOptions[] = \MYSQLI_SERVER_PUBLIC_KEY;
        }
209

210
        $exceptionMsg = "%s option '%s' with value '%s'";
211 212 213

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

214
            if (!in_array($option, $supportedDriverOptions, true)) {
215 216 217 218 219
                throw new MysqliException(
                    sprintf($exceptionMsg, 'Unsupported', $option, $value)
                );
            }

220 221
            if (@mysqli_options($this->_conn, $option, $value)) {
                continue;
222
            }
223 224 225 226 227 228

            $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,
229 230
                $this->_conn->sqlstate,
                $this->_conn->errno
231
            );
232 233
        }
    }
234 235 236 237 238 239 240 241 242 243

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