PoolingShardConnection.php 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  1. <?php
  2. namespace Doctrine\DBAL\Sharding;
  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 Doctrine\DBAL\Sharding\ShardChoser\ShardChoser;
  11. use InvalidArgumentException;
  12. use function array_merge;
  13. use function is_numeric;
  14. use function is_string;
  15. /**
  16. * Sharding implementation that pools many different connections
  17. * internally and serves data from the currently active connection.
  18. *
  19. * The internals of this class are:
  20. *
  21. * - All sharding clients are specified and given a shard-id during
  22. * configuration.
  23. * - By default, the global shard is selected. If no global shard is configured
  24. * an exception is thrown on access.
  25. * - Selecting a shard by distribution value delegates the mapping
  26. * "distributionValue" => "client" to the ShardChooser interface.
  27. * - An exception is thrown if trying to switch shards during an open
  28. * transaction.
  29. *
  30. * Instantiation through the DriverManager looks like:
  31. *
  32. * @example
  33. *
  34. * $conn = DriverManager::getConnection(array(
  35. * 'wrapperClass' => 'Doctrine\DBAL\Sharding\PoolingShardConnection',
  36. * 'driver' => 'pdo_mysql',
  37. * 'global' => array('user' => '', 'password' => '', 'host' => '', 'dbname' => ''),
  38. * 'shards' => array(
  39. * array('id' => 1, 'user' => 'slave1', 'password', 'host' => '', 'dbname' => ''),
  40. * array('id' => 2, 'user' => 'slave2', 'password', 'host' => '', 'dbname' => ''),
  41. * ),
  42. * 'shardChoser' => 'Doctrine\DBAL\Sharding\ShardChoser\MultiTenantShardChoser',
  43. * ));
  44. * $shardManager = $conn->getShardManager();
  45. * $shardManager->selectGlobal();
  46. * $shardManager->selectShard($value);
  47. */
  48. class PoolingShardConnection extends Connection
  49. {
  50. /** @var DriverConnection[] */
  51. private $activeConnections = [];
  52. /** @var int|null */
  53. private $activeShardId;
  54. /** @var mixed[] */
  55. private $connectionParameters = [];
  56. /**
  57. * {@inheritDoc}
  58. *
  59. * @throws InvalidArgumentException
  60. */
  61. public function __construct(array $params, Driver $driver, ?Configuration $config = null, ?EventManager $eventManager = null)
  62. {
  63. if (! isset($params['global'], $params['shards'])) {
  64. throw new InvalidArgumentException("Connection Parameters require 'global' and 'shards' configurations.");
  65. }
  66. if (! isset($params['shardChoser'])) {
  67. throw new InvalidArgumentException("Missing Shard Choser configuration 'shardChoser'");
  68. }
  69. if (is_string($params['shardChoser'])) {
  70. $params['shardChoser'] = new $params['shardChoser']();
  71. }
  72. if (! ($params['shardChoser'] instanceof ShardChoser)) {
  73. throw new InvalidArgumentException("The 'shardChoser' configuration is not a valid instance of Doctrine\DBAL\Sharding\ShardChoser\ShardChoser");
  74. }
  75. $this->connectionParameters[0] = array_merge($params, $params['global']);
  76. foreach ($params['shards'] as $shard) {
  77. if (! isset($shard['id'])) {
  78. throw new InvalidArgumentException("Missing 'id' for one configured shard. Please specify a unique shard-id.");
  79. }
  80. if (! is_numeric($shard['id']) || $shard['id'] < 1) {
  81. throw new InvalidArgumentException('Shard Id has to be a non-negative number.');
  82. }
  83. if (isset($this->connectionParameters[$shard['id']])) {
  84. throw new InvalidArgumentException('Shard ' . $shard['id'] . ' is duplicated in the configuration.');
  85. }
  86. $this->connectionParameters[$shard['id']] = array_merge($params, $shard);
  87. }
  88. parent::__construct($params, $driver, $config, $eventManager);
  89. }
  90. /**
  91. * Get active shard id.
  92. *
  93. * @return int
  94. */
  95. public function getActiveShardId()
  96. {
  97. return $this->activeShardId;
  98. }
  99. /**
  100. * {@inheritdoc}
  101. */
  102. public function getParams()
  103. {
  104. return $this->activeShardId ? $this->connectionParameters[$this->activeShardId] : $this->connectionParameters[0];
  105. }
  106. /**
  107. * {@inheritdoc}
  108. */
  109. public function getHost()
  110. {
  111. $params = $this->getParams();
  112. return $params['host'] ?? parent::getHost();
  113. }
  114. /**
  115. * {@inheritdoc}
  116. */
  117. public function getPort()
  118. {
  119. $params = $this->getParams();
  120. return $params['port'] ?? parent::getPort();
  121. }
  122. /**
  123. * {@inheritdoc}
  124. */
  125. public function getUsername()
  126. {
  127. $params = $this->getParams();
  128. return $params['user'] ?? parent::getUsername();
  129. }
  130. /**
  131. * {@inheritdoc}
  132. */
  133. public function getPassword()
  134. {
  135. $params = $this->getParams();
  136. return $params['password'] ?? parent::getPassword();
  137. }
  138. /**
  139. * Connects to a given shard.
  140. *
  141. * @param mixed $shardId
  142. *
  143. * @return bool
  144. *
  145. * @throws ShardingException
  146. */
  147. public function connect($shardId = null)
  148. {
  149. if ($shardId === null && $this->_conn) {
  150. return false;
  151. }
  152. if ($shardId !== null && $shardId === $this->activeShardId) {
  153. return false;
  154. }
  155. if ($this->getTransactionNestingLevel() > 0) {
  156. throw new ShardingException('Cannot switch shard when transaction is active.');
  157. }
  158. $this->activeShardId = (int) $shardId;
  159. if (isset($this->activeConnections[$this->activeShardId])) {
  160. $this->_conn = $this->activeConnections[$this->activeShardId];
  161. return false;
  162. }
  163. $this->_conn = $this->activeConnections[$this->activeShardId] = $this->connectTo($this->activeShardId);
  164. if ($this->_eventManager->hasListeners(Events::postConnect)) {
  165. $eventArgs = new ConnectionEventArgs($this);
  166. $this->_eventManager->dispatchEvent(Events::postConnect, $eventArgs);
  167. }
  168. return true;
  169. }
  170. /**
  171. * Connects to a specific connection.
  172. *
  173. * @param string $shardId
  174. *
  175. * @return \Doctrine\DBAL\Driver\Connection
  176. */
  177. protected function connectTo($shardId)
  178. {
  179. $params = $this->getParams();
  180. $driverOptions = $params['driverOptions'] ?? [];
  181. $connectionParams = $this->connectionParameters[$shardId];
  182. $user = $connectionParams['user'] ?? null;
  183. $password = $connectionParams['password'] ?? null;
  184. return $this->_driver->connect($connectionParams, $user, $password, $driverOptions);
  185. }
  186. /**
  187. * @param string|null $shardId
  188. *
  189. * @return bool
  190. */
  191. public function isConnected($shardId = null)
  192. {
  193. if ($shardId === null) {
  194. return $this->_conn !== null;
  195. }
  196. return isset($this->activeConnections[$shardId]);
  197. }
  198. /**
  199. * @return void
  200. */
  201. public function close()
  202. {
  203. $this->_conn = null;
  204. $this->activeConnections = [];
  205. $this->activeShardId = null;
  206. }
  207. }