MasterSlaveConnection.php 9.7 KB

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