MasterSlaveConnection.php 10.1 KB
Newer Older
1 2 3 4
<?php

namespace Doctrine\DBAL\Connections;

5 6
use Doctrine\Common\EventManager;
use Doctrine\DBAL\Configuration;
Benjamin Morel's avatar
Benjamin Morel committed
7 8
use Doctrine\DBAL\Connection;
use Doctrine\DBAL\Driver;
9
use Doctrine\DBAL\Driver\Connection as DriverConnection;
Benjamin Morel's avatar
Benjamin Morel committed
10 11
use Doctrine\DBAL\Event\ConnectionEventArgs;
use Doctrine\DBAL\Events;
12
use InvalidArgumentException;
13 14 15
use function array_rand;
use function count;
use function func_get_args;
16 17 18 19

/**
 * Master-Slave Connection
 *
20 21
 * Connection can be used with master-slave setups.
 *
22 23
 * Important for the understanding of this connection should be how and when
 * it picks the slave or master.
24
 *
25 26 27 28 29 30 31
 * 1. Slave if master was never picked before and ONLY if 'getWrappedConnection'
 *    or 'executeQuery' is used.
 * 2. Master picked when 'exec', 'executeUpdate', 'insert', 'delete', 'update', 'createSavepoint',
 *    'releaseSavepoint', 'beginTransaction', 'rollback', 'commit', 'query' or
 *    'prepare' is called.
 * 3. If master was picked once during the lifetime of the connection it will always get picked afterwards.
 * 4. One slave connection is randomly picked ONCE during a request.
32 33 34 35 36
 *
 * ATTENTION: You can write to the slave with this connection if you execute a write query without
 * opening up a transaction. For example:
 *
 *      $conn = DriverManager::getConnection(...);
37 38 39 40 41 42 43 44 45 46 47 48 49 50
 *      $conn->executeQuery("DELETE FROM table");
 *
 * Be aware that Connection#executeQuery is a method specifically for READ
 * operations only.
 *
 * This connection is limited to slave operations using the
 * Connection#executeQuery operation only, because it wouldn't be compatible
 * with the ORM or SchemaManager code otherwise. Both use all the other
 * operations in a context where writes could happen to a slave, which makes
 * this restricted approach necessary.
 *
 * You can manually connect to the master at any time by calling:
 *
 *      $conn->connect('master');
51 52
 *
 * Instantiation through the DriverManager looks like:
53 54 55 56
 *
 * @example
 *
 * $conn = DriverManager::getConnection(array(
57
 *    'wrapperClass' => 'Doctrine\DBAL\Connections\MasterSlaveConnection',
58 59
 *    'driver' => 'pdo_mysql',
 *    'master' => array('user' => '', 'password' => '', 'host' => '', 'dbname' => ''),
60 61 62 63 64 65 66 67 68 69 70
 *    'slaves' => array(
 *        array('user' => 'slave1', 'password', 'host' => '', 'dbname' => ''),
 *        array('user' => 'slave2', 'password', 'host' => '', 'dbname' => ''),
 *    )
 * ));
 *
 * You can also pass 'driverOptions' and any other documented option to each of this drivers to pass additional information.
 */
