PoolingShardManager.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. <?php
  2. namespace Doctrine\DBAL\Sharding;
  3. use Doctrine\DBAL\Sharding\ShardChoser\ShardChoser;
  4. use Doctrine\Deprecations\Deprecation;
  5. use RuntimeException;
  6. /**
  7. * Shard Manager for the Connection Pooling Shard Strategy
  8. *
  9. * @deprecated
  10. */
  11. class PoolingShardManager implements ShardManager
  12. {
  13. /** @var PoolingShardConnection */
  14. private $conn;
  15. /** @var ShardChoser */
  16. private $choser;
  17. /** @var string|null */
  18. private $currentDistributionValue;
  19. public function __construct(PoolingShardConnection $conn)
  20. {
  21. Deprecation::trigger(
  22. 'doctrine/dbal',
  23. 'https://github.com/doctrine/dbal/issues/3595',
  24. 'Native Sharding support in DBAL is removed without replacement.'
  25. );
  26. $params = $conn->getParams();
  27. $this->conn = $conn;
  28. $this->choser = $params['shardChoser'];
  29. }
  30. /**
  31. * {@inheritDoc}
  32. */
  33. public function selectGlobal()
  34. {
  35. $this->conn->connect(0);
  36. $this->currentDistributionValue = null;
  37. }
  38. /**
  39. * {@inheritDoc}
  40. */
  41. public function selectShard($distributionValue)
  42. {
  43. $shardId = $this->choser->pickShard($distributionValue, $this->conn);
  44. $this->conn->connect($shardId);
  45. $this->currentDistributionValue = $distributionValue;
  46. }
  47. /**
  48. * {@inheritDoc}
  49. */
  50. public function getCurrentDistributionValue()
  51. {
  52. return $this->currentDistributionValue;
  53. }
  54. /**
  55. * {@inheritDoc}
  56. */
  57. public function getShards()
  58. {
  59. $params = $this->conn->getParams();
  60. $shards = [];
  61. foreach ($params['shards'] as $shard) {
  62. $shards[] = ['id' => $shard['id']];
  63. }
  64. return $shards;
  65. }
  66. /**
  67. * {@inheritDoc}
  68. *
  69. * @throws RuntimeException
  70. */
  71. public function queryAll($sql, array $params, array $types)
  72. {
  73. $shards = $this->getShards();
  74. if (! $shards) {
  75. throw new RuntimeException('No shards found.');
  76. }
  77. $result = [];
  78. $oldDistribution = $this->getCurrentDistributionValue();
  79. foreach ($shards as $shard) {
  80. $this->conn->connect($shard['id']);
  81. foreach ($this->conn->fetchAllAssociative($sql, $params, $types) as $row) {
  82. $result[] = $row;
  83. }
  84. }
  85. if ($oldDistribution === null) {
  86. $this->selectGlobal();
  87. } else {
  88. $this->selectShard($oldDistribution);
  89. }
  90. return $result;
  91. }
  92. }