ShardConnectionManager.php 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * SPDX-FileCopyrightText: 2024 Robin Appelman <robin@icewind.nl>
  5. * SPDX-License-Identifier: AGPL-3.0-or-later
  6. */
  7. namespace OC\DB\QueryBuilder\Sharded;
  8. use OC\DB\ConnectionAdapter;
  9. use OC\DB\ConnectionFactory;
  10. use OC\SystemConfig;
  11. use OCP\IDBConnection;
  12. /**
  13. * Keeps track of the db connections to the various shards
  14. */
  15. class ShardConnectionManager {
  16. /** @var array<string, IDBConnection> */
  17. private array $connections = [];
  18. public function __construct(
  19. private SystemConfig $config,
  20. private ConnectionFactory $factory,
  21. ) {
  22. }
  23. public function getConnection(ShardDefinition $shardDefinition, int $shard): IDBConnection {
  24. $connectionKey = $shardDefinition->table . '_' . $shard;
  25. if (!isset($this->connections[$connectionKey])) {
  26. $this->connections[$connectionKey] = $this->createConnection($shardDefinition->shards[$shard]);
  27. }
  28. return $this->connections[$connectionKey];
  29. }
  30. private function createConnection(array $shardConfig): IDBConnection {
  31. $shardConfig['sharding'] = [];
  32. $type = $this->config->getValue('dbtype', 'sqlite');
  33. return new ConnectionAdapter($this->factory->getConnection($type, $shardConfig));
  34. }
  35. }