PoolingShardConnection.php 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214
  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\DBAL\Connection;
  21. use Doctrine\DBAL\Event\ConnectionEventArgs;
  22. use Doctrine\DBAL\Events;
  23. use Doctrine\DBAL\Driver;
  24. use Doctrine\DBAL\Configuration;
  25. use Doctrine\Common\EventManager;
  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. * Connects to a given shard.
  115. *
  116. * @param mixed $shardId
  117. *
  118. * @return boolean
  119. *
  120. * @throws \Doctrine\DBAL\Sharding\ShardingException
  121. */
  122. public function connect($shardId = null)
  123. {
  124. if ($shardId === null && $this->_conn) {
  125. return false;
  126. }
  127. if ($shardId !== null && $shardId === $this->activeShardId) {
  128. return false;
  129. }
  130. if ($this->getTransactionNestingLevel() > 0) {
  131. throw new ShardingException("Cannot switch shard when transaction is active.");
  132. }
  133. $this->activeShardId = (int)$shardId;
  134. if (isset($this->activeConnections[$this->activeShardId])) {
  135. $this->_conn = $this->activeConnections[$this->activeShardId];
  136. return false;
  137. }
  138. $this->_conn = $this->activeConnections[$this->activeShardId] = $this->connectTo($this->activeShardId);
  139. if ($this->_eventManager->hasListeners(Events::postConnect)) {
  140. $eventArgs = new \Doctrine\DBAL\Event\ConnectionEventArgs($this);
  141. $this->_eventManager->dispatchEvent(Events::postConnect, $eventArgs);
  142. }
  143. return true;
  144. }
  145. /**
  146. * Connects to a specific connection.
  147. *
  148. * @param string $shardId
  149. *
  150. * @return \Doctrine\DBAL\Driver\Connection
  151. */
  152. protected function connectTo($shardId)
  153. {
  154. $params = $this->getParams();
  155. $driverOptions = isset($params['driverOptions']) ? $params['driverOptions'] : array();
  156. $connectionParams = $this->connections[$shardId];
  157. $user = isset($connectionParams['user']) ? $connectionParams['user'] : null;
  158. $password = isset($connectionParams['password']) ? $connectionParams['password'] : null;
  159. return $this->_driver->connect($connectionParams, $user, $password, $driverOptions);
  160. }
  161. /**
  162. * @param string|null $shardId
  163. *
  164. * @return boolean
  165. */
  166. public function isConnected($shardId = null)
  167. {
  168. if ($shardId === null) {
  169. return $this->_conn !== null;
  170. }
  171. return isset($this->activeConnections[$shardId]);
  172. }
  173. /**
  174. * @return void
  175. */
  176. public function close()
  177. {
  178. $this->_conn = null;
  179. $this->activeConnections = null;
  180. }
  181. }