PoolingShardConnection.php 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264
  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 ShardChoser 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. * @deprecated
  33. *
  34. * @example
  35. *
  36. * $conn = DriverManager::getConnection(array(
  37. * 'wrapperClass' => 'Doctrine\DBAL\Sharding\PoolingShardConnection',
  38. * 'driver' => 'pdo_mysql',
  39. * 'global' => array('user' => '', 'password' => '', 'host' => '', 'dbname' => ''),
  40. * 'shards' => array(
  41. * array('id' => 1, 'user' => 'slave1', 'password', 'host' => '', 'dbname' => ''),
  42. * array('id' => 2, 'user' => 'slave2', 'password', 'host' => '', 'dbname' => ''),
  43. * ),
  44. * 'shardChoser' => 'Doctrine\DBAL\Sharding\ShardChoser\MultiTenantShardChoser',
  45. * ));
  46. * $shardManager = $conn->getShardManager();
  47. * $shardManager->selectGlobal();
  48. * $shardManager->selectShard($value);
  49. */
  50. class PoolingShardConnection extends Connection
  51. {
  52. /** @var DriverConnection[] */
  53. private $activeConnections = [];
  54. /** @var string|int|null */
  55. private $activeShardId;
  56. /** @var mixed[] */
  57. private $connectionParameters = [];
  58. /**
  59. * {@inheritDoc}
  60. *
  61. * @internal The connection can be only instantiated by the driver manager.
  62. *
  63. * @throws InvalidArgumentException
  64. */
  65. public function __construct(
  66. array $params,
  67. Driver $driver,
  68. ?Configuration $config = null,
  69. ?EventManager $eventManager = null
  70. ) {
  71. if (! isset($params['global'], $params['shards'])) {
  72. throw new InvalidArgumentException("Connection Parameters require 'global' and 'shards' configurations.");
  73. }
  74. if (! isset($params['shardChoser'])) {
  75. throw new InvalidArgumentException("Missing Shard Choser configuration 'shardChoser'");
  76. }
  77. if (is_string($params['shardChoser'])) {
  78. $params['shardChoser'] = new $params['shardChoser']();
  79. }
  80. if (! ($params['shardChoser'] instanceof ShardChoser)) {
  81. throw new InvalidArgumentException(
  82. "The 'shardChoser' configuration is not a valid instance of " . ShardChoser::class
  83. );
  84. }
  85. $this->connectionParameters[0] = array_merge($params, $params['global']);
  86. foreach ($params['shards'] as $shard) {
  87. if (! isset($shard['id'])) {
  88. throw new InvalidArgumentException(
  89. "Missing 'id' for one configured shard. Please specify a unique shard-id."
  90. );
  91. }
  92. if (! is_numeric($shard['id']) || $shard['id'] < 1) {
  93. throw new InvalidArgumentException('Shard Id has to be a non-negative number.');
  94. }
  95. if (isset($this->connectionParameters[$shard['id']])) {
  96. throw new InvalidArgumentException('Shard ' . $shard['id'] . ' is duplicated in the configuration.');
  97. }
  98. $this->connectionParameters[$shard['id']] = array_merge($params, $shard);
  99. }
  100. parent::__construct($params, $driver, $config, $eventManager);
  101. }
  102. /**
  103. * Get active shard id.
  104. *
  105. * @return string|int|null
  106. */
  107. public function getActiveShardId()
  108. {
  109. return $this->activeShardId;
  110. }
  111. /**
  112. * {@inheritdoc}
  113. */
  114. public function getParams()
  115. {
  116. return $this->activeShardId
  117. ? $this->connectionParameters[$this->activeShardId]
  118. : $this->connectionParameters[0];
  119. }
  120. /**
  121. * {@inheritdoc}
  122. */
  123. public function getHost()
  124. {
  125. $params = $this->getParams();
  126. return $params['host'] ?? parent::getHost();
  127. }
  128. /**
  129. * {@inheritdoc}
  130. */
  131. public function getPort()
  132. {
  133. $params = $this->getParams();
  134. return $params['port'] ?? parent::getPort();
  135. }
  136. /**
  137. * {@inheritdoc}
  138. */
  139. public function getUsername()
  140. {
  141. $params = $this->getParams();
  142. return $params['user'] ?? parent::getUsername();
  143. }
  144. /**
  145. * {@inheritdoc}
  146. */
  147. public function getPassword()
  148. {
  149. $params = $this->getParams();
  150. return $params['password'] ?? parent::getPassword();
  151. }
  152. /**
  153. * Connects to a given shard.
  154. *
  155. * @param string|int|null $shardId
  156. *
  157. * @return bool
  158. *
  159. * @throws ShardingException
  160. */
  161. public function connect($shardId = null)
  162. {
  163. if ($shardId === null && $this->_conn) {
  164. return false;
  165. }
  166. if ($shardId !== null && $shardId === $this->activeShardId) {
  167. return false;
  168. }
  169. if ($this->getTransactionNestingLevel() > 0) {
  170. throw new ShardingException('Cannot switch shard when transaction is active.');
  171. }
  172. $activeShardId = $this->activeShardId = (int) $shardId;
  173. if (isset($this->activeConnections[$activeShardId])) {
  174. $this->_conn = $this->activeConnections[$activeShardId];
  175. return false;
  176. }
  177. $this->_conn = $this->activeConnections[$activeShardId] = $this->connectTo($activeShardId);
  178. if ($this->_eventManager->hasListeners(Events::postConnect)) {
  179. $eventArgs = new ConnectionEventArgs($this);
  180. $this->_eventManager->dispatchEvent(Events::postConnect, $eventArgs);
  181. }
  182. return true;
  183. }
  184. /**
  185. * Connects to a specific connection.
  186. *
  187. * @param string|int $shardId
  188. *
  189. * @return \Doctrine\DBAL\Driver\Connection
  190. */
  191. protected function connectTo($shardId)
  192. {
  193. $params = $this->getParams();
  194. $driverOptions = $params['driverOptions'] ?? [];
  195. $connectionParams = $this->connectionParameters[$shardId];
  196. $user = $connectionParams['user'] ?? null;
  197. $password = $connectionParams['password'] ?? null;
  198. return $this->_driver->connect($connectionParams, $user, $password, $driverOptions);
  199. }
  200. /**
  201. * @param string|int|null $shardId
  202. *
  203. * @return bool
  204. */
  205. public function isConnected($shardId = null)
  206. {
  207. if ($shardId === null) {
  208. return $this->_conn !== null;
  209. }
  210. return isset($this->activeConnections[$shardId]);
  211. }
  212. /**
  213. * @return void
  214. */
  215. public function close()
  216. {
  217. $this->_conn = null;
  218. $this->activeConnections = [];
  219. $this->activeShardId = null;
  220. }
  221. }