MasterSlaveConnection.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353
  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. Doctrine\DBAL\Driver,
  22. Doctrine\DBAL\Configuration,
  23. Doctrine\Common\EventManager,
  24. Doctrine\DBAL\Event\ConnectionEventArgs,
  25. 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 bool
  93. */
  94. protected $keepSlave = false;
  95. /**
  96. * Create Master Slave Connection
  97. *
  98. * @param array $params
  99. * @param Driver $driver
  100. * @param Configuration $config
  101. * @param EventManager $eventManager
  102. */
  103. public function __construct(array $params, Driver $driver, Configuration $config = null, EventManager $eventManager = null)
  104. {
  105. if ( !isset($params['slaves']) || !isset($params['master']) ) {
  106. throw new \InvalidArgumentException('master or slaves configuration missing');
  107. }
  108. if ( count($params['slaves']) == 0 ) {
  109. throw new \InvalidArgumentException('You have to configure at least one slaves.');
  110. }
  111. $params['master']['driver'] = $params['driver'];
  112. foreach ($params['slaves'] as $slaveKey => $slave) {
  113. $params['slaves'][$slaveKey]['driver'] = $params['driver'];
  114. }
  115. $this->keepSlave = isset($params['keepSlave']) ? (bool)$params['keepSlave'] : false;
  116. parent::__construct($params, $driver, $config, $eventManager);
  117. }
  118. /**
  119. * Check if the connection is currently towards the master or not.
  120. *
  121. * @return bool
  122. */
  123. public function isConnectedToMaster()
  124. {
  125. return $this->_conn !== null && $this->_conn === $this->connections['master'];
  126. }
  127. /**
  128. * {@inheritDoc}
  129. */
  130. public function connect($connectionName = null)
  131. {
  132. $requestedConnectionChange = ($connectionName !== null);
  133. $connectionName = $connectionName ?: 'slave';
  134. if ( $connectionName !== 'slave' && $connectionName !== 'master' ) {
  135. throw new \InvalidArgumentException("Invalid option to connect(), only master or slave allowed.");
  136. }
  137. // If we have a connection open, and this is not an explicit connection
  138. // change request, then abort right here, because we are already done.
  139. // This prevents writes to the slave in case of "keepSlave" option enabled.
  140. if ($this->_conn && !$requestedConnectionChange) {
  141. return false;
  142. }
  143. $forceMasterAsSlave = false;
  144. if ($this->getTransactionNestingLevel() > 0) {
  145. $connectionName = 'master';
  146. $forceMasterAsSlave = true;
  147. }
  148. if ($this->connections[$connectionName]) {
  149. if ($forceMasterAsSlave) {
  150. $this->connections['slave'] = $this->_conn = $this->connections['master'];
  151. } else {
  152. $this->_conn = $this->connections[$connectionName];
  153. }
  154. return false;
  155. }
  156. if ($connectionName === 'master') {
  157. // Set slave connection to master to avoid invalid reads
  158. if ($this->connections['slave'] && ! $this->keepSlave) {
  159. unset($this->connections['slave']);
  160. }
  161. $this->connections['master'] = $this->_conn = $this->connectTo($connectionName);
  162. if ( ! $this->keepSlave) {
  163. $this->connections['slave'] = $this->connections['master'];
  164. }
  165. } else {
  166. $this->connections['slave'] = $this->_conn = $this->connectTo($connectionName);
  167. }
  168. if ($this->_eventManager->hasListeners(Events::postConnect)) {
  169. $eventArgs = new ConnectionEventArgs($this);
  170. $this->_eventManager->dispatchEvent(Events::postConnect, $eventArgs);
  171. }
  172. return true;
  173. }
  174. /**
  175. * Connect to a specific connection
  176. *
  177. * @param string $connectionName
  178. * @return Driver
  179. */
  180. protected function connectTo($connectionName)
  181. {
  182. $params = $this->getParams();
  183. $driverOptions = isset($params['driverOptions']) ? $params['driverOptions'] : array();
  184. $connectionParams = $this->chooseConnectionConfiguration($connectionName, $params);
  185. $user = isset($connectionParams['user']) ? $connectionParams['user'] : null;
  186. $password = isset($connectionParams['password']) ? $connectionParams['password'] : null;
  187. return $this->_driver->connect($connectionParams, $user, $password, $driverOptions);
  188. }
  189. protected function chooseConnectionConfiguration($connectionName, $params)
  190. {
  191. if ($connectionName === 'master') {
  192. return $params['master'];
  193. }
  194. return $params['slaves'][array_rand($params['slaves'])];
  195. }
  196. /**
  197. * {@inheritDoc}
  198. */
  199. public function executeUpdate($query, array $params = array(), array $types = array())
  200. {
  201. $this->connect('master');
  202. return parent::executeUpdate($query, $params, $types);
  203. }
  204. /**
  205. * {@inheritDoc}
  206. */
  207. public function beginTransaction()
  208. {
  209. $this->connect('master');
  210. return parent::beginTransaction();
  211. }
  212. /**
  213. * {@inheritDoc}
  214. */
  215. public function commit()
  216. {
  217. $this->connect('master');
  218. return parent::commit();
  219. }
  220. /**
  221. * {@inheritDoc}
  222. */
  223. public function rollBack()
  224. {
  225. $this->connect('master');
  226. return parent::rollBack();
  227. }
  228. /**
  229. * {@inheritDoc}
  230. */
  231. public function delete($tableName, array $identifier)
  232. {
  233. $this->connect('master');
  234. return parent::delete($tableName, $identifier);
  235. }
  236. /**
  237. * {@inheritDoc}
  238. */
  239. public function update($tableName, array $data, array $identifier, array $types = array())
  240. {
  241. $this->connect('master');
  242. return parent::update($tableName, $data, $identifier, $types);
  243. }
  244. /**
  245. * {@inheritDoc}
  246. */
  247. public function insert($tableName, array $data, array $types = array())
  248. {
  249. $this->connect('master');
  250. return parent::insert($tableName, $data, $types);
  251. }
  252. /**
  253. * {@inheritDoc}
  254. */
  255. public function exec($statement)
  256. {
  257. $this->connect('master');
  258. return parent::exec($statement);
  259. }
  260. /**
  261. * {@inheritDoc}
  262. */
  263. public function createSavepoint($savepoint)
  264. {
  265. $this->connect('master');
  266. return parent::createSavepoint($savepoint);
  267. }
  268. /**
  269. * {@inheritDoc}
  270. */
  271. public function releaseSavepoint($savepoint)
  272. {
  273. $this->connect('master');
  274. return parent::releaseSavepoint($savepoint);
  275. }
  276. /**
  277. * {@inheritDoc}
  278. */
  279. public function rollbackSavepoint($savepoint)
  280. {
  281. $this->connect('master');
  282. return parent::rollbackSavepoint($savepoint);
  283. }
  284. public function query()
  285. {
  286. $this->connect('master');
  287. $args = func_get_args();
  288. $logger = $this->getConfiguration()->getSQLLogger();
  289. if ($logger) {
  290. $logger->startQuery($args[0]);
  291. }
  292. $statement = call_user_func_array(array($this->_conn, 'query'), $args);
  293. if ($logger) {
  294. $logger->stopQuery();
  295. }
  296. return $statement;
  297. }
  298. public function prepare($statement)
  299. {
  300. $this->connect('master');
  301. return parent::prepare($statement);
  302. }
  303. }