MasterSlaveConnection.php 9.81 KB
Newer Older
1 2
<?php

Michael Moravec's avatar
Michael Moravec committed
3 4
declare(strict_types=1);

5 6
namespace Doctrine\DBAL\Connections;

7 8
use Doctrine\Common\EventManager;
use Doctrine\DBAL\Configuration;
Benjamin Morel's avatar
Benjamin Morel committed
9 10
use Doctrine\DBAL\Connection;
use Doctrine\DBAL\Driver;
11
use Doctrine\DBAL\Driver\Connection as DriverConnection;
12 13
use Doctrine\DBAL\Driver\ResultStatement;
use Doctrine\DBAL\Driver\Statement;
Benjamin Morel's avatar
Benjamin Morel committed
14 15
use Doctrine\DBAL\Event\ConnectionEventArgs;
use Doctrine\DBAL\Events;
16
use InvalidArgumentException;
17
use function array_rand;
Sergei Morozov's avatar
Sergei Morozov committed
18
use function assert;
19
use function count;
20 21 22 23

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

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

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

107 108
        if (count($params['slaves']) === 0) {
            throw new InvalidArgumentException('You have to configure at least one slaves.');
109 110 111 112 113 114 115
        }

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

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

118 119 120
        parent::__construct($params, $driver, $config, $eventManager);
    }

121
    /**
Benjamin Morel's avatar
Benjamin Morel committed
122
     * Checks if the connection is currently towards the master or not.
123
     */
124
    public function isConnectedToMaster() : bool
125 126 127 128
    {
        return $this->_conn !== null && $this->_conn === $this->connections['master'];
    }

129
    public function connect(?string $connectionName = null) : void
130
    {
131 132 133
        $requestedConnectionChange = ($connectionName !== null);
        $connectionName            = $connectionName ?: 'slave';

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

138 139 140
        // 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
141
        if ($this->_conn !== null && ! $requestedConnectionChange) {
142
            return;
143 144
        }

145 146 147
        $forceMasterAsSlave = false;

        if ($this->getTransactionNestingLevel() > 0) {
148
            $connectionName     = 'master';
149 150 151
            $forceMasterAsSlave = true;
        }

Sergei Morozov's avatar
Sergei Morozov committed
152
        if (isset($this->connections[$connectionName])) {
153 154 155 156
            $this->_conn = $this->connections[$connectionName];

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

159
            return;
160 161 162
        }

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

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

173 174
        if (! $this->_eventManager->hasListeners(Events::postConnect)) {
            return;
175 176
        }

177 178
        $eventArgs = new ConnectionEventArgs($this);
        $this->_eventManager->dispatchEvent(Events::postConnect, $eventArgs);
179 180 181
    }

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

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

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

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

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

Benjamin Morel's avatar
Benjamin Morel committed
198
    /**
199
     * @param array<string, mixed> $params
Benjamin Morel's avatar
Benjamin Morel committed
200
     *
201
     * @return array<string, mixed>
Benjamin Morel's avatar
Benjamin Morel committed
202
     */
203
    protected function chooseConnectionConfiguration(string $connectionName, array $params) : array
204 205 206 207 208
    {
        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(string $query, array $params = [], array $types = []) : int
222 223
    {
        $this->connect('master');
Benjamin Morel's avatar
Benjamin Morel committed
224

225 226 227
        return parent::executeUpdate($query, $params, $types);
    }

228
    public function beginTransaction() : void
229 230
    {
        $this->connect('master');
Benjamin Morel's avatar
Benjamin Morel committed
231

232
        parent::beginTransaction();
233 234
    }

235
    public function commit() : void
236 237
    {
        $this->connect('master');
Benjamin Morel's avatar
Benjamin Morel committed
238

239
        parent::commit();
240 241
    }

242
    public function rollBack() : void
243 244
    {
        $this->connect('master');
Benjamin Morel's avatar
Benjamin Morel committed
245

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

    /**
     * {@inheritDoc}
     */
252
    public function delete(string $table, array $identifier, array $types = []) : int
253 254
    {
        $this->connect('master');
Benjamin Morel's avatar
Benjamin Morel committed
255

256
        return parent::delete($table, $identifier, $types);
257 258
    }

259
    public function close() : void
260
    {
261
        unset($this->connections['master'], $this->connections['slave']);
262 263

        parent::close();
264

265
        $this->_conn       = null;
266
        $this->connections = ['master' => null, 'slave' => null];
267 268
    }

269 270 271
    /**
     * {@inheritDoc}
     */
272
    public function update(string $table, array $data, array $identifier, array $types = []) : int
273 274
    {
        $this->connect('master');
Benjamin Morel's avatar
Benjamin Morel committed
275

276
        return parent::update($table, $data, $identifier, $types);
277 278 279 280 281
    }

    /**
     * {@inheritDoc}
     */
282
    public function insert(string $table, array $data, array $types = []) : int
283 284
    {
        $this->connect('master');
Benjamin Morel's avatar
Benjamin Morel committed
285

286
        return parent::insert($table, $data, $types);
287 288
    }

289
    public function exec(string $statement) : int
290 291
    {
        $this->connect('master');
Benjamin Morel's avatar
Benjamin Morel committed
292

293 294 295
        return parent::exec($statement);
    }

296
    public function createSavepoint(string $savepoint) : void
297 298 299
    {
        $this->connect('master');

300
        parent::createSavepoint($savepoint);
301 302
    }

303
    public function releaseSavepoint(string $savepoint) : void
304 305 306
    {
        $this->connect('master');

307
        parent::releaseSavepoint($savepoint);
308 309
    }

310
    public function rollbackSavepoint(string $savepoint) : void
311 312 313
    {
        $this->connect('master');

314
        parent::rollbackSavepoint($savepoint);
315
    }
316

317
    public function query(string $sql) : ResultStatement
318 319
    {
        $this->connect('master');
Sergei Morozov's avatar
Sergei Morozov committed
320
        assert($this->_conn instanceof DriverConnection);
321 322

        $logger = $this->getConfiguration()->getSQLLogger();
323
        $logger->startQuery($sql);
324

325
        $statement = $this->_conn->query($sql);
326

327 328
        $statement->setFetchMode($this->defaultFetchMode);

329
        $logger->stopQuery();
330 331 332 333

        return $statement;
    }

334
    public function prepare(string $sql) : Statement
335 336 337
    {
        $this->connect('master');

338
        return parent::prepare($sql);
339
    }
340
}