MasterSlaveConnection.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390
  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. $this->_conn = $this->connections[$connectionName];
  152. if ($forceMasterAsSlave && ! $this->keepSlave) {
  153. $this->connections['slave'] = $this->_conn;
  154. }
  155. return false;
  156. }
  157. if ($connectionName === 'master') {
  158. // Set slave connection to master to avoid invalid reads
  159. if ($this->connections['slave'] && ! $this->keepSlave) {
  160. unset($this->connections['slave']);
  161. }
  162. $this->connections['master'] = $this->_conn = $this->connectTo($connectionName);
  163. if ( ! $this->keepSlave) {
  164. $this->connections['slave'] = $this->connections['master'];
  165. }
  166. } else {
  167. $this->connections['slave'] = $this->_conn = $this->connectTo($connectionName);
  168. }
  169. if ($this->_eventManager->hasListeners(Events::postConnect)) {
  170. $eventArgs = new ConnectionEventArgs($this);
  171. $this->_eventManager->dispatchEvent(Events::postConnect, $eventArgs);
  172. }
  173. return true;
  174. }
  175. /**
  176. * Connects to a specific connection.
  177. *
  178. * @param string $connectionName
  179. *
  180. * @return \Doctrine\DBAL\Driver
  181. */
  182. protected function connectTo($connectionName)
  183. {
  184. $params = $this->getParams();
  185. $driverOptions = isset($params['driverOptions']) ? $params['driverOptions'] : array();
  186. $connectionParams = $this->chooseConnectionConfiguration($connectionName, $params);
  187. $user = isset($connectionParams['user']) ? $connectionParams['user'] : null;
  188. $password = isset($connectionParams['password']) ? $connectionParams['password'] : null;
  189. return $this->_driver->connect($connectionParams, $user, $password, $driverOptions);
  190. }
  191. /**
  192. * @param string $connectionName
  193. * @param array $params
  194. *
  195. * @return mixed
  196. */
  197. protected function chooseConnectionConfiguration($connectionName, $params)
  198. {
  199. if ($connectionName === 'master') {
  200. return $params['master'];
  201. }
  202. return $params['slaves'][array_rand($params['slaves'])];
  203. }
  204. /**
  205. * {@inheritDoc}
  206. */
  207. public function executeUpdate($query, array $params = array(), array $types = array())
  208. {
  209. $this->connect('master');
  210. return parent::executeUpdate($query, $params, $types);
  211. }
  212. /**
  213. * {@inheritDoc}
  214. */
  215. public function beginTransaction()
  216. {
  217. $this->connect('master');
  218. parent::beginTransaction();
  219. }
  220. /**
  221. * {@inheritDoc}
  222. */
  223. public function commit()
  224. {
  225. $this->connect('master');
  226. parent::commit();
  227. }
  228. /**
  229. * {@inheritDoc}
  230. */
  231. public function rollBack()
  232. {
  233. $this->connect('master');
  234. return parent::rollBack();
  235. }
  236. /**
  237. * {@inheritDoc}
  238. */
  239. public function delete($tableName, array $identifier, array $types = array())
  240. {
  241. $this->connect('master');
  242. return parent::delete($tableName, $identifier, $types);
  243. }
  244. /**
  245. * {@inheritDoc}
  246. */
  247. public function close()
  248. {
  249. unset($this->connections['master']);
  250. unset($this->connections['slave']);
  251. parent::close();
  252. $this->_conn = null;
  253. $this->connections = array('master' => null, 'slave' => null);
  254. }
  255. /**
  256. * {@inheritDoc}
  257. */
  258. public function update($tableName, array $data, array $identifier, array $types = array())
  259. {
  260. $this->connect('master');
  261. return parent::update($tableName, $data, $identifier, $types);
  262. }
  263. /**
  264. * {@inheritDoc}
  265. */
  266. public function insert($tableName, array $data, array $types = array())
  267. {
  268. $this->connect('master');
  269. return parent::insert($tableName, $data, $types);
  270. }
  271. /**
  272. * {@inheritDoc}
  273. */
  274. public function exec($statement)
  275. {
  276. $this->connect('master');
  277. return parent::exec($statement);
  278. }
  279. /**
  280. * {@inheritDoc}
  281. */
  282. public function createSavepoint($savepoint)
  283. {
  284. $this->connect('master');
  285. parent::createSavepoint($savepoint);
  286. }
  287. /**
  288. * {@inheritDoc}
  289. */
  290. public function releaseSavepoint($savepoint)
  291. {
  292. $this->connect('master');
  293. parent::releaseSavepoint($savepoint);
  294. }
  295. /**
  296. * {@inheritDoc}
  297. */
  298. public function rollbackSavepoint($savepoint)
  299. {
  300. $this->connect('master');
  301. parent::rollbackSavepoint($savepoint);
  302. }
  303. /**
  304. * {@inheritDoc}
  305. */
  306. public function query()
  307. {
  308. $this->connect('master');
  309. $args = func_get_args();
  310. $logger = $this->getConfiguration()->getSQLLogger();
  311. if ($logger) {
  312. $logger->startQuery($args[0]);
  313. }
  314. $statement = call_user_func_array(array($this->_conn, 'query'), $args);
  315. if ($logger) {
  316. $logger->stopQuery();
  317. }
  318. return $statement;
  319. }
  320. /**
  321. * {@inheritDoc}
  322. */
  323. public function prepare($statement)
  324. {
  325. $this->connect('master');
  326. return parent::prepare($statement);
  327. }
  328. }