PoolingShardConnection.php 8.2 KB

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