MasterSlaveConnection.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  1. <?php
  2. /*
  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.
  14. *
  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>.
  18. */
  19. namespace Doctrine\DBAL\Connections;
  20. use Doctrine\DBAL\Connection;
  21. use Doctrine\DBAL\Driver;
  22. use Doctrine\DBAL\Configuration;
  23. use Doctrine\Common\EventManager;
  24. use Doctrine\DBAL\Event\ConnectionEventArgs;
  25. use Doctrine\DBAL\Events;
  26. /**
  27. * Master-Slave Connection
  28. *
  29. * Connection can be used with master-slave setups.
  30. *
  31. * Important for the understanding of this connection should be how and when
  32. * it picks the slave or master.
  33. *
  34. * 1. Slave if master was never picked before and ONLY if 'getWrappedConnection'
  35. * or 'executeQuery' is used.
  36. * 2. Master picked when 'exec', 'executeUpdate', 'insert', 'delete', 'update', 'createSavepoint',
  37. * 'releaseSavepoint', 'beginTransaction', 'rollback', 'commit', 'query' or
  38. * 'prepare' is called.
  39. * 3. If master was picked once during the lifetime of the connection it will always get picked afterwards.
  40. * 4. One slave connection is randomly picked ONCE during a request.
  41. *
  42. * ATTENTION: You can write to the slave with this connection if you execute a write query without
  43. * opening up a transaction. For example:
  44. *
  45. * $conn = DriverManager::getConnection(...);
  46. * $conn->executeQuery("DELETE FROM table");
  47. *
  48. * Be aware that Connection#executeQuery is a method specifically for READ
  49. * operations only.
  50. *
  51. * This connection is limited to slave operations using the
  52. * Connection#executeQuery operation only, because it wouldn't be compatible
  53. * with the ORM or SchemaManager code otherwise. Both use all the other
  54. * operations in a context where writes could happen to a slave, which makes
  55. * this restricted approach necessary.
  56. *
  57. * You can manually connect to the master at any time by calling:
  58. *
  59. * $conn->connect('master');
  60. *
  61. * Instantiation through the DriverManager looks like:
  62. *
  63. * @example
  64. *
  65. * $conn = DriverManager::getConnection(array(
  66. * 'wrapperClass' => 'Doctrine\DBAL\Connections\MasterSlaveConnection',
  67. * 'driver' => 'pdo_mysql',
  68. * 'master' => array('user' => '', 'password' => '', 'host' => '', 'dbname' => ''),
  69. * 'slaves' => array(
  70. * array('user' => 'slave1', 'password', 'host' => '', 'dbname' => ''),
  71. * array('user' => 'slave2', 'password', 'host' => '', 'dbname' => ''),
  72. * )
  73. * ));
  74. *
  75. * You can also pass 'driverOptions' and any other documented option to each of this drivers to pass additional information.
  76. *
  77. * @author Lars Strojny <lstrojny@php.net>
  78. * @author Benjamin Eberlei <kontakt@beberlei.de>
  79. */
  80. class MasterSlaveConnection extends Connection
  81. {
  82. /**
  83. * Master and slave connection (one of the randomly picked slaves).
  84. *
  85. * @var \Doctrine\DBAL\Driver\Connection[]
  86. */
  87. protected $connections = array('master' => null, 'slave' => null);
  88. /**
  89. * You can keep the slave connection and then switch back to it
  90. * during the request if you know what you are doing.
  91. *
  92. * @var boolean
  93. */
  94. protected $keepSlave = false;
  95. /**
  96. * Creates Master Slave Connection.
  97. *
  98. * @param array $params
  99. * @param \Doctrine\DBAL\Driver $driver
  100. * @param \Doctrine\DBAL\Configuration|null $config
  101. * @param \Doctrine\Common\EventManager|null $eventManager
  102. *
  103. * @throws \InvalidArgumentException
  104. */
  105. public function __construct(array $params, Driver $driver, Configuration $config = null, EventManager $eventManager = null)
  106. {
  107. if ( !isset($params['slaves']) || !isset($params['master']) ) {
  108. throw new \InvalidArgumentException('master or slaves configuration missing');
  109. }
  110. if ( count($params['slaves']) == 0 ) {
  111. throw new \InvalidArgumentException('You have to configure at least one slaves.');
  112. }
  113. $params['master']['driver'] = $params['driver'];
  114. foreach ($params['slaves'] as $slaveKey => $slave) {
  115. $params['slaves'][$slaveKey]['driver'] = $params['driver'];
  116. }
  117. $this->keepSlave = isset($params['keepSlave']) ? (bool)$params['keepSlave'] : false;
  118. parent::__construct($params, $driver, $config, $eventManager);
  119. }
  120. /**
  121. * Checks if the connection is currently towards the master or not.
  122. *
  123. * @return boolean
  124. */
  125. public function isConnectedToMaster()
  126. {
  127. return $this->_conn !== null && $this->_conn === $this->connections['master'];
  128. }
  129. /**
  130. * {@inheritDoc}
  131. */
  132. public function connect($connectionName = null)
  133. {
  134. $requestedConnectionChange = ($connectionName !== null);
  135. $connectionName = $connectionName ?: 'slave';
  136. if ( $connectionName !== 'slave' && $connectionName !== 'master' ) {
  137. throw new \InvalidArgumentException("Invalid option to connect(), only master or slave allowed.");
  138. }
  139. // If we have a connection open, and this is not an explicit connection
  140. // change request, then abort right here, because we are already done.
  141. // This prevents writes to the slave in case of "keepSlave" option enabled.
  142. if ($this->_conn && !$requestedConnectionChange) {
  143. return false;
  144. }
  145. $forceMasterAsSlave = false;
  146. if ($this->getTransactionNestingLevel() > 0) {
  147. $connectionName = 'master';
  148. $forceMasterAsSlave = true;
  149. }
  150. if ($this->connections[$connectionName]) {
  151. if ($forceMasterAsSlave) {
  152. $this->connections['slave'] = $this->_conn = $this->connections['master'];
  153. } else {
  154. $this->_conn = $this->connections[$connectionName];
  155. }
  156. return false;
  157. }
  158. if ($connectionName === 'master') {
  159. // Set slave connection to master to avoid invalid reads
  160. if ($this->connections['slave'] && ! $this->keepSlave) {
  161. unset($this->connections['slave']);
  162. }
  163. $this->connections['master'] = $this->_conn = $this->connectTo($connectionName);
  164. if ( ! $this->keepSlave) {
  165. $this->connections['slave'] = $this->connections['master'];
  166. }
  167. } else {
  168. $this->connections['slave'] = $this->_conn = $this->connectTo($connectionName);
  169. }
  170. if ($this->_eventManager->hasListeners(Events::postConnect)) {
  171. $eventArgs = new ConnectionEventArgs($this);
  172. $this->_eventManager->dispatchEvent(Events::postConnect, $eventArgs);
  173. }
  174. return true;
  175. }
  176. /**
  177. * Connects to a specific connection.
  178. *
  179. * @param string $connectionName
  180. *
  181. * @return \Doctrine\DBAL\Driver
  182. */
  183. protected function connectTo($connectionName)
  184. {
  185. $params = $this->getParams();
  186. $driverOptions = isset($params['driverOptions']) ? $params['driverOptions'] : array();
  187. $connectionParams = $this->chooseConnectionConfiguration($connectionName, $params);
  188. $user = isset($connectionParams['user']) ? $connectionParams['user'] : null;
  189. $password = isset($connectionParams['password']) ? $connectionParams['password'] : null;
  190. return $this->_driver->connect($connectionParams, $user, $password, $driverOptions);
  191. }
  192. /**
  193. * @param string $connectionName
  194. * @param array $params
  195. *
  196. * @return mixed
  197. */
  198. protected function chooseConnectionConfiguration($connectionName, $params)
  199. {
  200. if ($connectionName === 'master') {
  201. return $params['master'];
  202. }
  203. return $params['slaves'][array_rand($params['slaves'])];
  204. }
  205. /**
  206. * {@inheritDoc}
  207. */
  208. public function executeUpdate($query, array $params = array(), array $types = array())
  209. {
  210. $this->connect('master');
  211. return parent::executeUpdate($query, $params, $types);
  212. }
  213. /**
  214. * {@inheritDoc}
  215. */
  216. public function beginTransaction()
  217. {
  218. $this->connect('master');
  219. return parent::beginTransaction();
  220. }
  221. /**
  222. * {@inheritDoc}
  223. */
  224. public function commit()
  225. {
  226. $this->connect('master');
  227. return parent::commit();
  228. }
  229. /**
  230. * {@inheritDoc}
  231. */
  232. public function rollBack()
  233. {
  234. $this->connect('master');
  235. return parent::rollBack();
  236. }
  237. /**
  238. * {@inheritDoc}
  239. */
  240. public function delete($tableName, array $identifier, array $types = array())
  241. {
  242. $this->connect('master');
  243. return parent::delete($tableName, $identifier, $types);
  244. }
  245. /**
  246. * {@inheritDoc}
  247. */
  248. public function update($tableName, array $data, array $identifier, array $types = array())
  249. {
  250. $this->connect('master');
  251. return parent::update($tableName, $data, $identifier, $types);
  252. }
  253. /**
  254. * {@inheritDoc}
  255. */
  256. public function insert($tableName, array $data, array $types = array())
  257. {
  258. $this->connect('master');
  259. return parent::insert($tableName, $data, $types);
  260. }
  261. /**
  262. * {@inheritDoc}
  263. */
  264. public function exec($statement)
  265. {
  266. $this->connect('master');
  267. return parent::exec($statement);
  268. }
  269. /**
  270. * {@inheritDoc}
  271. */
  272. public function createSavepoint($savepoint)
  273. {
  274. $this->connect('master');
  275. return parent::createSavepoint($savepoint);
  276. }
  277. /**
  278. * {@inheritDoc}
  279. */
  280. public function releaseSavepoint($savepoint)
  281. {
  282. $this->connect('master');
  283. return parent::releaseSavepoint($savepoint);
  284. }
  285. /**
  286. * {@inheritDoc}
  287. */
  288. public function rollbackSavepoint($savepoint)
  289. {
  290. $this->connect('master');
  291. return parent::rollbackSavepoint($savepoint);
  292. }
  293. /**
  294. * {@inheritDoc}
  295. */
  296. public function query()
  297. {
  298. $this->connect('master');
  299. $args = func_get_args();
  300. $logger = $this->getConfiguration()->getSQLLogger();
  301. if ($logger) {
  302. $logger->startQuery($args[0]);
  303. }
  304. $statement = call_user_func_array(array($this->_conn, 'query'), $args);
  305. if ($logger) {
  306. $logger->stopQuery();
  307. }
  308. return $statement;
  309. }
  310. /**
  311. * {@inheritDoc}
  312. */
  313. public function prepare($statement)
  314. {
  315. $this->connect('master');
  316. return parent::prepare($statement);
  317. }
  318. }