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
use function array_rand;
Sergei Morozov's avatar
Sergei Morozov committed
14
use function assert;
15 16
use function count;
use function func_get_args;
17 18 19 20

/**
 * Master-Slave Connection
 *
21 22
 * Connection can be used with master-slave setups.
 *
23 24
 * Important for the understanding of this connection should be how and when
 * it picks the slave or master.
25
 *
26 27 28 29 30 31 32
 * 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.
33 34 35 36 37
 *
 * 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(...);
38 39 40 41 42 43 44 45 46 47 48 49 50 51
 *      $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');
52 53
 *
 * Instantiation through the DriverManager looks like:
54 55 56 57
 *
 * @example
 *
 * $conn = DriverManager::getConnection(array(
58
 *    'wrapperClass' => 'Doctrine\DBAL\Connections\MasterSlaveConnection',
59 60
 *    'driver' => 'pdo_mysql',
 *    'master' => array('user' => '', 'password' => '', 'host' => '', 'dbname' => ''),
61 62 63 64 65 66 67 68 69 70 71
 *    '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
72
     * Master and slave connection (one of the randomly picked slaves).
73
     *
74
     * @var DriverConnection[]|null[]
75
     */
76
    protected $connections = ['master' => null, 'slave' => null];
77

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

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

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

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

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

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

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

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

134 135 136
        // 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.
Sergei Morozov's avatar
Sergei Morozov committed
137
        if ($this->_conn !== null && ! $requestedConnectionChange) {
138 139 140
            return false;
        }

141 142 143
        $forceMasterAsSlave = false;

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

Sergei Morozov's avatar
Sergei Morozov committed
148
        if (isset($this->connections[$connectionName])) {
149 150 151 152
            $this->_conn = $this->connections[$connectionName];

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

155 156 157 158
            return false;
        }

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

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

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

        return true;
    }

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

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

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

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

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

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

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

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

        return $config;
217 218 219 220 221
    }

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

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

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

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

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

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

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

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

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

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

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

        parent::close();
277

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        $args = func_get_args();

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

357
        $statement = $this->_conn->query(...$args);
358

359 360
        $statement->setFetchMode($this->defaultFetchMode);

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

        return $statement;
    }

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

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