MasterSlaveConnection.php 10 KB

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