class MasterSlaveConnection extends Connection
{
    /**
Benjamin Morel's avatar
Benjamin Morel committed
71
     * Master and slave connection (one of the randomly picked slaves).
72
     *
73
     * @var DriverConnection[]|null[]
74
     */
75
    protected $connections = ['master' => null, 'slave' => null];
76

77 78 79 80
    /**
     * You can keep the slave connection and then switch back to it
     * during the request if you know what you are doing.
     *
81
     * @var bool
82 83 84
     */
    protected $keepSlave = false;

85
    /**
Benjamin Morel's avatar
Benjamin Morel committed
86 87
     * Creates Master Slave Connection.
     *
88
     * @param mixed[] $params
89
     *
90
     * @throws InvalidArgumentException
91
     */
92
    public function __construct(array $params, Driver $driver, ?Configuration $config = null, ?EventManager $eventManager = null)
93
    {
94
        if (! isset($params['slaves'], $params['master'])) {
95
            throw new InvalidArgumentException('master or slaves configuration missing');
96
        }
97 98
        if (count($params['slaves']) === 0) {
            throw new InvalidArgumentException('You have to configure at least one slaves.');
99 100 101 102 103 104 105
        }

        $params['master']['driver'] = $params['driver'];
        foreach ($params['slaves'] as $slaveKey => $slave) {
            $params['slaves'][$slaveKey]['driver'] = $params['driver'];
        }

106
        $this->keepSlave = (bool) ($params['keepSlave'] ?? false);
107

108 109 110
        parent::__construct($params, $driver, $config, $eventManager);
    }

111
    /**
Benjamin Morel's avatar
Benjamin Morel committed
112
     * Checks if the connection is currently towards the master or not.
113
     *
114
     * @return bool
115 116 117 118 119 120
     */
    public function isConnectedToMaster()
    {
        return $this->_conn !== null && $this->_conn === $this->connections['master'];
    }

121 122 123
    /**
     * {@inheritDoc}
     */
124
    public function connect($connectionName = null)
125
    {
126 127 128
        $requestedConnectionChange = ($connectionName !== null);
        $connectionName            = $connectionName ?: 'slave';

Steve Müller's avatar
Steve Müller committed
129
        if ($connectionName !== 'slave' && $connectionName !== 'master') {
130
            throw new InvalidArgumentException('Invalid option to connect(), only master or slave allowed.');
131 132
        }

133 134 135
        // If we have a connection open, and this is not an explicit connection
        // change request, then abort right here, because we are already done.
        // This prevents writes to the slave in case of "keepSlave" option enabled.
136
        if (isset($this->_conn) && $this->_conn && ! $requestedConnectionChange) {
137 138 139
            return false;
        }

140 141 142
        $forceMasterAsSlave = false;

        if ($this->getTransactionNestingLevel() > 0) {
143
            $connectionName     = 'master';
144 145 146
            $forceMasterAsSlave = true;
        }

147
        if (isset($this->connections[$connectionName]) && $this->connections[$connectionName]) {
148 149 150 151
            $this->_conn = $this->connections[$connectionName];

            if ($forceMasterAsSlave && ! $this->keepSlave) {
                $this->connections['slave'] = $this->_conn;
152
            }
153

154 155 156 157
            return false;
        }

        if ($connectionName === 'master') {
158 159
            $this->connections['master'] = $this->_conn = $this->connectTo($connectionName);

160
            // Set slave connection to master to avoid invalid reads
161
            if (! $this->keepSlave) {
162 163
                $this->connections['slave'] = $this->connections['master'];
            }
164 165 166 167 168
        } else {
            $this->connections['slave'] = $this->_conn = $this->connectTo($connectionName);
        }

        if ($this->_eventManager->hasListeners(Events::postConnect)) {
169
            $eventArgs = new ConnectionEventArgs($this);
170 171 172 173 174 175 176
            $this->_eventManager->dispatchEvent(Events::postConnect, $eventArgs);
        }

        return true;
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
177 178 179
     * Connects to a specific connection.
     *
     * @param string $connectionName
180
     *
181
     * @return DriverConnection
182 183 184 185 186
     */
    protected function connectTo($connectionName)
    {
        $params = $this->getParams();

187
        $driverOptions = $params['driverOptions'] ?? [];
188 189 190

        $connectionParams = $this->chooseConnectionConfiguration($connectionName, $params);

191
        $user     = $connectionParams['user'] ?? null;
192
        $password = $connectionParams['password'] ?? null;
193 194 195 196

        return $this->_driver->connect($connectionParams, $user, $password, $driverOptions);
    }

Benjamin Morel's avatar
Benjamin Morel committed
197
    /**
198 199
     * @param string  $connectionName
     * @param mixed[] $params
Benjamin Morel's avatar
Benjamin Morel committed
200 201 202
     *
     * @return mixed
     */
203 204 205 206 207 208
    protected function chooseConnectionConfiguration($connectionName, $params)
    {
        if ($connectionName === 'master') {
            return $params['master'];
        }

209 210
        $config = $params['slaves'][array_rand($params['slaves'])];

211
        if (! isset($config['charset']) && isset($params['master']['charset'])) {
212 213 214 215
            $config['charset'] = $params['master']['charset'];
        }

        return $config;
216 217 218 219 220
    }

    /**
     * {@inheritDoc}
     */
221
    public function executeUpdate($query, array $params = [], array $types = [])
222 223
    {
        $this->connect('master');
Benjamin Morel's avatar
Benjamin Morel committed
224

225 226 227 228 229 230 231 232 233
        return parent::executeUpdate($query, $params, $types);
    }

    /**
     * {@inheritDoc}
     */
    public function beginTransaction()
    {
        $this->connect('master');
Benjamin Morel's avatar
Benjamin Morel committed
234

235
        parent::beginTransaction();
236 237 238 239 240 241 242 243
    }

    /**
     * {@inheritDoc}
     */
    public function commit()
    {
        $this->connect('master');
Benjamin Morel's avatar
Benjamin Morel committed
244

245
        parent::commit();
246 247 248 249 250
    }

    /**
     * {@inheritDoc}
     */
Nazin's avatar
Nazin committed
251
    public function rollBack()
252 253
    {
        $this->connect('master');
Benjamin Morel's avatar
Benjamin Morel committed
254

Nazin's avatar
Nazin committed
255
        return parent::rollBack();
256 257 258 259 260
    }

    /**
     * {@inheritDoc}
     */
261
    public function delete($tableName, array $identifier, array $types = [])
262 263
    {
        $this->connect('master');
Benjamin Morel's avatar
Benjamin Morel committed
264

265
        return parent::delete($tableName, $identifier, $types);
266 267
    }

268 269 270 271 272
    /**
     * {@inheritDoc}
     */
    public function close()
    {
273
        unset($this->connections['master'], $this->connections['slave']);
274 275

        parent::close();
276

277
        $this->_conn       = null;
278
        $this->connections = ['master' => null, 'slave' => null];
279 280
    }

281 282 283
    /**
     * {@inheritDoc}
     */
284
    public function update($tableName, array $data, array $identifier, array $types = [])
285 286
    {
        $this->connect('master');
Benjamin Morel's avatar
Benjamin Morel committed
287

288
        return parent::update($tableName, $data, $identifier, $types);
289 290 291 292 293
    }

    /**
     * {@inheritDoc}
     */
294
    public function insert($tableName, array $data, array $types = [])
295 296
    {
        $this->connect('master');
Benjamin Morel's avatar
Benjamin Morel committed
297

298
        return parent::insert($tableName, $data, $types);
299 300 301 302 303 304 305 306
    }

    /**
     * {@inheritDoc}
     */
    public function exec($statement)
    {
        $this->connect('master');
Benjamin Morel's avatar
Benjamin Morel committed
307

308 309 310 311 312 313 314 315 316 317
        return parent::exec($statement);
    }

    /**
     * {@inheritDoc}
     */
    public function createSavepoint($savepoint)
    {
        $this->connect('master');

318
        parent::createSavepoint($savepoint);
319 320 321 322 323 324 325 326 327
    }

    /**
     * {@inheritDoc}
     */
    public function releaseSavepoint($savepoint)
    {
        $this->connect('master');

328
        parent::releaseSavepoint($savepoint);
329 330 331 332 333 334 335 336 337
    }

    /**
     * {@inheritDoc}
     */
    public function rollbackSavepoint($savepoint)
    {
        $this->connect('master');

338
        parent::rollbackSavepoint($savepoint);
339
    }
340

Benjamin Morel's avatar
Benjamin Morel committed
341 342 343
    /**
     * {@inheritDoc}
     */
344 345 346 347 348 349 350 351 352 353
    public function query()
    {
        $this->connect('master');

        $args = func_get_args();

        $logger = $this->getConfiguration()->getSQLLogger();
        if ($logger) {
            $logger->startQuery($args[0]);
        }
354

355
        $statement = $this->_conn->query(...$args);
356

357 358
        $statement->setFetchMode($this->defaultFetchMode);

359 360 361 362 363 364 365
        if ($logger) {
            $logger->stopQuery();
        }

        return $statement;
    }

Benjamin Morel's avatar
Benjamin Morel committed
366 367 368
    /**
     * {@inheritDoc}
     */
369 370 371 372 373 374
    public function prepare($statement)
    {
        $this->connect('master');

        return parent::prepare($statement);
    }
375
}