3 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
4 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
5 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
6 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
7 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
8 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
9 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
10 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
11 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
12 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
13 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
15 * This software consists of voluntary contributions made by many individuals
16 * and is licensed under the MIT license. For more information, see
17 * <http://www.doctrine-project.org>.
20 namespace Doctrine\DBAL\Connections;
23 use Doctrine\DBAL\Connection,
25 Doctrine\DBAL\Configuration,
26 Doctrine\Common\EventManager,
27 Doctrine\DBAL\Event\ConnectionEventArgs,
31 * Master-Slave Connection
33 * Connection can be used with master-slave setups.
35 * Important for the understanding of this connection should be how and when
36 * it picks the slave or master.
38 * 1. Slave if master was never picked before and ONLY if 'getWrappedConnection'
39 * or 'executeQuery' is used.
40 * 2. Master picked when 'exec', 'executeUpdate', 'insert', 'delete', 'update', 'createSavepoint',
41 * 'releaseSavepoint', 'beginTransaction', 'rollback', 'commit', 'query' or
42 * 'prepare' is called.
43 * 3. If master was picked once during the lifetime of the connection it will always get picked afterwards.
44 * 4. One slave connection is randomly picked ONCE during a request.
46 * ATTENTION: You can write to the slave with this connection if you execute a write query without
47 * opening up a transaction. For example:
49 * $conn = DriverManager::getConnection(...);
50 * $conn->executeQuery("DELETE FROM table");
52 * Be aware that Connection#executeQuery is a method specifically for READ
55 * This connection is limited to slave operations using the
56 * Connection#executeQuery operation only, because it wouldn't be compatible
57 * with the ORM or SchemaManager code otherwise. Both use all the other
58 * operations in a context where writes could happen to a slave, which makes
59 * this restricted approach necessary.
61 * You can manually connect to the master at any time by calling:
63 * $conn->connect('master');
65 * Instantiation through the DriverManager looks like:
69 * $conn = DriverManager::getConnection(array(
70 * 'wrapperClass' => 'Doctrine\DBAL\Connections\MasterSlaveConnection',
71 * 'driver' => 'pdo_mysql',
72 * 'master' => array('user' => '', 'password' => '', 'host' => '', 'dbname' => ''),
74 * array('user' => 'slave1', 'password', 'host' => '', 'dbname' => ''),
75 * array('user' => 'slave2', 'password', 'host' => '', 'dbname' => ''),
79 * You can also pass 'driverOptions' and any other documented option to each of this drivers to pass additional information.
81 * @author Lars Strojny <lstrojny@php.net>
82 * @author Benjamin Eberlei <kontakt@beberlei.de>
84 class MasterSlaveConnection extends Connection
87 * Master and slave connection (one of the randomly picked slaves)
89 * @var Doctrine\DBAL\Driver\Connection[]
91 protected $connections = array('master' => null, 'slave' => null);
94 * You can keep the slave connection and then switch back to it
95 * during the request if you know what you are doing.
99 protected $keepSlave = false;
102 * Create Master Slave Connection
104 * @param array $params
105 * @param Driver $driver
106 * @param Configuration $config
107 * @param EventManager $eventManager
109 public function __construct(array $params, Driver $driver, Configuration $config = null, EventManager $eventManager = null)
111 if ( !isset($params['slaves']) || !isset($params['master']) ) {
112 throw new \InvalidArgumentException('master or slaves configuration missing');
114 if ( count($params['slaves']) == 0 ) {
115 throw new \InvalidArgumentException('You have to configure at least one slaves.');
118 $params['master']['driver'] = $params['driver'];
119 foreach ($params['slaves'] as $slaveKey => $slave) {
120 $params['slaves'][$slaveKey]['driver'] = $params['driver'];
123 $this->keepSlave = isset($params['keepSlave']) ? (bool)$params['keepSlave'] : false;
125 parent::__construct($params, $driver, $config, $eventManager);
129 * Check if the connection is currently towards the master or not.
133 public function isConnectedToMaster()
135 return $this->_conn !== null && $this->_conn === $this->connections['master'];
141 public function connect($connectionName = null)
143 $requestedConnectionChange = ($connectionName !== null);
144 $connectionName = $connectionName ?: 'slave';
146 if ( $connectionName !== 'slave' && $connectionName !== 'master' ) {
147 throw new \InvalidArgumentException("Invalid option to connect(), only master or slave allowed.");
150 // If we have a connection open, and this is not an explicit connection
151 // change request, then abort right here, because we are already done.
152 // This prevents writes to the slave in case of "keepSlave" option enabled.
153 if ($this->_conn && !$requestedConnectionChange) {
157 $forceMasterAsSlave = false;
159 if ($this->getTransactionNestingLevel() > 0) {
160 $connectionName = 'master';
161 $forceMasterAsSlave = true;
164 if ($this->connections[$connectionName]) {
165 if ($forceMasterAsSlave) {
166 $this->connections['slave'] = $this->_conn = $this->connections['master'];
168 $this->_conn = $this->connections[$connectionName];
173 if ($connectionName === 'master') {
174 // Set slave connection to master to avoid invalid reads
175 if ($this->connections['slave'] && ! $this->keepSlave) {
176 unset($this->connections['slave']);
179 $this->connections['master'] = $this->_conn = $this->connectTo($connectionName);
181 if ( ! $this->keepSlave) {
182 $this->connections['slave'] = $this->connections['master'];
185 $this->connections['slave'] = $this->_conn = $this->connectTo($connectionName);
188 if ($this->_eventManager->hasListeners(Events::postConnect)) {
189 $eventArgs = new ConnectionEventArgs($this);
190 $this->_eventManager->dispatchEvent(Events::postConnect, $eventArgs);
197 * Connect to a specific connection
199 * @param string $connectionName
202 protected function connectTo($connectionName)
204 $params = $this->getParams();
206 $driverOptions = isset($params['driverOptions']) ? $params['driverOptions'] : array();
208 $connectionParams = $this->chooseConnectionConfiguration($connectionName, $params);
210 $user = isset($connectionParams['user']) ? $connectionParams['user'] : null;
211 $password = isset($connectionParams['password']) ? $connectionParams['password'] : null;
213 return $this->_driver->connect($connectionParams, $user, $password, $driverOptions);
216 protected function chooseConnectionConfiguration($connectionName, $params)
218 if ($connectionName === 'master') {
219 return $params['master'];
222 return $params['slaves'][array_rand($params['slaves'])];
228 public function executeUpdate($query, array $params = array(), array $types = array())
230 $this->connect('master');
231 return parent::executeUpdate($query, $params, $types);
237 public function beginTransaction()
239 $this->connect('master');
240 return parent::beginTransaction();
246 public function commit()
248 $this->connect('master');
249 return parent::commit();
255 public function rollBack()
257 $this->connect('master');
258 return parent::rollBack();
264 public function delete($tableName, array $identifier)
266 $this->connect('master');
267 return parent::delete($tableName, $identifier);
273 public function update($tableName, array $data, array $identifier, array $types = array())
275 $this->connect('master');
276 return parent::update($tableName, $data, $identifier, $types);
282 public function insert($tableName, array $data, array $types = array())
284 $this->connect('master');
285 return parent::insert($tableName, $data, $types);
291 public function exec($statement)
293 $this->connect('master');
294 return parent::exec($statement);
300 public function createSavepoint($savepoint)
302 $this->connect('master');
304 return parent::createSavepoint($savepoint);
310 public function releaseSavepoint($savepoint)
312 $this->connect('master');
314 return parent::releaseSavepoint($savepoint);
320 public function rollbackSavepoint($savepoint)
322 $this->connect('master');
324 return parent::rollbackSavepoint($savepoint);
327 public function query()
329 $this->connect('master');
331 $args = func_get_args();
333 $logger = $this->getConfiguration()->getSQLLogger();
335 $logger->startQuery($args[0]);
338 $statement = call_user_func_array(array($this->_conn, 'query'), $args);
341 $logger->stopQuery();
347 public function prepare($statement)
349 $this->connect('master');
351 return parent::prepare($statement);